diff --git a/docs/incidents/bo_alarm_reads_its_evidence.md b/docs/incidents/bo_alarm_reads_its_evidence.md index 7fbc9a456..d88c343b9 100644 --- a/docs/incidents/bo_alarm_reads_its_evidence.md +++ b/docs/incidents/bo_alarm_reads_its_evidence.md @@ -2,4 +2,4 @@ **What happened:** An alert route sends a WAF signature-drift alarm (a Count rule seeing crawler A get past a Block rule after it changed its JA4 or user agent) to the team's terraform repository, where the fix is a pull request that updates the block rule's match. The run ended `needs_input` with a long question asking a person to grant the team's read-only role WAF and Athena access, "Default if unanswered in 4 hours: Grant access". `wafv2:ListWebACLs` and `GetSampledRequests` were denied: the role's setup script never added any WAF read. The web ACL logs to an `aws-waf-logs-*` bucket with an Athena table, and nothing read it. -**The guarantee:** The role's setup script adds `coderhelm-read-waf`: WAF reads, and read-only Athena queries over the Glue tables on `aws-waf-logs-*` buckets, in the WAF log workgroups, with results written only under the workgroup's own results prefix. With those reads the run gathers the rule's matches before it plans (sampled requests, and the logs in S3 by JA4, JA3, user agent, accept language, path and cookie presence, over the last three hours) and goes on to its pull request. Without them the refusal is the install's one setup item, **AWS role reads**, with the one-line CloudShell update; the run names it in one line and goes on. The stop judge turns an ask or a hold for the role's reads into a proceed, the hand-back list doesn't carry it, and an access question never shows a default that can't happen. +**The guarantee:** The role stack's template (`CoderHelmLogReader`) has the WAF reads and a WAF log group (`WafLogs`): read-only Athena queries over the Glue tables on `aws-waf-logs-*` buckets, with results written only under the workgroup's own results location. With those reads the run gathers the rule's matches before it plans (sampled requests, and the logs in S3 by JA4, JA3, user agent, accept language, path and cookie presence, over the last three hours) and goes on to its pull request. Without them the refusal is the install's one setup item, **AWS role reads**, with the role stack's one-click update ([cw](./cw_role_reads_arrive_by_stack_update.md)); the run names it in one line and goes on. The stop judge turns an ask or a hold for the role's reads into a proceed, the hand-back list doesn't carry it, and an access question never shows a default that can't happen. diff --git a/docs/incidents/cw_role_reads_arrive_by_stack_update.md b/docs/incidents/cw_role_reads_arrive_by_stack_update.md new file mode 100644 index 000000000..fc74e596e --- /dev/null +++ b/docs/incidents/cw_role_reads_arrive_by_stack_update.md @@ -0,0 +1,5 @@ +# cw. `cw_role_reads_arrive_by_stack_update` + +**What happened:** AWS WAF alarm runs needed WAF, Athena and Glue reads on the WAF logs. They were first added to the CloudShell setup script (`coderhelm-read-waf`), with a one-line update shown as a setup item. Every team would have had to find and paste a script for each new read. The line patched a role CloudFormation had made, and it gave the reads to the data-source role `CoderhelmReadOnly`, while alarm runs read through `CoderHelmLogReader`. A release can't add a read by itself: CoderHelm's own roles may not change IAM. + +**The guarantee:** Every read is declared in the role stack's one versioned template (`infra/cfn/coderhelm-log-reader.yaml`, published with each release), as named groups a stack parameter switches on: `WafLogs` (with `WafLogResults` and `WafLogKey`), `DatabaseClusters` and `Warehouses`. A WAF alarm run on an old role reads what it may and records what it was refused and what it found: the log bucket's KMS key and the workgroup's results location. It asks nobody. The install's one item, **AWS role reads**, is this release's one-click update of that stack, with those values filled in, which an AWS admin of the account creates. The same item names a role that is older than the release, and data sources the old script made. Those sources move onto the stack's role only after it reads them end to end. The data-source script no longer writes any permission: it creates or updates the role stack. diff --git a/docs/self-host/check-your-install.md b/docs/self-host/check-your-install.md index c19f781bc..5f9007630 100644 --- a/docs/self-host/check-your-install.md +++ b/docs/self-host/check-your-install.md @@ -156,8 +156,8 @@ The last result is kept in `.coderhelm/doctor.json`. ### Integrations - **AWS role reads** (`aws_role_reads`, in the dashboard only)\ - *If it warns:* A team's connected AWS role was refused a read an alert route needed, such as AWS WAF's sampled requests for a WAF alarm. Alarm runs read what the role allows and go on without the rest; no run asks a person for it.\ - *Fix:* The one line to paste into AWS CloudShell in that account. It adds the read-only `coderhelm-read-waf` policy to the role and changes nothing else. The item clears the next time an alarm run reads with it. + *If it warns:* A connected AWS account's role stack needs this release's update: a run was refused a read an alert route needed (such as the WAF log tables for a WAF alarm), the role is older than this release, or data sources still read through the older `CoderhelmReadOnly` role. Runs read what the role allows and go on without the rest; no run asks a person for it.\ + *Fix:* The link opens CloudFormation's quick-create of this release's update stack on `CoderHelmLogReader`, with the account's groups and what CoderHelm found filled in. An AWS admin of that account reviews it and presses **Create stack**. The item clears once the role has the reads. ## The guided install @@ -213,7 +213,7 @@ Install admins (`admins` in the config) who are team admins can call these while } ``` -`status` is `pass`, `warn`, `fail` or `skip` (an optional integration that isn't set up). `fix` has `text` and any of `command` (to copy), `url` (outside CoderHelm) and `href` (a dashboard page). `ready` is true when nothing fails. Keys: `url`, `domain`, `github_keys`, `github_app`, `github_permissions`, `github_workflow_starts`, `github_installations`, `github_webhook`, `github_sign_in`, `email_sender`, `email_identity`, `email_sandbox`, `email_cognito`, `model`, `dlq`, `updates`, `slack`, `teams`, `jira`, `aws_connections`, `aws_role_reads`. `aws_role_reads` warns, and never blocks an update, while a team's connected AWS role lacks a read an alert route used; its `fix.command` is the one-line CloudShell update. A self-hosted install has no Google sign-in, so there is no `google_sign_in` check. On an install that uses CoderHelm's GitHub App (hybrid), `github_app` and `github_installations` say whether the app is linked instead, and never block an update. `github_sign_in` passes when the install's own GitHub App has its OAuth client id and secret stored, or when the install has neither and is registered with CoderHelm (GitHub sign-in then goes through CoderHelm's app, [Sign in with GitHub through CoderHelm](./hybrid.md#sign-in-with-github-through-coderhelm)). It warns when only one of the two is stored, when the install's own app has neither, and when an install on CoderHelm's GitHub App isn't registered yet: the sign-in page doesn't offer Continue with GitHub until then. It never blocks an update. +`status` is `pass`, `warn`, `fail` or `skip` (an optional integration that isn't set up). `fix` has `text` and any of `command` (to copy), `url` (outside CoderHelm) and `href` (a dashboard page). `ready` is true when nothing fails. Keys: `url`, `domain`, `github_keys`, `github_app`, `github_permissions`, `github_workflow_starts`, `github_installations`, `github_webhook`, `github_sign_in`, `email_sender`, `email_identity`, `email_sandbox`, `email_cognito`, `model`, `dlq`, `updates`, `slack`, `teams`, `jira`, `aws_connections`, `aws_role_reads`. `aws_role_reads` warns, and never blocks an update, while a connected account's role stack needs this release's update; its `fix.url` is that account's one-click update stack. A self-hosted install has no Google sign-in, so there is no `google_sign_in` check. On an install that uses CoderHelm's GitHub App (hybrid), `github_app` and `github_installations` say whether the app is linked instead, and never block an update. `github_sign_in` passes when the install's own GitHub App has its OAuth client id and secret stored, or when the install has neither and is registered with CoderHelm (GitHub sign-in then goes through CoderHelm's app, [Sign in with GitHub through CoderHelm](./hybrid.md#sign-in-with-github-through-coderhelm)). It warns when only one of the two is stored, when the install's own app has neither, and when an install on CoderHelm's GitHub App isn't registered yet: the sign-in page doesn't offer Continue with GitHub until then. It never blocks an update. ### `GET /api/system/domain`, `PUT /api/system/domain`, `DELETE /api/system/domain` diff --git a/docs/self-host/integrations.md b/docs/self-host/integrations.md index 4fab1c7c3..efdc8685d 100644 --- a/docs/self-host/integrations.md +++ b/docs/self-host/integrations.md @@ -24,16 +24,24 @@ Teams connect their own AWS accounts so CoderHelm can read CloudWatch logs, alar Connect it the same way: the `CoderHelmLogReader` role there, with the team's External ID, proves the team may read it. After that, the install reads its own account with its gateway's and worker's own roles, which the install's stack gives this release's read-only permissions (`infra/lib/own-account-read.ts`, the same list as the update template). Each version update brings any new permission, so the install's own account never shows **Update in AWS**; if a permission is still missing, the page says it comes with the next version update. - **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. -- **The data-source role, and AWS WAF alarms**\ - AWS data sources (databases, warehouses) use the read-only role `CoderhelmReadOnly`, made by the setup script a team pastes into AWS CloudShell from **Settings, Data sources, AWS**. The script also gives it `coderhelm-read-waf`, so a run an alert rule starts for an AWS WAF alarm can read what the alarm's rule matched: - - `wafv2:Get*` and `wafv2:List*`: web ACLs, sampled requests, where a web ACL logs; - - `s3:GetObject`, `s3:ListBucket` and `s3:GetBucketLocation` on `aws-waf-logs-*` buckets only; - - when the account has an Athena workgroup with `waf` in its name (with a results location) and a Glue table on an `aws-waf-logs-*` bucket, in the region the script runs in: `glue:Get*` on those databases and tables, `athena:StartQueryExecution`, `athena:Get*` and `athena:StopQueryExecution` in those workgroups, and `s3:PutObject` only under each workgroup's own results prefix; - - every change to WAF, Athena, Glue or a bucket, Glue's connections, and any object written outside the results prefix are denied. - - A web ACL that logs to S3 is read with one Athena query: the alarm's rule only, the last three hours (bounded by the table's projected date partition, or by the workgroup's scan limit; with neither the bucket isn't queried), counted by JA4, JA3, user agent, accept language, path and whether a cookie was sent. No client address, cookie or other header value is selected. -- **When a role lacks a read an alert route needs**\ - It is one setup item for the whole install, **AWS role reads** (`aws_role_reads` in Settings, then **Setup**), with one line to paste into AWS CloudShell in the role's account. The line adds `coderhelm-read-waf` to the existing role and changes nothing else. Until then, alarm runs read what the role allows, name the item in one line and go on to the pull request they can justify: no run asks a person for access, and none waits on it. +- **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: + + | Group (parameter) | What it reads, and why | + |---|---| + | Logs, alarms, metrics, Airflow, ECS, the code behind a log group, AWS WAF requests, bucket and key settings (always) | Error lines, alarm states and metrics to find what broke; the tasks and tags behind a log group to find its repository; for a WAF alarm, the web ACL, the requests its rule matched (`wafv2:GetSampledRequests`) and where it logs. | + | WAF logs (`WafLogs`, `WafLogResults`, `WafLogKey`) | For a WAF alarm, what the web ACL logged to its `aws-waf-logs-*` bucket: the log objects, the Glue table definitions Athena needs (`glue:GetDatabases`, `GetDatabase`, `GetTables`, `GetTable`, `GetPartitions`) and the Athena workgroups' settings (`athena:ListWorkGroups`, `GetWorkGroup`). With `WafLogResults` (the WAF log workgroup's results location, `bucket/prefix/`) it runs read-only queries (`athena:StartQueryExecution`, `GetQueryExecution`, `GetQueryResults`, `StopQueryExecution`) and writes their results only there (`s3:PutObject`). With `WafLogKey` (the log bucket's customer-managed KMS key) it may `kms:Decrypt` with that key only through S3 (`kms:ViaService` `s3.*.amazonaws.com`). Writes anywhere but the results location, every change to WAF, Athena, Glue or a bucket, and Glue's connections are denied. | + | Databases (`DatabaseClusters`) | The Aurora PostgreSQL clusters named, through the RDS Data API, as the read-only user `coderhelm_readonly`, inside transactions that are rolled back (`CommitTransaction` is denied); only that user's password secret (`coderhelm-readonly-*`). | + | Warehouses (`Warehouses`) | The Redshift clusters named, signed in only as the passwordless read-only user `coderhelm_readonly`, one statement at a time, its own results only. | + | Knowledge bases, imports, copying into Bedrock, infrastructure versions, Inspector, Health, approved maintenance | Each named on the AWS page with its reason; knowledge bases and imports are in [Knowledge sources](./knowledge-sources.md). | + + A WAF alarm on an alert route turns the WAF log group on for that account: the run reads the bucket's default encryption for `WafLogKey` and the workgroup's results location for `WafLogResults`, and every later update link carries them. Until the results location is known the group reads the logs' tables and settings and writes nothing; the next WAF alarm finds the location and the item offers the update that adds the queries. +- **Data sources: databases and warehouses**\ + **Settings, Data sources, AWS** gives a script to paste into AWS CloudShell. It makes only what a stack can't: the read-only user inside the database or warehouse you pick (and the database user's password secret). Then it creates CoderHelm's role stack `CoderHelmLogReader`, or updates it to this release's template, naming that database in `DatabaseClusters` or that warehouse in `Warehouses` and keeping every other parameter as it was. The script never writes a permission on a role by itself. A role named `CoderHelmLogReader` that the stack didn't make is left alone, and the script says so. +- **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. - **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 a0454f6eb..00ef64b9f 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. `CoderhelmReadOnly`'s one write is `s3:PutObject` for Athena query results, held by an explicit deny to the WAF log workgroup's own results prefix (see [Integrations](./integrations.md#connected-aws-accounts)). 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 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 diff --git a/infra/cfn/coderhelm-log-reader-update.yaml b/infra/cfn/coderhelm-log-reader-update.yaml index 2071f3033..89ea79b99 100644 --- a/infra/cfn/coderhelm-log-reader-update.yaml +++ b/infra/cfn/coderhelm-log-reader-update.yaml @@ -1,20 +1,16 @@ AWSTemplateFormatVersion: "2010-09-09" Description: > - Brings the existing CoderHelmLogReader role up to date with the read-only - permissions the current CoderHelm release uses, lets it search the - Bedrock knowledge bases named in KnowledgeBases, and lets it read the - documents in the S3 buckets named in ImportBuckets. Every permission is - read-only (list, describe and query), except one you opt into: copying - your chosen CoderHelm knowledge bases into the Bedrock knowledge bases - named in SyncKnowledgeBases. With InfrastructureVulnerabilities "on" it - also reads, read-only, which versions your EC2, EKS, RDS, ElastiCache and - OpenSearch resources run, for matching against security advisories. - With ApplyMaintenance "on" it may also apply a pending RDS or Aurora - maintenance action that a person approved in CoderHelm. - It only adds: to drop a permission an older release granted, update the - CoderHelmLogReader stack itself with the current role template. - Created from the dashboard's Update link; you can delete older - CoderHelmLogReaderUpdate stacks once this one is in place. + Brings the existing CoderHelmLogReader role up to this CoderHelm release's + template: its read-only permissions, plus the groups its parameters switch + on (Bedrock knowledge bases, S3 imports, infrastructure versions, + Inspector, Health, WAF logs, databases, warehouses). Every permission is + read-only except three you opt into: copying chosen knowledge bases into + Bedrock (SyncKnowledgeBases), applying approved RDS maintenance + (ApplyMaintenance), and writing Athena query results only under + WafLogResults. It only adds: to drop a permission an older release + granted, update the CoderHelmLogReader stack itself. Created from the + dashboard's Update link; delete older CoderHelmLogReaderUpdate stacks + once this one is in place. Parameters: RoleName: @@ -98,6 +94,63 @@ Parameters: own ApplyPendingMaintenanceAction, only on this account's database clusters and instances. Nothing is applied without that approval. + WafLogs: + Type: String + Default: "off" + AllowedValues: ["off", "on"] + Description: > + "on" lets CoderHelm read what an AWS WAF web ACL logs to S3 (the + aws-waf-logs-* buckets, the names AWS requires) when a WAF alarm on + one of your alert routes fires: the log objects, the Glue table + definitions Athena needs, and your Athena workgroups' settings. With + WafLogResults set it also runs read-only Athena queries over those + logs, writing their results only under that location. Every change to + WAF, Athena, Glue or a bucket is denied. + + WafLogResults: + Type: String + Default: "" + Description: > + Where the Athena workgroup that queries your WAF logs writes query + results: its "Query result location" without s3:// (bucket/prefix/). + CoderHelm fills it in from the workgroup when it can. Empty: no Athena + query and nothing written anywhere. + AllowedPattern: "^(|[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]/[A-Za-z0-9!_.'()=/-]*)$" + ConstraintDescription: A bucket name, a slash and a prefix (bucket/prefix/), or empty. + + WafLogKey: + Type: String + Default: "" + Description: > + The ARN of the customer-managed KMS key the WAF log bucket is + encrypted with, if it is. CoderHelm fills it in from the bucket's + default encryption. The role may decrypt with it only through S3, so + only objects it may read anyway. Empty: none (SSE-S3 needs nothing). + AllowedPattern: "^(|arn:aws:kms:[a-z0-9-]+:[0-9]{12}:key/[a-f0-9-]{36})$" + ConstraintDescription: A KMS key ARN, or empty. + + DatabaseClusters: + Type: String + Default: "" + Description: > + Aurora PostgreSQL clusters CoderHelm may query as the read-only + database user coderhelm_readonly (their ARNs separated by commas), + through the RDS Data API inside transactions that are always rolled + back. The user and its password secret (coderhelm-readonly-*) are made + by the data source setup on Settings, Data sources, AWS. Empty: none. + AllowedPattern: "^(|arn:aws:rds:[a-z0-9-]+:[0-9]{12}:cluster:[a-z][a-z0-9-]{0,62}(,arn:aws:rds:[a-z0-9-]+:[0-9]{12}:cluster:[a-z][a-z0-9-]{0,62})*)$" + ConstraintDescription: Aurora cluster ARNs separated by commas, or empty. + + Warehouses: + Type: String + Default: "" + Description: > + Redshift clusters CoderHelm may query, signed in only as the + passwordless read-only user coderhelm_readonly (their names separated + by commas). Empty: none. + AllowedPattern: "^(|[a-z][a-z0-9-]{0,62}(,[a-z][a-z0-9-]{0,62})*)$" + ConstraintDescription: Redshift cluster names separated by commas, or empty. + Conditions: ReadsKnowledgeBases: !Not [!Equals [!Ref KnowledgeBases, ""]] ReadsEveryKnowledgeBase: !Equals [!Ref KnowledgeBases, "all"] @@ -108,6 +161,12 @@ Conditions: ReadsInspector: !Equals [!Ref InspectorFindings, "on"] ReadsHealth: !Equals [!Ref HealthEvents, "on"] AppliesMaintenance: !Equals [!Ref ApplyMaintenance, "on"] + ReadsWafLogs: !Equals [!Ref WafLogs, "on"] + QueriesWafLogs: !And [!Condition ReadsWafLogs, !Not [!Equals [!Ref WafLogResults, ""]]] + NoWafLogQueries: !And [!Condition ReadsWafLogs, !Equals [!Ref WafLogResults, ""]] + DecryptsWafLogs: !And [!Condition ReadsWafLogs, !Not [!Equals [!Ref WafLogKey, ""]]] + ReadsDatabases: !Not [!Equals [!Ref DatabaseClusters, ""]] + ReadsWarehouses: !Not [!Equals [!Ref Warehouses, ""]] Resources: CoderHelmReadOnlyUpdate: @@ -381,3 +440,202 @@ Resources: - "health:DescribeEventDetails" Resource: "*" - !Ref AWS::NoValue + # AWS WAF logs in S3, only when WafLogs is "on" (an alert route takes + # WAF alarms): the log objects, the table definitions and workgroup + # settings Athena needs, and, with WafLogResults, read-only queries whose + # results are written only there (the role's one write, held there by a + # deny). Everything that changes WAF, Athena, Glue or a bucket is denied. + - !If + - ReadsWafLogs + - Sid: ReadWafLogObjects + Effect: Allow + Action: + - "s3:GetObject" + Resource: "arn:aws:s3:::aws-waf-logs-*/*" + - !Ref AWS::NoValue + - !If + - ReadsWafLogs + - Sid: ListWafLogBuckets + Effect: Allow + Action: + - "s3:ListBucket" + - "s3:GetBucketLocation" + Resource: "arn:aws:s3:::aws-waf-logs-*" + - !Ref AWS::NoValue + # Table definitions only (names, columns, where the data is): Athena + # reads them to plan a query. The data itself is readable only in the + # aws-waf-logs-* buckets above. + - !If + - ReadsWafLogs + - Sid: FindWafLogTables + Effect: Allow + Action: + - "glue:GetDatabases" + - "glue:GetDatabase" + - "glue:GetTables" + - "glue:GetTable" + - "glue:GetPartitions" + Resource: + - !Sub "arn:aws:glue:*:${AWS::AccountId}:catalog" + - !Sub "arn:aws:glue:*:${AWS::AccountId}:database/*" + - !Sub "arn:aws:glue:*:${AWS::AccountId}:table/*/*" + - !Ref AWS::NoValue + # Which workgroup queries the logs and where it writes its results. + - !If + - ReadsWafLogs + - Sid: FindWafLogWorkgroups + Effect: Allow + Action: + - "athena:ListWorkGroups" + - "athena:GetWorkGroup" + Resource: "*" + - !Ref AWS::NoValue + - !If + - QueriesWafLogs + - Sid: QueryWafLogs + Effect: Allow + Action: + - "athena:StartQueryExecution" + - "athena:GetQueryExecution" + - "athena:GetQueryResults" + - "athena:StopQueryExecution" + Resource: !Sub "arn:aws:athena:*:${AWS::AccountId}:workgroup/*" + - !Ref AWS::NoValue + - !If + - QueriesWafLogs + - Sid: WriteQueryResultsOnly + Effect: Allow + Action: + - "s3:PutObject" + - "s3:GetObject" + Resource: !Sub "arn:aws:s3:::${WafLogResults}*" + - !Ref AWS::NoValue + - !If + - QueriesWafLogs + - Sid: FindQueryResults + Effect: Allow + Action: + - "s3:ListBucket" + - "s3:GetBucketLocation" + Resource: !Sub + - "arn:aws:s3:::${Bucket}" + - Bucket: !Select [0, !Split ["/", !Ref WafLogResults]] + - !Ref AWS::NoValue + - !If + - QueriesWafLogs + - Sid: NoWritesButQueryResults + Effect: Deny + Action: ["s3:PutObject"] + NotResource: !Sub "arn:aws:s3:::${WafLogResults}*" + - !Ref AWS::NoValue + - !If + - NoWafLogQueries + - Sid: NoWrites + Effect: Deny + Action: ["s3:PutObject"] + Resource: "*" + - !Ref AWS::NoValue + - !If + - DecryptsWafLogs + - Sid: DecryptWafLogsThroughS3 + Effect: Allow + Action: + - "kms:Decrypt" + Resource: !Ref WafLogKey + Condition: + StringLike: + kms:ViaService: "s3.*.amazonaws.com" + - !Ref AWS::NoValue + - !If + - ReadsWafLogs + - Sid: NeverChangeWafOrItsLogs + Effect: Deny + Action: ["wafv2:Create*", "wafv2:Update*", "wafv2:Delete*", "wafv2:Put*", "wafv2:Associate*", "wafv2:Disassociate*", "wafv2:Tag*", "wafv2:Untag*", "athena:Create*", "athena:Update*", "athena:Delete*", "athena:Put*", "athena:Import*", "athena:Tag*", "athena:Untag*", "glue:Create*", "glue:Update*", "glue:Delete*", "glue:Put*", "glue:BatchCreate*", "glue:BatchDelete*", "glue:BatchUpdate*", "glue:GetConnection*", "s3:Delete*", "s3:PutBucket*", "s3:PutObjectAcl*", "s3:PutObjectTagging*"] + Resource: "*" + - !Ref AWS::NoValue + # Databases, only those named in DatabaseClusters: queries as the + # read-only database user inside transactions that are rolled back, never + # committed; the only secret readable is that user's password. + - !If + - ReadsDatabases + - Sid: QueryChosenDatabases + Effect: Allow + Action: + - "rds-data:BeginTransaction" + - "rds-data:ExecuteStatement" + - "rds-data:RollbackTransaction" + Resource: !Split [",", !Ref DatabaseClusters] + - !Ref AWS::NoValue + - !If + - ReadsDatabases + - Sid: ReadOnlyUserPassword + Effect: Allow + Action: + - "secretsmanager:GetSecretValue" + Resource: !Sub "arn:aws:secretsmanager:*:${AWS::AccountId}:secret:coderhelm-readonly-*" + - !Ref AWS::NoValue + - !If + - ReadsDatabases + - Sid: NeverCommit + Effect: Deny + Action: ["rds-data:CommitTransaction", "rds-data:BatchExecuteStatement"] + Resource: "*" + - !Ref AWS::NoValue + # Warehouses, only those named in Warehouses: signed in only as the + # passwordless read-only user, single statements, its own results. + - !If + - ReadsWarehouses + - Sid: SignInAsTheReadOnlyUser + Effect: Allow + Action: + - "redshift:GetClusterCredentials" + Resource: !Split + - "," + - !Sub + - "arn:aws:redshift:*:*:dbuser:${Ids}/coderhelm_readonly" + - Ids: !Join ["/coderhelm_readonly,arn:aws:redshift:*:*:dbuser:", !Split [",", !Ref Warehouses]] + - !Ref AWS::NoValue + - !If + - ReadsWarehouses + - Sid: IntoTheirDatabases + Effect: Allow + Action: + - "redshift:GetClusterCredentials" + Resource: !Split + - "," + - !Sub + - "arn:aws:redshift:*:*:dbname:${Ids}/*" + - Ids: !Join ["/*,arn:aws:redshift:*:*:dbname:", !Split [",", !Ref Warehouses]] + - !Ref AWS::NoValue + - !If + - ReadsWarehouses + - Sid: RunOneStatement + Effect: Allow + Action: + - "redshift-data:ExecuteStatement" + Resource: !Split + - "," + - !Sub + - "arn:aws:redshift:*:*:cluster:${Ids}" + - Ids: !Join [",arn:aws:redshift:*:*:cluster:", !Split [",", !Ref Warehouses]] + - !Ref AWS::NoValue + - !If + - ReadsWarehouses + - Sid: ReadOwnResults + Effect: Allow + Action: + - "redshift-data:DescribeStatement" + - "redshift-data:GetStatementResult" + - "redshift-data:CancelStatement" + Resource: "*" + Condition: + StringEquals: + redshift-data:statement-owner-iam-userid: "${aws:userid}" + - !Ref AWS::NoValue + - !If + - ReadsWarehouses + - Sid: NothingElseInTheWarehouse + Effect: Deny + Action: ["redshift-data:BatchExecuteStatement", "redshift:CreateClusterUser", "redshift:GetClusterCredentialsWithIAM", "redshift:ModifyCluster*", "redshift:Delete*"] + Resource: "*" + - !Ref AWS::NoValue diff --git a/infra/cfn/coderhelm-log-reader.yaml b/infra/cfn/coderhelm-log-reader.yaml index 8f87872ba..53e557919 100644 --- a/infra/cfn/coderhelm-log-reader.yaml +++ b/infra/cfn/coderhelm-log-reader.yaml @@ -7,7 +7,12 @@ Description: > InfrastructureVulnerabilities "on" it also reads, read-only, which versions your EC2, EKS, RDS, ElastiCache and OpenSearch resources run. With ApplyMaintenance "on" it may also apply a pending RDS or Aurora - maintenance action that a person approved in CoderHelm. + maintenance action that a person approved in CoderHelm. With WafLogs "on" + it reads your AWS WAF logs in S3 through Athena, writing query results + only under WafLogResults. With DatabaseClusters or Warehouses it queries + those databases and warehouses as their read-only user. Every read is + declared here, by group; a CoderHelm release reaches this role only + through an update you create from its template. This role uses an External ID to prevent confused deputy attacks. Parameters: @@ -108,6 +113,63 @@ Parameters: own ApplyPendingMaintenanceAction, only on this account's database clusters and instances. Nothing is applied without that approval. + WafLogs: + Type: String + Default: "off" + AllowedValues: ["off", "on"] + Description: > + "on" lets CoderHelm read what an AWS WAF web ACL logs to S3 (the + aws-waf-logs-* buckets, the names AWS requires) when a WAF alarm on + one of your alert routes fires: the log objects, the Glue table + definitions Athena needs, and your Athena workgroups' settings. With + WafLogResults set it also runs read-only Athena queries over those + logs, writing their results only under that location. Every change to + WAF, Athena, Glue or a bucket is denied. + + WafLogResults: + Type: String + Default: "" + Description: > + Where the Athena workgroup that queries your WAF logs writes query + results: its "Query result location" without s3:// (bucket/prefix/). + CoderHelm fills it in from the workgroup when it can. Empty: no Athena + query and nothing written anywhere. + AllowedPattern: "^(|[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]/[A-Za-z0-9!_.'()=/-]*)$" + ConstraintDescription: A bucket name, a slash and a prefix (bucket/prefix/), or empty. + + WafLogKey: + Type: String + Default: "" + Description: > + The ARN of the customer-managed KMS key the WAF log bucket is + encrypted with, if it is. CoderHelm fills it in from the bucket's + default encryption. The role may decrypt with it only through S3, so + only objects it may read anyway. Empty: none (SSE-S3 needs nothing). + AllowedPattern: "^(|arn:aws:kms:[a-z0-9-]+:[0-9]{12}:key/[a-f0-9-]{36})$" + ConstraintDescription: A KMS key ARN, or empty. + + DatabaseClusters: + Type: String + Default: "" + Description: > + Aurora PostgreSQL clusters CoderHelm may query as the read-only + database user coderhelm_readonly (their ARNs separated by commas), + through the RDS Data API inside transactions that are always rolled + back. The user and its password secret (coderhelm-readonly-*) are made + by the data source setup on Settings, Data sources, AWS. Empty: none. + AllowedPattern: "^(|arn:aws:rds:[a-z0-9-]+:[0-9]{12}:cluster:[a-z][a-z0-9-]{0,62}(,arn:aws:rds:[a-z0-9-]+:[0-9]{12}:cluster:[a-z][a-z0-9-]{0,62})*)$" + ConstraintDescription: Aurora cluster ARNs separated by commas, or empty. + + Warehouses: + Type: String + Default: "" + Description: > + Redshift clusters CoderHelm may query, signed in only as the + passwordless read-only user coderhelm_readonly (their names separated + by commas). Empty: none. + AllowedPattern: "^(|[a-z][a-z0-9-]{0,62}(,[a-z][a-z0-9-]{0,62})*)$" + ConstraintDescription: Redshift cluster names separated by commas, or empty. + Conditions: ReadsKnowledgeBases: !Not [!Equals [!Ref KnowledgeBases, ""]] ReadsEveryKnowledgeBase: !Equals [!Ref KnowledgeBases, "all"] @@ -118,6 +180,12 @@ Conditions: ReadsInspector: !Equals [!Ref InspectorFindings, "on"] ReadsHealth: !Equals [!Ref HealthEvents, "on"] AppliesMaintenance: !Equals [!Ref ApplyMaintenance, "on"] + ReadsWafLogs: !Equals [!Ref WafLogs, "on"] + QueriesWafLogs: !And [!Condition ReadsWafLogs, !Not [!Equals [!Ref WafLogResults, ""]]] + NoWafLogQueries: !And [!Condition ReadsWafLogs, !Equals [!Ref WafLogResults, ""]] + DecryptsWafLogs: !And [!Condition ReadsWafLogs, !Not [!Equals [!Ref WafLogKey, ""]]] + ReadsDatabases: !Not [!Equals [!Ref DatabaseClusters, ""]] + ReadsWarehouses: !Not [!Equals [!Ref Warehouses, ""]] Resources: CoderHelmLogReaderRole: @@ -468,6 +536,188 @@ Resources: Resource: "*" - !Ref AWS::NoValue + # AWS WAF logs in S3, only when WafLogs is "on" (an alert route takes + # WAF alarms): the log objects, the table definitions and workgroup + # settings Athena needs, and, with WafLogResults, read-only queries whose + # results are written only there (the role's one write, held there by a + # deny). Everything that changes WAF, Athena, Glue or a bucket is denied. + - !If + - ReadsWafLogs + - PolicyName: WafLogsReadOnly + PolicyDocument: + Version: "2012-10-17" + Statement: + - Sid: ReadWafLogObjects + Effect: Allow + Action: + - "s3:GetObject" + Resource: "arn:aws:s3:::aws-waf-logs-*/*" + - Sid: ListWafLogBuckets + Effect: Allow + Action: + - "s3:ListBucket" + - "s3:GetBucketLocation" + Resource: "arn:aws:s3:::aws-waf-logs-*" + # Table definitions only (names, columns, where the data is): Athena + # reads them to plan a query. The data itself is readable only in the + # aws-waf-logs-* buckets above. + - Sid: FindWafLogTables + Effect: Allow + Action: + - "glue:GetDatabases" + - "glue:GetDatabase" + - "glue:GetTables" + - "glue:GetTable" + - "glue:GetPartitions" + Resource: + - !Sub "arn:aws:glue:*:${AWS::AccountId}:catalog" + - !Sub "arn:aws:glue:*:${AWS::AccountId}:database/*" + - !Sub "arn:aws:glue:*:${AWS::AccountId}:table/*/*" + # Which workgroup queries the logs and where it writes its results. + - Sid: FindWafLogWorkgroups + Effect: Allow + Action: + - "athena:ListWorkGroups" + - "athena:GetWorkGroup" + Resource: "*" + - !If + - QueriesWafLogs + - Sid: QueryWafLogs + Effect: Allow + Action: + - "athena:StartQueryExecution" + - "athena:GetQueryExecution" + - "athena:GetQueryResults" + - "athena:StopQueryExecution" + Resource: !Sub "arn:aws:athena:*:${AWS::AccountId}:workgroup/*" + - !Ref AWS::NoValue + - !If + - QueriesWafLogs + - Sid: WriteQueryResultsOnly + Effect: Allow + Action: + - "s3:PutObject" + - "s3:GetObject" + Resource: !Sub "arn:aws:s3:::${WafLogResults}*" + - !Ref AWS::NoValue + - !If + - QueriesWafLogs + - Sid: FindQueryResults + Effect: Allow + Action: + - "s3:ListBucket" + - "s3:GetBucketLocation" + Resource: !Sub + - "arn:aws:s3:::${Bucket}" + - Bucket: !Select [0, !Split ["/", !Ref WafLogResults]] + - !Ref AWS::NoValue + - !If + - QueriesWafLogs + - Sid: NoWritesButQueryResults + Effect: Deny + Action: ["s3:PutObject"] + NotResource: !Sub "arn:aws:s3:::${WafLogResults}*" + - !Ref AWS::NoValue + - !If + - NoWafLogQueries + - Sid: NoWrites + Effect: Deny + Action: ["s3:PutObject"] + Resource: "*" + - !Ref AWS::NoValue + - !If + - DecryptsWafLogs + - Sid: DecryptWafLogsThroughS3 + Effect: Allow + Action: + - "kms:Decrypt" + Resource: !Ref WafLogKey + Condition: + StringLike: + kms:ViaService: "s3.*.amazonaws.com" + - !Ref AWS::NoValue + - Sid: NeverChangeWafOrItsLogs + Effect: Deny + Action: ["wafv2:Create*", "wafv2:Update*", "wafv2:Delete*", "wafv2:Put*", "wafv2:Associate*", "wafv2:Disassociate*", "wafv2:Tag*", "wafv2:Untag*", "athena:Create*", "athena:Update*", "athena:Delete*", "athena:Put*", "athena:Import*", "athena:Tag*", "athena:Untag*", "glue:Create*", "glue:Update*", "glue:Delete*", "glue:Put*", "glue:BatchCreate*", "glue:BatchDelete*", "glue:BatchUpdate*", "glue:GetConnection*", "s3:Delete*", "s3:PutBucket*", "s3:PutObjectAcl*", "s3:PutObjectTagging*"] + Resource: "*" + - !Ref AWS::NoValue + # Databases, only those named in DatabaseClusters: queries as the + # read-only database user inside transactions that are rolled back, never + # committed; the only secret readable is that user's password. + - !If + - ReadsDatabases + - PolicyName: DatabasesReadOnly + PolicyDocument: + Version: "2012-10-17" + Statement: + - Sid: QueryChosenDatabases + Effect: Allow + Action: + - "rds-data:BeginTransaction" + - "rds-data:ExecuteStatement" + - "rds-data:RollbackTransaction" + Resource: !Split [",", !Ref DatabaseClusters] + - Sid: ReadOnlyUserPassword + Effect: Allow + Action: + - "secretsmanager:GetSecretValue" + Resource: !Sub "arn:aws:secretsmanager:*:${AWS::AccountId}:secret:coderhelm-readonly-*" + - Sid: NeverCommit + Effect: Deny + Action: ["rds-data:CommitTransaction", "rds-data:BatchExecuteStatement"] + Resource: "*" + - !Ref AWS::NoValue + # Warehouses, only those named in Warehouses: signed in only as the + # passwordless read-only user, single statements, its own results. + - !If + - ReadsWarehouses + - PolicyName: WarehousesReadOnly + PolicyDocument: + Version: "2012-10-17" + Statement: + - Sid: SignInAsTheReadOnlyUser + Effect: Allow + Action: + - "redshift:GetClusterCredentials" + Resource: !Split + - "," + - !Sub + - "arn:aws:redshift:*:*:dbuser:${Ids}/coderhelm_readonly" + - Ids: !Join ["/coderhelm_readonly,arn:aws:redshift:*:*:dbuser:", !Split [",", !Ref Warehouses]] + - Sid: IntoTheirDatabases + Effect: Allow + Action: + - "redshift:GetClusterCredentials" + Resource: !Split + - "," + - !Sub + - "arn:aws:redshift:*:*:dbname:${Ids}/*" + - Ids: !Join ["/*,arn:aws:redshift:*:*:dbname:", !Split [",", !Ref Warehouses]] + - Sid: RunOneStatement + Effect: Allow + Action: + - "redshift-data:ExecuteStatement" + Resource: !Split + - "," + - !Sub + - "arn:aws:redshift:*:*:cluster:${Ids}" + - Ids: !Join [",arn:aws:redshift:*:*:cluster:", !Split [",", !Ref Warehouses]] + - Sid: ReadOwnResults + Effect: Allow + Action: + - "redshift-data:DescribeStatement" + - "redshift-data:GetStatementResult" + - "redshift-data:CancelStatement" + Resource: "*" + Condition: + StringEquals: + redshift-data:statement-owner-iam-userid: "${aws:userid}" + - Sid: NothingElseInTheWarehouse + Effect: Deny + Action: ["redshift-data:BatchExecuteStatement", "redshift:CreateClusterUser", "redshift:GetClusterCredentialsWithIAM", "redshift:ModifyCluster*", "redshift:Delete*"] + Resource: "*" + - !Ref AWS::NoValue + Outputs: RoleArn: Description: > diff --git a/infra/lib/own-account-read.ts b/infra/lib/own-account-read.ts index 82c06367e..555381d83 100644 --- a/infra/lib/own-account-read.ts +++ b/infra/lib/own-account-read.ts @@ -66,6 +66,20 @@ const OWN_CONDITIONS: Record = { SyncsEveryKnowledgeBase: false, // The install's own role only reads: it never applies database maintenance. AppliesMaintenance: false, + // WAF logs, databases and warehouses are read through the connected + // account's role stack (CoderHelmLogReader), in the install's own account + // too: a WAF alarm run reads with the connection's role (log_findings.rs, + // session_for) and a database or warehouse is never read through the + // install's role (live/aws.rs, install_target). So these groups reach a + // team by the same one-click update of that stack, an AWS admin's step, + // and never widen the install's runtime roles or their boundary (no + // Athena, Glue or results write on the gateway and worker). + ReadsWafLogs: false, + QueriesWafLogs: false, + NoWafLogQueries: false, + DecryptsWafLogs: false, + ReadsDatabases: false, + ReadsWarehouses: false, }; /** @@ -134,7 +148,7 @@ export function decideConditions(v: unknown, conditions: Record */ export function updateTemplateStatements(): Statement[] { const scratch = new cdk.Stack(new cdk.App(), "Scratch"); - const inc = new CfnInclude(scratch, "T", { templateFile: repoPath(UPDATE_TEMPLATE), parameters: { RoleName: ROLE_NAME_MARK, KnowledgeBases: OWN_KNOWLEDGE_BASES, ImportBuckets: "", SyncKnowledgeBases: "", InfrastructureVulnerabilities: "on", InspectorFindings: "on", HealthEvents: "on" } }); + const inc = new CfnInclude(scratch, "T", { templateFile: repoPath(UPDATE_TEMPLATE), parameters: { RoleName: ROLE_NAME_MARK, KnowledgeBases: OWN_KNOWLEDGE_BASES, ImportBuckets: "", SyncKnowledgeBases: "", InfrastructureVulnerabilities: "on", InspectorFindings: "on", HealthEvents: "on", WafLogs: "off", WafLogResults: "", WafLogKey: "", DatabaseClusters: "", Warehouses: "" } }); const p = inc.getResource(UPDATE_POLICY_ID) as iam.CfnPolicy; const kept = Object.fromEntries(OWN_OPTIONS.map((o) => [o.condition, o.own])); return decideConditions(scratch.resolve(p.policyDocument).Statement, OWN_CONDITIONS, kept) as Statement[]; diff --git a/infra/test/access.test.ts b/infra/test/access.test.ts index e583dd417..8bb465daf 100644 --- a/infra/test/access.test.ts +++ b/infra/test/access.test.ts @@ -182,7 +182,9 @@ test("boundary: the read role names are the ones CoderHelm's own template and se assert.match(tmpl, /^\s+RoleName: CoderHelmLogReader$/m); const aws = fs.readFileSync(repoPath("services", "common", "src", "live", "aws.rs"), "utf8"); assert.match(aws, /pub const ROLE_PREFIX: &str = "CoderhelmReadOnly";/); - assert.match(aws, /^ROLE=\{ROLE_PREFIX\}$/m, "the setup script creates exactly ROLE_PREFIX"); + // The setup script now creates or updates the role stack's CoderHelmLogReader; roles an + // older script made under ROLE_PREFIX are still taken on until their sources move. + assert.match(aws, /^ROLE=\{LOG_READER_ROLE\}$/m, "the setup script uses exactly LOG_READER_ROLE"); assert.match(aws, /pub const LOG_READER_ROLE: &str = "CoderHelmLogReader";/); assert.deepEqual(OWN_READ_ROLES, ["CoderHelmLogReader", "CoderhelmReadOnly"]); const stacks = hardened(); diff --git a/infra/test/role-groups.test.ts b/infra/test/role-groups.test.ts new file mode 100644 index 000000000..aa589e0f7 --- /dev/null +++ b/infra/test/role-groups.test.ts @@ -0,0 +1,133 @@ +/** + * The role stack's read groups (infra/cfn/coderhelm-log-reader.yaml and its + * update template): the exact statements each parameter adds, as + * CloudFormation resolves them. Reads only; the WAF log group's one write + * is the Athena results location, held there by a deny. + */ +import { strict as assert } from "assert"; +import { test } from "node:test"; +import * as cdk from "aws-cdk-lib"; +import * as iam from "aws-cdk-lib/aws-iam"; +import { CfnInclude } from "aws-cdk-lib/cloudformation-include"; +import { decideConditions } from "../lib/own-account-read"; +import { repoPath } from "../lib/paths"; + +const KEY = "arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"; +const OFF: Record = { + ReadsKnowledgeBases: false, + ReadsEveryKnowledgeBase: false, + ReadsImportBuckets: false, + SyncsKnowledgeBases: false, + SyncsEveryKnowledgeBase: false, + ReadsInfrastructure: false, + ReadsInspector: false, + ReadsHealth: false, + AppliesMaintenance: false, + ReadsWafLogs: false, + QueriesWafLogs: false, + NoWafLogQueries: false, + DecryptsWafLogs: false, + ReadsDatabases: false, + ReadsWarehouses: false, +}; + +/** The update stack's statements for these parameters and conditions, by Sid. */ +function statements(parameters: Record, on: Record): Record { + const stack = new cdk.Stack(new cdk.App(), "T"); + const inc = new CfnInclude(stack, "I", { + templateFile: repoPath("infra/cfn/coderhelm-log-reader-update.yaml"), + parameters: { RoleName: "CoderHelmLogReader", ...parameters }, + }); + const p = inc.getResource("CoderHelmReadOnlyUpdate") as iam.CfnPolicy; + const list = decideConditions(stack.resolve(p.policyDocument).Statement, { ...OFF, ...on }) as any[]; + return Object.fromEntries(list.map((s) => [s.Sid, s])); +} + +const ACCOUNT = { Ref: "AWS::AccountId" }; +const sub = (s: string) => ({ "Fn::Sub": s }); + +test("the WAF log group with a results location and a key: exact statements", () => { + const all = statements( + { WafLogs: "on", WafLogResults: "aws-waf-logs-acme/athena-results/", WafLogKey: KEY }, + { ReadsWafLogs: true, QueriesWafLogs: true, DecryptsWafLogs: true }, + ); + const waf = Object.fromEntries(Object.entries(all).filter(([k]) => /Waf|Query|NoWrites|NeverChange/.test(k))); + assert.deepEqual(Object.keys(waf).sort(), [ + "DecryptWafLogsThroughS3", + "FindQueryResults", + "FindWafLogTables", + "FindWafLogWorkgroups", + "ListWafLogBuckets", + "NeverChangeWafOrItsLogs", + "NoWritesButQueryResults", + "QueryWafLogs", + "ReadWafLogObjects", + "WriteQueryResultsOnly", + ]); + assert.deepEqual(waf.ReadWafLogObjects, { Sid: "ReadWafLogObjects", Effect: "Allow", Action: ["s3:GetObject"], Resource: "arn:aws:s3:::aws-waf-logs-*/*" }); + assert.deepEqual(waf.ListWafLogBuckets, { Sid: "ListWafLogBuckets", Effect: "Allow", Action: ["s3:ListBucket", "s3:GetBucketLocation"], Resource: "arn:aws:s3:::aws-waf-logs-*" }); + assert.deepEqual(waf.FindWafLogTables.Action, ["glue:GetDatabases", "glue:GetDatabase", "glue:GetTables", "glue:GetTable", "glue:GetPartitions"]); + assert.deepEqual(waf.FindWafLogTables.Resource, [ + sub("arn:aws:glue:*:${AWS::AccountId}:catalog"), + sub("arn:aws:glue:*:${AWS::AccountId}:database/*"), + sub("arn:aws:glue:*:${AWS::AccountId}:table/*/*"), + ]); + assert.deepEqual(waf.FindWafLogWorkgroups, { Sid: "FindWafLogWorkgroups", Effect: "Allow", Action: ["athena:ListWorkGroups", "athena:GetWorkGroup"], Resource: "*" }); + assert.deepEqual(waf.QueryWafLogs.Action, ["athena:StartQueryExecution", "athena:GetQueryExecution", "athena:GetQueryResults", "athena:StopQueryExecution"]); + // The one write: the results location only, and denied everywhere else. + const results = sub("arn:aws:s3:::aws-waf-logs-acme/athena-results/*"); + assert.deepEqual(waf.WriteQueryResultsOnly, { Sid: "WriteQueryResultsOnly", Effect: "Allow", Action: ["s3:PutObject", "s3:GetObject"], Resource: results }); + assert.deepEqual(waf.NoWritesButQueryResults, { Sid: "NoWritesButQueryResults", Effect: "Deny", Action: ["s3:PutObject"], NotResource: results }); + assert.equal(JSON.stringify(waf.FindQueryResults.Resource).includes("aws-waf-logs-acme"), true); + // KMS: that key, through S3 only. + assert.deepEqual(waf.DecryptWafLogsThroughS3, { + Sid: "DecryptWafLogsThroughS3", + Effect: "Allow", + Action: ["kms:Decrypt"], + Resource: KEY, + Condition: { StringLike: { "kms:ViaService": "s3.*.amazonaws.com" } }, + }); + assert.equal(waf.NeverChangeWafOrItsLogs.Effect, "Deny"); + for (const a of ["wafv2:Update*", "athena:Delete*", "glue:Update*", "glue:GetConnection*", "s3:Delete*", "s3:PutBucket*"]) { + assert.ok(waf.NeverChangeWafOrItsLogs.Action.includes(a), a); + } + // Every allow in every group is a read, but the results write. + const reads = /^(Get|List|Describe|BatchGet|Retrieve|Search|Filter|Simulate|Lookup)|^(StartQuery|StopQuery|StartQueryExecution|StopQueryExecution|GetQueryExecution|InvokeRestApi|BeginTransaction|ExecuteStatement|RollbackTransaction|CancelStatement|GetClusterCredentials)$/; + const groups = statements( + { WafLogs: "on", WafLogResults: "aws-waf-logs-acme/athena-results/", WafLogKey: KEY, DatabaseClusters: "arn:aws:rds:us-east-1:111122223333:cluster:app-db", Warehouses: "analytics" }, + { ReadsWafLogs: true, QueriesWafLogs: true, DecryptsWafLogs: true, ReadsDatabases: true, ReadsWarehouses: true }, + ); + for (const s of Object.values(groups)) { + if (s.Effect !== "Allow") continue; + for (const a of [].concat(s.Action) as string[]) { + const verb = a.split(":")[1]; + if (a === "s3:PutObject") assert.equal(s.Sid, "WriteQueryResultsOnly"); + else if (a === "kms:Decrypt") assert.ok(s.Condition?.StringLike?.["kms:ViaService"], s.Sid); + else assert.ok(reads.test(verb), `${a} in ${s.Sid}`); + } + } +}); + +test("without a results location the WAF log group writes nothing; off, it adds nothing", () => { + const bare = statements({ WafLogs: "on" }, { ReadsWafLogs: true, NoWafLogQueries: true }); + assert.ok(bare.ReadWafLogObjects && bare.FindWafLogTables && bare.FindWafLogWorkgroups); + for (const no of ["QueryWafLogs", "WriteQueryResultsOnly", "FindQueryResults", "NoWritesButQueryResults", "DecryptWafLogsThroughS3"]) assert.equal(bare[no], undefined, no); + assert.deepEqual(bare.NoWrites, { Sid: "NoWrites", Effect: "Deny", Action: ["s3:PutObject"], Resource: "*" }); + const off = statements({}, {}); + for (const k of Object.keys(off)) assert.ok(!/Waf|Query|NoWrites|NeverChange|Database|Warehouse|Commit|OwnResults|ReadOnlyUser/.test(k), k); +}); + +test("databases and warehouses: only those named, never a commit", () => { + const s = statements( + { DatabaseClusters: "arn:aws:rds:us-east-1:111122223333:cluster:app-db,arn:aws:rds:us-east-1:111122223333:cluster:b", Warehouses: "analytics,marts" }, + { ReadsDatabases: true, ReadsWarehouses: true }, + ); + assert.deepEqual(s.QueryChosenDatabases.Resource, ["arn:aws:rds:us-east-1:111122223333:cluster:app-db", "arn:aws:rds:us-east-1:111122223333:cluster:b"]); + assert.deepEqual(s.ReadOnlyUserPassword.Resource, sub("arn:aws:secretsmanager:*:${AWS::AccountId}:secret:coderhelm-readonly-*")); + assert.deepEqual(s.NeverCommit, { Sid: "NeverCommit", Effect: "Deny", Action: ["rds-data:CommitTransaction", "rds-data:BatchExecuteStatement"], Resource: "*" }); + const users = JSON.stringify(s.SignInAsTheReadOnlyUser.Resource); + assert.ok(users.includes("dbuser:${Ids}/coderhelm_readonly") && users.includes("[\"analytics\",\"marts\"]"), users); + assert.deepEqual(s.ReadOwnResults.Condition, { StringEquals: { "redshift-data:statement-owner-iam-userid": "${aws:userid}" } }); + assert.equal(s.NothingElseInTheWarehouse.Effect, "Deny"); + void ACCOUNT; +}); diff --git a/infra/test/synth.test.ts b/infra/test/synth.test.ts index da53ab6c9..9c2c75148 100644 --- a/infra/test/synth.test.ts +++ b/infra/test/synth.test.ts @@ -199,7 +199,10 @@ test("self-host: the gateway and worker read the install's own account with this // vulnerabilities (on by default): their statements are there, each behind its condition. // Applying approved database maintenance is a write a team grants its own // CoderHelmLogReader role; the install's own role only reads. - const abilities = ["imports", "sync", "maintenance"].reduce(without, all); + // WAF logs, databases and warehouses are read through the connected account's + // CoderHelmLogReader role in every account, the install's own too (own-account-read.ts, + // OWN_CONDITIONS): the install's own role gains no Athena, Glue, bucket or database reads. + const abilities = ["imports", "sync", "maintenance", "waf_logs", "databases", "warehouses"].reduce(without, all); const needed = [...new Set([...abilities.matchAll(/"([a-z0-9-]+:[A-Za-z]+)"/g)].map((m) => m[1]))]; assert.ok(needed.length > 20, `${needed.length} actions`); for (const [stack, fn] of [ diff --git a/services/common/src/alarm_evidence.rs b/services/common/src/alarm_evidence.rs index 2cdacac71..ebd2d5e9e 100644 --- a/services/common/src/alarm_evidence.rs +++ b/services/common/src/alarm_evidence.rs @@ -14,7 +14,8 @@ //! query on its log group, or, when it logs to an `aws-waf-logs-*` bucket, //! one bounded Athena query over the Glue table on that bucket ([`athena_query`]: //! the last three hours, the alarm's rule only), in a WAF log workgroup -//! the role may query (`live::aws::waf_policy_template`). Request values +//! the role may query (the role template's WAF log group, +//! `infra/cfn/coderhelm-log-reader.yaml`, `WafLogs`). Request values //! that can carry secrets or people's data (client addresses, cookies, //! authorization and every other header value but the user agent and //! accept language, query strings) are never kept; from the logs in S3, @@ -542,6 +543,14 @@ fn waf_client(s: &Session) -> aws_sdk_wafv2::Client { pub struct Gathered { pub text: String, pub refused: Vec, + /// What the run found for the role stack's WAF log group, so its update + /// link names them: the Athena workgroup's results location + /// (`bucket/prefix/`, the stack's WafLogResults) and the log bucket's + /// customer-managed KMS key (WafLogKey). Empty when not found. + pub waf_log_results: String, + pub waf_log_key: String, + /// The web ACL logs to an S3 bucket (so the WAF log group is needed). + pub logs_to_s3: bool, } /// The evidence lines and the refusals met while reading them. @@ -549,6 +558,9 @@ pub struct Gathered { struct Notes { lines: Vec, refused: Vec, + results: String, + key: String, + logs_to_s3: bool, } impl Notes { @@ -571,7 +583,12 @@ impl Notes { } fn done(self, alarm: &WafAlarm) -> Gathered { - evidence(alarm, self.lines, self.refused) + Gathered { + waf_log_results: self.results, + waf_log_key: self.key, + logs_to_s3: self.logs_to_s3, + ..evidence(alarm, self.lines, self.refused) + } } } @@ -584,9 +601,30 @@ pub fn evidence(alarm: &WafAlarm, mut lines: Vec, refused: Vec) Gathered { text: render(alarm, &lines), refused, + ..Default::default() } } +/// Pure: the customer-managed KMS key a bucket's default encryption names, +/// as an ARN (a bare key id is in the bucket's `region` and `account`). +/// `None` for SSE-S3, an AWS managed key or an alias: S3 decrypts those +/// for anyone who may read the object. +pub fn bucket_key_arn( + rules: &[crate::live::aws_settings::EncryptionRule], + region: &str, + account: &str, +) -> Option { + let id = rules + .iter() + .filter(|r| r.algorithm.starts_with("aws:kms")) + .find_map(|r| r.kms_key.clone())?; + if crate::log_reader::is_kms_key(&id) { + return Some(id); + } + let arn = format!("arn:aws:kms:{region}:{account}:key/{id}"); + crate::log_reader::is_kms_key(&arn).then_some(arn) +} + /// Read the evidence for a WAF alarm. Every lookup that fails says why in /// the result, so a missing permission is named, not silent. pub async fn gather(session: &Session, alarm: &WafAlarm, now: DateTime) -> Gathered { @@ -742,6 +780,15 @@ pub async fn gather(session: &Session, alarm: &WafAlarm, now: DateTime) -> .extend(fingerprints(session, ®ion, &name, &query, start, end).await); } (None, Some(bucket), _) => { + n.logs_to_s3 = true; + // The bucket's own KMS key, for the role stack's WafLogKey + // (its settings, read with the role's settings reads). + let b = crate::live::aws_settings::read_bucket(session, &bucket).await; + if let crate::live::aws_settings::Read::Got(rules) = &b.encryption { + let account = arn.split(':').nth(4).unwrap_or_default(); + let at = b.region.clone().unwrap_or_else(|| session.region.clone()); + n.key = bucket_key_arn(rules, &at, account).unwrap_or_default(); + } let mut regions = vec![session.region.clone()]; if region != session.region { regions.push(region.clone()); @@ -880,9 +927,9 @@ async fn find_log_table( None } -/// A workgroup the role may query: one of the account's, WAF log ones -/// first (`live::aws::waf_policy_template` allows only those), enabled, -/// with a results location; and whether it caps the bytes a query scans. +/// A workgroup to query: one of the account's, WAF log ones first, +/// enabled, with a results location (kept in `n` for the role stack's +/// WafLogResults); and whether it caps the bytes a query scans. async fn find_workgroup(athena: &aws_sdk_athena::Client, n: &mut Notes) -> Option<(String, bool)> { use aws_sdk_athena::error::ProvideErrorMetadata; use aws_sdk_athena::types::WorkGroupState; @@ -929,13 +976,14 @@ async fn find_workgroup(athena: &aws_sdk_athena::Client, n: &mut Notes) -> Optio continue; } let cfg = wg.configuration(); - let has_results = cfg + let location = cfg .and_then(|c| c.result_configuration()) .and_then(|r| r.output_location()) - .is_some_and(|l| l.starts_with("s3://")); - if !has_results { + .filter(|l| l.starts_with("s3://")); + let Some(location) = location else { continue; - } + }; + n.results = crate::log_reader::waf_log_results(location).unwrap_or_default(); let capped = cfg .and_then(|c| c.bytes_scanned_cutoff_per_query()) .is_some_and(|b| b > 0); diff --git a/services/common/src/aws_role_reads.rs b/services/common/src/aws_role_reads.rs index bd70dd981..a6e420ac2 100644 --- a/services/common/src/aws_role_reads.rs +++ b/services/common/src/aws_role_reads.rs @@ -9,10 +9,20 @@ //! the install's, like a GitHub App permission //! (`github_grants::install_item`): it is recorded here once per connected //! account when a read is refused ([`record`]), the install's setup checks -//! show it as one item with the one-line CloudShell update -//! (`live::aws::waf_update_line`), and the first read that works again -//! clears it ([`clear`]). A run names the item in one line ([`run_line`]) -//! and goes on with what it could read. +//! show it as one item, and the first read that works again clears it +//! ([`clear`]). A run names the item in one line ([`run_line`]) and goes +//! on with what it could read. +//! +//! Every read is declared in one versioned template, the role stack's +//! (`infra/cfn/coderhelm-log-reader.yaml`, published with each release), +//! as named groups a stack parameter switches on. A release can't widen +//! the role by itself (CoderHelm's own roles may not change IAM), so the +//! item is the one-click update of that stack ([`role_update`]): the +//! release's template with the account's groups and what CoderHelm found +//! filled in (the WAF log workgroup's results location, the log bucket's +//! KMS key), which an AWS admin of the account reviews and creates. The +//! same item names an account whose role is older than the release and one +//! whose data sources still read through the script-made role. //! //! [`is_install_grant`] is how the stop judge and the hand-back list know a //! question or a blocker is this item, so neither can turn it into a wait @@ -43,6 +53,149 @@ pub struct Gap { /// What needed them, in a few words (`an AWS WAF alarm's evidence`). pub needed_for: String, pub seen_at: String, + /// What the run found for the role stack's WAF log group: the Athena + /// workgroup's results location (`bucket/prefix/`) and the log + /// bucket's customer-managed KMS key. Empty when not found. + pub waf_log_results: String, + pub waf_log_key: String, +} + +impl Gap { + /// The template groups the refused reads belong to, once each: the WAF + /// log group for its actions, otherwise the ability that has the action. + pub fn groups(&self) -> Vec<&'static str> { + let mut out: Vec<&'static str> = Vec::new(); + for a in &self.actions { + if let Some(k) = group_of(a) { + if !out.contains(&k) { + out.push(k); + } + } + } + out + } +} + +/// Pure: the template group an action a WAF alarm run was refused belongs +/// to: the WAF log group when it has the action (Athena, Glue, the log +/// buckets), else the first ability that has it. +pub fn group_of(action: &str) -> Option<&'static str> { + let logs = crate::log_reader::ability("waf_logs")?; + if logs.actions.contains(&action) { + return Some(logs.key); + } + crate::log_reader::ability_of(action).map(|a| a.key) +} + +/// Why an account's role stack needs updating, in a few words each. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RoleUpdate { + pub account: String, + pub reasons: Vec, + /// The groups the update adds, by name (what it reads, in plain words). + pub adds: Vec<&'static str>, + /// The one-click update: CloudFormation's quick-create of this + /// release's update stack on the role, its parameters filled in. + pub url: String, + pub stack_name: String, +} + +/// Pure: the update an account's role stack needs, or `None` when it needs +/// none. `account` is the connected account with what the team chose there +/// filled in (knowledge bases, buckets, data sources); `gap` the reads a +/// run was refused there; `legacy_sources` how many data sources still read +/// through the script-made `CoderhelmReadOnly` role in that account; +/// `update_template_url` this release's update template. +pub fn role_update( + account: &crate::live::aws_account::AwsAccount, + gap: Option<&Gap>, + legacy_sources: usize, + update_template_url: &str, +) -> Option { + use crate::log_reader; + let mut reasons: Vec = Vec::new(); + let mut adds: Vec<&'static str> = Vec::new(); + let groups = gap.map(|g| g.groups()).unwrap_or_default(); + let waf_logs = account.waf_logs || groups.contains(&"waf_logs"); + let (results, key) = match gap { + Some(g) => crate::live::aws_account::waf_logs_after( + &account.waf_log_results, + &account.waf_log_key, + &g.waf_log_results, + &g.waf_log_key, + ), + None => (account.waf_log_results.clone(), account.waf_log_key.clone()), + }; + if let Some(g) = gap.filter(|g| !g.actions.is_empty()) { + reasons.push(format!( + "{} was refused {} ({})", + role_name(&g.role_arn), + g.actions.join(", "), + g.needed_for + )); + for k in &groups { + if let Some(a) = log_reader::ability(k) { + if !adds.contains(&a.name) { + adds.push(a.name); + } + } + } + } + let check = account.permissions.as_ref().filter(|c| !c.install_account); + if let Some(c) = check.filter(|c| c.status() == "update_needed") { + reasons.push(format!( + "its role is older than this release ({} read{} missing)", + c.missing.len(), + if c.missing.len() == 1 { "" } else { "s" } + )); + for k in c.missing_abilities() { + if let Some(a) = log_reader::ability(k) { + if !adds.contains(&a.name) { + adds.push(a.name); + } + } + } + } + if legacy_sources > 0 { + reasons.push(format!( + "{legacy_sources} data source{} still read through the script-made CoderhelmReadOnly role", + if legacy_sources == 1 { "" } else { "s" } + )); + for k in ["databases", "warehouses"] { + let named = match k { + "databases" => !account.database_clusters.is_empty(), + _ => !account.warehouses.is_empty(), + }; + if let Some(a) = log_reader::ability(k).filter(|_| named) { + if !adds.contains(&a.name) { + adds.push(a.name); + } + } + } + } + if reasons.is_empty() { + return None; + } + let mut chosen = account.chosen(); + if waf_logs { + chosen = chosen.with_waf_logs(&results, &key); + } + Some(RoleUpdate { + account: account.account.clone(), + reasons, + adds, + url: log_reader::update_url(update_template_url, &account.region, &chosen), + stack_name: log_reader::update_stack_name_for(&chosen), + }) +} + +fn role_name(arn: &str) -> String { + let n = arn.rsplit('/').next().unwrap_or_default(); + if n.is_empty() { + "CoderHelm's AWS role".to_string() + } else { + format!("The role {n}") + } } /// Pure: the one line a run says about the missing reads: what was @@ -51,8 +204,9 @@ pub struct Gap { pub fn run_line(actions: &[String]) -> String { format!( "CoderHelm's AWS role was refused {}: that is the install's setup item \"{ITEM_LABEL}\" \ - (one line in AWS CloudShell), asked once for the whole install {INSTALL_LEVEL}. This run \ - asks nobody for it and goes on with what it could read.", + (a one-click update of CoderHelm's role stack that an AWS admin of the account approves), \ + asked once for the whole install {INSTALL_LEVEL}. This run asks nobody for it and goes on \ + with what it could read.", if actions.is_empty() { "a read".to_string() } else { @@ -76,6 +230,7 @@ pub fn gap( actions: refused.to_vec(), needed_for: needed_for.to_string(), seen_at: now.to_string(), + ..Default::default() }) } @@ -186,12 +341,18 @@ pub async fn record(dynamo: &DynamoClient, table: &str, team_id: &str, gap: &Gap if !is_account(&gap.account) || gap.actions.is_empty() { return; } - let mut actions: Vec = list(dynamo, table, team_id) + let before = list(dynamo, table, team_id) .await .into_iter() .find(|g| g.account == gap.account) - .map(|g| g.actions) .unwrap_or_default(); + let (results, key) = crate::live::aws_account::waf_logs_after( + &before.waf_log_results, + &before.waf_log_key, + &gap.waf_log_results, + &gap.waf_log_key, + ); + let mut actions = before.actions; for a in &gap.actions { if !actions.contains(a) { actions.push(a.clone()); @@ -211,6 +372,8 @@ pub async fn record(dynamo: &DynamoClient, table: &str, team_id: &str, gap: &Gap ) .item("needed_for", attr(&gap.needed_for)) .item("seen_at", attr(&gap.seen_at)) + .item("waf_log_results", attr(&results)) + .item("waf_log_key", attr(&key)) .send() .await; if let Err(e) = res { @@ -263,6 +426,8 @@ pub async fn list(dynamo: &DynamoClient, table: &str, team_id: &str) -> Vec .unwrap_or_default(), needed_for: s(i, "needed_for"), seen_at: s(i, "seen_at"), + waf_log_results: s(i, "waf_log_results"), + waf_log_key: s(i, "waf_log_key"), }) .filter(|g| is_account(&g.account)) .collect() @@ -295,6 +460,88 @@ mod tests { } } + fn account(region: &str) -> crate::live::aws_account::AwsAccount { + crate::live::aws_account::AwsAccount { + account: "111122223333".into(), + role_arn: "arn:aws:iam::111122223333:role/CoderHelmLogReader".into(), + region: region.into(), + ..Default::default() + } + } + + const TEMPLATE: &str = + "https://b.s3.amazonaws.com/launch/v1.2.3/coderhelm-log-reader-update.yaml"; + + #[test] + fn a_refused_waf_log_read_is_the_role_stacks_one_click_update() { + let gap = Gap { + account: "111122223333".into(), + role_arn: "arn:aws:iam::111122223333:role/CoderHelmLogReader".into(), + actions: vec!["glue:GetDatabases".into()], + needed_for: "an AWS WAF alarm's evidence".into(), + seen_at: "t".into(), + waf_log_results: String::new(), + waf_log_key: + "arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab".into(), + }; + assert_eq!(gap.groups(), vec!["waf_logs"]); + let u = role_update(&account("us-east-1"), Some(&gap), 0, TEMPLATE).expect("an update"); + assert!(u.url.starts_with("https://console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/quickcreate?")); + assert!(u.url.contains("¶m_WafLogs=on"), "{}", u.url); + assert!(u.url.contains("¶m_WafLogKey="), "{}", u.url); + assert!(!u.url.contains("WafLogResults"), "not found yet: {}", u.url); + assert!(u.url.contains(&format!("stackName={}", u.stack_name))); + assert_eq!(u.adds, vec!["AWS WAF logs in S3"]); + assert!(u.reasons[0].contains("CoderHelmLogReader was refused glue:GetDatabases")); + // The next run found the workgroup and was refused the query: the + // link now carries the results location too. + let later = Gap { + actions: vec!["athena:StartQueryExecution".into()], + waf_log_results: "aws-waf-logs-acme/athena-results/".into(), + ..gap.clone() + }; + let mut a = account("us-east-1"); + a.waf_logs = true; + a.waf_log_key = gap.waf_log_key.clone(); + let u2 = role_update(&a, Some(&later), 0, TEMPLATE).unwrap(); + assert!( + u2.url + .contains("¶m_WafLogResults=aws-waf-logs-acme%2Fathena-results%2F"), + "{}", + u2.url + ); + assert_ne!(u2.stack_name, u.stack_name); + // Base WAF reads belong to the release's always-on group. + assert_eq!(group_of("wafv2:GetSampledRequests"), Some("waf")); + // Nothing to do: no item. + assert!(role_update(&account("us-east-1"), None, 0, TEMPLATE).is_none()); + } + + #[test] + fn an_older_role_and_script_made_sources_are_the_same_item() { + let mut a = account("eu-west-1"); + let mut c = crate::live::permissions::PermissionCheck::new(&a.target(), "t"); + c.works = true; + c.missing = vec!["ecs:ListTasks".into()]; + a.permissions = Some(c); + a.database_clusters = vec!["arn:aws:rds:eu-west-1:111122223333:cluster:app-db".into()]; + // A stored WAF log group stays on in every later link. + a.waf_logs = true; + a.waf_log_results = "aws-waf-logs-acme/athena-results/".into(); + let u = role_update(&a, None, 1, TEMPLATE).unwrap(); + assert!(u + .reasons + .iter() + .any(|r| r.contains("older than this release"))); + assert!(u.reasons.iter().any(|r| r.contains("CoderhelmReadOnly"))); + assert!(u.adds.contains(&"ECS services and tasks") && u.adds.contains(&"Databases")); + assert!(u.url.contains("param_DatabaseClusters=") && u.url.contains("param_WafLogs=on")); + // The install's own account gets its reads with version updates. + let mut own = a.clone(); + own.permissions.as_mut().unwrap().install_account = true; + assert!(role_update(&own, None, 0, TEMPLATE).is_none()); + } + #[test] fn the_run_line_names_the_item_once_for_the_install() { let l = run_line(&[ diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index d25943501..07ba8f206 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -78,6 +78,7 @@ pub mod coder_shell; /// Chat notifications (Teams and Slack): one message model, a renderer per /// channel, sealed webhook URLs. pub mod notify; +pub mod role_move; pub mod tool_aliases; /// The team's daily alert token budget (alerts route and Setup). diff --git a/services/common/src/live/aws.rs b/services/common/src/live/aws.rs index ba7d16ebc..3585f0503 100644 --- a/services/common/src/live/aws.rs +++ b/services/common/src/live/aws.rs @@ -2,16 +2,21 @@ //! //! The team creates a role in its own account that Coderhelm may use, with a //! private ID only that team is given (so nobody else using Coderhelm can point -//! it at their role), and with permissions that only read. The setup is one -//! script the team pastes into AWS CloudShell ([`setup_script`]); it prints a -//! line they paste back into Coderhelm ([`parse_setup_code`]). +//! it at their role), and with permissions that only read. The role and all +//! its permissions come from one CloudFormation template +//! (`infra/cfn/coderhelm-log-reader.yaml`, `CoderHelmLogReader`); a database +//! or a warehouse also needs a read-only user inside it, which the script a +//! team pastes into AWS CloudShell makes ([`setup_script`]) before it creates +//! or updates that stack. It prints a line they paste back into Coderhelm +//! ([`parse_setup_code`]). Roles the older script made (`CoderhelmReadOnly`) +//! are still accepted, and move to the stack's role +//! (`crate::role_move`). //! //! Every use takes a fresh, 15-minute session on that role, named after the //! agent using it, so the team's own AWS records show who looked at what. use base64::{engine::general_purpose::STANDARD, Engine}; use serde::{Deserialize, Serialize}; -use serde_json::json; use super::StepError; @@ -289,359 +294,37 @@ pub fn new_external_id() -> String { format!("coderhelm-{}{}", ulid::Ulid::new(), ulid::Ulid::new()).to_lowercase() } -pub fn trust_policy(our_account: &str, external_id: &str) -> serde_json::Value { - json!({ - "Version": "2012-10-17", - "Statement": [{ - "Effect": "Allow", - "Principal": { "AWS": format!("arn:aws:iam::{our_account}:root") }, - "Action": "sts:AssumeRole", - "Condition": { "StringEquals": { "sts:ExternalId": external_id } } - }] - }) -} - -/// Reads logs. Masked values stay masked: unmasking is explicitly denied. -pub fn logs_policy() -> serde_json::Value { - json!({ - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "ReadLogs", - "Effect": "Allow", - "Action": [ - "logs:DescribeLogGroups", - "logs:GetLogGroupFields", - "logs:StartQuery", - "logs:GetQueryResults", - "logs:StopQuery" - ], - "Resource": "*" - }, - { - "Sid": "DescribeTasksBehindLogErrors", - "Effect": "Allow", - "Action": [ - "ecs:ListClusters", - "ecs:ListServices", - "ecs:DescribeServices", - "ecs:DescribeTaskDefinition", - "ecs:ListTasks", - "ecs:DescribeTasks" - ], - "Resource": "*" - }, - { "Sid": "NeverUnmask", "Effect": "Deny", "Action": "logs:Unmask", "Resource": "*" } - ] - }) -} - -/// Queries one database, inside transactions that can be started and rolled -/// back but never committed, as the read-only user whose password is the only -/// secret readable. -pub fn database_policy_template(account: &str) -> serde_json::Value { - json!({ - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "QueryOneDatabase", - "Effect": "Allow", - "Action": ["rds-data:BeginTransaction", "rds-data:ExecuteStatement", "rds-data:RollbackTransaction"], - "Resource": "CLUSTER_ARN" - }, - { - "Sid": "ReadOnlyUserPassword", - "Effect": "Allow", - "Action": "secretsmanager:GetSecretValue", - "Resource": format!("arn:aws:secretsmanager:*:{account}:secret:{SECRET_PREFIX}*") - }, - { "Sid": "NeverCommit", "Effect": "Deny", "Action": ["rds-data:CommitTransaction", "rds-data:BatchExecuteStatement"], "Resource": "*" } - ] - }) -} - -/// Reads one Redshift warehouse: may sign in only as the read-only user, with -/// no password, and only run single statements and read their own results. -pub fn warehouse_policy_template(account: &str) -> serde_json::Value { - json!({ - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "SignInAsTheReadOnlyUser", - "Effect": "Allow", - "Action": "redshift:GetClusterCredentials", - "Resource": [ - format!("arn:aws:redshift:*:{account}:dbuser:RS_CLUSTER/{DB_USER}"), - format!("arn:aws:redshift:*:{account}:dbname:RS_CLUSTER/*") - ] - }, - { - "Sid": "RunOneStatement", - "Effect": "Allow", - "Action": "redshift-data:ExecuteStatement", - "Resource": format!("arn:aws:redshift:*:{account}:cluster:RS_CLUSTER") - }, - { - "Sid": "ReadOwnResults", - "Effect": "Allow", - "Action": ["redshift-data:DescribeStatement", "redshift-data:GetStatementResult", "redshift-data:CancelStatement"], - "Resource": "*", - "Condition": { "StringEquals": { "redshift-data:statement-owner-iam-userid": "${aws:userid}" } } - }, - { - "Sid": "NothingElse", - "Effect": "Deny", - "Action": ["redshift-data:BatchExecuteStatement", "redshift:CreateClusterUser", "redshift:GetClusterCredentialsWithIAM", "redshift:ModifyCluster*", "redshift:Delete*"], - "Resource": "*" - } - ] - }) -} - -/// The role's inline policy for AWS WAF and its logs. -pub const WAF_POLICY_NAME: &str = "coderhelm-read-waf"; - -/// Placeholders the setup script fills with what it finds in the account: -/// the Athena workgroups for WAF logs (`WAF_WORKGROUPS`, their ARNs), the -/// Glue databases and tables over `aws-waf-logs-*` buckets (`WAF_GLUE`), -/// and where each of those workgroups writes its query results -/// (`WAF_RESULT_OBJECTS`, `WAF_RESULT_BUCKETS`, `WAF_RESULT_PREFIXES`). -/// Each sits alone in a JSON array, as a string, so a list of quoted ARNs -/// replaces it. -pub const WAF_PLACEHOLDERS: &[&str] = &[ - "WAF_WORKGROUPS", - "WAF_GLUE", - "WAF_RESULT_OBJECTS", - "WAF_RESULT_BUCKETS", - "WAF_RESULT_PREFIXES", -]; - -/// What the WAF policy never allows, whatever else on the role does: every -/// change to WAF, Athena, Glue or a bucket, and Glue's connections (they -/// carry passwords). -const WAF_NEVER: &[&str] = &[ - "wafv2:Create*", - "wafv2:Update*", - "wafv2:Delete*", - "wafv2:Put*", - "wafv2:Associate*", - "wafv2:Disassociate*", - "wafv2:Tag*", - "wafv2:Untag*", - "athena:Create*", - "athena:Update*", - "athena:Delete*", - "athena:Put*", - "athena:Import*", - "athena:Tag*", - "athena:Untag*", - "glue:Create*", - "glue:Update*", - "glue:Delete*", - "glue:Put*", - "glue:Batch*", - "glue:GetConnection", - "glue:GetConnections", - "s3:Delete*", - "s3:PutBucket*", - "s3:PutObjectAcl", - "s3:PutObjectTagging", -]; - -/// Reads AWS WAF (web ACLs, sampled requests, where a web ACL logs) and, -/// with `athena`, the web ACL's logs held in S3 through their Athena table: -/// read-only queries in the WAF log workgroups the script found, over the -/// Glue tables on `aws-waf-logs-*` buckets, with results written only -/// under those workgroups' own results prefix. Everything that changes -/// WAF, Athena, Glue or a bucket is denied, and so is any object written -/// anywhere but the results prefix. Without `athena` (no WAF log -/// workgroup or table in the account) it reads WAF and the log buckets' -/// objects only, and writes nothing. -pub fn waf_policy_template(account: &str, athena: bool) -> serde_json::Value { - let mut statements = vec![ - json!({ - "Sid": "ReadWaf", - "Effect": "Allow", - "Action": ["wafv2:Get*", "wafv2:List*"], - "Resource": "*" - }), - json!({ - "Sid": "ReadWafLogObjects", - "Effect": "Allow", - "Action": ["s3:GetObject"], - "Resource": "arn:aws:s3:::aws-waf-logs-*/*" - }), - json!({ - "Sid": "ListWafLogBuckets", - "Effect": "Allow", - "Action": ["s3:ListBucket", "s3:GetBucketLocation"], - "Resource": "arn:aws:s3:::aws-waf-logs-*" - }), - ]; - if athena { - statements.extend([ - json!({ - "Sid": "FindWafLogWorkgroups", - "Effect": "Allow", - "Action": ["athena:ListWorkGroups"], - "Resource": "*" - }), - json!({ - "Sid": "FindWafLogDatabases", - "Effect": "Allow", - "Action": ["glue:GetDatabases"], - "Resource": [ - format!("arn:aws:glue:*:{account}:catalog"), - format!("arn:aws:glue:*:{account}:database/*") - ] - }), - json!({ - "Sid": "ReadWafLogTables", - "Effect": "Allow", - "Action": ["glue:Get*"], - "Resource": [format!("arn:aws:glue:*:{account}:catalog"), "WAF_GLUE".to_string()] - }), - json!({ - "Sid": "QueryWafLogs", - "Effect": "Allow", - "Action": ["athena:StartQueryExecution", "athena:Get*", "athena:StopQueryExecution"], - "Resource": ["WAF_WORKGROUPS"] - }), - json!({ - "Sid": "WriteQueryResultsOnly", - "Effect": "Allow", - "Action": ["s3:PutObject", "s3:GetObject"], - "Resource": ["WAF_RESULT_OBJECTS"] - }), - json!({ - "Sid": "FindQueryResults", - "Effect": "Allow", - "Action": ["s3:GetBucketLocation", "s3:ListBucket"], - "Resource": ["WAF_RESULT_BUCKETS"], - "Condition": { "StringLike": { "s3:prefix": ["WAF_RESULT_PREFIXES"] } } - }), - json!({ - "Sid": "NoWritesButQueryResults", - "Effect": "Deny", - "Action": "s3:PutObject", - "NotResource": ["WAF_RESULT_OBJECTS"] - }), - ]); - } else { - statements.push(json!({ - "Sid": "NoWrites", - "Effect": "Deny", - "Action": "s3:PutObject", - "Resource": "*" - })); - } - statements.push(json!({ - "Sid": "NeverChange", - "Effect": "Deny", - "Action": WAF_NEVER, - "Resource": "*" - })); - json!({ "Version": "2012-10-17", "Statement": statements }) -} - -/// The part of the setup script that finds the account's WAF log -/// workgroups and tables and puts [`WAF_POLICY_NAME`] on `$ROLE`. Needs -/// `ROLE`, `REGION` and `ACCOUNT`; asks nothing, and changes nothing but -/// that one policy, so running it again is safe. -fn waf_policy_step() -> String { - let athena = waf_policy_template("ACCOUNT_ID", true).to_string(); - let plain = waf_policy_template("ACCOUNT_ID", false).to_string(); - format!( - r##"WAF_WG=""; WAF_OBJ=""; WAF_BKT=""; WAF_PFX=""; WAF_GLUE="" -for W in $(aws athena list-work-groups --region "$REGION" --query 'WorkGroups[].Name' --output text 2>/dev/null | tr '\t' '\n' | grep -i waf || true); do - OUT=$(aws athena get-work-group --region "$REGION" --work-group "$W" --query 'WorkGroup.Configuration.ResultConfiguration.OutputLocation' --output text 2>/dev/null || true) - case "$OUT" in s3://*) ;; *) continue;; esac - B="${{OUT#s3://}}"; B="${{B%%/*}}"; P="${{OUT#s3://$B}}"; P="${{P#/}}" - WAF_WG="$WAF_WG${{WAF_WG:+,}}\"arn:aws:athena:$REGION:$ACCOUNT:workgroup/$W\"" - WAF_OBJ="$WAF_OBJ${{WAF_OBJ:+,}}\"arn:aws:s3:::$B/$P*\"" - WAF_BKT="$WAF_BKT${{WAF_BKT:+,}}\"arn:aws:s3:::$B\"" - WAF_PFX="$WAF_PFX${{WAF_PFX:+,}}\"$P*\"" -done -for D in $(aws glue get-databases --region "$REGION" --query 'DatabaseList[].Name' --output text 2>/dev/null | tr '\t' '\n'); do - T=$(aws glue get-tables --region "$REGION" --database-name "$D" --query "TableList[?StorageDescriptor.Location && starts_with(StorageDescriptor.Location, 's3://aws-waf-logs-')].Name" --output text 2>/dev/null || true) - if [ -n "$T" ] && [ "$T" != "None" ]; then - WAF_GLUE="$WAF_GLUE${{WAF_GLUE:+,}}\"arn:aws:glue:$REGION:$ACCOUNT:database/$D\",\"arn:aws:glue:$REGION:$ACCOUNT:table/$D/*\"" - fi -done -if [ -n "$WAF_WG" ] && [ -n "$WAF_GLUE" ]; then - WAF_DOC=$(echo '{athena}' | sed -e "s#\"WAF_WORKGROUPS\"#$WAF_WG#g" -e "s#\"WAF_GLUE\"#$WAF_GLUE#g" -e "s#\"WAF_RESULT_OBJECTS\"#$WAF_OBJ#g" -e "s#\"WAF_RESULT_BUCKETS\"#$WAF_BKT#g" -e "s#\"WAF_RESULT_PREFIXES\"#$WAF_PFX#g" -e "s#ACCOUNT_ID#$ACCOUNT#g") - WAF_SAID="AWS WAF, and its logs in S3 through Athena (results only under the workgroup's results prefix)" -else - WAF_DOC=$(echo '{plain}' | sed -e "s#ACCOUNT_ID#$ACCOUNT#g") - WAF_SAID="AWS WAF and its log buckets (no Athena workgroup with waf in its name, or no Glue table on an aws-waf-logs- bucket, in $REGION)" -fi -aws iam put-role-policy --role-name "$ROLE" --policy-name {WAF_POLICY_NAME} --policy-document "$WAF_DOC" -echo "WAF reads ready: $WAF_SAID." -"## - ) -} - -/// Pure: a role name the update line may name. -fn is_role_name(name: &str) -> bool { - !name.is_empty() - && name.len() <= 64 - && name - .chars() - .all(|c| c.is_ascii_alphanumeric() || "+=,.@_-".contains(c)) -} - -/// The update that adds only [`WAF_POLICY_NAME`] to an existing role -/// (`role`, its name), for a team whose role was made before it: no -/// questions, nothing pasted back, and safe to run again. -pub fn waf_update_script(role: &str) -> Option { - is_role_name(role).then(|| { - format!( - "coderhelm_waf_update() (\nset -euo pipefail\nROLE={role}\nREGION=\"${{AWS_REGION:-us-east-1}}\"\nACCOUNT=$(aws sts get-caller-identity --query Account --output text)\necho \"Adding read-only AWS WAF access to $ROLE in account $ACCOUNT ($REGION)...\"\n{}\n)\ncoderhelm_waf_update\n", - waf_policy_step() - ) - }) -} - -/// [`waf_update_script`] as the one line a person pastes into AWS -/// CloudShell in the role's account (and the region of its Athena -/// workgroup). -pub fn waf_update_line(role_arn: &str) -> Option { - let role = role_arn.rsplit('/').next().unwrap_or(role_arn); - let script = waf_update_script(role)?; - Some(format!( - "echo {} | base64 -d | bash", - STANDARD.encode(script) - )) -} - -/// The script a team pastes into AWS CloudShell. It creates (or updates) the -/// role, lets them pick a database to share, creates a database user that can -/// only read, and prints the line to paste back. It defines a function and -/// calls it on the last line, so the questions it asks read from the keyboard -/// rather than from the rest of the paste. The function runs in a subshell, so -/// a failed step stops the script without closing the person's terminal. -pub fn setup_script(our_account: &str, external_id: &str) -> String { - let trust = trust_policy(our_account, external_id).to_string(); - let logs = logs_policy().to_string(); - let db = database_policy_template("ACCOUNT_ID").to_string(); - let wh = warehouse_policy_template("ACCOUNT_ID").to_string(); - let waf = waf_policy_step(); +/// The script a team pastes into AWS CloudShell to read a database or a +/// warehouse. It makes only what a CloudFormation stack can't: the +/// read-only database user (and its password secret) inside the database +/// they pick. The role's permissions are never written by the script: it +/// creates, or updates, CoderHelm's role stack (`CoderHelmLogReader`) with +/// this release's template (`template_url`), naming the database or the +/// warehouse in the stack's DatabaseClusters or Warehouses parameter and +/// keeping every other parameter as it was. So every read the role has is +/// in that one template, and a later release reaches it through the same +/// one-click update as every other read. It prints the line to paste back +/// into CoderHelm. It defines a function and calls it on the last line, so +/// the questions it asks read from the keyboard rather than from the rest +/// of the paste. The function runs in a subshell, so a failed step stops +/// the script without closing the person's terminal. +pub fn setup_script( + our_account: &str, + external_id: &str, + template_url: &str, + trusted_prefix: &str, +) -> String { + let stack = crate::log_reader::ROLE_STACK; format!( r#"coderhelm_setup() ( set -euo pipefail -ROLE={ROLE_PREFIX} +ROLE={LOG_READER_ROLE} +STACK={stack} +TEMPLATE_URL='{template_url}' REGION="${{AWS_REGION:-us-east-1}}" ACCOUNT=$(aws sts get-caller-identity --query Account --output text) echo "Setting up read-only access for Coderhelm in account $ACCOUNT ($REGION)..." -if aws iam get-role --role-name "$ROLE" >/dev/null 2>&1; then - aws iam update-assume-role-policy --role-name "$ROLE" --policy-document '{trust}' -else - aws iam create-role --role-name "$ROLE" --description "Coderhelm: read-only access to logs and one database" --max-session-duration 3600 --assume-role-policy-document '{trust}' >/dev/null -fi -aws iam put-role-policy --role-name "$ROLE" --policy-name coderhelm-read-logs --policy-document '{logs}' -{waf}ROLE_ARN=$(aws iam get-role --role-name "$ROLE" --query Role.Arn --output text) -echo "Role ready: $ROLE_ARN (it can read logs and AWS WAF; it can't change anything)." -DB_PART="" +DB_ARN=""; RS_ID=""; DB_PART=""; RS_PART="" CLUSTERS=$(aws rds describe-db-clusters --region "$REGION" --query "DBClusters[?Engine=='aurora-postgresql' && HttpEndpointEnabled].DBClusterIdentifier" --output text | tr '\t' '\n' | sed '/^$/d') if [ -n "$CLUSTERS" ]; then echo @@ -682,12 +365,11 @@ if [ -n "$CLUSTERS" ]; then aws secretsmanager create-secret --region "$REGION" --name "$SECRET_NAME" --description "Coderhelm read-only database user" --secret-string "$SECRET_VALUE" >/dev/null fi SECRET_ARN=$(aws secretsmanager describe-secret --region "$REGION" --secret-id "$SECRET_NAME" --query ARN --output text) - aws iam put-role-policy --role-name "$ROLE" --policy-name "coderhelm-read-database-$CLUSTER_ID" --policy-document "$(echo '{db}' | sed -e "s#CLUSTER_ARN#$CLUSTER_ARN#" -e "s#ACCOUNT_ID#$ACCOUNT#")" + DB_ARN="$CLUSTER_ARN" DB_PART=",\"cluster_arn\":\"$CLUSTER_ARN\",\"secret_arn\":\"$SECRET_ARN\",\"database\":\"$DB_NAME\"" echo "Database user ready. It can read every table and change none." fi fi -RS_PART="" WAREHOUSES=$(aws redshift describe-clusters --region "$REGION" --query 'Clusters[].ClusterIdentifier' --output text 2>/dev/null | tr '\t' '\n' | sed '/^$/d') if [ -n "$WAREHOUSES" ]; then echo @@ -724,11 +406,42 @@ if [ -n "$WAREHOUSES" ]; then RS_JSON="$RS_JSON${{RS_JSON:+,}}\"$D\"" echo " $D: can read, can't change" done - aws iam put-role-policy --role-name "$ROLE" --policy-name "coderhelm-read-warehouse-$RS_ID" --policy-document "$(echo '{wh}' | sed -e "s#RS_CLUSTER#$RS_ID#g" -e "s#ACCOUNT_ID#$ACCOUNT#g")" RS_PART=",\"engine\":\"redshift\",\"cluster_id\":\"$RS_ID\",\"db_user\":\"{DB_USER}\",\"databases\":[$RS_JSON]" echo "Warehouse user ready." fi fi +# The role's permissions: only through CoderHelm's role stack, with this +# release's template. A list parameter keeps what it named and adds the new one. +add_to() {{ if [ -z "$1" ] || [ "$1" = "None" ]; then echo "$2"; elif [ -z "$2" ] || echo ",$1," | grep -q ",$2,"; then echo "$1"; else echo "$1,$2"; fi; }} +STACK_REGION="" +for R in "$REGION" $(aws ec2 describe-regions --region "$REGION" --query 'Regions[].RegionName' --output text 2>/dev/null); do + if aws cloudformation describe-stacks --region "$R" --stack-name "$STACK" >/dev/null 2>&1; then STACK_REGION="$R"; break; fi +done +if [ -n "$STACK_REGION" ]; then + q() {{ aws cloudformation describe-stacks --region "$STACK_REGION" --stack-name "$STACK" --query "$1" --output text; }} + KEYS=$(q 'Stacks[0].Parameters[].ParameterKey') + DBS=$(add_to "$(q "Stacks[0].Parameters[?ParameterKey=='DatabaseClusters'].ParameterValue | [0]")" "$DB_ARN") + WHS=$(add_to "$(q "Stacks[0].Parameters[?ParameterKey=='Warehouses'].ParameterValue | [0]")" "$RS_ID") + P="[{{\"ParameterKey\":\"DatabaseClusters\",\"ParameterValue\":\"$DBS\"}},{{\"ParameterKey\":\"Warehouses\",\"ParameterValue\":\"$WHS\"}}" + for K in $KEYS; do case "$K" in DatabaseClusters|Warehouses) ;; *) P="$P,{{\"ParameterKey\":\"$K\",\"UsePreviousValue\":true}}";; esac; done + P="$P]" + echo "Updating CoderHelm's role stack $STACK ($STACK_REGION) to this release's template..." + if OUT=$(aws cloudformation update-stack --region "$STACK_REGION" --stack-name "$STACK" --template-url "$TEMPLATE_URL" --capabilities CAPABILITY_NAMED_IAM --parameters "$P" 2>&1); then + aws cloudformation wait stack-update-complete --region "$STACK_REGION" --stack-name "$STACK" + elif ! echo "$OUT" | grep -q "No updates are to be performed"; then + echo "$OUT"; echo "The role stack wasn't updated; see its Events tab in CloudFormation."; exit 1 + fi +elif aws iam get-role --role-name "$ROLE" >/dev/null 2>&1; then + echo "The role $ROLE exists, but not from CoderHelm's stack $STACK, so its permissions can't be kept current." + echo "Delete the role (or the stack that made it), then run this again."; exit 1 +else + echo "Creating CoderHelm's role stack $STACK ($REGION)..." + P="[{{\"ParameterKey\":\"ExternalId\",\"ParameterValue\":\"{external_id}\"}},{{\"ParameterKey\":\"CoderHelmAccountId\",\"ParameterValue\":\"{our_account}\"}},{{\"ParameterKey\":\"TrustedRolePrefix\",\"ParameterValue\":\"{trusted_prefix}\"}},{{\"ParameterKey\":\"DatabaseClusters\",\"ParameterValue\":\"$DB_ARN\"}},{{\"ParameterKey\":\"Warehouses\",\"ParameterValue\":\"$RS_ID\"}}]" + aws cloudformation create-stack --region "$REGION" --stack-name "$STACK" --template-url "$TEMPLATE_URL" --capabilities CAPABILITY_NAMED_IAM --parameters "$P" >/dev/null + aws cloudformation wait stack-create-complete --region "$REGION" --stack-name "$STACK" +fi +ROLE_ARN=$(aws iam get-role --role-name "$ROLE" --query Role.Arn --output text) +echo "Role ready: $ROLE_ARN (it reads; the only change it may make is an Athena query's results, only when you turn WAF logs on)." CODE=$(printf '{{"role_arn":"%s","region":"%s"%s%s}}' "$ROLE_ARN" "$REGION" "$DB_PART" "$RS_PART" | base64 | tr -d '\n') echo echo "Done. Copy this whole line and paste it into Coderhelm:" @@ -809,12 +522,15 @@ pub fn in_install_account(role_arn: &str, own: Option<&str>) -> bool { pub fn install_target(target: &AwsTarget, own: Option<&str>) -> Option { let own = own?; let name = target.role_arn.rsplit('/').next().unwrap_or(""); - (name == LOG_READER_ROLE && in_install_account(&target.role_arn, Some(own))).then(|| { - AwsTarget { + // A database or a warehouse is read through the role stack's own + // groups (DatabaseClusters, Warehouses), never the install's role. + let data = !target.cluster_arn.is_empty() || !target.cluster_id.is_empty(); + (name == LOG_READER_ROLE && !data && in_install_account(&target.role_arn, Some(own))).then( + || AwsTarget { role_arn: own.to_string(), ..target.clone() - } - }) + }, + ) } /// A session on the function's own role (its environment's credentials), @@ -966,7 +682,6 @@ pub fn rdsdata_client(s: &Session) -> aws_sdk_rdsdata::Client { #[cfg(test)] mod tests { use super::*; - use serde_json::Value; const ROLE: &str = "arn:aws:iam::123456789012:role/CoderhelmReadOnly"; @@ -1158,193 +873,53 @@ mod tests { assert!(!t.allows_log_group("/aws/lambda/other")); } - #[test] - fn the_script_carries_the_private_id_and_only_read_permissions() { - let s = setup_script("654654210434", "coderhelm-abc"); - assert!(s.contains("\"sts:ExternalId\":\"coderhelm-abc\"")); - assert!(s.contains("arn:aws:iam::654654210434:root")); - assert!(s.contains("logs:StartQuery")); - assert!(s.contains("\"Action\":\"logs:Unmask\"")); - assert!(s.contains("rds-data:CommitTransaction")); - assert!(s.contains("default_transaction_read_only = on")); - assert!(s.trim_end().ends_with("coderhelm_setup")); - // one permission per database, so adding a second keeps the first - assert!(s.contains("--policy-name \"coderhelm-read-database-$CLUSTER_ID\"")); - assert!(s.contains("PASSWORD DISABLE")); - assert!(s.contains("redshift-data:BatchExecuteStatement")); - // nothing in the policies can write - for p in [ - logs_policy(), - database_policy_template("1"), - warehouse_policy_template("1"), - ] { - for st in p["Statement"].as_array().unwrap() { - if st["Effect"] == "Allow" { - let actions = st["Action"].to_string(); - for w in [ - "Put", "Create", "Delete", "Update", "Commit", "Batch", "Unmask", - ] { - assert!(!actions.contains(w), "{actions}"); - } - } - } - } - assert_eq!( - session_name("a person@example.com"), - "coderhelm-a-person@example.com" - ); - assert!(new_external_id().starts_with("coderhelm-")); - } + const TEMPLATE_URL: &str = + "https://coderhelm-public.s3.amazonaws.com/launch/v1.2.3/coderhelm-log-reader.yaml"; - #[test] - fn the_waf_policy_reads_waf_and_queries_only_its_logs() { - let never = serde_json::to_value(WAF_NEVER).unwrap(); - assert_eq!( - waf_policy_template("111122223333", true), - json!({ - "Version": "2012-10-17", - "Statement": [ - { "Sid": "ReadWaf", "Effect": "Allow", - "Action": ["wafv2:Get*", "wafv2:List*"], "Resource": "*" }, - { "Sid": "ReadWafLogObjects", "Effect": "Allow", - "Action": ["s3:GetObject"], "Resource": "arn:aws:s3:::aws-waf-logs-*/*" }, - { "Sid": "ListWafLogBuckets", "Effect": "Allow", - "Action": ["s3:ListBucket", "s3:GetBucketLocation"], - "Resource": "arn:aws:s3:::aws-waf-logs-*" }, - { "Sid": "FindWafLogWorkgroups", "Effect": "Allow", - "Action": ["athena:ListWorkGroups"], "Resource": "*" }, - { "Sid": "FindWafLogDatabases", "Effect": "Allow", - "Action": ["glue:GetDatabases"], - "Resource": ["arn:aws:glue:*:111122223333:catalog", - "arn:aws:glue:*:111122223333:database/*"] }, - { "Sid": "ReadWafLogTables", "Effect": "Allow", "Action": ["glue:Get*"], - "Resource": ["arn:aws:glue:*:111122223333:catalog", "WAF_GLUE"] }, - { "Sid": "QueryWafLogs", "Effect": "Allow", - "Action": ["athena:StartQueryExecution", "athena:Get*", - "athena:StopQueryExecution"], - "Resource": ["WAF_WORKGROUPS"] }, - { "Sid": "WriteQueryResultsOnly", "Effect": "Allow", - "Action": ["s3:PutObject", "s3:GetObject"], - "Resource": ["WAF_RESULT_OBJECTS"] }, - { "Sid": "FindQueryResults", "Effect": "Allow", - "Action": ["s3:GetBucketLocation", "s3:ListBucket"], - "Resource": ["WAF_RESULT_BUCKETS"], - "Condition": { "StringLike": { "s3:prefix": ["WAF_RESULT_PREFIXES"] } } }, - { "Sid": "NoWritesButQueryResults", "Effect": "Deny", - "Action": "s3:PutObject", "NotResource": ["WAF_RESULT_OBJECTS"] }, - { "Sid": "NeverChange", "Effect": "Deny", "Action": never, "Resource": "*" } - ] - }) - ); - assert_eq!( - waf_policy_template("111122223333", false), - json!({ - "Version": "2012-10-17", - "Statement": [ - { "Sid": "ReadWaf", "Effect": "Allow", - "Action": ["wafv2:Get*", "wafv2:List*"], "Resource": "*" }, - { "Sid": "ReadWafLogObjects", "Effect": "Allow", - "Action": ["s3:GetObject"], "Resource": "arn:aws:s3:::aws-waf-logs-*/*" }, - { "Sid": "ListWafLogBuckets", "Effect": "Allow", - "Action": ["s3:ListBucket", "s3:GetBucketLocation"], - "Resource": "arn:aws:s3:::aws-waf-logs-*" }, - { "Sid": "NoWrites", "Effect": "Deny", "Action": "s3:PutObject", - "Resource": "*" }, - { "Sid": "NeverChange", "Effect": "Deny", "Action": never, "Resource": "*" } - ] - }) - ); - // Every allow is a read but the one write, which is held to the - // workgroup's results prefix by its own deny. - for athena in [true, false] { - let p = waf_policy_template("1", athena); - for st in p["Statement"].as_array().unwrap() { - let actions: Vec<&str> = match &st["Action"] { - Value::String(a) => vec![a.as_str()], - v => v - .as_array() - .unwrap() - .iter() - .map(|a| a.as_str().unwrap()) - .collect(), - }; - if st["Effect"] == "Allow" { - for a in &actions { - let verb = a.split(':').nth(1).unwrap(); - let read = ["Get", "List"].iter().any(|r| verb.starts_with(r)) - || matches!( - *a, - "athena:StartQueryExecution" | "athena:StopQueryExecution" - ); - assert!(read || *a == "s3:PutObject", "{a} is not a read"); - if *a == "s3:PutObject" { - assert_eq!(st["Resource"], json!(["WAF_RESULT_OBJECTS"])); - } - } - assert_ne!(st["Action"], json!("*")); - } - } - // Every placeholder is alone in its array, so the script's list replaces it. - let text = p.to_string(); - for ph in WAF_PLACEHOLDERS { - if athena { - assert!(text.contains(&format!("\"{ph}\"")), "{ph}"); - } else { - assert!(!text.contains(ph), "{ph}"); - } - } - } - // Glue's connections carry passwords: never readable. - assert!(WAF_NEVER.contains(&"glue:GetConnection")); + fn script() -> String { + setup_script( + "654654210434", + "0b5f1a5e-0000-4000-8000-000000000000", + TEMPLATE_URL, + "", + ) } + /// The script writes no permission itself: every read is the role + /// stack's, created or updated with this release's template, keeping + /// every parameter but the database or warehouse it adds. #[test] - fn the_setup_script_adds_the_waf_policy_and_the_update_line_only_that() { - let s = setup_script("654654210434", "coderhelm-abc"); - assert!(s.contains(&format!("--policy-name {WAF_POLICY_NAME}"))); - assert!(s.contains("grep -i waf")); - assert!(s.contains("starts_with(StorageDescriptor.Location, 's3://aws-waf-logs-')")); - let line = waf_update_line("arn:aws:iam::111122223333:role/CoderhelmReadOnly").unwrap(); - assert!(line.starts_with("echo ") && line.ends_with(" | base64 -d | bash")); - assert!(!line.contains('\n')); - let b64 = line - .trim_start_matches("echo ") - .trim_end_matches(" | base64 -d | bash"); - let script = String::from_utf8(STANDARD.decode(b64).unwrap()).unwrap(); - assert!(script.contains("ROLE=CoderhelmReadOnly\n")); - assert!(script.contains(&format!("--policy-name {WAF_POLICY_NAME}"))); - // Nothing else: no trust change, no other policy, nothing pasted back. - assert_eq!(script.matches("put-role-policy").count(), 1); + fn the_script_only_creates_or_updates_the_role_stack() { + let s = script(); for no in [ - "update-assume-role-policy", + "put-role-policy", "create-role", - "coderhelm:$CODE", - "read -r", + "update-assume-role-policy", + "attach-role-policy", + "coderhelm-read-waf", ] { - assert!(!script.contains(no), "{no}"); - } - assert!(waf_update_line("arn:aws:iam::111122223333:role/x;rm -rf").is_none()); - for sh in [script, s] { - use std::io::Write; - let mut child = std::process::Command::new("bash") - .arg("-n") - .stdin(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .expect("bash is installed"); - child - .stdin - .take() - .unwrap() - .write_all(sh.as_bytes()) - .unwrap(); - let out = child.wait_with_output().unwrap(); - assert!( - out.status.success(), - "{}", - String::from_utf8_lossy(&out.stderr) - ); + assert!(!s.contains(no), "{no}"); } + assert!(s.contains("STACK=CoderHelmLogReader\n")); + assert!(s.contains(&format!("TEMPLATE_URL='{TEMPLATE_URL}'"))); + assert!(s.contains("aws cloudformation update-stack")); + assert!(s.contains("aws cloudformation create-stack")); + assert!(s.contains("\\\"UsePreviousValue\\\":true")); + assert!(s.contains("ParameterKey\\\":\\\"DatabaseClusters")); + assert!(s.contains("ParameterKey\\\":\\\"Warehouses")); + assert!(s.contains("\\\"ParameterValue\\\":\\\"0b5f1a5e-0000-4000-8000-000000000000\\\"")); + assert!(s.contains("No updates are to be performed")); + // A role the stack didn't make is never patched by hand. + assert!(s.contains("not from CoderHelm's stack")); + // Inside the database: a user that can only read. + assert!(s.contains("default_transaction_read_only = on")); + assert!(s.contains("PASSWORD DISABLE")); + assert!(s.trim_end().ends_with("coderhelm_setup")); + assert_eq!( + session_name("a person@example.com"), + "coderhelm-a-person@example.com" + ); + assert!(new_external_id().starts_with("coderhelm-")); } #[test] @@ -1360,7 +935,7 @@ mod tests { .stdin .take() .unwrap() - .write_all(setup_script("654654210434", "coderhelm-abc").as_bytes()) + .write_all(script().as_bytes()) .unwrap(); let out = child.wait_with_output().unwrap(); assert!( @@ -1370,6 +945,17 @@ mod tests { ); } + #[test] + fn a_database_on_the_log_reader_is_read_with_that_role_in_the_install_account() { + let mut t = db_target(); + t.role_arn = format!("arn:aws:iam::111122223333:role/{LOG_READER_ROLE}"); + assert!(install_target(&t, Some(OWN)).is_none()); + let mut w = t.clone(); + w.cluster_arn.clear(); + w.cluster_id = "analytics".into(); + assert!(install_target(&w, Some(OWN)).is_none()); + } + /// Writes the setup script to the file named by SETUP_SCRIPT_OUT, for /// running it by hand. Needs SETUP_ACCOUNT and SETUP_EXTERNAL_ID. #[test] @@ -1378,7 +964,12 @@ mod tests { let env = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("{k} not set")); std::fs::write( env("SETUP_SCRIPT_OUT"), - setup_script(&env("SETUP_ACCOUNT"), &env("SETUP_EXTERNAL_ID")), + setup_script( + &env("SETUP_ACCOUNT"), + &env("SETUP_EXTERNAL_ID"), + &crate::public_urls::log_reader_template_url(), + "", + ), ) .unwrap(); } diff --git a/services/common/src/live/aws_account.rs b/services/common/src/live/aws_account.rs index dc3b63c07..29ce02486 100644 --- a/services/common/src/live/aws_account.rs +++ b/services/common/src/live/aws_account.rs @@ -78,13 +78,32 @@ pub struct AwsAccount { /// by the caller, never stored here): an update keeps the role able to /// read them. pub import_buckets: Vec, + /// An alert route took an AWS WAF alarm in this account, so its role + /// stack keeps the WAF log group on (stored: `waf_logs`), with what a + /// WAF alarm run found: the Athena workgroup's results location + /// (`bucket/prefix/`) and the log bucket's own KMS key, empty until + /// known. Every update link for the account carries them. + pub waf_logs: bool, + pub waf_log_results: String, + pub waf_log_key: String, + /// The Aurora clusters (ARNs) and Redshift clusters (names) the team's + /// data sources read in this account (filled by the caller, never + /// stored here): an update keeps the role able to query them. + pub database_clusters: Vec, + pub warehouses: Vec, } impl AwsAccount { /// What the team chose for the role here. pub fn chosen(&self) -> crate::log_reader::Chosen<'_> { - crate::log_reader::Chosen::new(&self.knowledge_bases, &self.import_buckets) + let c = crate::log_reader::Chosen::new(&self.knowledge_bases, &self.import_buckets) .with_infrastructure(self.abilities.infra_on) + .with_data_sources(&self.database_clusters, &self.warehouses); + if self.waf_logs { + c.with_waf_logs(&self.waf_log_results, &self.waf_log_key) + } else { + c + } } /// Infrastructure vulnerabilities is on here. @@ -166,6 +185,11 @@ impl AwsAccount { status: s(item, "status"), knowledge_bases: Vec::new(), import_buckets: Vec::new(), + waf_logs: b(item, "waf_logs"), + waf_log_results: s(item, "waf_log_results"), + 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()) @@ -435,6 +459,55 @@ pub async fn save_permissions( .map_err(|e| format!("save aws permissions: {e}")) } +/// Pure: the WAF log group's settings after a WAF alarm run in the +/// account, from what was stored and what the run found: the group stays +/// on, and a location or key found replaces an unknown one (a found one +/// that differs replaces it too: the workgroup or the bucket changed). +pub fn waf_logs_after( + stored_results: &str, + stored_key: &str, + found_results: &str, + found_key: &str, +) -> (String, String) { + let pick = |stored: &str, found: &str| { + if found.is_empty() { + stored.to_string() + } else { + found.to_string() + } + }; + ( + pick(stored_results, found_results), + pick(stored_key, found_key), + ) +} + +/// Turns the WAF log group on for the account and stores what a WAF alarm +/// run found (results location, KMS key), only while it is still connected. +pub async fn save_waf_logs( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + account: &str, + results: &str, + key: &str, +) -> Result<(), String> { + dynamo + .update_item() + .table_name(table) + .key("pk", av_s(team_id)) + .key("sk", av_s(&format!("{PREFIX}{account}"))) + .condition_expression("attribute_exists(pk)") + .update_expression("SET waf_logs = :on, waf_log_results = :r, waf_log_key = :k") + .expression_attribute_values(":on", AttributeValue::Bool(true)) + .expression_attribute_values(":r", av_s(results)) + .expression_attribute_values(":k", av_s(key)) + .send() + .await + .map(|_| ()) + .map_err(|e| format!("save waf log settings: {e}")) +} + /// Writes only the ability fields, and only while the account is still /// connected (a disconnect in between wins). pub async fn save_abilities( diff --git a/services/common/src/log_reader.rs b/services/common/src/log_reader.rs index 99e61d534..8f92c44e9 100644 --- a/services/common/src/log_reader.rs +++ b/services/common/src/log_reader.rs @@ -233,6 +233,55 @@ pub const ABILITIES: &[Ability] = &[ ], chosen: true, }, + Ability { + key: "waf_logs", + name: "AWS WAF logs in S3", + why: "When a WAF alarm on an alert route fires, reads what the web ACL logged to its aws-waf-logs-* bucket: the log objects, the Glue table definitions Athena needs to plan a query, and the Athena workgroups' settings (which one queries the logs, where it writes results). With a results location (WafLogResults) it runs one bounded, read-only Athena query over the alarm's rule and writes the query's results only under that location: the role's one write, held there by a deny. Decrypts with the log bucket's own KMS key only through S3 (WafLogKey). Only when the stack's WafLogs parameter is on; every change to WAF, Athena, Glue or a bucket is denied.", + actions: &[ + "s3:GetObject", + "s3:ListBucket", + "s3:GetBucketLocation", + "glue:GetDatabases", + "glue:GetDatabase", + "glue:GetTables", + "glue:GetTable", + "glue:GetPartitions", + "athena:ListWorkGroups", + "athena:GetWorkGroup", + "athena:StartQueryExecution", + "athena:GetQueryExecution", + "athena:GetQueryResults", + "athena:StopQueryExecution", + "s3:PutObject", + "kms:Decrypt", + ], + chosen: true, + }, + Ability { + key: "databases", + name: "Databases", + why: "Queries the Aurora PostgreSQL clusters a team connects as data sources, as the read-only database user coderhelm_readonly, through the RDS Data API inside transactions that are rolled back and never committed; reads only that user's password secret (coderhelm-readonly-*). Only the clusters named in the stack's DatabaseClusters parameter.", + actions: &[ + "rds-data:BeginTransaction", + "rds-data:ExecuteStatement", + "rds-data:RollbackTransaction", + "secretsmanager:GetSecretValue", + ], + chosen: true, + }, + Ability { + key: "warehouses", + name: "Redshift warehouses", + why: "Queries the Redshift clusters a team connects as data sources, signed in only as the passwordless read-only user coderhelm_readonly, one statement at a time, reading only its own results. Only the clusters named in the stack's Warehouses parameter.", + actions: &[ + "redshift:GetClusterCredentials", + "redshift-data:ExecuteStatement", + "redshift-data:DescribeStatement", + "redshift-data:GetStatementResult", + "redshift-data:CancelStatement", + ], + chosen: true, + }, Ability { key: "maintenance", name: "Applying approved database maintenance", @@ -260,6 +309,11 @@ pub const SYNC_WRITES: &[&str] = &[ "bedrock:StartIngestionJob", ]; +/// The one write of [`ability`] `waf_logs`: an Athena query's results, +/// allowed only under the stack's WafLogResults location and denied +/// everywhere else by the same policy. +pub const WAF_RESULT_WRITES: &[&str] = &["s3:PutObject"]; + /// What a team chose for the role in one account: the knowledge bases it /// connects and the buckets it imports. The update stack grants exactly /// these. @@ -277,6 +331,17 @@ pub struct Chosen<'a> { pub health: bool, /// The team lets CoderHelm apply approved database maintenance. pub maintenance: bool, + /// An alert route takes AWS WAF alarms in this account: the WAF log + /// group is on, with the workgroup's results location + /// (`bucket/prefix/`, empty until known) and the log bucket's own KMS + /// key (empty when it has none). + pub waf_logs: bool, + pub waf_log_results: &'a str, + pub waf_log_key: &'a str, + /// Aurora clusters (ARNs) and Redshift clusters (names) the team's data + /// sources in this account read. + pub database_clusters: &'a [String], + pub warehouses: &'a [String], } impl<'a> Chosen<'a> { @@ -289,6 +354,31 @@ impl<'a> Chosen<'a> { inspector: false, health: false, maintenance: false, + waf_logs: false, + waf_log_results: "", + waf_log_key: "", + database_clusters: &[], + warehouses: &[], + } + } + + /// The same, with the WAF log group on (`results` and `key` as the + /// stack's WafLogResults and WafLogKey; empty when not known). + pub fn with_waf_logs(self, results: &'a str, key: &'a str) -> Chosen<'a> { + Chosen { + waf_logs: true, + waf_log_results: results, + waf_log_key: key, + ..self + } + } + + /// The same, with the team's data sources' databases and warehouses. + pub fn with_data_sources(self, clusters: &'a [String], warehouses: &'a [String]) -> Chosen<'a> { + Chosen { + database_clusters: clusters, + warehouses, + ..self } } @@ -333,6 +423,9 @@ impl<'a> Chosen<'a> { && !self.inspector && !self.health && !self.maintenance + && !self.waf_logs + && self.database_clusters.is_empty() + && self.warehouses.is_empty() } } @@ -563,9 +656,83 @@ pub fn update_url(update_template_url: &str, region: &str, chosen: &Chosen) -> S if chosen.maintenance { u.push_str("¶m_ApplyMaintenance=on"); } + if chosen.waf_logs { + u.push_str("¶m_WafLogs=on"); + if let Some(r) = waf_log_results(chosen.waf_log_results) { + u.push_str(&format!("¶m_WafLogResults={}", urlencoding::encode(&r))); + } + if is_kms_key(chosen.waf_log_key) { + u.push_str(&format!( + "¶m_WafLogKey={}", + urlencoding::encode(chosen.waf_log_key) + )); + } + } + if !chosen.database_clusters.is_empty() { + u.push_str(&format!( + "¶m_DatabaseClusters={}", + urlencoding::encode(&sorted(chosen.database_clusters).join(",")) + )); + } + if !chosen.warehouses.is_empty() { + u.push_str(&format!( + "¶m_Warehouses={}", + urlencoding::encode(&sorted(chosen.warehouses).join(",")) + )); + } u } +/// Pure: an Athena workgroup's results location as the stack's +/// WafLogResults (`bucket/prefix/`, always ending in `/` so the write +/// covers that prefix and no sibling): from `s3://bucket/prefix` or +/// `bucket/prefix`. `None` when it isn't a bucket and a prefix the +/// template accepts. A bare bucket gets `bucket/`. +pub fn waf_log_results(location: &str) -> Option { + let l = location.trim(); + let l = l.strip_prefix("s3://").unwrap_or(l); + let (bucket, prefix) = l.split_once('/').unwrap_or((l, "")); + let bucket_ok = (3..=63).contains(&bucket.len()) + && bucket + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '.' || c == '-') + && bucket + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphanumeric()) + && bucket + .chars() + .last() + .is_some_and(|c| c.is_ascii_alphanumeric()); + let prefix_ok = prefix + .chars() + .all(|c| c.is_ascii_alphanumeric() || "!_.'()=/-".contains(c)); + if !bucket_ok || !prefix_ok { + return None; + } + let mut out = format!("{bucket}/{prefix}"); + if !out.ends_with('/') { + out.push('/'); + } + Some(out) +} + +/// Pure: a KMS key ARN the template's WafLogKey accepts. +pub fn is_kms_key(arn: &str) -> bool { + let p: Vec<&str> = arn.split(':').collect(); + p.len() == 6 + && p[0] == "arn" + && p[1] == "aws" + && p[2] == "kms" + && !p[3].is_empty() + && is_account(p[4]) + && p[5].strip_prefix("key/").is_some_and(|k| { + k.len() == 36 + && k.chars() + .all(|c| c == '-' || c.is_ascii_digit() || ('a'..='f').contains(&c)) + }) +} + fn sorted(v: &[String]) -> Vec<&str> { let mut out: Vec<&str> = v.iter().map(String::as_str).collect(); out.sort_unstable(); @@ -604,6 +771,25 @@ pub fn update_stack_name_for(chosen: &Chosen) -> String { if chosen.maintenance { seed.push_str("|maintenance"); } + if chosen.waf_logs { + seed.push_str(&format!( + "|waf:{}:{}", + waf_log_results(chosen.waf_log_results).unwrap_or_default(), + if is_kms_key(chosen.waf_log_key) { + chosen.waf_log_key + } else { + "" + } + )); + } + if !chosen.database_clusters.is_empty() { + seed.push_str("|db:"); + seed.push_str(&sorted(chosen.database_clusters).join(",")); + } + if !chosen.warehouses.is_empty() { + seed.push_str("|wh:"); + seed.push_str(&sorted(chosen.warehouses).join(",")); + } format!( "{}-kb{}", update_stack_name(), @@ -657,10 +843,20 @@ mod tests { "Put", "Create", "Delete", "Update", "Start", "Stop", "Run", "Invoke", "Attach", "Pass", "Tag", "Untag", "Register", ]; - let ok_reads = ["logs:StartQuery", "logs:StopQuery", "airflow:InvokeRestApi"]; + let ok_reads = [ + "logs:StartQuery", + "logs:StopQuery", + "airflow:InvokeRestApi", + // Run and stop one read-only query; its results are the one write. + "athena:StartQueryExecution", + "athena:StopQueryExecution", + ]; for a in all_actions() { let verb = a.split(':').nth(1).unwrap(); - if ok_reads.contains(&a) || SYNC_WRITES.contains(&a) || MAINTENANCE_WRITES.contains(&a) + if ok_reads.contains(&a) + || SYNC_WRITES.contains(&a) + || MAINTENANCE_WRITES.contains(&a) + || WAF_RESULT_WRITES.contains(&a) { continue; } @@ -804,7 +1000,12 @@ mod tests { .find("Sid: ReadImportBuckets") .expect("the import statements"); let end = t.find("kms:ViaService").expect("decrypt only through S3"); - let rest = format!("{}{}", &t[..start], &t[end..]); + // And but the WAF log group, which reads only aws-waf-logs-* + // objects and decrypts only through S3 with its named key + // (the_waf_log_group_reads_and_writes_only_query_results). + let waf = t.find("# AWS WAF logs in S3").expect("the WAF log group"); + assert!(end < waf); + let rest = format!("{}{}", &t[..start], &t[end..waf]); let all = template_actions(&rest); for x in a.actions { assert!(template_actions(t).iter().any(|y| y == x), "{x}"); @@ -873,8 +1074,9 @@ mod tests { // Knowledge bases (6), imports (4), copying into Bedrock (6 more: // its Get calls are the knowledge bases' too) and infrastructure // reads (20), Inspector (3), Health (3) and applying approved - // maintenance (1). - assert_eq!(checked.len() + 43, all_actions().len()); + // maintenance (1), WAF logs (12 more: Glue, Athena and the results + // write), databases (4) and warehouses (5). + assert_eq!(checked.len() + 64, all_actions().len()); assert!(!checked.contains(&"bedrock:IngestKnowledgeBaseDocuments")); // Copying into Bedrock rides along as its own parameter and stack. let sync = ["arn:aws:bedrock:us-east-1:111122223333:knowledge-base/SYNC123456".to_string()]; @@ -1041,4 +1243,131 @@ mod tests { assert_eq!(trusted_role_prefix_from(Some(" ".into())), ""); assert_eq!(trusted_role_prefix_from(Some("a*b".into())), ""); } + + /// The WAF log group: on only with WafLogs, its one write held to the + /// results location by a deny, decrypt only through S3 with the named + /// key, and every change to WAF, Athena, Glue or a bucket denied. + #[test] + fn the_waf_log_group_reads_and_writes_only_query_results() { + let a = ability("waf_logs").unwrap(); + assert!(a.chosen && !OPTIONAL.contains(&"waf_logs")); + for t in [ROLE_TEMPLATE, UPDATE_TEMPLATE] { + assert!(t.contains("ReadsWafLogs: !Equals [!Ref WafLogs, \"on\"]")); + assert!(t.contains( + "QueriesWafLogs: !And [!Condition ReadsWafLogs, !Not [!Equals [!Ref WafLogResults, \"\"]]]" + )); + // The one write: listed once, on the results location only. + assert_eq!(t.matches("- \"s3:PutObject\"").count(), 1); + let w = t.split("Sid: WriteQueryResultsOnly").nth(1).unwrap(); + let w = w.split("- !Ref AWS::NoValue").next().unwrap(); + assert!( + w.contains("Resource: !Sub \"arn:aws:s3:::${WafLogResults}*\""), + "{w}" + ); + // And denied everywhere else, or everywhere without a location. + let d = t.split("Sid: NoWritesButQueryResults").nth(1).unwrap(); + let d = d.split("- !Ref AWS::NoValue").next().unwrap(); + assert!( + d.contains("Effect: Deny") + && d.contains("NotResource: !Sub \"arn:aws:s3:::${WafLogResults}*\"") + ); + let n = t.split("Sid: NoWrites\n").nth(1).unwrap(); + assert!(n.contains("Effect: Deny") && n.contains("Resource: \"*\"")); + assert!(t.contains("NoWafLogQueries: !And [!Condition ReadsWafLogs, !Equals [!Ref WafLogResults, \"\"]]")); + // Log objects only in the buckets AWS requires WAF logs to use. + let o = t.split("Sid: ReadWafLogObjects").nth(1).unwrap(); + assert!(o.contains("arn:aws:s3:::aws-waf-logs-*/*")); + // KMS: the named key, only through S3. + let k = t.split("Sid: DecryptWafLogsThroughS3").nth(1).unwrap(); + let k = k.split("- !Ref AWS::NoValue").next().unwrap(); + assert!( + k.contains("Resource: !Ref WafLogKey") + && k.contains("kms:ViaService: \"s3.*.amazonaws.com\"") + ); + // Never a change, never Glue's connections (they hold passwords). + let never = t.split("Sid: NeverChangeWafOrItsLogs").nth(1).unwrap(); + for x in [ + "wafv2:Update*", + "athena:Delete*", + "glue:Update*", + "glue:GetConnection*", + "s3:Delete*", + "s3:PutBucket*", + ] { + assert!(never.lines().take(3).any(|l| l.contains(x)), "{x}"); + } + // Databases and warehouses: only the clusters named, never a commit. + assert!(t.contains("!Split [\",\", !Ref DatabaseClusters]")); + assert!(t.contains("secret:coderhelm-readonly-*")); + assert!( + t.contains("[\"rds-data:CommitTransaction\", \"rds-data:BatchExecuteStatement\"]") + ); + assert!(t.contains("dbuser:${Ids}/coderhelm_readonly")); + assert!(t.contains("redshift-data:statement-owner-iam-userid: \"${aws:userid}\"")); + } + } + + #[test] + fn the_update_link_carries_the_waf_log_group_and_data_sources() { + let none = update_url("https://b/x/y.yaml", "us-east-1", &Chosen::default()); + assert!(!none.contains("WafLogs") && !none.contains("DatabaseClusters")); + let key = "arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"; + let c = Chosen::default().with_waf_logs("s3://aws-waf-logs-acme/athena-results", key); + let u = update_url("https://b/x/y.yaml", "us-east-1", &c); + assert!(u.contains("¶m_WafLogs=on"), "{u}"); + assert!( + u.contains("¶m_WafLogResults=aws-waf-logs-acme%2Fathena-results%2F"), + "{u}" + ); + assert!(u.contains("¶m_WafLogKey=arn%3Aaws%3Akms%3Aus-east-1%3A111122223333%3Akey%2F1234abcd-12ab-34cd-56ef-1234567890ab"), "{u}"); + // Not known yet: the group still turns on, without queries. + let bare = Chosen::default().with_waf_logs("", ""); + let u2 = update_url("https://b/x/y.yaml", "us-east-1", &bare); + assert!( + u2.contains("¶m_WafLogs=on") + && !u2.contains("WafLogResults") + && !u2.contains("WafLogKey") + ); + // Each is its own stack, so a newer one never collides with an older one. + assert_ne!(update_stack_name_for(&c), update_stack_name_for(&bare)); + assert_ne!(update_stack_name_for(&bare), update_stack_name()); + assert!(update_stack_name_for(&c).len() <= 128); + let dbs = ["arn:aws:rds:us-east-1:111122223333:cluster:app-db".to_string()]; + let whs = ["analytics".to_string()]; + let d = Chosen::default().with_data_sources(&dbs, &whs); + let u3 = update_url("https://b/x/y.yaml", "us-east-1", &d); + assert!(u3.contains("¶m_DatabaseClusters=arn%3Aaws%3Ards%3Aus-east-1%3A111122223333%3Acluster%3Aapp-db"), "{u3}"); + assert!(u3.contains("¶m_Warehouses=analytics")); + assert!(!d.is_empty()); + } + + #[test] + fn the_results_location_is_a_bucket_and_prefix_the_template_accepts() { + assert_eq!( + waf_log_results("s3://aws-waf-logs-acme/athena-results/").as_deref(), + Some("aws-waf-logs-acme/athena-results/") + ); + assert_eq!( + waf_log_results("results-bucket").as_deref(), + Some("results-bucket/") + ); + assert_eq!( + waf_log_results("s3://q.results/a/b").as_deref(), + Some("q.results/a/b/") + ); + for bad in ["", "s3://", "Bad_Bucket/x", "b/x y", "s3://ab/x", "x;rm/"] { + assert!(waf_log_results(bad).is_none(), "{bad}"); + } + assert!(is_kms_key( + "arn:aws:kms:eu-west-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab" + )); + for bad in [ + "", + "alias/aws/s3", + "arn:aws:kms:eu-west-1:111122223333:alias/x", + "arn:aws:kms:eu-west-1:1:key/1234abcd-12ab-34cd-56ef-1234567890ab", + ] { + assert!(!is_kms_key(bad), "{bad}"); + } + } } diff --git a/services/common/src/role_move.rs b/services/common/src/role_move.rs new file mode 100644 index 000000000..84b6bb3bf --- /dev/null +++ b/services/common/src/role_move.rs @@ -0,0 +1,230 @@ +//! Moving data sources off the script-made `CoderhelmReadOnly` role and +//! onto CoderHelm's role stack (`CoderHelmLogReader`), whose one template +//! declares every read (`infra/cfn/coderhelm-log-reader.yaml`). +//! +//! The older setup script made `CoderhelmReadOnly` and wrote its policies +//! by hand, so a release could never reach it. Nothing about a working +//! connection is changed until the stack's role is proven on it: +//! +//! 1. The account's update link names every database and warehouse the +//! team's data sources read there ([`data_sources_in`]), so once an AWS +//! admin creates the update stack the stack's role may query them +//! (`aws_role_reads::role_update` says why: "N data sources still read +//! through the script-made role"). +//! 2. Each day the permissions sweep tries every such source with the +//! stack's role ([`candidate`]): the same database, user, secret and +//! log groups, only the role and the team's private ID of the account's +//! connection. Only a check that passes end to end (the role is taken +//! on, the read-only user signs in, tables are listed) switches the +//! source ([`try_move`]); anything else leaves it on the old role and +//! tries again the next day. +//! 3. The old role keeps working throughout. Once no source uses it, an +//! admin may delete it; CoderHelm never changes or deletes it. + +use crate::live::aws::{AwsTarget, LOG_READER_ROLE, ROLE_PREFIX}; +use crate::live::aws_account::AwsAccount; +use crate::live::store::Source; + +/// The target reads through a role the older script made. +pub fn is_legacy(t: &AwsTarget) -> bool { + t.role_arn + .rsplit('/') + .next() + .is_some_and(|n| n.starts_with(ROLE_PREFIX)) +} + +/// Pure: the same target on `account`'s stack role (its connection's role +/// and private ID), when `t` is a script-made role's target in that +/// account. `None` for anything else. +pub fn candidate(t: &AwsTarget, account: &AwsAccount) -> Option { + let stack_role = account.role_arn.rsplit('/').next() == Some(LOG_READER_ROLE); + (is_legacy(t) + && stack_role + && !account.external_id.is_empty() + && t.account() == account.account) + .then(|| AwsTarget { + role_arn: account.role_arn.clone(), + external_id: account.external_id.clone(), + ..t.clone() + }) +} + +/// Pure: the Aurora clusters (ARNs) and Redshift clusters (names) the +/// team's data sources read in `account`, sorted and once each: what the +/// role stack's DatabaseClusters and Warehouses must name. +pub fn data_sources_in(sources: &[Source], account: &str) -> (Vec, Vec) { + let mut dbs: Vec = Vec::new(); + let mut whs: Vec = Vec::new(); + for t in sources.iter().filter_map(|s| s.aws.as_ref()) { + if t.account() != account { + continue; + } + if !t.cluster_arn.is_empty() && !dbs.contains(&t.cluster_arn) { + dbs.push(t.cluster_arn.clone()); + } + if !t.cluster_id.is_empty() && !whs.contains(&t.cluster_id) { + whs.push(t.cluster_id.clone()); + } + } + dbs.sort(); + whs.sort(); + (dbs, whs) +} + +/// Pure: how many of the team's data sources in `account` still read +/// through a script-made role. +pub fn legacy_in(sources: &[Source], account: &str) -> usize { + sources + .iter() + .filter_map(|s| s.aws.as_ref()) + .filter(|t| t.account() == account && is_legacy(t)) + .count() +} + +/// Proves `candidate` reads what `source` reads, end to end, and returns +/// it; or why not. Nothing in the account is changed. +pub async fn try_move( + sts: &aws_sdk_sts::Client, + source: &Source, + candidate: &AwsTarget, +) -> Result { + let session = crate::live::aws::assume_exact(sts, candidate, "role-move").await; + if !candidate.cluster_id.is_empty() { + let s = session.map_err(|e| e.message)?; + let r = crate::live::redshift::connect_checks(&s, candidate).await; + return if r.ok { + Ok(candidate.clone()) + } else { + Err(first_failure(r.checks.iter().map(|c| (c.ok, &c.detail)))) + }; + } + if !candidate.cluster_arn.is_empty() { + let r = crate::live::db::connect_checks(session, candidate).await; + return if r.ok { + Ok(candidate.clone()) + } else { + Err(first_failure(r.checks.iter().map(|c| (c.ok, &c.detail)))) + }; + } + // A logs source: the log groups it names must still be listed. + let s = session.map_err(|e| e.message)?; + let groups = crate::live::logs::list_groups(&s) + .await + .map_err(|e| e.message)?; + let wanted = &source + .aws + .as_ref() + .map(|t| t.log_groups.clone()) + .unwrap_or_default(); + let all_seen = wanted.iter().all(|g| { + groups.iter().any(|lg| match g.strip_suffix('*') { + Some(p) => lg.name.starts_with(p), + None => lg.name == *g, + }) + }); + if all_seen { + Ok(candidate.clone()) + } else { + Err("the stack's role doesn't list every log group the source reads".into()) + } +} + +fn first_failure<'a>(checks: impl Iterator) -> String { + checks + .filter(|(ok, _)| !ok) + .map(|(_, d)| d.clone()) + .next() + .unwrap_or_else(|| "the check didn't pass".into()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn account() -> AwsAccount { + AwsAccount { + account: "111122223333".into(), + role_arn: "arn:aws:iam::111122223333:role/CoderHelmLogReader".into(), + external_id: "0b5f1a5e-0000-4000-8000-000000000000".into(), + region: "us-east-1".into(), + ..Default::default() + } + } + + fn db() -> AwsTarget { + AwsTarget { + role_arn: "arn:aws:iam::111122223333:role/CoderhelmReadOnly".into(), + external_id: "0b5f1a5e-0000-4000-8000-000000000000".into(), + region: "us-east-1".into(), + cluster_arn: "arn:aws:rds:us-east-1:111122223333:cluster:app-db".into(), + secret_arn: + "arn:aws:secretsmanager:us-east-1:111122223333:secret:coderhelm-readonly-app-db-AbCdEf" + .into(), + database: "app".into(), + ..Default::default() + } + } + + fn source(t: AwsTarget) -> Source { + use crate::live::connectors::{ConnKind, Connector}; + let mut s = Source::from_connection(&Connector::new(ConnKind::Rest), "x").unwrap(); + s.aws = Some(t); + s + } + + #[test] + fn a_script_made_source_moves_to_the_stack_role_with_the_same_database() { + let c = candidate(&db(), &account()).expect("a candidate"); + assert_eq!( + c.role_arn, + "arn:aws:iam::111122223333:role/CoderHelmLogReader" + ); + // Everything that names the data stays the same. + assert_eq!(c.cluster_arn, db().cluster_arn); + assert_eq!(c.secret_arn, db().secret_arn); + assert_eq!(c.database, "app"); + assert!(crate::live::aws::check_target(&c).is_ok()); + // Only a script-made role, only in the account, only onto the stack's role. + let on_stack = AwsTarget { + role_arn: account().role_arn, + ..db() + }; + assert!(candidate(&on_stack, &account()).is_none()); + let elsewhere = AwsTarget { + role_arn: "arn:aws:iam::444455556666:role/CoderhelmReadOnly".into(), + ..db() + }; + assert!(candidate(&elsewhere, &account()).is_none()); + let mut no_id = account(); + no_id.external_id.clear(); + assert!(candidate(&db(), &no_id).is_none()); + } + + #[test] + fn the_update_link_names_every_database_and_warehouse_in_the_account() { + let wh = AwsTarget { + role_arn: "arn:aws:iam::111122223333:role/CoderhelmReadOnly".into(), + region: "us-east-1".into(), + engine: "redshift".into(), + cluster_id: "analytics".into(), + db_user: "coderhelm_readonly".into(), + databases: vec!["dev".into()], + ..Default::default() + }; + let other = AwsTarget { + cluster_arn: "arn:aws:rds:us-east-1:444455556666:cluster:x".into(), + role_arn: "arn:aws:iam::444455556666:role/CoderhelmReadOnly".into(), + ..db() + }; + let sources = vec![source(db()), source(db()), source(wh), source(other)]; + let (dbs, whs) = data_sources_in(&sources, "111122223333"); + assert_eq!(dbs, vec![db().cluster_arn]); + assert_eq!(whs, vec!["analytics".to_string()]); + assert_eq!(legacy_in(&sources, "111122223333"), 3); + let mut a = account(); + a.database_clusters = dbs; + a.warehouses = whs; + let u = crate::log_reader::update_url("https://b/x/y.yaml", "us-east-1", &a.chosen()); + assert!(u.contains("param_DatabaseClusters=") && u.contains("param_Warehouses=analytics")); + } +} diff --git a/services/gateway/src/routes/data_sources.rs b/services/gateway/src/routes/data_sources.rs index efe66fea9..81646f5bf 100644 --- a/services/gateway/src/routes/data_sources.rs +++ b/services/gateway/src/routes/data_sources.rs @@ -1585,12 +1585,18 @@ pub async fn aws_setup( .and_then(|o| o.account().map(str::to_string)) .ok_or_else(|| internal("read our account id", "no account".into()))?; Ok(Json(json!({ - "script": live_aws::setup_script(&our_account, &ext), + // The database user is made inside the database; the role's + // permissions only through CoderHelm's role stack, from this + // release's template. + "script": live_aws::setup_script( + &our_account, + &ext, + &common::public_urls::log_reader_template_url(), + &common::log_reader::trusted_role_prefix(), + ), "existing": existing_connections(&state, &claims.team_id).await, "role_prefix": live_aws::ROLE_PREFIX, - // For a role made before the WAF reads: the one line that adds - // only those (the install's "AWS role reads" setup item). - "waf_update": live_aws::waf_update_line(live_aws::ROLE_PREFIX), + "role_name": live_aws::LOG_READER_ROLE, }))) } diff --git a/services/gateway/src/routes/integrations.rs b/services/gateway/src/routes/integrations.rs index 8158afce1..e5f519ead 100644 --- a/services/gateway/src/routes/integrations.rs +++ b/services/gateway/src/routes/integrations.rs @@ -1405,6 +1405,8 @@ async fn load_account( let kbs = common::knowledge::remote::arns_in(&team_bases(state, team_id).await, account); let buckets = common::knowledge::sources::s3::buckets_in(&team_sources(state, team_id).await, account); + let (dbs, whs) = + common::role_move::data_sources_in(&team_data_sources(state, team_id).await, account); aws_account::list( &state.dynamo, &state.config.aws_insights_table_name, @@ -1418,22 +1420,38 @@ async fn load_account( .map(|mut a| { a.knowledge_bases = kbs; a.import_buckets = buckets; + a.database_clusters = dbs; + a.warehouses = whs; a }) } -/// Each account's connected knowledge bases and import buckets, so its -/// update link keeps the role able to search and read them. -async fn with_knowledge_bases( +/// The team's data sources (the databases and warehouses its accounts' +/// role stacks must name). +pub(crate) async fn team_data_sources( + state: &AppState, + team_id: &str, +) -> Vec { + common::live::store::list_sources(&state.dynamo, &state.config.settings_table_name, team_id) + .await + .unwrap_or_default() +} + +/// Each account's connected knowledge bases, import buckets and data +/// sources' databases and warehouses, so its update link keeps the role +/// able to search, read and query them. +pub(crate) async fn with_knowledge_bases( state: &AppState, team_id: &str, accounts: &mut [AwsAccount], ) -> Vec { let bases = team_bases(state, team_id).await; let sources = team_sources(state, team_id).await; + let data = team_data_sources(state, team_id).await; for a in accounts { a.knowledge_bases = common::knowledge::remote::arns_in(&bases, &a.account); a.import_buckets = common::knowledge::sources::s3::buckets_in(&sources, &a.account); + (a.database_clusters, a.warehouses) = common::role_move::data_sources_in(&data, &a.account); } sources } diff --git a/services/gateway/src/routes/setup_checks.rs b/services/gateway/src/routes/setup_checks.rs index d541b630e..7c9b7b751 100644 --- a/services/gateway/src/routes/setup_checks.rs +++ b/services/gateway/src/routes/setup_checks.rs @@ -1005,66 +1005,92 @@ pub fn aws_connections( } } -/// Reads an alert route needs that a team's connected AWS role was -/// refused (`common::aws_role_reads`): one item for the whole install, -/// with the one line that adds them in AWS CloudShell. Never a failure, -/// and never a question on a run: alarm runs go on with what they could -/// read until it is done. Passes when every connected role read what it -/// was asked to. -pub fn aws_role_reads(gaps: &[common::aws_role_reads::Gap]) -> Check { +/// Every connected AWS account whose role stack needs this release's +/// one-click update (`common::aws_role_reads::role_update`): a read an +/// alert route needed was refused (the WAF log group for a WAF alarm), the +/// role is older than this release, or data sources still read through the +/// script-made role. One item for the whole install, with the update link, +/// which an AWS admin of the account reviews and creates: a release never +/// widens a team's role by itself. Never a failure, and never a question on +/// a run: runs go on with what they can read until it is done. +pub fn aws_role_reads(updates: &[common::aws_role_reads::RoleUpdate]) -> Check { use common::aws_role_reads::{CHECK_KEY, ITEM_LABEL}; - let Some(first) = gaps.first() else { + let Some(first) = updates.first() else { return Check::pass( CHECK_KEY, X, ITEM_LABEL, - "Every connected AWS role has the reads its alert routes used.", + "Every connected AWS account's role stack has the reads this release and its alert routes use.", ); }; - let accounts: Vec<&str> = gaps.iter().map(|g| g.account.as_str()).collect(); - let mut actions: Vec<&str> = Vec::new(); - for a in gaps.iter().flat_map(|g| g.actions.iter()) { - if !actions.contains(&a.as_str()) { - actions.push(a); - } - } - let role = if first.role_arn.is_empty() { - format!( - "arn:aws:iam::{}:role/{}", - first.account, - common::live::aws::ROLE_PREFIX - ) + let detail = updates + .iter() + .map(|u| format!("Account {}: {}.", u.account, u.reasons.join("; "))) + .collect::>() + .join(" "); + let adds = if first.adds.is_empty() { + "this release's reads".to_string() } else { - first.role_arn.clone() + first.adds.join(", ") }; - let mut fix = Fix::text(format!( - "Paste this one line into AWS CloudShell in account {} (in the region of its WAF log \ - Athena workgroup). It adds the read-only {} policy to the role: AWS WAF reads, and \ - queries of the WAF logs through Athena with results only under the workgroup's own \ - results prefix.", - accounts.join(", "), - common::live::aws::WAF_POLICY_NAME - )) - .url("https://docs.coderhelm.com/self-host/integrations#connected-aws-accounts"); - if let Some(line) = common::live::aws::waf_update_line(&role) { - fix = fix.command(line); + let mut text = format!( + "An AWS admin of account {} opens this link signed in to that account, reviews it and \ + presses Create stack ({}). It updates CoderHelm's read-only role from this release's \ + template, adding: {adds}. Every read it adds is listed with its reason on Settings, \ + Integrations, AWS.", + first.account, first.stack_name + ); + if updates.len() > 1 { + let others: Vec<&str> = updates[1..].iter().map(|u| u.account.as_str()).collect(); + text.push_str(&format!( + " Accounts {} have their own link on that page.", + others.join(", ") + )); } Check::not_ok( Status::Warn, CHECK_KEY, X, ITEM_LABEL, - format!( - "CoderHelm's AWS role in account {} was refused {} ({}).", - accounts.join(", "), - actions.join(", "), - first.needed_for - ), - "Alarm runs read what the role allows and go on without the rest; no run asks for this.", - fix, + detail, + "Runs read what the role allows and go on without the rest; no run asks for this.", + Fix::text(text).url(first.url.clone()), ) } +/// The update each connected account's role stack needs, from the +/// accounts (with what the team chose in each), the reads runs were +/// refused and the team's data sources. +async fn aws_role_updates( + state: &AppState, + team_id: &str, +) -> Vec { + let Some(template) = + common::log_reader::update_template_url(&common::public_urls::log_reader_template_url()) + else { + return Vec::new(); + }; + let (accounts, gaps, sources) = tokio::join!( + common::live::aws_account::list( + &state.dynamo, + &state.config.aws_insights_table_name, + team_id + ), + common::aws_role_reads::list(&state.dynamo, &state.config.settings_table_name, team_id), + super::integrations::team_data_sources(state, team_id), + ); + let mut accounts = accounts.unwrap_or_default(); + super::integrations::with_knowledge_bases(state, team_id, &mut accounts).await; + accounts + .iter() + .filter_map(|a| { + let gap = gaps.iter().find(|g| g.account == a.account); + let legacy = common::role_move::legacy_in(&sources, &a.account); + common::aws_role_reads::role_update(a, gap, legacy, &template) + }) + .collect() +} + // ── Your own domain ─────────────────────────────────────────────────────── // // The updater requests the certificate and moves the domain along @@ -2048,7 +2074,7 @@ async fn integration_checks(state: &AppState, team_id: &str) -> Vec { super::api::load_jira_secret(state, team_id), get_item(state, &state.config.jira_config_table_name, &jira_key), aws_connections_check(state), - common::aws_role_reads::list(&state.dynamo, &state.config.settings_table_name, team_id), + aws_role_updates(state, team_id), ); let forge = jira_config.as_ref().is_some_and(|i| { i.get("add_comment_url") @@ -2894,44 +2920,58 @@ mod tests { } #[test] - fn a_read_the_aws_role_lacks_is_one_install_item_with_the_update_line() { + fn a_read_the_aws_role_lacks_is_one_install_item_with_the_update_link() { use super::{aws_role_reads, Status}; - use common::aws_role_reads::Gap; + use common::aws_role_reads::{role_update, Gap}; + use common::live::aws_account::AwsAccount; let ok = aws_role_reads(&[]); assert_eq!(ok.status, Status::Pass); + let account = |id: &str| AwsAccount { + account: id.into(), + role_arn: format!("arn:aws:iam::{id}:role/CoderHelmLogReader"), + region: "us-east-1".into(), + ..Default::default() + }; let gap = Gap { account: "111122223333".into(), - role_arn: "arn:aws:iam::111122223333:role/CoderhelmReadOnly".into(), - actions: vec![ - "wafv2:ListWebACLs".into(), - "wafv2:GetSampledRequests".into(), - ], + role_arn: "arn:aws:iam::111122223333:role/CoderHelmLogReader".into(), + actions: vec!["glue:GetDatabases".into()], needed_for: "an AWS WAF alarm's evidence".into(), - seen_at: "2026-11-17T10:00:00Z".into(), + ..Default::default() }; - let c = aws_role_reads(&[ - gap.clone(), - Gap { - account: "444455556666".into(), - ..gap - }, - ]); + let t = "https://b.s3.amazonaws.com/launch/v1.2.3/coderhelm-log-reader-update.yaml"; + let updates = vec![ + role_update(&account("111122223333"), Some(&gap), 0, t).unwrap(), + role_update(&account("444455556666"), None, 2, t).unwrap(), + ]; + let c = aws_role_reads(&updates); // A warning for the install, never a failure that blocks an update. assert_eq!(c.status, Status::Warn); assert_eq!(c.key, "aws_role_reads"); assert!( - c.detail.contains("111122223333, 444455556666"), + c.detail.contains( + "Account 111122223333: The role CoderHelmLogReader was refused glue:GetDatabases" + ), + "{}", + c.detail + ); + assert!( + c.detail + .contains("Account 444455556666: 2 data sources still read"), "{}", c.detail ); - assert!(c - .detail - .contains("wafv2:ListWebACLs, wafv2:GetSampledRequests")); assert!(c.why.contains("no run asks")); let fix = c.fix.unwrap(); - let line = fix.command.unwrap(); - assert!(line.ends_with(" | base64 -d | bash") && !line.contains('\n')); - assert!(fix.text.contains("coderhelm-read-waf")); + // The one-click stack update, never a script to paste. + assert!(fix.command.is_none()); + let url = fix.url.unwrap(); + assert!( + url.contains("#/stacks/quickcreate?") && url.contains("param_WafLogs=on"), + "{url}" + ); + assert!(fix.text.contains("AWS WAF logs in S3") && fix.text.contains("Create stack")); + assert!(fix.text.contains("444455556666")); } #[test] diff --git a/services/worker/src/passes/aws_permissions.rs b/services/worker/src/passes/aws_permissions.rs index 1793f02d2..3819410f6 100644 --- a/services/worker/src/passes/aws_permissions.rs +++ b/services/worker/src/passes/aws_permissions.rs @@ -4,6 +4,11 @@ //! tells each team once per new set of permissions when an account needs //! the update (where the team's notifications post: Slack, Teams). //! +//! The same sweep moves data sources off the script-made +//! `CoderhelmReadOnly` role onto the account's role stack +//! (`common::role_move`): a source switches only when the stack's role +//! passed the source's own connection check end to end. +//! //! "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. @@ -24,6 +29,8 @@ 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, } /// Every connected account, by team. @@ -112,6 +119,48 @@ async fn told(state: &WorkerState, team_id: &str) -> Option { .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 +/// the next sweep. Returns how many moved. +async fn move_sources(state: &WorkerState, team_id: &str, accounts: &[AwsAccount]) -> usize { + use common::live::store; + use common::role_move; + let table = &state.config.settings_table_name; + let Ok(sources) = store::list_sources(&state.dynamo, table, team_id).await else { + return 0; + }; + let mut moved = 0; + for src in &sources { + let Some(t) = src.aws.as_ref() else { continue }; + let Some(account) = accounts.iter().find(|a| a.account == t.account()) else { + continue; + }; + let Some(candidate) = role_move::candidate(t, account) else { + continue; + }; + match role_move::try_move(&state.sts, src, &candidate).await { + Ok(next) => { + let mut s = src.clone(); + s.aws = Some(next); + match store::put_source(&state.dynamo, table, team_id, &s).await { + Ok(()) => { + moved += 1; + info!(team_id, source = %src.id, account = %account.account, "Data source moved onto the account's role stack"); + } + Err(e) => { + warn!(team_id, source = %src.id, error = %e, "Could not save the moved data source") + } + } + } + Err(why) => { + info!(team_id, source = %src.id, account = %account.account, why = %why, "Data source stays on the script-made role until the role stack reads it") + } + } + } + moved +} + pub async fn run(state: &WorkerState) -> Result { let teams = accounts_by_team(state).await?; let mut report = Report::default(); @@ -136,6 +185,7 @@ pub async fn run(state: &WorkerState) -> Result { } checks.push(c); } + report.sources_moved += move_sources(state, team_id, accounts).await; let last = told(state, team_id).await; if !should_tell(&checks, last.as_deref()) || !claim_notice(state, team_id).await { continue; @@ -180,6 +230,7 @@ pub async fn run(state: &WorkerState) -> Result { accounts = report.accounts, need_update = report.need_update, teams_told = report.teams_told, + sources_moved = report.sources_moved, "AWS permissions sweep" ); Ok(report) diff --git a/services/worker/src/passes/incidents/bo_alarm_reads_its_evidence.rs b/services/worker/src/passes/incidents/bo_alarm_reads_its_evidence.rs index cf9a7b5a7..63c5432d9 100644 --- a/services/worker/src/passes/incidents/bo_alarm_reads_its_evidence.rs +++ b/services/worker/src/passes/incidents/bo_alarm_reads_its_evidence.rs @@ -8,13 +8,14 @@ //! setup script had never added any WAF read. The web ACL logs to an //! `aws-waf-logs-*` bucket with an Athena table, and nothing read it. //! -//! Guarantee: the role's setup script adds `coderhelm-read-waf` (WAF reads, -//! Athena queries over the WAF log tables with results only under the -//! workgroup's results prefix). With those reads the run gathers the rule's -//! matches (sampled requests, and the logs in S3 by JA4, JA3, user agent, -//! accept language, path and cookie presence) before it plans, and goes on -//! to its pull request. Without them, the refusal is the install's one -//! setup item ("AWS role reads", with the one-line CloudShell update), +//! Guarantee: the role stack's template has the WAF reads, and a WAF log +//! group (`WafLogs`: Athena queries over the WAF log tables with results +//! only under the workgroup's results location). With those reads the run +//! gathers the rule's matches (sampled requests, and the logs in S3 by JA4, +//! JA3, user agent, accept language, path and cookie presence) before it +//! plans, and goes on to its pull request. Without them, the refusal is the +//! install's one setup item ("AWS role reads", with the role stack's +//! one-click update, `cw_role_reads_arrive_by_stack_update`), //! never a question or a wait on the run: the stop judge turns such an ask //! or hold into a proceed, the hand-back list doesn't carry it, and an //! access question never shows a default that can't happen. @@ -193,8 +194,8 @@ fn without_waf_reads_no_question_and_one_install_item() { // One short line in the run names the install's setup item. assert!(got.text.contains("\"AWS role reads\"")); assert!(got.text.contains("asks nobody")); - // The install-level item exists, with the one-line update for the role. - let role = "arn:aws:iam::111122223333:role/CoderhelmReadOnly"; + // The install-level item exists, with the role stack's update. + let role = "arn:aws:iam::111122223333:role/CoderHelmLogReader"; let gap = aws_role_reads::gap( "111122223333", role, @@ -204,8 +205,20 @@ fn without_waf_reads_no_question_and_one_install_item() { ) .expect("the install item"); assert_eq!(gap.actions, refused); - let line = common::live::aws::waf_update_line(&gap.role_arn).unwrap(); - assert!(line.ends_with("| base64 -d | bash")); + let account = common::live::aws_account::AwsAccount { + account: "111122223333".into(), + role_arn: role.into(), + region: "us-east-1".into(), + ..Default::default() + }; + let u = aws_role_reads::role_update( + &account, + Some(&gap), + 0, + "https://b/launch/v1/coderhelm-log-reader-update.yaml", + ) + .expect("the update"); + assert!(u.url.contains("#/stacks/quickcreate?")); let checks = include_str!("../../../../gateway/src/routes/setup_checks.rs"); assert!(checks.contains("aws_role_reads(&gaps)")); assert!(checks.contains("common::aws_role_reads::list(")); diff --git a/services/worker/src/passes/incidents/cw_role_reads_arrive_by_stack_update.rs b/services/worker/src/passes/incidents/cw_role_reads_arrive_by_stack_update.rs new file mode 100644 index 000000000..0a2a201d5 --- /dev/null +++ b/services/worker/src/passes/incidents/cw_role_reads_arrive_by_stack_update.rs @@ -0,0 +1,242 @@ +//! cw. A team's read-only AWS role is behind the release, and an alert +//! route sends it AWS WAF alarms. The WAF reads of the alarm runs were +//! first added to a CloudShell setup script (`coderhelm-read-waf`) with a +//! one-line update shown as a setup item: every team had to find and paste +//! a script for each new read, the script patched a role CloudFormation had +//! made, and it added the reads to the data-source role `CoderhelmReadOnly` +//! while the alarm runs read through `CoderHelmLogReader`. A release can't +//! add a read itself: CoderHelm's own roles may not change IAM. +//! +//! Guarantee: every read is declared in the role stack's one versioned +//! template, as named groups a stack parameter switches on (the WAF log +//! group `WafLogs`, `DatabaseClusters`, `Warehouses`). A WAF alarm run on +//! the old role reads what it may, records what it was refused and what it +//! found (the log bucket's KMS key, the workgroup's results location), and +//! asks nobody. The install's one item, "AWS role reads", is the release's +//! one-click update of that stack with those filled in, which an AWS admin +//! of the account creates. Data sources the old script made move onto the +//! stack's role only once it reads them end to end. + +use common::alarm_evidence::{self as ae}; +use common::aws_role_reads::{self, Gap}; +use common::live::aws::AwsTarget; +use common::live::aws_account::AwsAccount; +use common::log_reader::{self, UPDATE_TEMPLATE}; +use common::stop_judge::{self as sj, JudgeModel, Kind, Picture}; +use serde_json::{json, Value}; +use std::sync::Mutex; + +const ACCOUNT: &str = "111122223333"; +const KEY: &str = "arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"; +const RELEASE_UPDATE: &str = + "https://coderhelm-public.s3.amazonaws.com/launch/v1.2.3/coderhelm-log-reader-update.yaml"; + +/// The ticket the alert route wrote for the alarm. +const TICKET: &str = "- Alarm: acme-crawler-a-signature-drift\n\ + - State: ALARM (was OK)\n\ + - Metric: AWS/WAFV2 / CountedRequests\n\ + - Dimensions: WebACL=acme-web-acl, Rule=CrawlerASignatureCount\n"; + +struct Recorded(Mutex>); + +impl JudgeModel for Recorded { + async fn answer(&self, _: &str, _: &str, _: &Value) -> Result { + self.0.lock().unwrap().pop().ok_or_else(|| "no more".into()) + } +} + +fn run(f: F) -> F::Output { + tokio::runtime::Builder::new_current_thread() + .enable_time() + .build() + .unwrap() + .block_on(f) +} + +/// The team's connected account: its role stack made from an older +/// release's template (one read of this release missing), nothing chosen. +fn old_role() -> AwsAccount { + let mut a = AwsAccount { + account: ACCOUNT.into(), + role_arn: format!("arn:aws:iam::{ACCOUNT}:role/CoderHelmLogReader"), + external_id: "0b5f1a5e-0000-4000-8000-000000000000".into(), + region: "us-east-1".into(), + ..Default::default() + }; + let mut c = common::live::permissions::PermissionCheck::new(&a.target(), "t"); + c.works = true; + c.missing = vec!["ecs:DescribeTasks".into()]; + a.permissions = Some(c); + a +} + +/// The `param_=` pairs of a quick-create link. +fn params(url: &str) -> Vec<(String, String)> { + url.split(['?', '&']) + .filter_map(|p| p.strip_prefix("param_")) + .filter_map(|p| p.split_once('=')) + .map(|(k, v)| (k.to_string(), urlencoding::decode(v).unwrap().into_owned())) + .collect() +} + +/// The update template's parameters, with the pattern each must match. +fn template_params() -> Vec<(String, Option)> { + let t: serde_yaml::Value = serde_yaml::from_str(UPDATE_TEMPLATE).expect("the template parses"); + t["Parameters"] + .as_mapping() + .unwrap() + .iter() + .map(|(k, v)| { + ( + k.as_str().unwrap().to_string(), + v["AllowedPattern"].as_str().map(str::to_string), + ) + }) + .collect() +} + +/// The link opens CloudFormation's quick-create of this release's update +/// template, and every value it fills is one the template accepts. +fn assert_works(url: &str) { + assert!(url.starts_with( + "https://console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/quickcreate?" + )); + assert!(url.contains(&format!( + "templateURL={}", + urlencoding::encode(RELEASE_UPDATE) + ))); + let declared = template_params(); + for (k, v) in params(url) { + let (_, pattern) = declared + .iter() + .find(|(n, _)| *n == k) + .unwrap_or_else(|| panic!("{k} isn't a parameter of the update template")); + if let Some(p) = pattern { + assert!( + regex::Regex::new(p).unwrap().is_match(&v), + "{k}={v} fails {p}" + ); + } + } +} + +#[test] +fn an_old_role_with_a_waf_alert_route_gets_one_working_update_and_no_question() { + let alarm = ae::waf_alarm(TICKET).expect("a WAF alarm"); + // First run on the old role: WAF's own reads work, the log tables are + // refused; the bucket's settings read gave its KMS key. + let refused = vec!["glue:GetDatabases".to_string()]; + let mut got = ae::evidence( + &alarm, + vec!["Couldn't list the Glue databases: CoderHelm's AWS role doesn't allow glue:GetDatabases yet.".into()], + refused.clone(), + ); + got.logs_to_s3 = true; + got.waf_log_key = KEY.into(); + assert!(got.text.contains("\"AWS role reads\"") && got.text.contains("asks nobody")); + assert!(!got.text.contains("CloudShell")); + // The worker records it with what it found. + let gap = Gap { + waf_log_results: got.waf_log_results.clone(), + waf_log_key: got.waf_log_key.clone(), + ..aws_role_reads::gap( + ACCOUNT, + &old_role().role_arn, + &got.refused, + "an AWS WAF alarm's evidence", + "t", + ) + .unwrap() + }; + let worker = include_str!("../mod.rs"); + assert!(worker.contains("waf_log_key: got.waf_log_key.clone()")); + assert!(worker.contains("remember_waf_logs(state, &msg.team_id, &account, &got)")); + // One item: the role is behind the release and the WAF log group is needed. + let u = + aws_role_reads::role_update(&old_role(), Some(&gap), 0, RELEASE_UPDATE).expect("one item"); + assert_works(&u.url); + let p = params(&u.url); + assert!(p.contains(&("WafLogs".into(), "on".into()))); + assert!(p.contains(&("WafLogKey".into(), KEY.into()))); + assert!(p.contains(&("RoleName".into(), "CoderHelmLogReader".into()))); + assert!(u + .reasons + .iter() + .any(|r| r.contains("older than this release"))); + assert!(u.adds.contains(&"AWS WAF logs in S3")); + assert!(u.stack_name.starts_with(&log_reader::update_stack_name())); + // The next run, with the group on but no results location yet, found + // the workgroup's and was refused the query: the next link names it. + let mut stored = old_role(); + stored.permissions = None; + stored.waf_logs = true; + stored.waf_log_key = KEY.into(); + let later = Gap { + actions: vec!["athena:StartQueryExecution".into()], + waf_log_results: log_reader::waf_log_results("s3://aws-waf-logs-acme/athena-results/") + .unwrap(), + ..gap.clone() + }; + let u2 = aws_role_reads::role_update(&stored, Some(&later), 0, RELEASE_UPDATE).unwrap(); + assert_works(&u2.url); + assert!(params(&u2.url).contains(&( + "WafLogResults".into(), + "aws-waf-logs-acme/athena-results/".into() + ))); + // A later release's ordinary update keeps the group on. + stored.waf_log_results = later.waf_log_results.clone(); + let plain = log_reader::update_url(RELEASE_UPDATE, "us-east-1", &stored.chosen()); + assert!(plain.contains("param_WafLogs=on") && plain.contains("param_WafLogResults=")); + // The run asks nobody: its access question becomes a proceed. + let ask = json!({"verdict":"ask","assumption":"","person_only":"access", + "question":"Can someone grant the team's read-only role Glue and Athena access? glue:GetDatabases was denied for CoderHelm's role.", + "tried":["glue:GetDatabases was denied"],"options":["Grant access"],"default":"Grant access", + "deadline_hours":4,"blocker":"","evidence":[],"category":"","location":""}); + let m = Recorded(Mutex::new(vec![ask.clone(), ask])); + let mut pic = Picture::new(Kind::Ask, "plan", "the planner asks before it can plan"); + pic.ticket_body = got.text.clone(); + let j = run(sj::judge(&m, pic)); + assert!(j.proceeds(), "{:?}", j.verdict()); + assert!(j.run_question().is_none()); +} + +#[test] +fn no_script_writes_a_permission_and_the_script_role_moves_over() { + // The pasted script only makes the database user and creates or updates + // the role stack from this release's template. + let s = common::live::aws::setup_script( + "654654210434", + "0b5f1a5e-0000-4000-8000-000000000000", + "https://coderhelm-public.s3.amazonaws.com/launch/v1.2.3/coderhelm-log-reader.yaml", + "", + ); + assert!(!s.contains("put-role-policy") && !s.contains("create-role")); + assert!(s.contains("aws cloudformation update-stack") && s.contains("UsePreviousValue")); + // A database source on the script-made role: the update link names its + // cluster, and it moves only onto the account's stack role. + let src = AwsTarget { + role_arn: format!("arn:aws:iam::{ACCOUNT}:role/CoderhelmReadOnly"), + region: "us-east-1".into(), + cluster_arn: format!("arn:aws:rds:us-east-1:{ACCOUNT}:cluster:app-db"), + secret_arn: format!( + "arn:aws:secretsmanager:us-east-1:{ACCOUNT}:secret:coderhelm-readonly-app-db-AbCdEf" + ), + database: "app".into(), + ..Default::default() + }; + let mut a = old_role(); + a.permissions = None; + a.database_clusters = vec![src.cluster_arn.clone()]; + let u = aws_role_reads::role_update(&a, None, 1, RELEASE_UPDATE) + .expect("the move is the same item"); + assert_works(&u.url); + assert!(u.reasons[0].contains("CoderhelmReadOnly")); + let next = common::role_move::candidate(&src, &a).unwrap(); + assert_eq!(next.role_arn, a.role_arn); + assert_eq!(next.cluster_arn, src.cluster_arn); + // The sweep switches a source only after its own check passed. + let sweep = include_str!("../aws_permissions.rs"); + let tried = sweep.find("role_move::try_move(").unwrap(); + let saved = sweep.find("store::put_source(").unwrap(); + assert!(tried < saved); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 6d43d8302..b4298ac25 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1934,6 +1934,39 @@ async fn read_ticket_comments( Ok(()) } +/// Turns the account's WAF log group on and keeps what a WAF alarm run +/// found (best effort): the account's update link carries them from then on. +async fn remember_waf_logs( + state: &WorkerState, + team_id: &str, + account: &str, + got: &common::alarm_evidence::Gathered, +) { + use common::live::aws_account; + let table = &state.config.aws_insights_table_name; + let stored = aws_account::list(&state.dynamo, table, team_id) + .await + .unwrap_or_default() + .into_iter() + .find(|a| a.account == account); + let Some(stored) = stored else { return }; + let (results, key) = aws_account::waf_logs_after( + &stored.waf_log_results, + &stored.waf_log_key, + &got.waf_log_results, + &got.waf_log_key, + ); + let same = stored.waf_logs && results == stored.waf_log_results && key == stored.waf_log_key; + if same { + return; + } + if let Err(e) = + aws_account::save_waf_logs(&state.dynamo, table, team_id, account, &results, &key).await + { + warn!(team_id, account, error = %e, "Could not save the account's WAF log settings"); + } +} + /// The evidence a run an alert rule started (it has the rule's repo) reads /// before planning, when its alarm is an AWS WAF alarm: through the team's /// read-only connection to the alarm's account (the alert's topic is in it). @@ -1976,6 +2009,12 @@ async fn alarm_evidence_for_run(state: &WorkerState, msg: &TicketMessage) -> Opt Some(match session { Ok(Some(s)) => { let got = ae::gather(&s, &alarm, chrono::Utc::now()).await; + // The web ACL logs to S3: the account's role stack keeps its + // WAF log group on from now on, with the results location and + // key this run found, so every later update link carries them. + if got.logs_to_s3 { + remember_waf_logs(state, &msg.team_id, &account, &got).await; + } // A refused read is the install's setup item, recorded once for // the account; a read that works again clears it. let table = &state.config.settings_table_name; @@ -1995,7 +2034,12 @@ async fn alarm_evidence_for_run(state: &WorkerState, msg: &TicketMessage) -> Opt &got.refused, "an AWS WAF alarm's evidence", &chrono::Utc::now().to_rfc3339(), - ) { + ) + .map(|g| common::aws_role_reads::Gap { + waf_log_results: got.waf_log_results.clone(), + waf_log_key: got.waf_log_key.clone(), + ..g + }) { common::aws_role_reads::record(&state.dynamo, table, &msg.team_id, &gap).await; } info!(team_id = %msg.team_id, account = %account, refused = ?got.refused, "AWS role lacks reads an alert route needs: install setup item");