diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9e4a581b8..ab692e788 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -181,12 +181,19 @@ jobs: # The publish job uploads this same launch-stack.yaml to S3. node selfhost/launch/stamp-template.mjs infra/cfn/coderhelm-selfhost-launch.yaml "$TAG" > dist/launch-stack.yaml cp selfhost/launch/bootstrap.mjs dist/launch-bootstrap.mjs + # The read-only role teams create in their own AWS accounts, and the + # stack that brings an existing role up to date: byte for byte the + # templates built into this release's gateway + # (services/common/src/log_reader.rs), published by version so a + # self-hosted install's Launch Stack links match its code. + cp infra/cfn/coderhelm-log-reader.yaml dist/coderhelm-log-reader.yaml + cp infra/cfn/coderhelm-log-reader-update.yaml dist/coderhelm-log-reader-update.yaml # The models this release calls, read from the code, with their # Bedrock ids per inference profile prefix. In the signed # SHA256SUMS: the updater reads it only through the update build, # after the signature check (lambda/updater, model_check). node selfhost/launch/release-models.mjs "$TAG" > dist/models.json - (cd dist && sha256sum gateway.zip worker.zip mcp-proxy.zip dashboard.tar.gz source.tar.gz coderhelm-selfhost.tgz install.sh launch-stack.yaml launch-bootstrap.mjs models.json > SHA256SUMS) + (cd dist && sha256sum gateway.zip worker.zip mcp-proxy.zip dashboard.tar.gz source.tar.gz coderhelm-selfhost.tgz install.sh launch-stack.yaml launch-bootstrap.mjs models.json coderhelm-log-reader.yaml coderhelm-log-reader-update.yaml > SHA256SUMS) cat dist/SHA256SUMS # The release's own CDK app synthesizes for a fresh self-host config. @@ -264,6 +271,8 @@ jobs: dist/launch-bootstrap.mjs dist/launch-stack.yaml dist/models.json + dist/coderhelm-log-reader.yaml + dist/coderhelm-log-reader-update.yaml # A published release's files are never replaced: a re-run only fills in # a release that has no SHA256SUMS yet (one made by hand, without @@ -298,7 +307,7 @@ jobs: role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_ID }}:role/coderhelm-prod-release-publisher role-duration-seconds: 3600 aws-region: us-east-1 - - name: Upload the template and latest.json + - name: Upload the templates and latest.json run: | key="launch/$TAG/coderhelm-launch.yaml" url="https://$PUBLIC_BUCKET.s3.amazonaws.com/$key" @@ -309,6 +318,16 @@ jobs: aws s3api put-object --bucket "$PUBLIC_BUCKET" --key "$key" --body dist/launch-stack.yaml --if-none-match '*' \ --content-type text/yaml --cache-control "public, max-age=31536000, immutable" >/dev/null fi + # The AWS role templates, by version, written once the same way. + for f in coderhelm-log-reader.yaml coderhelm-log-reader-update.yaml; do + k="launch/$TAG/$f" + if curl --proto =https -fsSL -o "$RUNNER_TEMP/existing-$f" "https://$PUBLIC_BUCKET.s3.amazonaws.com/$k"; then + cmp -s "$RUNNER_TEMP/existing-$f" "dist/$f" || { echo "::error::$k already holds another template"; exit 1; } + else + aws s3api put-object --bucket "$PUBLIC_BUCKET" --key "$k" --body "dist/$f" --if-none-match '*' \ + --content-type text/yaml --cache-control "public, max-age=31536000, immutable" >/dev/null + fi + done # Pre-releases (v1.2.3-rc.1) are published by version but never become latest, # and latest.json only ever moves forward. if [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then diff --git a/docs/self-host/check-your-install.md b/docs/self-host/check-your-install.md index d0fb5663e..53060a4ec 100644 --- a/docs/self-host/check-your-install.md +++ b/docs/self-host/check-your-install.md @@ -219,7 +219,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_installations`, `github_webhook`, `email_identity`, `email_sandbox`, `model`, `dlq`, `updates`, `slack`, `teams`, `jira`, `google_sign_in`. +`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_installations`, `github_webhook`, `email_identity`, `email_sandbox`, `model`, `dlq`, `updates`, `slack`, `teams`, `jira`, `aws_connections`, `google_sign_in`. ### `GET /api/system/domain`, `PUT /api/system/domain`, `DELETE /api/system/domain` diff --git a/docs/self-host/config-reference.md b/docs/self-host/config-reference.md index a07bf545e..0663c1e5b 100644 --- a/docs/self-host/config-reference.md +++ b/docs/self-host/config-reference.md @@ -141,8 +141,8 @@ These are the starting point; admins change them in **Settings, then System** wi Anonymous install, upgrade and health pings from the installer. - **`telemetry.endpoint`** *string, default CoderHelm's*\ Where pings go. -- **`logReaderTemplateUrl`** *string, default CoderHelm's public copy*\ - The CloudFormation template teams create the log reader role from. +- **`logReaderTemplateUrl`** *string, default this release's published copy*\ + The CloudFormation template teams create the read-only AWS role from. By default a release links to the copy published with it (`https://coderhelm-public.s3.amazonaws.com/launch//coderhelm-log-reader.yaml`, byte for byte the template built into that release); a development build links to CoderHelm's current copy. To host it yourself, put this release's `infra/cfn/coderhelm-log-reader.yaml` and `coderhelm-log-reader-update.yaml` side by side in an S3 bucket and set this to the first one's URL. Setup checks compare both with the release. - **`publicBucketName`** *string or null, default `null`*\ Create a public bucket that serves the templates in `infra/cfn` (the hosted deployment does). - **`siteUrl`** *string or null, default `null`*\ @@ -164,8 +164,9 @@ The CDK app turns the config into environment variables on the gateway, streamin | `PUBLIC_URL_PARAMETER` | The SSM parameter that holds the CloudFront URL, when you have no domain | | `SELF_HOSTED` | `1` on every self-hosted install: links never fall back to CoderHelm's hosted addresses, and support goes to `SUPPORT_INBOX` | | `SITE_URL` | `siteUrl` | -| `CODERHELM_ACCOUNT_ID` | `account` (the account teams' read-only roles trust) | -| `LOG_READER_TEMPLATE_URL` | `logReaderTemplateUrl` | +| `CODERHELM_ACCOUNT_ID` | `account` (the account teams' read-only roles trust; a self-hosted install never falls back to CoderHelm's) | +| `LOG_READER_TEMPLATE_URL` | `logReaderTemplateUrl`, or this release's published copy | +| `RESOURCE_PREFIX` | `resourcePrefix` (a self-hosted install's role link narrows the role's trust to roles named `-*`) | | `PLATFORM_ADMIN_EMAILS` | `admins` | | `CODERHELM_VERSION`, `CODERHELM_COMMIT`, `CODERHELM_RELEASED_AT`, `CODERHELM_CONFIG_FINGERPRINT` | The release stamp and a hash of the config | | `UPDATER_FUNCTION_NAME` | The updater, when `updates.enabled` | diff --git a/docs/self-host/integrations.md b/docs/self-host/integrations.md index 60f909ac9..c1c464151 100644 --- a/docs/self-host/integrations.md +++ b/docs/self-host/integrations.md @@ -1,48 +1,145 @@ --- title: Integrations -description: Jira, Slack and Teams, connected AWS accounts, Google sign-in, the build sandbox and the other optional parts. +description: What each integration needs on a self-hosted install, how to connect it, and what changes with hybrid. order: 6 --- -Optional parts are switched with `integrations.*` in the config. Integrations a team connects from the dashboard (Jira, chat channels, MCP servers, data sources) need nothing in the config. +Every integration points at your own install. Its addresses (webhooks, sign-in callbacks, approval links) are built from your install's URL, never from CoderHelm's. Most need nothing in the config: teams connect them from the dashboard. Where an integration needs an app of your own, this page says which, and whether [hybrid](./hybrid.md) can lend you CoderHelm's instead. + +Settings, then **Setup** checks the ones it can, each with what is wrong and the fix in one sentence. In the examples below, `https://coderhelm.example.com` stands for your install's address. + +## Connected AWS accounts + +Teams connect their own AWS accounts so CoderHelm can read CloudWatch logs, alarms, metrics, Airflow (MWAA) and the ECS services behind a log group. Everything it can do there is read-only: it can list, describe and query, never change anything. + +- **What you need**\ + Nothing in the config. Each team needs permission to create an IAM role in the account it connects. +- **How a team connects one**\ + In **Settings, Integrations, AWS**, **Open the stack in AWS** creates a role named `CoderHelmLogReader` from a CloudFormation template. The role trusts **your install's own AWS account** (`CODERHELM_ACCOUNT_ID`, set by every deploy), never CoderHelm's, and only on the condition of the team's External ID. On a self-hosted install the link also narrows the trust to your install's own roles (`TrustedRolePrefix` = `-`), because the install's account is often shared with other workloads. The team pastes the role's ARN back and CoderHelm checks it. +- **Where the template comes from**\ + CloudFormation's Launch Stack links only open templates stored in S3. Each release publishes its templates by version (`https://coderhelm-public.s3.amazonaws.com/launch//coderhelm-log-reader.yaml`), byte for byte the ones built into that release, and your install links to its own release's copy. The same template can be downloaded from the AWS page with your account already filled in, for teams that upload it by hand. To host the templates yourself, see `logReaderTemplateUrl` in the [config reference](./config-reference.md). The `aws_connections` setup check confirms that your install knows its account and that the templates it links to are this release's. +- **Making the role by hand**\ + The AWS page lists every action the role needs, grouped by what CoderHelm reads with it, and your install's account id. Create the role named `CoderHelmLogReader`, let your install's account assume it only with the team's External ID, and allow those actions. +- **Reading the install's own account**\ + Nothing special: create the same role in that account. The install's functions may already take on `CoderHelmLogReader` in any account, their own included, so no permission on the install changes. It is also safer than widening the install's own roles to read every log group. +- **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. +- **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. +- **With hybrid**\ + No change: AWS accounts always connect to your install directly. + +`integrations.logAnalyzer` (on by default) analyzes the connected accounts' logs every 6 hours. ## GitHub -Required. See [The GitHub App](./github-app.md). +- **What you need**\ + A GitHub App of your own, made in one click by the installer or the install guide. See [The GitHub App](./github-app.md). Its webhook, callback and setup URLs are your install's. +- **Setup checks**\ + `github_keys`, `github_app`, `github_permissions`, `github_installations` and `github_webhook`. +- **With hybrid**\ + You can use CoderHelm's GitHub App instead. Events reach your install through CoderHelm's signed relay, and tokens come from CoderHelm's token broker, limited to the repositories you link. Setup checks then say whether CoderHelm's app is linked, and never block an update because the install has no app of its own. ## Jira -Two ways, both pointing at your own URL: +Two ways. A team picks one in **Settings, Integrations, Jira**. + +- **Jira webhook (simplest, nothing to install)**\ + CoderHelm shows a webhook URL for the team (`https://coderhelm.example.com/webhooks/jira/`) and its secret. Add them as a webhook in Jira's system settings for issue events. This is the default on a self-hosted install. +- **Your own copy of the Forge app**\ + The Forge app in [`coderhelm-jira/`](../../coderhelm-jira) adds the settings page inside Jira and Confluence publishing. The copy CoderHelm publishes only talks to CoderHelm's hosted API, so on its own it sends nothing to your install. Forge apps belong to the account that registers them, so deploy your own copy: + + ```sh + cd coderhelm-jira + npm ci + node scripts/set-gateway.js https://coderhelm.example.com # your URL + npx @forge/cli login + npx @forge/cli register # gives the copy its own app id + npx @forge/cli deploy -e production + npx @forge/cli install -e production --site your-site.atlassian.net --product jira + ``` + + `set-gateway.js` changes the one place the app reads the URL, and the manifest's permission to call it. +- **Setup check**\ + `jira` says whether a team has connected either way. +- **With hybrid**\ + You can install CoderHelm's published Jira app. Enter your **install ID** (Settings, System, Hybrid) where the app asks for a Team ID, and CoderHelm relays the events to your install. The Jira page shows the install ID when hybrid's Jira relay is on. + +## Slack and Microsoft Teams -**Jira webhook (simplest).** In **Settings, Integrations, Jira**, CoderHelm shows a webhook URL for your team (`/webhooks/jira/`) and its secret. Add it as a webhook in Jira's system settings for issue events. Nothing else to install. +- **Alerts and pull request links**\ + Teams paste their own incoming webhook URLs in **Settings, Alerts**. The URLs are sealed with your KMS key. No app registration is needed, with or without hybrid. Setup checks: `slack` and `teams`. +- **Plugin commands**\ + A plugin can answer a Slack slash command or a Teams outgoing webhook. The **Plugins** page shows the full addresses to paste: the Slack command's Request URL is `https://coderhelm.example.com/webhooks/slack/plugins`, checked with your Slack app's signing secret, and each Teams outgoing webhook gets its own `https://coderhelm.example.com/webhooks/teams/plugins/`. You need a Slack app of your own for slash commands. There is no shared one, with or without hybrid. +- **Approve and Deny buttons**\ + The buttons in Slack, Teams and email open `https://coderhelm.example.com/agent-approvals/link` and `/plugins/approve` on your install, which CloudFront sends to the API. -**Your own copy of the Forge app.** The Forge app in [`coderhelm-jira/`](../../coderhelm-jira) adds the settings page inside Jira and Confluence publishing. Forge apps are owned by the account that registers them, so you deploy your own copy: +## Email -```sh -cd coderhelm-jira -npm ci -node scripts/set-gateway.js https://coderhelm.example.com # your URL -npx @forge/cli login -npx @forge/cli register # gives the copy its own app id -npx @forge/cli deploy -e production -npx @forge/cli install -e production --site your-site.atlassian.net --product jira -``` +- **What you need**\ + Amazon SES in your account, with the sender you chose at install (`email.from`). See [Email](./email.md). Setup checks: `email_identity` and `email_sandbox`. +- **Links**\ + Unsubscribe and every link in an email point at your install. A self-hosted install never sends as CoderHelm: with no sender set, sending fails visibly instead. +- **With hybrid**\ + No change. -`set-gateway.js` changes the one place the app reads the URL and the manifest's permission to call it. +## Monitoring and data sources -## Slack and Microsoft Teams +New Relic, Confluence, OpenSearch, REST APIs, SQL databases, CloudWatch metrics and Airflow connect from **Settings, Integrations** or **Data sources** with keys or the AWS role. None needs an app of its own or a URL of CoderHelm's. -Teams connect their own incoming webhooks in the dashboard's notification settings. The webhook URLs are sealed with your KMS key. No app registration is needed. +- **New Relic**\ + A user API key, and the US or EU region. +- **Sentry, Datadog and other tools with an MCP server**\ + Add them as connected apps (next section). Datadog has no built-in connection. +- **With hybrid**\ + No change. -## Connected AWS accounts (logs, metrics, Airflow) +## Connected apps (MCP servers) + +- **What you need**\ + Nothing. Servers that support OAuth dynamic client registration register your install by themselves the first time someone signs in. The redirect URI is your install's `https://coderhelm.example.com/settings/integrations/mcp-callback/`, and the add flow shows it for servers that need an app registered by hand. +- **With hybrid**\ + No change: MCP sign-ins always go to your install directly. + +## Knowledge sources -Teams connect their own AWS accounts read-only from **Settings, Integrations, AWS**. CoderHelm shows a CloudFormation quick-create link for a `CoderHelmLogReader` role that trusts **your** install's account with an external id. The template comes from `logReaderTemplateUrl` (CoderHelm's public copy by default; the same template is in [`infra/cfn/`](../../infra/cfn) if you prefer to host it). +- **What you need**\ + Sanity, GitHub and website sources work with nothing to set up. Notion and Confluence work with a token pasted in the add flow. One-click sign-in for Notion, Confluence and Google Drive, and instant updates from Notion, need OAuth apps of your own, registered with your install's redirect URI. See [Knowledge sources](./knowledge-sources.md). +- **With hybrid**\ + CoderHelm's Notion, Confluence and Google Drive apps can sign you in instead. This only works on your install's CloudFront address or its `.coderhelm.com` address, not on a domain of your own yet. With CoderHelm's Notion app there are no instant updates: those sources sync every hour. -`integrations.logAnalyzer` (on by default) runs a scheduled analysis of those accounts' logs every 6 hours. +## Plugins + +- **What you need**\ + Nothing: plugin schedules use EventBridge Scheduler in your account (the deploy creates the role), and plugin connections are keys saved for the team. +- **With hybrid**\ + No change. + +## CI test results + +- **What you need**\ + Nothing. The workflow CoderHelm adds reads results through your GitHub App. A workflow can also post them directly to `https://coderhelm.example.com/webhooks/ci/tests/results` with a GitHub Actions OIDC token whose audience is `coderhelm`. The token proves which repository sent it, and only repositories connected to your install are accepted. +- **With hybrid**\ + No change. + +## Outbound webhooks + +- **What you need**\ + Nothing. An admin adds endpoints in **Settings, Webhooks** (or through the API). Your install signs each event (Standard Webhooks) with the endpoint's secret, sealed with your KMS key, and sends it from your own AWS account. Links inside events point at your install. +- **Where events can go**\ + The address must be `https://` on the public internet. Private, local and metadata addresses are refused, also when a public name resolves to one, so an endpoint inside your own network needs a public address in front of it. +- **With hybrid**\ + No change: events go straight from your install to your endpoints. + +The release notes webhook a team sets on the Releases page works the same way. + +## API keys + +The **API keys** page shows your install's own API address. The API reference at docs.coderhelm.com uses `https://api.coderhelm.com`: on a self-hosted install, use your install's address instead. Your install serves its own OpenAPI document at `https://coderhelm.example.com/openapi.json`. ## The build sandbox -`integrations.sandbox` (on by default) creates a CodeBuild project that runs a repository's real build, lint and tests in an isolated container while CoderHelm works, so it fixes real errors instead of guessing. The project's role can only read and write one bucket of source tarballs that expire after a day; it has no GitHub token, no table access and no KMS key. Turn it off to skip those checks. +`integrations.sandbox` (on by default) creates a CodeBuild project that runs a repository's real build, lint and tests in an isolated container while CoderHelm works, so it fixes real errors instead of guessing. The project's role can only read and write one bucket of source tarballs that expire after a day. It has no GitHub token, no table access and no KMS key. Turn it off to skip those checks. ## Google sign-in @@ -50,7 +147,7 @@ Teams connect their own AWS accounts read-only from **Settings, Integrations, AW "integrations": { "googleSignIn": true } ``` -Needs a domain (Google requires a fixed callback URL). Create an OAuth client in Google Cloud with the authorized redirect URI `https:///oauth2/idpresponse` (the deploy output `SignInDomain` shows it), then add `google_client_id` and `google_client_secret` to your deployment's secret (`coderhelm//secrets`) before deploying. +Needs a domain (Google requires a fixed callback URL). Create an OAuth client in Google Cloud with the authorized redirect URI `https:///oauth2/idpresponse` (the deploy output `SignInDomain` shows it). Then add `google_client_id` and `google_client_secret` to your deployment's secret (`coderhelm//secrets`) before deploying. ## Weekly summary email @@ -60,17 +157,21 @@ Needs a domain (Google requires a fixed callback URL). Create an OAuth client in These run in every install, as EventBridge rules that drop a message on the ticket queue: -| Job | When | -|---|---| -| Review reminders | every 20 minutes | -| Stuck review sweep | every 15 minutes | -| Stuck run cleanup | every 10 minutes | -| Log finding fixes (teams that turned them on) | hourly | -| Weekly summary | Mondays 13:00 UTC | -| Usage reconciliation (only with an Anthropic admin key) | daily 06:00 UTC | -| Dead-letter queue cleanup | daily 07:00 UTC | -| Knowledge source syncs that are due | every 15 minutes | - -## Knowledge sources - -Notion, Confluence, Sanity, Google Drive, GitHub and website sources work without settings, and Sanity connects by signing in with nothing to set up. One-click sign-in for Notion, Confluence and Google Drive, and instant updates from Notion, need OAuth apps of your own: see [Knowledge sources](./knowledge-sources.md). +- **Review reminders**\ + Every 20 minutes. +- **Stuck review sweep**\ + Every 15 minutes. +- **Stuck run cleanup**\ + Every 10 minutes. +- **Log finding fixes**\ + Hourly, for teams that turned them on. +- **AWS permissions check**\ + Daily at 14:00 UTC: checks every connected AWS account against this release's read-only permissions. +- **Weekly summary**\ + Mondays at 13:00 UTC. +- **Usage reconciliation**\ + Daily at 06:00 UTC, only with an Anthropic admin key. +- **Dead-letter queue cleanup**\ + Daily at 07:00 UTC. +- **Knowledge source syncs that are due**\ + Every 15 minutes. diff --git a/infra/cfn/coderhelm-log-reader-update.yaml b/infra/cfn/coderhelm-log-reader-update.yaml new file mode 100644 index 000000000..d4b998452 --- /dev/null +++ b/infra/cfn/coderhelm-log-reader-update.yaml @@ -0,0 +1,83 @@ +AWSTemplateFormatVersion: "2010-09-09" +Description: > + Brings the existing CoderHelmLogReader role up to date with the read-only + permissions the current CoderHelm release uses. Every permission here is + read-only: CoderHelm can list, describe and query, never change anything. + Created from the dashboard's Update link; you can delete older + CoderHelmLogReaderUpdate stacks once this one is in place. + +Parameters: + RoleName: + Type: String + Default: CoderHelmLogReader + Description: The CoderHelm role to update (do not change this value). + AllowedPattern: "^CoderHelmLogReader$" + +Resources: + CoderHelmReadOnlyUpdate: + Type: AWS::IAM::Policy + Properties: + # One policy per update stack, so a newer update never collides with + # an older one. + PolicyName: !Ref AWS::StackName + Roles: + - !Ref RoleName + PolicyDocument: + Version: "2012-10-17" + Statement: + - Sid: LogsAndAlarms + Effect: Allow + Action: + - "logs:DescribeLogGroups" + - "logs:FilterLogEvents" + - "logs:GetLogEvents" + - "logs:StartQuery" + - "logs:GetQueryResults" + - "logs:StopQuery" + - "cloudwatch:DescribeAlarms" + - "sts:GetCallerIdentity" + Resource: "*" + - Sid: CheckOwnPermissions + Effect: Allow + Action: + - "iam:SimulatePrincipalPolicy" + Resource: !Sub "arn:aws:iam::${AWS::AccountId}:role/${RoleName}" + - Sid: ReadMetrics + Effect: Allow + Action: + - "cloudwatch:GetMetricData" + - "cloudwatch:ListMetrics" + Resource: "*" + - Sid: ListAirflowEnvironments + Effect: Allow + Action: + - "airflow:ListEnvironments" + - "airflow:GetEnvironment" + Resource: "*" + - Sid: ReadAirflowAsViewer + Effect: Allow + Action: + - "airflow:InvokeRestApi" + Resource: "arn:aws:airflow:*:*:role/*/Viewer" + - Sid: DescribeServicesAndTasks + Effect: Allow + Action: + - "ecs:ListClusters" + - "ecs:ListServices" + - "ecs:DescribeServices" + - "ecs:DescribeTaskDefinition" + - "ecs:ListTasks" + - "ecs:DescribeTasks" + Resource: "*" + - Sid: FindTheCodeBehindALogGroup + Effect: Allow + Action: + - "lambda:GetFunction" + - "lambda:GetFunctionConfiguration" + - "lambda:ListFunctions" + - "lambda:ListTags" + - "logs:ListTagsForResource" + - "cloudformation:DescribeStacks" + - "ecr:BatchGetImage" + - "ecr:ListTagsForResource" + Resource: "*" diff --git a/infra/cfn/coderhelm-log-reader.yaml b/infra/cfn/coderhelm-log-reader.yaml index bf51a259e..4844d42af 100644 --- a/infra/cfn/coderhelm-log-reader.yaml +++ b/infra/cfn/coderhelm-log-reader.yaml @@ -15,9 +15,18 @@ Parameters: CoderHelmAccountId: Type: String Default: "654654210434" - Description: The AWS account ID of Coderhelm (do not change this value). + Description: The AWS account ID of Coderhelm, or of your self-hosted install (do not change this value). AllowedPattern: "^\\d{12}$" + TrustedRolePrefix: + Type: String + Default: "" + Description: > + Only roles whose names start with this may take on the role (a self-hosted + install's resource prefix and a dash, such as coderhelm-prod-). Empty + allows any role in that account (do not change this value). + AllowedPattern: "^[A-Za-z0-9_-]{0,41}$" + Resources: CoderHelmLogReaderRole: Type: AWS::IAM::Role @@ -37,6 +46,11 @@ Resources: Condition: StringEquals: "sts:ExternalId": !Ref ExternalId + # Only CoderHelm's own roles in that account, not its people + # or other workloads (a self-hosted install's account is often + # shared). + ArnLike: + "aws:PrincipalArn": !Sub "arn:aws:iam::${CoderHelmAccountId}:role/${TrustedRolePrefix}*" Policies: - PolicyName: CloudWatchLogsReadOnly PolicyDocument: @@ -66,6 +80,14 @@ Resources: Action: - "sts:GetCallerIdentity" Resource: "*" + # Lets CoderHelm check which of these permissions the role + # has (IAM's policy simulator, on this role only), so the + # dashboard can say when a release needs a new one. + - Sid: CheckOwnPermissions + Effect: Allow + Action: + - "iam:SimulatePrincipalPolicy" + Resource: !Sub "arn:aws:iam::${AWS::AccountId}:role/CoderHelmLogReader" # Before a fix for a log error is written: which tasks of the # service behind a log group are running, since when, and how # they start. Lists and describes only. diff --git a/infra/lib/api-stack.ts b/infra/lib/api-stack.ts index 4d52c64ec..e47766553 100644 --- a/infra/lib/api-stack.ts +++ b/infra/lib/api-stack.ts @@ -420,6 +420,24 @@ export class ApiStack extends cdk.Stack { ], }); + // AWS permissions: daily 14:00 UTC, check every connected account's + // read-only role against the permissions this release uses, so the AWS + // page is current and each team hears once when a release needs an + // update. Read-only in the teams' accounts; does nothing without + // connected accounts. + new events.Rule(this, "AwsPermissionsSchedule", { + ruleName: `${prefix}-aws-permissions`, + description: "Check connected AWS accounts against this release's read-only permissions (daily)", + schedule: events.Schedule.cron({ minute: "0", hour: "14" }), + targets: [ + new targets.SqsQueue(this.ticketQueue, { + message: events.RuleTargetInput.fromObject({ + type: "aws_permissions_sweep", + }), + }), + ], + }); + // Usage reconciliation: daily 06:00 UTC, compares the previous day's // recorded model usage with Anthropic's usage/cost report. The worker // does nothing unless the coderhelm//anthropic-admin-keys secret diff --git a/infra/lib/config.ts b/infra/lib/config.ts index 22fa30d3d..5688c14f8 100644 --- a/infra/lib/config.ts +++ b/infra/lib/config.ts @@ -282,7 +282,8 @@ export interface ResolvedConfig { /** The updater's starting settings (lambda/updater/handler.py). */ defaults: { auto: boolean; channel: "stable" | "preview"; day: string; hour: number; timezone: string; majors: "ask" | "auto" }; }; - logReaderTemplateUrl: string; + /** The config's own template URL; null for the default (see service-env.ts, logReaderTemplateUrlFor). */ + logReaderTemplateUrl: string | null; publicBucketName: string | null; siteUrl: string | null; reviewerEvalsRepo: string | null; @@ -302,9 +303,24 @@ export class ConfigError extends Error { } } -/** Default public copy of the log reader template. */ +/** + * The public bucket CloudFormation's Launch Stack links open templates from + * (they only open templates stored in S3). + */ +export const PUBLIC_TEMPLATE_BUCKET = "coderhelm-public"; + +/** The hosted deployment's copy of the log reader template (follows main). */ export const DEFAULT_LOG_READER_TEMPLATE_URL = - "https://coderhelm-public.s3.amazonaws.com/cfn/coderhelm-log-reader.yaml"; + `https://${PUBLIC_TEMPLATE_BUCKET}.s3.amazonaws.com/cfn/coderhelm-log-reader.yaml`; + +/** + * A self-hosted release's own copy of the log reader template, published by + * the release workflow next to its Launch Stack template, byte for byte the + * one built into that release (services/common/src/log_reader.rs). + */ +export function releaseLogReaderTemplateUrl(version: string): string { + return `https://${PUBLIC_TEMPLATE_BUCKET}.s3.amazonaws.com/launch/${version}/coderhelm-log-reader.yaml`; +} const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; const HOST_RE = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/; @@ -642,7 +658,7 @@ export function resolveConfig(cfg: CoderhelmConfig, opts: { skipValidation?: boo }, }; })(), - logReaderTemplateUrl: cfg.logReaderTemplateUrl ?? DEFAULT_LOG_READER_TEMPLATE_URL, + logReaderTemplateUrl: cfg.logReaderTemplateUrl ?? null, publicBucketName: cfg.publicBucketName ?? null, siteUrl: cfg.siteUrl ?? null, reviewerEvalsRepo: cfg.ci?.reviewerEvalsRepo ?? null, diff --git a/infra/lib/service-env.ts b/infra/lib/service-env.ts index b088ae596..10f520c57 100644 --- a/infra/lib/service-env.ts +++ b/infra/lib/service-env.ts @@ -5,7 +5,7 @@ */ import * as cdk from "aws-cdk-lib"; import * as iam from "aws-cdk-lib/aws-iam"; -import { ResolvedConfig } from "./config"; +import { DEFAULT_LOG_READER_TEMPLATE_URL, ResolvedConfig, releaseLogReaderTemplateUrl } from "./config"; import { releaseStamp, stampEnvironment } from "./release"; /** Environment variables shared by gateway, streaming and worker. */ @@ -22,10 +22,13 @@ export function serviceEnvironment(cfg: ResolvedConfig, account: string): Record } // The marketing site linked from email footers ("" for none). env.SITE_URL = cfg.siteUrl ?? ""; - // The account teams' read-only roles trust, and the template they create - // them from. + // The account teams' read-only roles trust (always this deployment's own: + // a self-hosted install never falls back to CoderHelm's), the template + // they create them from, and the prefix of this deployment's roles, which + // the role's trust policy is narrowed to on a self-hosted install. env.CODERHELM_ACCOUNT_ID = account; - env.LOG_READER_TEMPLATE_URL = cfg.logReaderTemplateUrl; + env.LOG_READER_TEMPLATE_URL = logReaderTemplateUrlFor(cfg); + env.RESOURCE_PREFIX = cfg.prefix; if (cfg.admins.length) env.PLATFORM_ADMIN_EMAILS = cfg.admins.join(","); Object.assign(env, modelProviderEnvironment(cfg)); // Self-hosted installs: which release this is (Settings → System), and @@ -56,6 +59,19 @@ export function serviceEnvironment(cfg: ResolvedConfig, account: string): Record return env; } +/** + * The log reader template teams' Launch Stack links open: the config's own + * URL; else, on a self-hosted release, the copy published with that release + * (so the role matches the code that checks it); else the hosted copy. + */ +export function logReaderTemplateUrlFor(cfg: ResolvedConfig, version: string | null = releaseStamp(cfg).version): string { + if (cfg.logReaderTemplateUrl) return cfg.logReaderTemplateUrl; + if (cfg.layout === "single-origin" && version && /^v\d+\.\d+\.\d+(-[0-9A-Za-z.]+)?$/.test(version)) { + return releaseLogReaderTemplateUrl(version); + } + return DEFAULT_LOG_READER_TEMPLATE_URL; +} + /** * MODEL_PROVIDER and the Bedrock model mapping (nothing for the default * Anthropic API). On a self-hosted install this is only the first-boot diff --git a/infra/test/synth.test.ts b/infra/test/synth.test.ts index de8dfa99c..2ddaf3f95 100644 --- a/infra/test/synth.test.ts +++ b/infra/test/synth.test.ts @@ -290,6 +290,56 @@ test("the release stamp reaches the services and the dashboard", () => { assert.equal(hosted.updates.enabled, false); }); +test("AWS connections: a self-hosted install's roles trust its own account, from its own release's template", () => { + process.env.CODERHELM_VERSION = "v1.2.3"; + try { + const t = synth(selfHost()); + for (const [stack, fn] of [ + ["coderhelm-prod-api", "coderhelm-prod-gateway"], + ["coderhelm-prod-worker", "coderhelm-prod-worker"], + ["coderhelm-prod-streaming", "coderhelm-prod-streaming"], + ]) { + const env = envOf(t[stack], fn); + // This install's own account (the stack's), never CoderHelm's. + assert.equal(env.CODERHELM_ACCOUNT_ID, "111122223333", fn); + assert.equal(env.LOG_READER_TEMPLATE_URL, "https://coderhelm-public.s3.amazonaws.com/launch/v1.2.3/coderhelm-log-reader.yaml", fn); + assert.equal(env.RESOURCE_PREFIX, "coderhelm-prod", fn); + } + const analyzer = envOf(t["coderhelm-prod-log-analyzer"], "coderhelm-prod-log-analyzer"); + assert.equal(analyzer.CODERHELM_ACCOUNT_ID, "111122223333"); + } finally { + delete process.env.CODERHELM_VERSION; + } + // A development build (no release) and an operator's own template. + const dev = envOf(synth(selfHost())["coderhelm-prod-api"], "coderhelm-prod-gateway"); + assert.equal(dev.LOG_READER_TEMPLATE_URL, "https://coderhelm-public.s3.amazonaws.com/cfn/coderhelm-log-reader.yaml"); + const own = envOf(synth(selfHost({ logReaderTemplateUrl: "https://my-bucket.s3.amazonaws.com/coderhelm-log-reader.yaml" }))["coderhelm-prod-api"], "coderhelm-prod-gateway"); + assert.equal(own.LOG_READER_TEMPLATE_URL, "https://my-bucket.s3.amazonaws.com/coderhelm-log-reader.yaml"); + + // The gateway, the worker and the analyzer may take on a team's role + // (in any account, the install's own included), and nothing else of it. + const t = synth(selfHost()); + for (const stack of ["coderhelm-prod-api", "coderhelm-prod-worker", "coderhelm-prod-log-analyzer"]) { + const s = json(t[stack]); + assert.ok(s.includes("arn:aws:iam::*:role/CoderHelmLogReader"), `${stack} may assume the log reader role`); + } + // The role's name prefix the trust policy is narrowed to matches the + // stacks whose generated role names start with it. + for (const name of Object.keys(t)) assert.ok(name.startsWith("coderhelm-prod-"), name); +}); + +test("AWS connections: the role and update templates are released with each version", () => { + const wf = fs.readFileSync(path.join(INFRA, "..", ".github", "workflows", "release.yml"), "utf8"); + for (const f of ["coderhelm-log-reader.yaml", "coderhelm-log-reader-update.yaml"]) { + assert.ok(wf.includes(`cp infra/cfn/${f} dist/${f}`), `${f} is built into the release`); + assert.ok(wf.includes(`dist/${f}`) && wf.includes(f + " "), `${f} is in SHA256SUMS`); + } + assert.ok(wf.includes('k="launch/$TAG/$f"'), "published under launch//, which the publisher role may write"); + const role = fs.readFileSync(path.join(INFRA, "cfn", "coderhelm-log-reader.yaml"), "utf8"); + assert.ok(role.includes('"sts:ExternalId": !Ref ExternalId')); + assert.ok(role.includes('"aws:PrincipalArn": !Sub "arn:aws:iam::${CoderHelmAccountId}:role/${TrustedRolePrefix}*"')); +}); + /** Does an HTTP API route key (`GET /api/{proxy+}`) take this request? */ function routeTakes(routeKey: string, method: string, requestPath: string): boolean { const [m, pattern] = routeKey.split(" "); diff --git a/services/Cargo.lock b/services/Cargo.lock index 28632ee53..a56681bdb 100644 --- a/services/Cargo.lock +++ b/services/Cargo.lock @@ -464,6 +464,31 @@ dependencies = [ "tracing", ] +[[package]] +name = "aws-sdk-iam" +version = "1.107.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fb72c86b8b7aeb3967a3a9cebcb773d88350c04b9d0770ad75bea8f76c89bfa" +dependencies = [ + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-observability", + "aws-smithy-query", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-smithy-xml", + "aws-types", + "fastrand", + "http 0.2.12", + "http 1.4.0", + "regex-lite", + "tracing", +] + [[package]] name = "aws-sdk-kms" version = "1.104.0" @@ -1422,6 +1447,7 @@ dependencies = [ "aws-sdk-dynamodb", "aws-sdk-ecr", "aws-sdk-ecs", + "aws-sdk-iam", "aws-sdk-kms", "aws-sdk-lambda", "aws-sdk-mwaa", diff --git a/services/common/Cargo.toml b/services/common/Cargo.toml index e9149ea81..7bf9ff5cb 100644 --- a/services/common/Cargo.toml +++ b/services/common/Cargo.toml @@ -47,6 +47,7 @@ aws-sdk-ecs = "1" aws-sdk-lambda = "1" aws-sdk-cloudformation = "1" aws-sdk-ecr = "1" +aws-sdk-iam = "1" aws-sdk-mwaa = "1" # public_urls: the deployment's URL when CloudFront picked it (single origin) aws-sdk-ssm = "1" diff --git a/services/common/contract/worker_messages.json b/services/common/contract/worker_messages.json index 7e54731fc..140f0d14b 100644 --- a/services/common/contract/worker_messages.json +++ b/services/common/contract/worker_messages.json @@ -38,6 +38,7 @@ "usage_reconcile": {"type":"usage_reconcile"}, "dlq_cleanup": {"type":"dlq_cleanup"}, "log_autofix": {"type":"log_autofix"}, + "aws_permissions_sweep": {"type":"aws_permissions_sweep"}, "agent_resume_sweep": {"type":"agent_resume_sweep"}, "knowledge_sync_sweep": {"type":"knowledge_sync_sweep"}, "knowledge_sync": {"type":"knowledge_sync","team_id":"TEAM#team-a","kb_id":"kb1","source_id":"src1"}, diff --git a/services/common/src/dlq.rs b/services/common/src/dlq.rs index 0abe535c7..2a6c98119 100644 --- a/services/common/src/dlq.rs +++ b/services/common/src/dlq.rs @@ -58,6 +58,7 @@ pub const WORKER_MESSAGE_TYPES: &[&str] = &[ "jira_comment", "dlq_cleanup", "log_autofix", + "aws_permissions_sweep", // Resumes agent work kept while a team's agents were paused. "agent_resume_sweep", // A model call's usage, held because its counters couldn't be written. @@ -84,6 +85,7 @@ pub const GLOBAL_MESSAGE_TYPES: &[&str] = &[ "usage_reconcile", "dlq_cleanup", "log_autofix", + "aws_permissions_sweep", "agent_resume_sweep", "knowledge_sync_sweep", "plugin_sweep", diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index e6ec02eae..5b84b1b55 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -44,6 +44,7 @@ pub mod live; /// Log findings and the fix runs started from them. pub mod log_findings; // Which repo a log group's or alarm's code lives in, from evidence. +pub mod log_reader; pub mod log_repo; /// The MCP servers a team can switch on: one catalog for gateway and worker. pub mod mcp_catalog; diff --git a/services/common/src/live/aws_account.rs b/services/common/src/live/aws_account.rs index fc1b530d4..3d296bd17 100644 --- a/services/common/src/live/aws_account.rs +++ b/services/common/src/live/aws_account.rs @@ -65,6 +65,8 @@ pub struct AwsAccount { /// `active` or `error` (from connecting or the log reader's test). pub status: String, pub abilities: Abilities, + /// The last live check of this release's permissions, if any. + pub permissions: Option, } fn s(item: &Item, k: &str) -> String { @@ -113,6 +115,10 @@ impl AwsAccount { region }, status: s(item, "status"), + permissions: item + .get("permissions_check") + .and_then(|v| v.as_s().ok()) + .and_then(|j| serde_json::from_str(j).ok()), abilities: Abilities { checked_at: s(item, "abilities_checked_at"), check_error: s(item, "abilities_error"), @@ -297,6 +303,7 @@ impl AwsAccount { "skipped": a.airflow_skip, "environments": self.airflow_environments(), }, + "permissions": self.permissions.as_ref().map(|p| p.view(false, &crate::public_urls::log_reader_template_url())), }) } @@ -347,6 +354,29 @@ pub async fn list( .collect()) } +/// Saves a permissions check on the account, only while it is still +/// connected. +pub async fn save_permissions( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + c: &super::permissions::PermissionCheck, +) -> Result<(), String> { + let j = serde_json::to_string(c).map_err(|e| e.to_string())?; + dynamo + .update_item() + .table_name(table) + .key("pk", av_s(team_id)) + .key("sk", av_s(&format!("{PREFIX}{}", c.account))) + .condition_expression("attribute_exists(pk)") + .update_expression("SET permissions_check = :j") + .expression_attribute_values(":j", av_s(&j)) + .send() + .await + .map(|_| ()) + .map_err(|e| format!("save aws permissions: {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/live/mod.rs b/services/common/src/live/mod.rs index 036ca9ff3..feb3fcd3e 100644 --- a/services/common/src/live/mod.rs +++ b/services/common/src/live/mod.rs @@ -40,6 +40,7 @@ pub mod metrics; pub mod net; pub mod newrelic; pub mod opensearch; +pub mod permissions; pub mod redact; pub mod redshift; pub mod rest; diff --git a/services/common/src/live/permissions.rs b/services/common/src/live/permissions.rs new file mode 100644 index 000000000..f95462f71 --- /dev/null +++ b/services/common/src/live/permissions.rs @@ -0,0 +1,708 @@ +//! Whether a team's CoderHelmLogReader role has every permission this +//! release uses ([`crate::log_reader::ABILITIES`]), checked live. +//! +//! The exact way is IAM's policy simulator on the role itself +//! (`iam:SimulatePrincipalPolicy`, which the current template allows on +//! that one role): it answers per action, and says when a permissions +//! boundary or an organization policy (SCP) is what blocks it. A role made +//! before that permission falls back to the cheapest real read per ability +//! (one list call each), where a refusal marks the ability's actions +//! missing. Nothing is changed in the account. +//! +//! After someone presses Update, the check also looks for this release's +//! update stack (when the role may describe stacks), so a failure comes +//! back as one sentence and a fix: the stack failed, it isn't in the role's +//! account, a boundary or an SCP blocks the permissions. + +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +use super::aws::{assume, AwsTarget, Session}; +use crate::log_reader::{self, ABILITIES}; + +/// What the simulator said about one action. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Simulated { + pub action: String, + pub allowed: bool, + /// `Some(false)`: a permissions boundary on the role blocks it. + pub boundary_allows: Option, + /// `Some(false)`: an organization policy (SCP) blocks it. + pub org_allows: Option, +} + +/// This release's update stack, as CloudFormation describes it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "state", rename_all = "snake_case")] +pub enum UpdateStack { + /// The role may not describe stacks (roles made before it could). + Unknown, + NotFound, + Found { + status: String, + reason: String, + }, +} + +/// One live check of a role. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct PermissionCheck { + pub account: String, + pub region: String, + pub permissions_id: String, + pub checked_at: String, + /// The role could be taken on. + pub works: bool, + /// `simulate` or `probe` (empty when the role couldn't be taken on). + pub method: String, + /// Actions of this release the role lacks. + pub missing: Vec, + /// Missing actions a boundary blocks, and ones an SCP blocks. + pub boundary_blocks: Vec, + pub scp_blocks: Vec, + pub update_stack: UpdateStack, + pub error: String, +} + +/// What the page shows for one account. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Problem { + pub code: &'static str, + pub message: String, + pub fix: String, +} + +impl PermissionCheck { + pub fn new(target: &AwsTarget, now: &str) -> Self { + PermissionCheck { + account: target.account().to_string(), + region: target.region.clone(), + permissions_id: log_reader::permissions_id(), + checked_at: now.to_string(), + works: false, + method: String::new(), + missing: Vec::new(), + boundary_blocks: Vec::new(), + scp_blocks: Vec::new(), + update_stack: UpdateStack::Unknown, + error: String::new(), + } + } + + /// `up_to_date`, `update_needed` or `error`. + pub fn status(&self) -> &'static str { + if !self.works { + "error" + } else if self.missing.is_empty() { + "up_to_date" + } else { + "update_needed" + } + } + + /// The abilities that lack at least one action, in page order. + pub fn missing_abilities(&self) -> Vec<&'static str> { + ABILITIES + .iter() + .filter(|a| { + a.actions + .iter() + .any(|x| self.missing.iter().any(|m| m == x)) + }) + .map(|a| a.key) + .collect() + } + + /// Why an update can't fix it, or why it hasn't worked yet, in one + /// sentence and a fix. `pressed` says someone pressed Update for this + /// account, so a missing stack is worth naming. + pub fn problem(&self, pressed: bool) -> Option { + let a = &self.account; + if !self.works { + return Some(Problem { + code: "role", + message: if self.error.is_empty() { + format!("Coderhelm couldn't take on the role in account {a}.") + } else { + self.error.clone() + }, + fix: format!("Check that the CoderHelmLogReader role still exists in account {a} and trusts this Coderhelm install with your External ID."), + }); + } + if self.missing.is_empty() { + return None; + } + if !self.scp_blocks.is_empty() { + return Some(Problem { + code: "scp", + message: format!( + "An organization policy (SCP) blocks {} of these permissions in account {a}.", + self.scp_blocks.len() + ), + fix: "Ask your AWS organization's admin to allow these read-only actions for the CoderHelmLogReader role, then check again.".into(), + }); + } + if !self.boundary_blocks.is_empty() { + return Some(Problem { + code: "boundary", + message: format!( + "A permissions boundary on CoderHelmLogReader blocks {} of these permissions.", + self.boundary_blocks.len() + ), + fix: "Remove the boundary from the role, or add these read-only actions to it, then check again.".into(), + }); + } + let stack = log_reader::update_stack_name(); + match &self.update_stack { + UpdateStack::Found { status, reason } if failed(status) => Some(Problem { + code: "stack_failed", + message: if reason.is_empty() { + format!("The update stack {stack} failed in AWS ({status}).") + } else { + format!("The update stack {stack} failed in AWS ({status}: {reason}).") + }, + fix: "Open the stack's Events tab for the cause, delete the failed stack, then press Update again.".into(), + }), + UpdateStack::Found { status, .. } if status.ends_with("_IN_PROGRESS") => Some(Problem { + code: "stack_in_progress", + message: format!("The update stack {stack} is still being created ({status})."), + fix: "Wait for CREATE_COMPLETE; this page checks again by itself.".into(), + }), + UpdateStack::NotFound if pressed => Some(Problem { + code: "stack_not_found", + message: format!("There's no stack named {stack} in account {a}, region {}.", self.region), + fix: format!("Sign in to AWS account {a}, the role's account, and press Update again: the stack must be created there."), + }), + UpdateStack::Unknown if pressed => Some(Problem { + code: "not_yet", + message: "The new permissions aren't on the role yet.".into(), + fix: format!("Make sure you created the stack while signed in to account {a} and that it reached CREATE_COMPLETE, then check again."), + }), + _ => None, + } + } +} + +impl PermissionCheck { + /// Checked against this release's permissions (an older check is run + /// again before it is shown as current). + pub fn is_current(&self) -> bool { + self.permissions_id == log_reader::permissions_id() + } + + /// What the dashboard shows for the account: the state, every + /// permission of this release grouped by what it reads (and which are + /// missing), the one-click update and any problem. `template_url` is + /// the install's role template ([`crate::public_urls::log_reader_template_url`]). + pub fn view(&self, pressed: bool, template_url: &str) -> Value { + let missing: Vec = self + .missing + .iter() + .map(|a| { + let ab = log_reader::ability_of(a); + json!({ + "action": a, + "ability": ab.map(|x| x.key), + "ability_name": ab.map(|x| x.name), + }) + }) + .collect(); + let abilities: Vec = ABILITIES + .iter() + .map(|a| { + let gone: Vec<&str> = a + .actions + .iter() + .copied() + .filter(|x| self.missing.iter().any(|m| m == x)) + .collect(); + json!({ + "key": a.key, + "name": a.name, + "why": a.why, + "actions": a.actions, + "missing": gone, + }) + }) + .collect(); + let update = (self.status() == "update_needed") + .then(|| log_reader::update_template_url(template_url)) + .flatten() + .map(|t| { + json!({ + "url": log_reader::update_url(&t, &self.region), + "stack_name": log_reader::update_stack_name(), + "template_url": t, + "sign_in_account": self.account, + "stacks_url": log_reader::stack_list_url(&self.region), + }) + }); + json!({ + "account": self.account, + "region": self.region, + "status": self.status(), + "method": self.method, + "checked_at": self.checked_at, + "permissions_id": self.permissions_id, + "current": self.is_current(), + "missing_count": self.missing.len(), + "missing": missing, + "missing_abilities": self.missing_abilities(), + "abilities": abilities, + "update": update, + "problem": self.problem(pressed), + }) + } +} + +fn failed(status: &str) -> bool { + status.contains("FAILED") || status.contains("ROLLBACK") +} + +/// Pure: the simulator's answers folded into a check. +pub fn apply_simulation(c: &mut PermissionCheck, results: &[Simulated]) { + c.method = "simulate".into(); + for r in results { + if r.allowed || c.missing.contains(&r.action) { + continue; + } + c.missing.push(r.action.clone()); + if r.org_allows == Some(false) { + c.scp_blocks.push(r.action.clone()); + } else if r.boundary_allows == Some(false) { + c.boundary_blocks.push(r.action.clone()); + } + } + order(&mut c.missing); +} + +/// Pure: per-ability probe answers (`Some(false)`: refused) folded into a +/// check. The simulator itself was refused, so its action is missing too. +pub fn apply_probes(c: &mut PermissionCheck, probes: &[(&str, Option)]) { + c.method = "probe".into(); + let mut missing: Vec = vec!["iam:SimulatePrincipalPolicy".into()]; + for (key, ok) in probes { + if *ok == Some(false) { + if let Some(a) = log_reader::ability(key) { + missing.extend(a.actions.iter().map(|s| s.to_string())); + } + } + } + missing.dedup(); + c.missing = missing; + order(&mut c.missing); +} + +/// Template order, once each. +fn order(v: &mut Vec) { + let all = log_reader::all_actions(); + v.sort_by_key(|a| all.iter().position(|x| x == a).unwrap_or(usize::MAX)); + v.dedup(); +} + +/// The resource each action is simulated on: one that the template's +/// statement for it covers. +pub fn simulated_resource(action: &str, role_arn: &str, region: &str, account: &str) -> String { + match action { + "logs:StartQuery" + | "logs:GetQueryResults" + | "logs:StopQuery" + | "logs:FilterLogEvents" + | "logs:GetLogEvents" => { + format!("arn:aws:logs:{region}:{account}:log-group:coderhelm-permission-check") + } + "airflow:InvokeRestApi" => { + format!("arn:aws:airflow:{region}:{account}:role/coderhelm-permission-check/Viewer") + } + "iam:SimulatePrincipalPolicy" => role_arn.to_string(), + _ => "*".to_string(), + } +} + +macro_rules! client { + ($krate:ident, $s:expr, $region:expr) => {{ + use $krate::config::{BehaviorVersion, Credentials, Region}; + let s: &Session = $s; + let creds = Credentials::new( + &s.access_key_id, + &s.secret_access_key, + Some(s.session_token.clone()), + None, + "coderhelm-team-role", + ); + $krate::Client::from_conf( + $krate::Config::builder() + .behavior_version(BehaviorVersion::latest()) + .region(Region::new($region)) + .credentials_provider(creds) + .build(), + ) + }}; +} + +use aws_sdk_sts::error::ProvideErrorMetadata; + +fn refused(e: &impl ProvideErrorMetadata) -> bool { + if e.code() == Some("ClientException") { + return e + .message() + .is_some_and(|m| m.contains("not authorized") || m.contains("AccessDenied")); + } + crate::log_repo::live::is_refusal(e.code()) +} + +/// The simulator's answers, or `None` when the role may not ask it. +async fn simulate(s: &Session, target: &AwsTarget) -> Result, bool> { + let iam = client!(aws_sdk_iam, s, "us-east-1".to_string()); + let account = target.account(); + let mut groups: Vec<(String, Vec)> = Vec::new(); + for a in log_reader::all_actions() { + let r = simulated_resource(a, &target.role_arn, &target.region, account); + match groups.iter_mut().find(|(res, _)| *res == r) { + Some((_, v)) => v.push(a.to_string()), + None => groups.push((r, vec![a.to_string()])), + } + } + let mut out = Vec::new(); + for (resource, actions) in groups { + let r = iam + .simulate_principal_policy() + .policy_source_arn(&target.role_arn) + .set_action_names(Some(actions)) + .resource_arns(resource) + .send() + .await; + match r { + Ok(o) => { + for e in o.evaluation_results() { + use aws_sdk_iam::types::PolicyEvaluationDecisionType as D; + out.push(Simulated { + action: e.eval_action_name().to_string(), + allowed: matches!(e.eval_decision(), D::Allowed), + boundary_allows: e + .permissions_boundary_decision_detail() + .map(|d| d.allowed_by_permissions_boundary()), + org_allows: e + .organizations_decision_detail() + .map(|d| d.allowed_by_organizations()), + }); + } + } + // Refused: the role predates the permission. Anything else: + // the simulator didn't answer; fall back the same way. + Err(e) => return Err(refused(&e)), + } + } + Ok(out) +} + +/// The cheapest real read per ability: `Some(false)` when refused. +async fn probes(s: &Session) -> Vec<(&'static str, Option)> { + let ok = |r: Result<(), bool>| match r { + Ok(()) => Some(true), + Err(true) => Some(false), + Err(false) => None, + }; + let logs = super::aws::logs_client(s) + .describe_log_groups() + .limit(1) + .send() + .await + .map(|_| ()) + .map_err(|e| refused(&e)); + let metrics = super::metrics::probe(s).await.ok(); + let airflow = match super::airflow::list_environments(s).await { + Ok(Some(_)) => Some(true), + Ok(None) => Some(false), + Err(_) => None, + }; + let ecs = client!(aws_sdk_ecs, s, s.region.clone()) + .list_clusters() + .max_results(1) + .send() + .await + .map(|_| ()) + .map_err(|e| refused(&e)); + let code = client!(aws_sdk_lambda, s, s.region.clone()) + .list_functions() + .max_items(1) + .send() + .await + .map(|_| ()) + .map_err(|e| refused(&e)); + vec![ + ("logs", ok(logs)), + ("metrics", metrics), + ("airflow", airflow), + ("ecs", ok(ecs)), + ("code", ok(code)), + ] +} + +async fn update_stack(s: &Session) -> UpdateStack { + let cfn = client!(aws_sdk_cloudformation, s, s.region.clone()); + match cfn + .describe_stacks() + .stack_name(log_reader::update_stack_name()) + .send() + .await + { + Ok(o) => match o.stacks().first() { + Some(st) => UpdateStack::Found { + status: st + .stack_status() + .map(|x| x.as_str().to_string()) + .unwrap_or_default(), + reason: crate::truncate_str(st.stack_status_reason().unwrap_or(""), 300) + .to_string(), + }, + None => UpdateStack::NotFound, + }, + Err(e) if refused(&e) => UpdateStack::Unknown, + Err(e) => { + let not_found = e.code() == Some("ValidationError") + && e.message().is_some_and(|m| m.contains("does not exist")); + if not_found { + UpdateStack::NotFound + } else { + UpdateStack::Unknown + } + } + } +} + +/// Takes on the role and checks every permission of this release. +pub async fn check( + sts: &aws_sdk_sts::Client, + target: &AwsTarget, + actor: &str, + now: &str, +) -> PermissionCheck { + let mut c = PermissionCheck::new(target, now); + let session = match assume(sts, target, actor).await { + Ok(s) => s, + Err(e) => { + c.error = e.message; + return c; + } + }; + c.works = true; + match simulate(&session, target).await { + Ok(results) => apply_simulation(&mut c, &results), + Err(_) => { + let p = probes(&session).await; + apply_probes(&mut c, &p); + } + } + if !c.missing.is_empty() { + c.update_stack = update_stack(&session).await; + } + c +} + +#[cfg(test)] +mod tests { + use super::*; + + fn target() -> AwsTarget { + AwsTarget { + role_arn: "arn:aws:iam::111122223333:role/CoderHelmLogReader".into(), + external_id: "x".into(), + region: "eu-west-1".into(), + ..Default::default() + } + } + + fn sim(action: &str, allowed: bool) -> Simulated { + Simulated { + action: action.into(), + allowed, + boundary_allows: None, + org_allows: None, + } + } + + fn checked() -> PermissionCheck { + let mut c = PermissionCheck::new(&target(), "2026-10-26T00:00:00Z"); + c.works = true; + c + } + + #[test] + fn everything_allowed_is_up_to_date() { + let mut c = checked(); + let all: Vec = log_reader::all_actions() + .iter() + .map(|a| sim(a, true)) + .collect(); + apply_simulation(&mut c, &all); + assert_eq!(c.status(), "up_to_date"); + assert!(c.problem(true).is_none()); + assert_eq!(c.method, "simulate"); + } + + #[test] + fn missing_actions_are_listed_in_template_order() { + let mut c = checked(); + apply_simulation( + &mut c, + &[ + sim("ecs:DescribeTasks", false), + sim("ecs:ListTasks", false), + sim("logs:GetLogEvents", true), + ], + ); + assert_eq!(c.status(), "update_needed"); + assert_eq!(c.missing, vec!["ecs:ListTasks", "ecs:DescribeTasks"]); + assert_eq!(c.missing_abilities(), vec!["ecs"]); + // Nothing pressed yet: no problem to show, just the update. + assert!(c.problem(false).is_none()); + } + + #[test] + fn a_boundary_or_an_scp_is_named() { + let mut c = checked(); + apply_simulation( + &mut c, + &[ + Simulated { + boundary_allows: Some(false), + ..sim("ecs:ListTasks", false) + }, + Simulated { + org_allows: Some(false), + ..sim("ecs:DescribeTasks", false) + }, + ], + ); + assert_eq!(c.problem(false).unwrap().code, "scp"); + let mut b = checked(); + apply_simulation( + &mut b, + &[Simulated { + boundary_allows: Some(false), + ..sim("ecs:ListTasks", false) + }], + ); + let p = b.problem(false).unwrap(); + assert_eq!(p.code, "boundary"); + assert!(p.message.contains("permissions boundary")); + } + + #[test] + fn an_old_role_falls_back_to_probes() { + let mut c = checked(); + apply_probes( + &mut c, + &[ + ("logs", Some(true)), + ("metrics", Some(true)), + ("airflow", None), + ("ecs", Some(false)), + ("code", Some(false)), + ], + ); + assert_eq!(c.method, "probe"); + assert!(c + .missing + .contains(&"iam:SimulatePrincipalPolicy".to_string())); + assert!(c.missing.contains(&"ecs:DescribeTasks".to_string())); + assert!(c.missing.contains(&"lambda:GetFunction".to_string())); + assert!(!c.missing.iter().any(|m| m.starts_with("airflow:"))); + assert_eq!(c.missing_abilities(), vec!["check", "ecs", "code"]); + } + + #[test] + fn after_update_the_stack_says_what_went_wrong() { + let mut c = checked(); + c.missing = vec!["ecs:ListTasks".into()]; + c.update_stack = UpdateStack::Found { + status: "ROLLBACK_COMPLETE".into(), + reason: "The role with name CoderHelmLogReader cannot be found.".into(), + }; + let p = c.problem(true).unwrap(); + assert_eq!(p.code, "stack_failed"); + assert!(p.message.contains("cannot be found")); + c.update_stack = UpdateStack::NotFound; + assert!(c.problem(false).is_none()); + let p = c.problem(true).unwrap(); + assert_eq!(p.code, "stack_not_found"); + assert!(p.fix.contains("111122223333")); + c.update_stack = UpdateStack::Unknown; + assert_eq!(c.problem(true).unwrap().code, "not_yet"); + c.update_stack = UpdateStack::Found { + status: "CREATE_IN_PROGRESS".into(), + reason: String::new(), + }; + assert_eq!(c.problem(true).unwrap().code, "stack_in_progress"); + } + + #[test] + fn the_view_offers_the_update_for_this_release() { + let mut c = checked(); + c.missing = vec!["ecs:ListTasks".into(), "ecs:DescribeTasks".into()]; + let v = c.view( + false, + "https://b.s3.amazonaws.com/launch/v1.2.3/coderhelm-log-reader.yaml", + ); + assert_eq!(v["status"], "update_needed"); + assert_eq!(v["missing_count"], 2); + assert_eq!(v["missing"][0]["ability"], "ecs"); + assert_eq!(v["update"]["sign_in_account"], "111122223333"); + assert!(v["update"]["url"] + .as_str() + .unwrap() + .contains("region=eu-west-1")); + assert!(v["update"]["template_url"] + .as_str() + .unwrap() + .ends_with("/coderhelm-log-reader-update.yaml")); + let ecs = v["abilities"] + .as_array() + .unwrap() + .iter() + .find(|a| a["key"] == "ecs") + .unwrap(); + assert_eq!(ecs["missing"].as_array().unwrap().len(), 2); + assert!(v["problem"].is_null()); + // A template URL with no update template next to it: no link. + assert!(c.view(false, "https://b.s3.amazonaws.com/mine.yaml")["update"].is_null()); + // Round trip through storage. + let back: PermissionCheck = + serde_json::from_value(serde_json::to_value(&c).unwrap()).unwrap(); + assert_eq!(back, c); + assert!(back.is_current()); + } + + #[test] + fn a_role_that_cannot_be_taken_on_is_an_error() { + let mut c = PermissionCheck::new(&target(), "t"); + c.error = "Coderhelm couldn't use the role in your AWS account (AccessDenied).".into(); + assert_eq!(c.status(), "error"); + assert_eq!(c.problem(false).unwrap().code, "role"); + } + + #[test] + fn each_action_is_simulated_on_a_resource_its_statement_covers() { + let t = target(); + assert_eq!( + simulated_resource("logs:StartQuery", &t.role_arn, "eu-west-1", "111122223333"), + "arn:aws:logs:eu-west-1:111122223333:log-group:coderhelm-permission-check" + ); + assert!(simulated_resource( + "airflow:InvokeRestApi", + &t.role_arn, + "eu-west-1", + "111122223333" + ) + .ends_with("/Viewer")); + assert_eq!( + simulated_resource("iam:SimulatePrincipalPolicy", &t.role_arn, "r", "a"), + t.role_arn + ); + assert_eq!( + simulated_resource("ecs:ListTasks", &t.role_arn, "r", "a"), + "*" + ); + } +} diff --git a/services/common/src/log_reader.rs b/services/common/src/log_reader.rs new file mode 100644 index 000000000..b44b61c26 --- /dev/null +++ b/services/common/src/log_reader.rs @@ -0,0 +1,443 @@ +//! The read-only `CoderHelmLogReader` role teams create in their own AWS +//! accounts: its templates (built into every release), the Launch Stack +//! link, and what each ability of the role needs. +//! +//! The role trusts the install's own AWS account +//! ([`crate::public_urls::platform_account_id`]) on the condition of the +//! team's External ID, and only roles of the install itself +//! ([`trusted_role_prefix`]). CloudFormation's Launch Stack links only open +//! templates stored in S3, so the link points at a public copy +//! ([`crate::public_urls::log_reader_template_url`]): a self-hosted release +//! links to the copy published with that release +//! (`launch//coderhelm-log-reader.yaml`), byte for byte the +//! template below. The same template can be downloaded from the install, +//! with the install's account filled in, for teams that upload it by hand. + +/// The role's template, as built into this release. +pub const ROLE_TEMPLATE: &str = include_str!("../../../infra/cfn/coderhelm-log-reader.yaml"); +/// The add-on stack that brings an existing role up to date: every +/// permission of [`ABILITIES`], as one more policy on the role. +pub const UPDATE_TEMPLATE: &str = + include_str!("../../../infra/cfn/coderhelm-log-reader-update.yaml"); + +pub const ROLE_NAME: &str = "CoderHelmLogReader"; +pub const ROLE_STACK: &str = "CoderHelmLogReader"; +/// Update stacks are `CoderHelmLogReaderUpdate-`, one per +/// set of permissions, so each release's update is a new stack (a Launch +/// Stack link can only create one) and never collides with an older one. +pub const UPDATE_STACK_PREFIX: &str = "CoderHelmLogReaderUpdate"; +const ROLE_FILE: &str = "coderhelm-log-reader.yaml"; +const UPDATE_FILE: &str = "coderhelm-log-reader-update.yaml"; +/// The account the template names by default (the hosted deployment's). +/// A download from a self-hosted install replaces it with the install's. +const TEMPLATE_DEFAULT_ACCOUNT: &str = "Default: \"654654210434\""; + +/// One thing the role can do: the IAM actions it takes, and in plain words +/// what CoderHelm reads with them and why. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Ability { + pub key: &'static str, + pub name: &'static str, + pub why: &'static str, + pub actions: &'static [&'static str], +} + +/// Everything the current release's role allows, by ability. Tests keep +/// this equal to both templates' actions. +pub const ABILITIES: &[Ability] = &[ + Ability { + key: "logs", + name: "CloudWatch logs and alarms", + why: "Reads error lines and alarm states so Coderhelm can find what broke and propose a fix.", + actions: &[ + "logs:DescribeLogGroups", + "logs:StartQuery", + "logs:GetQueryResults", + "logs:StopQuery", + "logs:FilterLogEvents", + "logs:GetLogEvents", + "cloudwatch:DescribeAlarms", + "sts:GetCallerIdentity", + ], + }, + Ability { + key: "check", + name: "Checking its own permissions", + why: "Asks IAM which of these permissions the role has, so this page can say when an update is needed. It only looks at this one role.", + actions: &["iam:SimulatePrincipalPolicy"], + }, + Ability { + key: "metrics", + name: "CloudWatch metrics", + why: "Reads error rate, latency and other metrics before and after a deploy.", + actions: &["cloudwatch:GetMetricData", "cloudwatch:ListMetrics"], + }, + Ability { + key: "airflow", + name: "Airflow", + why: "Reads DAG runs, task logs and import errors as Airflow's Viewer role, which can't trigger or change anything.", + actions: &[ + "airflow:ListEnvironments", + "airflow:GetEnvironment", + "airflow:InvokeRestApi", + ], + }, + Ability { + key: "ecs", + name: "ECS services and tasks", + why: "Sees which tasks behind a failing log group are running, since when and how they start, as evidence before a fix.", + actions: &[ + "ecs:ListClusters", + "ecs:ListServices", + "ecs:DescribeServices", + "ecs:DescribeTaskDefinition", + "ecs:ListTasks", + "ecs:DescribeTasks", + ], + }, + Ability { + key: "code", + name: "Finding the code behind a log group", + why: "Reads function, image and stack tags to work out which repository a log group's code lives in, so a fix goes to the right repo.", + actions: &[ + "lambda:GetFunction", + "lambda:GetFunctionConfiguration", + "lambda:ListFunctions", + "lambda:ListTags", + "logs:ListTagsForResource", + "cloudformation:DescribeStacks", + "ecr:BatchGetImage", + "ecr:ListTagsForResource", + ], + }, +]; + +/// Every action of [`ABILITIES`], once each, in order. +pub fn all_actions() -> Vec<&'static str> { + let mut out: Vec<&'static str> = Vec::new(); + for a in ABILITIES { + for x in a.actions { + if !out.contains(x) { + out.push(x); + } + } + } + out +} + +/// A short id of this release's set of permissions: changes exactly when an +/// action is added or removed. +pub fn permissions_id() -> String { + use sha2::{Digest, Sha256}; + let mut all = all_actions(); + all.sort_unstable(); + hex::encode(&Sha256::digest(all.join(",").as_bytes())[..4]) +} + +/// This release's update stack name. +pub fn update_stack_name() -> String { + format!("{UPDATE_STACK_PREFIX}-{}", permissions_id()) +} + +/// The ability an action belongs to. +pub fn ability_of(action: &str) -> Option<&'static Ability> { + ABILITIES.iter().find(|a| a.actions.contains(&action)) +} + +pub fn ability(key: &str) -> Option<&'static Ability> { + ABILITIES.iter().find(|a| a.key == key) +} + +/// The IAM actions behind `missing` abilities, in template order, once each. +pub fn missing_actions(missing: &[&str]) -> Vec<&'static str> { + let mut out: Vec<&'static str> = Vec::new(); + for a in ABILITIES.iter().filter(|a| missing.contains(&a.key)) { + for x in a.actions { + if !out.contains(x) { + out.push(x); + } + } + } + out +} + +/// Every IAM action a template's policies allow (the quoted `- "svc:Action"` +/// list items; the trust policy's `sts:AssumeRole` is not a list item). +pub fn template_actions(template: &str) -> Vec { + let mut out: Vec = Vec::new(); + for line in template.lines() { + let t = line.trim(); + let Some(rest) = t.strip_prefix("- \"") else { + continue; + }; + let Some(v) = rest.strip_suffix('"') else { + continue; + }; + let ok = v.split_once(':').is_some_and(|(svc, act)| { + !svc.is_empty() + && svc + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') + && !act.is_empty() + && act.chars().all(|c| c.is_ascii_alphanumeric()) + }); + if ok && !out.iter().any(|x| x == v) { + out.push(v.to_string()); + } + } + out +} + +/// The update template's URL, next to the role's (same folder). +pub fn update_template_url(role_template_url: &str) -> Option { + role_template_url + .strip_suffix(ROLE_FILE) + .map(|base| format!("{base}{UPDATE_FILE}")) +} + +/// The role template with the install's account as its default, for +/// teams that download it and upload it by hand. +pub fn template_for(account: &str, which: Which) -> String { + match which { + Which::Role if is_account(account) => ROLE_TEMPLATE.replacen( + TEMPLATE_DEFAULT_ACCOUNT, + &format!("Default: \"{account}\""), + 1, + ), + Which::Role => ROLE_TEMPLATE.to_string(), + Which::Update => UPDATE_TEMPLATE.to_string(), + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Which { + Role, + Update, +} + +pub fn is_account(a: &str) -> bool { + a.len() == 12 && a.chars().all(|c| c.is_ascii_digit()) +} + +/// The name prefix of the install's own roles (`-`), which +/// the role's trust policy is narrowed to; "" when unknown (any role in the +/// install's account, as before). +pub fn trusted_role_prefix() -> String { + trusted_role_prefix_from(std::env::var("RESOURCE_PREFIX").ok()) +} + +pub fn trusted_role_prefix_from(v: Option) -> String { + v.map(|p| p.trim().to_string()) + .filter(|p| { + !p.is_empty() + && p.len() <= 40 + && p.chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') + }) + .map(|p| format!("{p}-")) + .unwrap_or_default() +} + +/// The Launch Stack link that creates the role in a team's account. +pub fn quick_create_url( + template_url: &str, + external_id: &str, + account: &str, + prefix: &str, +) -> String { + let mut u = format!( + "https://console.aws.amazon.com/cloudformation/home#/stacks/quickcreate?stackName={ROLE_STACK}&templateURL={}¶m_ExternalId={}¶m_CoderHelmAccountId={}", + urlencoding::encode(template_url), + urlencoding::encode(external_id), + account, + ); + if !prefix.is_empty() { + u.push_str(&format!( + "¶m_TrustedRolePrefix={}", + urlencoding::encode(prefix) + )); + } + u +} + +/// The one-click update: a Launch Stack link that adds this release's +/// update stack to the role, in `region` (IAM is global; the region only +/// decides where the stack is listed). +pub fn update_url(update_template_url: &str, region: &str) -> String { + format!( + "https://console.aws.amazon.com/cloudformation/home?region={region}#/stacks/quickcreate?stackName={}&templateURL={}¶m_RoleName={ROLE_NAME}", + update_stack_name(), + urlencoding::encode(update_template_url) + ) +} + +/// The CloudFormation console's stack list in `region`, filtered to +/// CoderHelm's stacks. +pub fn stack_list_url(region: &str) -> String { + format!( + "https://console.aws.amazon.com/cloudformation/home?region={region}#/stacks?filteringText={ROLE_STACK}" + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_abilities_list_every_action_the_template_allows() { + let mut listed: Vec = ABILITIES + .iter() + .flat_map(|a| a.actions.iter().map(|s| s.to_string())) + .collect(); + listed.sort(); + listed.dedup(); + let mut allowed = template_actions(ROLE_TEMPLATE); + allowed.sort(); + assert_eq!( + listed, allowed, + "ABILITIES and infra/cfn/coderhelm-log-reader.yaml disagree" + ); + } + + #[test] + fn the_update_stack_gives_every_permission() { + let mut listed: Vec = all_actions().iter().map(|s| s.to_string()).collect(); + listed.sort(); + let mut allowed = template_actions(UPDATE_TEMPLATE); + allowed.sort(); + assert_eq!( + listed, allowed, + "ABILITIES and infra/cfn/coderhelm-log-reader-update.yaml disagree" + ); + } + + #[test] + fn every_permission_is_read_only() { + let writes = [ + "Put", "Create", "Delete", "Update", "Start", "Stop", "Run", "Invoke", "Attach", + "Pass", "Tag", "Untag", "Register", + ]; + let ok_reads = ["logs:StartQuery", "logs:StopQuery", "airflow:InvokeRestApi"]; + for a in all_actions() { + let verb = a.split(':').nth(1).unwrap(); + if ok_reads.contains(&a) { + continue; + } + assert!( + !writes.iter().any(|w| verb.starts_with(w)), + "{a} is not read-only" + ); + } + // Airflow's REST API only as the Viewer role. + assert!(UPDATE_TEMPLATE.contains("arn:aws:airflow:*:*:role/*/Viewer")); + assert!(ROLE_TEMPLATE.contains("arn:aws:airflow:*:*:role/*/Viewer")); + } + + #[test] + fn each_release_has_its_own_update_stack() { + let id = permissions_id(); + assert_eq!(id.len(), 8); + assert_eq!( + update_stack_name(), + format!("CoderHelmLogReaderUpdate-{id}") + ); + let u = update_url( + "https://b.s3.amazonaws.com/launch/v1.2.3/coderhelm-log-reader-update.yaml", + "eu-west-1", + ); + assert!(u.starts_with("https://console.aws.amazon.com/cloudformation/home?region=eu-west-1#/stacks/quickcreate?")); + assert!(u.contains(&format!("stackName=CoderHelmLogReaderUpdate-{id}"))); + assert!(u.contains("param_RoleName=CoderHelmLogReader")); + assert!(u.contains("templateURL=https%3A%2F%2Fb.s3.amazonaws.com%2Flaunch%2Fv1.2.3%2Fcoderhelm-log-reader-update.yaml")); + assert!(ability_of("ecs:DescribeTasks").is_some_and(|a| a.key == "ecs")); + assert!(ABILITIES + .iter() + .all(|a| !a.why.is_empty() && !a.why.contains('\u{2192}'))); + } + + #[test] + fn the_ecs_actions_from_the_log_fixes_are_in_the_role() { + let all = template_actions(ROLE_TEMPLATE); + for a in [ + "ecs:ListTasks", + "ecs:DescribeTasks", + "ecs:DescribeServices", + "lambda:GetFunction", + ] { + assert!(all.iter().any(|x| x == a), "{a}"); + } + assert!(!all.iter().any(|x| x == "sts:AssumeRole")); + } + + #[test] + fn missing_actions_follow_the_abilities() { + assert!(missing_actions(&[]).is_empty()); + let m = missing_actions(&["ecs", "metrics"]); + assert_eq!(m[0], "cloudwatch:GetMetricData"); + assert_eq!(m.len(), 8); + assert!(m.contains(&"ecs:DescribeTasks")); + assert!(!m.contains(&"lambda:GetFunction")); + } + + #[test] + fn the_role_trusts_the_install_with_the_external_id_and_its_own_roles() { + assert!(ROLE_TEMPLATE.contains("\"sts:ExternalId\": !Ref ExternalId")); + assert!(ROLE_TEMPLATE.contains("arn:aws:iam::${CoderHelmAccountId}:root")); + assert!(ROLE_TEMPLATE.contains("aws:PrincipalArn")); + assert!(ROLE_TEMPLATE.contains("TrustedRolePrefix")); + } + + #[test] + fn a_download_names_the_install_account() { + let t = template_for("111122223333", Which::Role); + assert!(t.contains("Default: \"111122223333\"")); + assert!(!t.contains("654654210434")); + // Only the default changes. + assert_eq!(t.len(), ROLE_TEMPLATE.len()); + assert_eq!(template_for("bad", Which::Role), ROLE_TEMPLATE); + assert_eq!(template_for("111122223333", Which::Update), UPDATE_TEMPLATE); + } + + #[test] + fn the_update_template_sits_next_to_the_role_template() { + assert_eq!( + update_template_url( + "https://b.s3.amazonaws.com/launch/v1.2.3/coderhelm-log-reader.yaml" + ) + .as_deref(), + Some("https://b.s3.amazonaws.com/launch/v1.2.3/coderhelm-log-reader-update.yaml") + ); + assert_eq!( + update_template_url("https://b.s3.amazonaws.com/mine.yaml"), + None + ); + } + + #[test] + fn the_launch_link_carries_the_install_account_and_prefix() { + let u = quick_create_url( + "https://b.s3.amazonaws.com/launch/v1.2.3/coderhelm-log-reader.yaml", + "0b5f1a5e-0000-4000-8000-000000000000", + "111122223333", + "coderhelm-prod-", + ); + assert!(u.contains("param_CoderHelmAccountId=111122223333")); + assert!(u.contains("param_TrustedRolePrefix=coderhelm-prod-")); + assert!(u.contains("templateURL=https%3A%2F%2Fb.s3.amazonaws.com%2Flaunch%2Fv1.2.3%2Fcoderhelm-log-reader.yaml")); + assert!( + !quick_create_url("https://x/y.yaml", "e", "111122223333", "") + .contains("TrustedRolePrefix") + ); + } + + #[test] + fn the_prefix_is_the_install_resource_prefix() { + assert_eq!( + trusted_role_prefix_from(Some("coderhelm-prod".into())), + "coderhelm-prod-" + ); + assert_eq!(trusted_role_prefix_from(None), ""); + assert_eq!(trusted_role_prefix_from(Some(" ".into())), ""); + assert_eq!(trusted_role_prefix_from(Some("a*b".into())), ""); + } +} diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index 0526e3395..5b44076c7 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -135,6 +135,11 @@ pub enum WorkerMessage { /// teams that turned automatic fixes on. Does nothing for anyone else. #[serde(rename = "log_autofix")] LogAutofix, + /// Daily (EventBridge, then SQS): check every connected AWS account's role + /// against this release's permissions and tell each team once when an + /// update is needed. + #[serde(rename = "aws_permissions_sweep")] + AwsPermissionsSweep, /// People pushed back on a CoderHelm review (a reply, a dismissal, a close /// over its change request): judge whether the reviewer was wrong. #[serde(rename = "review_lesson")] @@ -351,7 +356,8 @@ impl WorkerMessage { | WorkerMessage::DlqCleanup | WorkerMessage::KnowledgeSyncSweep | WorkerMessage::AgentResumeSweep - | WorkerMessage::LogAutofix => f::OTHER, + | WorkerMessage::LogAutofix + | WorkerMessage::AwsPermissionsSweep => f::OTHER, WorkerMessage::PluginRun(_) | WorkerMessage::PluginPublish(_) | WorkerMessage::PluginSync(_) diff --git a/services/common/src/notify/messages.rs b/services/common/src/notify/messages.rs index 2fb88cc62..c0dcc49a5 100644 --- a/services/common/src/notify/messages.rs +++ b/services/common/src/notify/messages.rs @@ -73,6 +73,47 @@ pub fn release_notes_failed(owner: &str, repo: &str, tag: &str, error: &str) -> } } +/// Pure: this release needs new read-only permissions on the team's AWS +/// role in these accounts (account, how many are missing). Sent once per +/// set of permissions. +pub fn aws_permissions_update(accounts: &[(String, usize)], url: &str) -> Message { + let title = if accounts.len() == 1 { + format!( + "AWS account {} needs {} new read-only permission{}", + accounts[0].0, + accounts[0].1, + if accounts[0].1 == 1 { "" } else { "s" } + ) + } else { + format!( + "{} AWS accounts need new read-only permissions", + accounts.len() + ) + }; + let mut blocks = vec![ + Block::Text(Text::new(title.clone()).bold().color(Tone::Attention)), + Block::Text(Text::new( + "This CoderHelm release reads a little more from your AWS accounts (still read-only: it can list, describe and query, never change anything). Until an admin updates the CoderHelmLogReader role, the parts that need it are skipped and everything else keeps working.", + )), + ]; + if accounts.len() > 1 { + for (a, n) in accounts { + blocks.push(Block::Text( + Text::new(format!("Account {a}: {n} missing")).subtle(), + )); + } + } + blocks.push(Block::Text( + Text::new("An admin can update each account with one click on the AWS page.").subtle(), + )); + Message { + summary: title, + blocks, + buttons: vec![Button::new("Update permissions", url)], + full_width: false, + } +} + /// Pure: the message "Send test message" posts for a destination. pub fn test_message(destination: &str, dashboard_url: &str) -> Message { Message { @@ -122,6 +163,30 @@ mod tests { ) } + #[test] + fn the_permissions_notice_names_the_accounts_and_stays_read_only() { + let one = aws_permissions_update( + &[("111122223333".into(), 3)], + "https://coderhelm.example.com/settings/integrations/aws", + ); + assert_eq!( + one.summary, + "AWS account 111122223333 needs 3 new read-only permissions" + ); + assert_eq!( + one.buttons[0].url, + "https://coderhelm.example.com/settings/integrations/aws" + ); + let two = aws_permissions_update( + &[("111122223333".into(), 1), ("444455556666".into(), 2)], + "/x", + ); + assert!(two.summary.starts_with("2 AWS accounts")); + let text = format!("{:?}", two.blocks); + assert!(text.contains("444455556666") && text.contains("read-only")); + assert!(!text.contains('\u{2192}')); + } + #[test] fn the_review_reminder_teams_card_is_unchanged() { let m = reminder(&["ana".to_string(), "bo".to_string()]); diff --git a/services/common/src/public_urls.rs b/services/common/src/public_urls.rs index bec18aef8..dc8d7b26e 100644 --- a/services/common/src/public_urls.rs +++ b/services/common/src/public_urls.rs @@ -301,23 +301,45 @@ pub fn api_url_from_env() -> &'static str { api_url(&env_stage()) } +/// The hosted deployment's AWS account (the default only there). +const HOSTED_ACCOUNT: &str = "654654210434"; +/// The hosted deployment's public copy of the log reader template. +const HOSTED_LOG_READER_TEMPLATE: &str = + "https://coderhelm-public.s3.amazonaws.com/cfn/coderhelm-log-reader.yaml"; + /// The AWS account teams' read-only roles trust: this deployment's own -/// (CODERHELM_ACCOUNT_ID, set by the deploy), else the hosted one. +/// (CODERHELM_ACCOUNT_ID, set by the deploy). The hosted account is the +/// default on the hosted deployment only: a self-hosted install without it +/// gives "" (no Launch Stack link, and Setup checks fail), never an account +/// that isn't its own. pub fn platform_account_id() -> String { - std::env::var("CODERHELM_ACCOUNT_ID") - .ok() + platform_account_id_from(std::env::var("CODERHELM_ACCOUNT_ID").ok(), self_hosted()) +} + +/// [`platform_account_id`]'s rule, on given values. +pub fn platform_account_id_from(v: Option, self_hosted: bool) -> String { + match v + .map(|a| a.trim().to_string()) .filter(|a| a.len() == 12 && a.chars().all(|c| c.is_ascii_digit())) - .unwrap_or_else(|| "654654210434".to_string()) + { + Some(a) => a, + None if self_hosted => String::new(), + None => HOSTED_ACCOUNT.to_string(), + } } -/// The CloudFormation template teams create that role from. +/// The CloudFormation template teams create that role from: +/// LOG_READER_TEMPLATE_URL (set by the deploy: on a self-hosted release, the +/// copy published with that release), else the hosted public copy. pub fn log_reader_template_url() -> String { - std::env::var("LOG_READER_TEMPLATE_URL") - .ok() + log_reader_template_url_from(std::env::var("LOG_READER_TEMPLATE_URL").ok()) +} + +/// [`log_reader_template_url`]'s rule, on a given value. +pub fn log_reader_template_url_from(v: Option) -> String { + v.map(|u| u.trim().to_string()) .filter(|u| u.starts_with("https://")) - .unwrap_or_else(|| { - "https://coderhelm-public.s3.amazonaws.com/cfn/coderhelm-log-reader.yaml".to_string() - }) + .unwrap_or_else(|| HOSTED_LOG_READER_TEMPLATE.to_string()) } /// The marketing site linked from email footers: SITE_URL, none when it is @@ -529,6 +551,42 @@ mod tests { assert!(hosted_mentions("coderhelm.company").is_empty()); } + #[test] + fn a_self_hosted_install_trusts_only_its_own_account() { + let s = |v: &str| Some(v.to_string()); + assert_eq!( + platform_account_id_from(s("111122223333"), true), + "111122223333" + ); + assert_eq!( + platform_account_id_from(s(" 111122223333 "), false), + "111122223333" + ); + // Never the hosted account on a self-hosted install. + assert_eq!(platform_account_id_from(None, true), ""); + assert_eq!(platform_account_id_from(s("12"), true), ""); + assert_eq!(platform_account_id_from(None, false), HOSTED_ACCOUNT); + } + + #[test] + fn the_template_comes_from_the_deploy() { + let s = |v: &str| Some(v.to_string()); + assert_eq!( + log_reader_template_url_from(s( + "https://coderhelm-public.s3.amazonaws.com/launch/v1.2.3/coderhelm-log-reader.yaml" + )), + "https://coderhelm-public.s3.amazonaws.com/launch/v1.2.3/coderhelm-log-reader.yaml" + ); + assert_eq!( + log_reader_template_url_from(s("http://x/y.yaml")), + HOSTED_LOG_READER_TEMPLATE + ); + assert_eq!( + log_reader_template_url_from(None), + HOSTED_LOG_READER_TEMPLATE + ); + } + #[test] fn host_for_display() { assert_eq!(host_of("https://app.example.com/x"), "app.example.com"); diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index b8c3d1491..45985d4de 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -742,6 +742,10 @@ async fn main() -> Result<(), Error> { "/aws-connections/cfn-url", get(routes::log_analyzer::get_cfn_url), ) + .route( + "/aws-connections/template", + get(routes::log_analyzer::download_template), + ) .route( "/aws-connections/:id", put(routes::log_analyzer::update_connection) @@ -763,6 +767,10 @@ async fn main() -> Result<(), Error> { "/aws-connections/:id/abilities/check", post(routes::integrations::check_aws), ) + .route( + "/aws-connections/:id/permissions/check", + post(routes::integrations::check_aws_permissions), + ) .route("/integrations", get(routes::integrations::list)) // Recommendations .route( diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index 7257da94b..b48273774 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -464,6 +464,7 @@ pub const CAPABILITIES: &[Capability] = &[ "log_analyzer::delete_connection", "log_analyzer::test_connection", "log_analyzer::get_cfn_url", + "log_analyzer::download_template", "log_analyzer::get_rec_notify", "log_analyzer::put_rec_notify", "plugins::enable_plugin", @@ -483,6 +484,7 @@ pub const CAPABILITIES: &[Capability] = &[ "mcp_servers::set_prompt", "mcp_servers::activity", "integrations::check_aws", + "integrations::check_aws_permissions", "integrations::set_aws_abilities", ], }, diff --git a/services/gateway/src/routes/connectors.rs b/services/gateway/src/routes/connectors.rs index 798084155..1eeef9819 100644 --- a/services/gateway/src/routes/connectors.rs +++ b/services/gateway/src/routes/connectors.rs @@ -35,11 +35,6 @@ use crate::AppState; type Reply = Result, (StatusCode, Json)>; -/// The add-on stack that gives the existing CoderHelmLogReader role read -/// access to metrics and Airflow. -pub const OPS_TEMPLATE_URL: &str = - "https://coderhelm-public.s3.amazonaws.com/cfn/coderhelm-log-reader-ops.yaml"; -pub const OPS_STACK_NAME: &str = "CoderHelmLogReaderOps"; const MAX_LIST: usize = 50; fn fail(status: StatusCode, message: &str) -> (StatusCode, Json) { @@ -173,13 +168,14 @@ async fn log_reader( .map_err(step) } -/// The link that adds the metrics and Airflow permissions to the team's -/// existing CoderHelmLogReader role, as a stack in its own account. -pub fn ops_stack_url(region: &str) -> String { - format!( - "https://console.aws.amazon.com/cloudformation/home?region={region}#/stacks/quickcreate?stackName={OPS_STACK_NAME}&templateURL={}¶m_RoleName=CoderHelmLogReader", - urlencoding::encode(OPS_TEMPLATE_URL) - ) +/// The one-click link that brings the team's existing CoderHelmLogReader +/// role up to this release's permissions (metrics, Airflow, ECS and the +/// rest), as a stack in its own account, from the install's own template +/// copy. None when the install's template has no update template next to +/// it (a template URL an operator chose). +pub fn update_stack_url(region: &str) -> Option { + common::log_reader::update_template_url(&common::public_urls::log_reader_template_url()) + .map(|t| common::log_reader::update_url(&t, region)) } async fn record( @@ -849,12 +845,13 @@ pub async fn aws_check( ) .await; let missing = check.missing(); + let template = common::public_urls::log_reader_template_url(); Ok(Json(json!({ "check": check, "missing": missing, - "update_url": if missing.is_empty() { None } else { Some(ops_stack_url(&t.region)) }, - "stack_name": OPS_STACK_NAME, - "template_url": OPS_TEMPLATE_URL, + "update_url": if missing.is_empty() { None } else { update_stack_url(&t.region) }, + "stack_name": common::log_reader::update_stack_name(), + "template_url": common::log_reader::update_template_url(&template), }))) } @@ -901,11 +898,11 @@ mod tests { } #[test] - fn the_update_link_opens_the_add_on_stack_for_the_existing_role() { - let u = ops_stack_url("us-west-2"); + fn the_update_link_opens_the_update_stack_for_the_existing_role() { + let u = update_stack_url("us-west-2").unwrap(); assert!(u.starts_with("https://console.aws.amazon.com/cloudformation/home?region=us-west-2#/stacks/quickcreate?")); - assert!(u.contains("stackName=CoderHelmLogReaderOps")); - assert!(u.contains("templateURL=https%3A%2F%2Fcoderhelm-public.s3.amazonaws.com%2Fcfn%2Fcoderhelm-log-reader-ops.yaml")); + assert!(u.contains("stackName=CoderHelmLogReaderUpdate-")); + assert!(u.contains("coderhelm-log-reader-update.yaml")); assert!(u.contains("param_RoleName=CoderHelmLogReader")); } diff --git a/services/gateway/src/routes/integrations.rs b/services/gateway/src/routes/integrations.rs index 1a88e6bdb..4a7ae8034 100644 --- a/services/gateway/src/routes/integrations.rs +++ b/services/gateway/src/routes/integrations.rs @@ -219,6 +219,21 @@ pub fn aws_state(a: &AwsAccount) -> CardState { if a.status == "error" { return cs("error", "The last test of the role failed.", "check_again"); } + if let Some(p) = a + .permissions + .as_ref() + .filter(|p| p.status() == "update_needed") + { + let n = p.missing.len(); + return cs( + "connected", + format!( + "Update needed: {n} new read-only permission{}.", + if n == 1 { "" } else { "s" } + ), + "manage", + ); + } cs("connected", "", "manage") } @@ -234,6 +249,13 @@ pub fn aws_missing(a: &AwsAccount) -> Vec<&'static str> { out } +/// The last live check found permissions of this release missing. +pub fn needs_update(a: &AwsAccount) -> bool { + a.permissions + .as_ref() + .is_some_and(|p| p.status() == "update_needed") +} + fn card( id: &str, name: &str, @@ -264,8 +286,24 @@ pub(crate) async fn check_and_save( a: &mut AwsAccount, actor: &str, ) { - let c = identity::check(&state.sts, &a.target(), Vec::new(), actor, true).await; - a.apply_check(&c, &chrono::Utc::now().to_rfc3339()); + let now = chrono::Utc::now().to_rfc3339(); + let target = a.target(); + let (c, perms) = tokio::join!( + identity::check(&state.sts, &target, Vec::new(), actor, true), + common::live::permissions::check(&state.sts, &target, actor, &now), + ); + a.apply_check(&c, &now); + if let Err(e) = aws_account::save_permissions( + &state.dynamo, + &state.config.aws_insights_table_name, + team_id, + &perms, + ) + .await + { + warn!(error = %e, account = %a.account, "Could not save the permissions check"); + } + a.permissions = Some(perms); if let Err(e) = aws_account::save_abilities( &state.dynamo, &state.config.aws_insights_table_name, @@ -474,7 +512,9 @@ pub async fn list( // AWS accounts: one card each (or one to connect the first). let stack_url = |a: &AwsAccount| { - (!aws_missing(a).is_empty()).then(|| super::connectors::ops_stack_url(&a.region)) + (!aws_missing(a).is_empty() || needs_update(a)) + .then(|| super::connectors::update_stack_url(&a.region)) + .flatten() }; if accounts.is_empty() { items.push(card( @@ -491,7 +531,7 @@ pub async fn list( let mut detail = a.public_json(); detail["missing"] = json!(aws_missing(a)); detail["update_url"] = json!(stack_url(a)); - detail["stack_name"] = json!(super::connectors::OPS_STACK_NAME); + detail["stack_name"] = json!(common::log_reader::update_stack_name()); items.push(card( &format!("aws-{}", a.account), &format!("AWS account {}", a.account), @@ -691,9 +731,10 @@ async fn load_account( fn account_reply(a: &AwsAccount) -> Value { let mut detail = a.public_json(); detail["missing"] = json!(aws_missing(a)); - detail["update_url"] = - json!((!aws_missing(a).is_empty()).then(|| super::connectors::ops_stack_url(&a.region))); - detail["stack_name"] = json!(super::connectors::OPS_STACK_NAME); + detail["update_url"] = json!((!aws_missing(a).is_empty() || needs_update(a)) + .then(|| super::connectors::update_stack_url(&a.region)) + .flatten()); + detail["stack_name"] = json!(common::log_reader::update_stack_name()); let st = aws_state(a); json!({ "account": detail, "status": st.status, "reason": st.reason, "last_check": a.abilities.checked_at }) } @@ -714,6 +755,36 @@ pub async fn check_aws( Ok(Json(account_reply(&a))) } +/// POST /api/aws-connections/:id/permissions/check — checks the role +/// against this release's permissions, live, and saves the result. With +/// `{"pressed": true}` (someone pressed Update), a missing or failed update +/// stack comes back as the problem to show. +pub async fn check_aws_permissions( + State(state): State>, + Extension(claims): Extension, + Path(id): Path, + body: Option>, +) -> Reply { + if let Err(code) = claims.require_role(3) { + return Err(fail(code, "Only admins can check integrations.")); + } + let pressed = body + .as_ref() + .and_then(|b| b.get("pressed")) + .and_then(Value::as_bool) + .unwrap_or(false); + let account = account_of(&id)?; + let mut a = load_account(&state, &claims.team_id, account).await?; + check_and_save(&state, &claims.team_id, &mut a, &claims.email).await; + let mut reply = account_reply(&a); + reply["permissions"] = a + .permissions + .as_ref() + .map(|p| p.view(pressed, &common::public_urls::log_reader_template_url())) + .unwrap_or(Value::Null); + Ok(Json(reply)) +} + /// What an admin may change about an account's abilities. #[derive(Debug, Default, PartialEq, Eq)] pub struct AbilityChange { @@ -946,7 +1017,7 @@ mod tests { assert!(r["account"]["update_url"] .as_str() .unwrap() - .contains("CoderHelmLogReaderOps")); + .contains("CoderHelmLogReaderUpdate-")); assert!(account_reply(&account())["account"]["update_url"].is_null()); } diff --git a/services/gateway/src/routes/log_analyzer.rs b/services/gateway/src/routes/log_analyzer.rs index 2cce3a460..fee4423b9 100644 --- a/services/gateway/src/routes/log_analyzer.rs +++ b/services/gateway/src/routes/log_analyzer.rs @@ -678,34 +678,107 @@ pub async fn discover_log_groups( Ok(Json(json!({ "log_groups": log_groups }))) } -/// GET /api/aws-connections/cfn-url — get CloudFormation quick-create URL +/// GET /api/aws-connections/cfn-url — the Launch Stack link for the +/// team's read-only role, and what a person needs to make it by hand. +/// +/// The role trusts this install's own account (never CoderHelm's, on a +/// self-hosted install) and, on a self-hosted install, only the install's +/// own roles. The template is the install's copy +/// (`LOG_READER_TEMPLATE_URL`: a self-hosted release links to the copy +/// published with it). pub async fn get_cfn_url( State(state): State>, Extension(claims): Extension, -) -> Result, StatusCode> { +) -> Result, (StatusCode, Json)> { if !is_admin_or_owner(&claims.role) { - return Err(StatusCode::FORBIDDEN); + return Err(( + StatusCode::FORBIDDEN, + Json(json!({ "error": "Only admins can connect AWS accounts." })), + )); } - - let external_id = team_external_id(&state, &claims.team_id).await?; + let account = common::public_urls::platform_account_id(); + if account.is_empty() { + return Err(( + StatusCode::SERVICE_UNAVAILABLE, + Json(json!({ + "error": "This install doesn't know its own AWS account, so it can't make the role link yet. An install admin can fix it: deploy again with the installer, which sets it.", + "code": "account_unknown", + })), + )); + } + let external_id = team_external_id(&state, &claims.team_id) + .await + .map_err(|c| { + ( + c, + Json(json!({ "error": "Could not load your External ID. Try again." })), + ) + })?; let template_url = common::public_urls::log_reader_template_url(); - let stack_name = "CoderHelmLogReader"; - - let cfn_url = format!( - "https://console.aws.amazon.com/cloudformation/home#/stacks/quickcreate?stackName={}&templateURL={}¶m_ExternalId={}¶m_CoderHelmAccountId={}", - stack_name, - urlencoding::encode(&template_url), - external_id, - common::public_urls::platform_account_id(), - ); - + let prefix = if common::public_urls::self_hosted() { + common::log_reader::trusted_role_prefix() + } else { + String::new() + }; + let cfn_url = + common::log_reader::quick_create_url(&template_url, &external_id, &account, &prefix); + let abilities: Vec = common::log_reader::ABILITIES + .iter() + .map(|a| json!({ "key": a.key, "name": a.name, "why": a.why, "actions": a.actions })) + .collect(); Ok(Json(json!({ "cfn_url": cfn_url, "external_id": external_id, "template_url": template_url, + "account_id": account, + "trusted_role_prefix": prefix, + "self_hosted": common::public_urls::self_hosted(), + "abilities": abilities, + "permissions_id": common::log_reader::permissions_id(), }))) } +#[derive(serde::Deserialize)] +pub struct TemplateQuery { + which: Option, +} + +/// GET /api/aws-connections/template?which=role|update — the role's +/// template as built into this release, with this install's account filled +/// in, for teams that upload it to CloudFormation by hand. +pub async fn download_template( + Extension(claims): Extension, + Query(q): Query, +) -> Result { + use axum::response::IntoResponse; + if !is_admin_or_owner(&claims.role) { + return Err(StatusCode::FORBIDDEN); + } + let (which, name) = match q.which.as_deref().unwrap_or("role") { + "role" => (common::log_reader::Which::Role, "coderhelm-log-reader.yaml"), + "update" => ( + common::log_reader::Which::Update, + "coderhelm-log-reader-update.yaml", + ), + _ => return Err(StatusCode::BAD_REQUEST), + }; + let body = common::log_reader::template_for(&common::public_urls::platform_account_id(), which); + Ok(( + [ + ( + axum::http::header::CONTENT_TYPE, + "text/yaml; charset=utf-8".to_string(), + ), + ( + axum::http::header::CONTENT_DISPOSITION, + format!("attachment; filename=\"{name}\""), + ), + ], + body, + ) + .into_response()) +} + // ──────────────────────────────────────────────────────────────── // Recommendations // ──────────────────────────────────────────────────────────────── diff --git a/services/gateway/src/routes/setup_checks.rs b/services/gateway/src/routes/setup_checks.rs index b5c26efda..1bf703661 100644 --- a/services/gateway/src/routes/setup_checks.rs +++ b/services/gateway/src/routes/setup_checks.rs @@ -846,6 +846,87 @@ pub fn jira(connected: bool) -> Check { } } +/// What a download of a role template answered: the same bytes as the +/// template built into this release, other bytes, or nothing. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Fetched { + Same, + Different, + Unreachable, +} + +/// Connected AWS accounts: the install knows its own AWS account (teams' +/// roles trust it, never CoderHelm's), and the templates its Launch Stack +/// and update links open are this release's. `update` is None when the +/// role template's URL has no update template next to it. +pub fn aws_connections( + account: &str, + template_url: &str, + role: Fetched, + update: Option, +) -> Check { + const KEY: &str = "aws_connections"; + const LABEL: &str = "AWS connections"; + if account.is_empty() { + return Check::not_ok( + Status::Fail, + KEY, + X, + LABEL, + "This install doesn't know its own AWS account (CODERHELM_ACCOUNT_ID isn't set).", + "Teams' read-only AWS roles must trust this install's account, so the role link can't be made.", + Fix::text("Deploy again from your machine: the installer sets it.") + .command(format!("{CLI} deploy")), + ); + } + let fix = Fix::text("Remove logReaderTemplateUrl from the config to use this release's own copy, or publish this release's infra/cfn templates at that address, then deploy.") + .url("https://docs.coderhelm.com/self-host/integrations#connected-aws-accounts"); + match (role, update) { + (Fetched::Unreachable, _) => Check::not_ok( + Status::Warn, + KEY, + X, + LABEL, + format!("The role template at {template_url} didn't download."), + "Teams' Launch Stack links open this template, so connecting an AWS account fails.", + fix, + ), + (Fetched::Different, _) => Check::not_ok( + Status::Warn, + KEY, + X, + LABEL, + format!("The role template at {template_url} isn't the one built into this release."), + "New roles would get other permissions than this release checks for.", + fix, + ), + (Fetched::Same, None) => Check::not_ok( + Status::Warn, + KEY, + X, + LABEL, + "There's no coderhelm-log-reader-update.yaml next to the role template.", + "Without it, the one-click update for an existing role can't be offered.", + fix, + ), + (Fetched::Same, Some(Fetched::Same)) => Check::pass( + KEY, + X, + LABEL, + format!("Teams' roles trust account {account}, and the role and update templates are this release's."), + ), + (Fetched::Same, Some(_)) => Check::not_ok( + Status::Warn, + KEY, + X, + LABEL, + "The update template next to the role template is missing or isn't this release's.", + "The one-click update would give existing roles other permissions than this release checks for.", + fix, + ), + } +} + // ── Your own domain ─────────────────────────────────────────────────────── // // The updater requests the certificate and moves the domain along @@ -1740,13 +1821,47 @@ async fn url_status(state: &AppState) -> (String, Option) { (url, code) } +async fn fetched(state: &AppState, url: &str, built_in: &str) -> Fetched { + let got = state + .http + .get(url) + .timeout(Duration::from_secs(8)) + .send() + .await + .ok() + .filter(|r| r.status().is_success()); + match got { + Some(r) => match r.bytes().await { + Ok(b) if b.as_ref() == built_in.as_bytes() => Fetched::Same, + Ok(_) => Fetched::Different, + Err(_) => Fetched::Unreachable, + }, + None => Fetched::Unreachable, + } +} + +async fn aws_connections_check(state: &AppState) -> Check { + use common::log_reader; + let account = common::public_urls::platform_account_id(); + let url = common::public_urls::log_reader_template_url(); + let update_url = log_reader::update_template_url(&url); + let (role, update) = tokio::join!(fetched(state, &url, log_reader::ROLE_TEMPLATE), async { + match &update_url { + Some(u) => Some(fetched(state, u, log_reader::UPDATE_TEMPLATE).await), + None => None, + } + }); + aws_connections(&account, &url, role, update) +} + async fn integration_checks(state: &AppState, team_id: &str) -> Vec { use common::notify::{store, ChannelKind}; let jira_key = [("pk", team_id), ("sk", "JIRA#config")]; - let (notify, jira_secret, jira_config) = tokio::join!( + let (notify, jira_secret, jira_config, aws) = tokio::join!( super::alerts::team_notify_settings(state, team_id), super::api::load_jira_secret(state, team_id), get_item(state, &state.config.jira_config_table_name, &jira_key), + aws_connections_check(state), ); let forge = jira_config.as_ref().is_some_and(|i| { i.get("add_comment_url") @@ -1767,6 +1882,7 @@ async fn integration_checks(state: &AppState, team_id: &str) -> Vec { notify.enabled, ), jira(forge || jira_secret.is_some()), + aws, ] } @@ -2524,6 +2640,34 @@ pub async fn status( #[cfg(test)] mod tests { + #[test] + fn aws_connections_need_the_install_account_and_this_release_templates() { + use super::{aws_connections, Fetched, Status}; + let u = "https://coderhelm-public.s3.amazonaws.com/launch/v1.2.3/coderhelm-log-reader.yaml"; + let ok = aws_connections("111122223333", u, Fetched::Same, Some(Fetched::Same)); + assert_eq!(ok.status, Status::Pass); + assert!(ok.detail.contains("111122223333")); + let no_account = aws_connections("", u, Fetched::Same, Some(Fetched::Same)); + assert_eq!(no_account.status, Status::Fail); + assert!(no_account + .fix + .unwrap() + .command + .unwrap() + .ends_with(" deploy")); + for (role, update) in [ + (Fetched::Unreachable, None), + (Fetched::Different, Some(Fetched::Same)), + (Fetched::Same, None), + (Fetched::Same, Some(Fetched::Unreachable)), + ] { + let c = aws_connections("111122223333", u, role, update); + assert_eq!(c.status, Status::Warn, "{role:?} {update:?}"); + assert!(!c.detail.is_empty() && !c.why.is_empty()); + assert!(c.fix.unwrap().text.split(". ").count() <= 2); + } + } + use super::*; fn app(perms: Value, events: Value) -> Value { diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index c8d6697a7..7441c10ff 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -605,6 +605,11 @@ async fn handle_message(state: Arc, message: models::WorkerMessage) Err(e) => error!("DLQ cleanup failed: {e}"), } } + models::WorkerMessage::AwsPermissionsSweep => { + if let Err(e) = passes::aws_permissions::run(&state).await { + error!("AWS permissions sweep failed: {e}"); + } + } models::WorkerMessage::LogAutofix => match passes::log_autofix::run(&state).await { Ok(r) => info!( teams = r.teams, diff --git a/services/worker/src/passes/aws_permissions.rs b/services/worker/src/passes/aws_permissions.rs new file mode 100644 index 000000000..6bf8bcc4f --- /dev/null +++ b/services/worker/src/passes/aws_permissions.rs @@ -0,0 +1,209 @@ +//! Daily: checks every connected AWS account's CoderHelmLogReader role +//! against the permissions this release uses +//! (`common::live::permissions`), saves the result for the AWS page, and +//! tells each team once per new set of permissions when an account needs +//! the update (where the team's notifications post: Slack, Teams). +//! +//! "Once" is a team record (`AWS_PERMS_NOTICE`) holding the permissions id +//! it was told about, written with a condition before the message is sent, +//! so two sweeps never post twice. + +use std::collections::BTreeMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use common::live::aws_account::{self, AwsAccount}; +use common::live::permissions::{self, PermissionCheck}; +use tracing::{info, warn}; + +use crate::WorkerState; + +pub const NOTICE_SK: &str = "AWS_PERMS_NOTICE"; + +#[derive(Debug, Default)] +pub struct Report { + pub accounts: usize, + pub need_update: usize, + pub teams_told: usize, +} + +/// Every connected account, by team. +async fn accounts_by_team( + state: &WorkerState, +) -> Result>, String> { + let mut out: BTreeMap> = BTreeMap::new(); + let mut start = None; + loop { + let page = state + .dynamo + .scan() + .table_name(&state.config.aws_insights_table_name) + .filter_expression("begins_with(sk, :p)") + .expression_attribute_values(":p", AttributeValue::S(aws_account::PREFIX.into())) + .set_exclusive_start_key(start) + .send() + .await + .map_err(|e| format!("scan aws connections: {e}"))?; + for item in page.items() { + let team = item + .get("pk") + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default(); + if let (false, Some(a)) = (team.is_empty(), AwsAccount::from_item(item)) { + out.entry(team).or_default().push(a); + } + } + start = page.last_evaluated_key().cloned(); + if start.is_none() { + break; + } + } + Ok(out) +} + +/// Pure: whether a team that was last told about `told` should be told now. +pub fn should_tell(checks: &[PermissionCheck], told: Option<&str>) -> bool { + let id = common::log_reader::permissions_id(); + told != Some(id.as_str()) && checks.iter().any(|c| c.status() == "update_needed") +} + +/// Claims this permissions id for the team: true only for the one sweep that +/// writes it first. +async fn claim_notice(state: &WorkerState, team_id: &str) -> bool { + let id = common::log_reader::permissions_id(); + state + .dynamo + .put_item() + .table_name(&state.config.aws_insights_table_name) + .item("pk", AttributeValue::S(team_id.into())) + .item("sk", AttributeValue::S(NOTICE_SK.into())) + .item("permissions_id", AttributeValue::S(id.clone())) + .item( + "told_at", + AttributeValue::S(chrono::Utc::now().to_rfc3339()), + ) + .condition_expression("attribute_not_exists(pk) OR permissions_id <> :id") + .expression_attribute_values(":id", AttributeValue::S(id)) + .send() + .await + .is_ok() +} + +async fn told(state: &WorkerState, team_id: &str) -> Option { + state + .dynamo + .get_item() + .table_name(&state.config.aws_insights_table_name) + .key("pk", AttributeValue::S(team_id.into())) + .key("sk", AttributeValue::S(NOTICE_SK.into())) + .send() + .await + .ok()? + .item()? + .get("permissions_id")? + .as_s() + .ok() + .cloned() +} + +pub async fn run(state: &WorkerState) -> Result { + let teams = accounts_by_team(state).await?; + let mut report = Report::default(); + let now = chrono::Utc::now().to_rfc3339(); + for (team_id, accounts) in &teams { + let mut checks = Vec::new(); + for a in accounts { + let c = permissions::check(&state.sts, &a.target(), "permissions-check", &now).await; + if let Err(e) = aws_account::save_permissions( + &state.dynamo, + &state.config.aws_insights_table_name, + team_id, + &c, + ) + .await + { + warn!(team_id, account = %a.account, error = %e, "Could not save the permissions check"); + } + report.accounts += 1; + if c.status() == "update_needed" { + report.need_update += 1; + } + checks.push(c); + } + let last = told(state, team_id).await; + if !should_tell(&checks, last.as_deref()) || !claim_notice(state, team_id).await { + continue; + } + let cipher = common::mcp_credentials::Kms { + client: &state.kms, + key_id: "", + }; + let channels = common::log_findings::channels( + &state.dynamo, + &cipher, + &state.config.settings_table_name, + team_id, + ) + .await; + if channels.is_empty() { + continue; + } + let needing: Vec<(String, usize)> = checks + .iter() + .filter(|c| c.status() == "update_needed") + .map(|c| (c.account.clone(), c.missing.len())) + .collect(); + let url = format!( + "{}/settings/integrations/aws", + super::skills::app_url(&state.config.stage) + ); + let msg = common::notify::messages::aws_permissions_update(&needing, &url); + common::notify::deliver_recorded( + &common::notify::Http(&state.http), + &channels, + &msg, + "aws_permissions", + &state.dynamo, + &state.config.settings_table_name, + team_id, + ) + .await; + report.teams_told += 1; + } + info!( + accounts = report.accounts, + need_update = report.need_update, + teams_told = report.teams_told, + "AWS permissions sweep" + ); + Ok(report) +} + +#[cfg(test)] +mod tests { + use super::*; + use common::live::aws::AwsTarget; + + fn check(missing: &[&str]) -> PermissionCheck { + let t = AwsTarget { + role_arn: "arn:aws:iam::111122223333:role/CoderHelmLogReader".into(), + external_id: "x".into(), + region: "us-east-1".into(), + ..Default::default() + }; + let mut c = PermissionCheck::new(&t, "t"); + c.works = true; + c.missing = missing.iter().map(|s| s.to_string()).collect(); + c + } + + #[test] + fn a_team_is_told_once_per_set_of_permissions() { + let id = common::log_reader::permissions_id(); + let need = vec![check(&[]), check(&["ecs:ListTasks"])]; + assert!(should_tell(&need, None)); + assert!(should_tell(&need, Some("00000000"))); + assert!(!should_tell(&need, Some(&id))); + assert!(!should_tell(&[check(&[])], None)); + } +} diff --git a/services/worker/src/passes/log_evidence.rs b/services/worker/src/passes/log_evidence.rs index 9c87c9c62..df2ee098e 100644 --- a/services/worker/src/passes/log_evidence.rs +++ b/services/worker/src/passes/log_evidence.rs @@ -165,6 +165,23 @@ impl LogEvidence { self.tried.iter().filter(|t| !t.ok).collect() } + /// Lookups the team's role wasn't allowed to make (its permissions are + /// older than this release's): each source once. + pub fn refused_sources(&self) -> Vec<&str> { + let mut out: Vec<&str> = Vec::new(); + for t in self.tried.iter().filter(|t| !t.ok) { + let o = t.outcome.to_ascii_lowercase(); + let refused = o.contains("accessdenied") + || o.contains("access denied") + || o.contains("not authorized") + || o.contains("unauthorizedoperation"); + if refused && !out.contains(&t.source.as_str()) { + out.push(t.source.as_str()); + } + } + out + } + /// The tasks failing now. pub fn failing_now(&self) -> Vec<&TaskErrors> { self.tasks.iter().filter(|t| t.failing_now).collect() @@ -737,6 +754,13 @@ pub fn facts_markdown(ev: &LogEvidence) -> String { out.push_str(&format!("* Start path not resolved: {}.\n", sp.missing)); } } + let refused = ev.refused_sources(); + if !refused.is_empty() { + out.push_str(&format!( + "\nThe team's AWS role isn't allowed {} yet (its permissions predate this release). Work with the facts above; name these sources when something stays open, and never ask for more access in the PR.\n", + refused.iter().map(|r| format!("`{r}`")).collect::>().join(", ") + )); + } out.push_str("\nSources tried:\n"); for t in &ev.tried { out.push_str(&format!( @@ -1162,6 +1186,13 @@ pub fn summary_note(ev: &LogEvidence) -> String { if let Some(r) = ev.fill_mb_per_hour { s.push_str(&format!("; fills at about {} MB/h", fmt_f(r))); } + let refused = ev.refused_sources(); + if !refused.is_empty() { + s.push_str(&format!( + "; the AWS role can't read {} yet, so those steps were skipped (an admin can update its permissions in one click in Settings, Integrations, AWS)", + refused.join(", ") + )); + } let failing = ev.failing_now(); if !failing.is_empty() { s.push_str(&format!( @@ -1176,6 +1207,52 @@ pub fn summary_note(ev: &LogEvidence) -> String { s } +#[cfg(test)] +mod refused_tests { + use super::*; + + #[test] + fn refused_lookups_point_at_the_one_click_update() { + let ev = LogEvidence { + tried: vec![ + SourceTry { + source: "logs:StartQuery".into(), + question: "q".into(), + ok: true, + outcome: "12 rows".into(), + }, + SourceTry { + source: "ecs:DescribeTasks".into(), + question: "q".into(), + ok: false, + outcome: + "AccessDeniedException: User is not authorized to perform ecs:DescribeTasks" + .into(), + }, + SourceTry { + source: "ecs:DescribeTasks".into(), + question: "q2".into(), + ok: false, + outcome: "AccessDenied".into(), + }, + SourceTry { + source: "ecs:ListClusters".into(), + question: "q".into(), + ok: false, + outcome: "timed out".into(), + }, + ], + ..Default::default() + }; + assert_eq!(ev.refused_sources(), vec!["ecs:DescribeTasks"]); + let note = summary_note(&ev); + assert!(note.contains("can't read ecs:DescribeTasks yet"), "{note}"); + assert!(note.contains("Settings, Integrations, AWS")); + assert!(facts_markdown(&ev).contains("isn't allowed `ecs:DescribeTasks` yet")); + assert!(!summary_note(&LogEvidence::default()).contains("can't read")); + } +} + #[cfg(test)] pub(crate) mod fake { use super::*; diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index a5a7ef72f..b756551b5 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -688,6 +688,7 @@ fn has_time_for_remediation(start: &Instant) -> bool { pub mod agent_tools; pub mod await_merge; +pub mod aws_permissions; mod checks; pub mod code_graph; mod completeness;