Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/self-host/integrations.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Teams connect their own AWS accounts so CoderHelm can read CloudWatch logs, alar
- **Making the role by hand**\
The AWS page lists every action the role needs, grouped by what CoderHelm reads with it, and your install's account id. Create the role named `CoderHelmLogReader`, let your install's account assume it only with the team's External ID, and allow those actions.
- **Reading the install's own account**\
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.
Connect it the same way: the `CoderHelmLogReader` role there, with the team's External ID, proves the team may read it. After that, the install reads its own account with its gateway's and worker's own roles, which the install's stack gives this release's read-only permissions (`infra/lib/own-account-read.ts`, the same list as the update template). Each version update brings any new permission, so the install's own account never shows **Update in AWS**; if a permission is still missing, the page says it comes with the next version update.
- **When a release needs new permissions**\
Each AWS connection shows **Permissions up to date** or **Update needed: N new read-only permissions**. The check runs live: it asks IAM's policy simulator about the role (`iam:SimulatePrincipalPolicy` on that one role), or, for roles made before that, tries the cheapest read of each kind. **Update in AWS** opens a stack (`CoderHelmLogReaderUpdate-<id>`) 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)**\
Expand Down
17 changes: 14 additions & 3 deletions infra/lib/access.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,9 @@ export const LOG_ANALYZER_ROLE = "log-analyzer";
/** Every tag value the boundary lets take on the read roles in this account. */
export const READ_ROLE_CALLERS = [...RUNTIME_ROLES, LOG_ANALYZER_ROLE];
/** STS actions on a role in this account: all denied, except sts:AssumeRole on the read roles above. */
const ROLE_SESSION_ACTIONS = ["sts:AssumeRole", "sts:AssumeRoleWithWebIdentity", "sts:AssumeRoleWithSAML", "sts:TagSession", "sts:SetSourceIdentity"];
const ROLE_SESSION_ACTIONS = ["sts:AssumeRole*", "sts:TagSession", "sts:SetSourceIdentity"];
/** The same, without sts:AssumeRole itself (AssumeRoleWithWebIdentity and AssumeRoleWithSAML). */
const OTHER_SESSION_ACTIONS = ["sts:AssumeRoleWith*", "sts:TagSession", "sts:SetSourceIdentity"];

/** Role and policy writes: only with the boundary on the role. */
export const ROLE_WRITES = [
Expand Down Expand Up @@ -196,6 +198,15 @@ const POLICY_MANAGE = [
*/
export const BOUNDARY_SERVICES = [
"acm:*",
// A self-hosted install reading its own account (own-account-read.ts):
// Airflow as a Viewer, ECS services and image manifests, read-only.
"airflow:Get*",
"airflow:List*",
"airflow:InvokeRestApi",
"ecs:Describe*",
"ecs:List*",
"ecr:BatchGetImage",
"ecr:List*",
"apigateway:*",
"bedrock:InvokeModel",
"bedrock:InvokeModelWithResponseStream",
Expand Down Expand Up @@ -339,7 +350,7 @@ export function guardrails(n: AccessNames, otherBoundaries: string[] = []): Stat
// On the read roles: sts:AssumeRole only, no other STS action.
Sid: "ReadRolesHereAssumeOnly",
Effect: "Deny",
Action: ROLE_SESSION_ACTIONS.filter((x) => x !== "sts:AssumeRole"),
Action: OTHER_SESSION_ACTIONS,
Resource: a.ownReadRoles,
},
{
Expand Down Expand Up @@ -376,7 +387,7 @@ export function boundaryPolicy(n: AccessNames, otherBoundaries: string[] = []):
{ Sid: "CoderHelmServices", Effect: "Allow", Action: BOUNDARY_SERVICES, Resource: "*" },
{ Sid: "InstallRoleWrites", Effect: "Allow", Action: ROLE_WRITES, Resource: a.role, Condition: { StringEquals: { "iam:PermissionsBoundary": n.boundaryArn } } },
// The same calls as ROLE_MANAGE and POLICY_MANAGE, shorter (the boundary must fit IAM's 6,144 characters).
{ Sid: "InstallRoles", Effect: "Allow", Action: ["iam:Get*", "iam:List*", "iam:DeleteRole", "iam:UpdateRole*", "iam:UpdateAssumeRolePolicy", "iam:TagRole", "iam:UntagRole", "iam:PassRole"], Resource: a.role },
{ Sid: "InstallRoles", Effect: "Allow", Action: ["iam:Get*", "iam:List*", "iam:Simulate*", "iam:DeleteRole", "iam:UpdateRole*", "iam:UpdateAssumeRolePolicy", "iam:TagRole", "iam:UntagRole", "iam:PassRole"], Resource: a.role },
{ Sid: "InstallPolicies", Effect: "Allow", Action: ["iam:CreatePolicy*", "iam:DeletePolicy*", "iam:Get*", "iam:List*", "iam:TagPolicy", "iam:UntagPolicy"], Resource: a.policy },
...guardrails(n, otherBoundaries),
]);
Expand Down
4 changes: 4 additions & 0 deletions infra/lib/api-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import * as scheduler from "aws-cdk-lib/aws-scheduler";
import { Construct } from "constructs";
import { ResolvedConfig } from "./config";
import { repoPath } from "./paths";
import { grantOwnAccountRead } from "./own-account-read";
import { Hybrid } from "./hybrid";
import { serviceEnvironment, modelPolicyStatements, publicUrlReadStatement, recordNameIn, setupEnvironment, setupStatements, updaterInvokeStatement, weeklySummaryScheduled } from "./service-env";
import { MailRelay, relaySendStatement } from "./mail-relay";
Expand Down Expand Up @@ -625,6 +626,9 @@ export class ApiStack extends cdk.Stack {
...serviceEnvironment(cfg, this.account),
},
});
// A self-hosted install reads its own AWS account with this role, whose
// read-only permissions arrive with each version update (own-account-read.ts).
if (cfg.layout === "single-origin") grantOwnAccountRead(this, "GatewayOwnAccountRead", this.gatewayFunction);
for (const st of [...modelPolicyStatements(cfg, this), publicUrlReadStatement(cfg, this), updaterInvokeStatement(cfg, this), relaySendStatement(cfg, this.account)]) {
if (st) this.gatewayFunction.addToRolePolicy(st);
}
Expand Down
57 changes: 57 additions & 0 deletions infra/lib/own-account-read.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/**
* A self-hosted install reading its own AWS account (logs, metrics, Airflow,
* ECS and the rest): its gateway and worker read with their own roles, and
* this stack gives those roles the read-only permissions of the release.
* Every version update brings them along, so nobody launches an extra stack
* to grant the install what its own release needs.
*
* The permissions are the update template's (infra/cfn/coderhelm-log-reader-update.yaml),
* read from that file: the same one the services check a role against
* (services/common/src/log_reader.rs), so the two can't drift apart.
*
* Connecting the account still proves the team's own CoderHelmLogReader role
* with its private ID (routes/log_analyzer.rs); only reading uses the
* install's role (services/common/src/live/aws.rs, install_target).
*/
import * as cdk from "aws-cdk-lib";
import * as iam from "aws-cdk-lib/aws-iam";
import { CfnInclude } from "aws-cdk-lib/cloudformation-include";
import { Construct } from "constructs";
import { repoPath } from "./paths";

/** The environment variable naming the function's own role (live/aws.rs, OWN_ROLE_ENV). */
export const OWN_ROLE_ENV = "INSTALL_OWN_ROLE_ARN";
const UPDATE_TEMPLATE = "infra/cfn/coderhelm-log-reader-update.yaml";
const UPDATE_POLICY_ID = "CoderHelmReadOnlyUpdate";
const ROLE_NAME_MARK = "__CODERHELM_ROLE__";

type Statement = { Sid?: string; Effect: string; Action: string | string[]; Resource: unknown };

/** The update template's statements, as the template has them. */
export function updateTemplateStatements(): Statement[] {
const scratch = new cdk.Stack(new cdk.App(), "Scratch");
const inc = new CfnInclude(scratch, "T", { templateFile: repoPath(UPDATE_TEMPLATE), parameters: { RoleName: ROLE_NAME_MARK } });
const p = inc.getResource(UPDATE_POLICY_ID) as iam.CfnPolicy;
return scratch.resolve(p.policyDocument).Statement as Statement[];
}

/**
* The statements for `roleArn`: the template's, with the one statement that
* names the role (the permission check on itself) pointed at `roleArn`.
*/
export function ownAccountStatements(roleArn: string): Statement[] {
return updateTemplateStatements().map((s) =>
JSON.stringify(s.Resource).includes(ROLE_NAME_MARK) ? { ...s, Resource: roleArn } : s,
);
}

/** Gives `fn`'s role this release's read-only permissions in its own account, and tells it so. */
export function grantOwnAccountRead(scope: Construct, id: string, fn: cdk.aws_lambda.Function): void {
const role = fn.role!;
new iam.CfnManagedPolicy(scope, id, {
description: "CoderHelm: reads this install's own AWS account (logs, metrics, Airflow, ECS), read-only; kept current by each version update",
roles: [role.roleName],
policyDocument: { Version: "2012-10-17", Statement: ownAccountStatements(role.roleArn) },
});
fn.addEnvironment(OWN_ROLE_ENV, role.roleArn);
}
4 changes: 4 additions & 0 deletions infra/lib/worker-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { Construct } from "constructs";
import { ResolvedConfig } from "./config";
import { HYBRID_SIGNER_TAG, grantHybridMaster, grantNameRecords, hybridSigningAlias } from "./hybrid";
import { repoPath } from "./paths";
import { grantOwnAccountRead } from "./own-account-read";
import * as path from "path";
import { relaySendStatement } from "./mail-relay";
import { serviceEnvironment, modelPolicyStatements, publicUrlReadStatement, weeklySummaryScheduled } from "./service-env";
Expand Down Expand Up @@ -141,6 +142,9 @@ export class WorkerStack extends cdk.Stack {
...serviceEnvironment(cfg, this.account),
},
});
// A self-hosted install reads its own AWS account with this role, whose
// read-only permissions arrive with each version update (own-account-read.ts).
if (cfg.layout === "single-origin") grantOwnAccountRead(this, "WorkerOwnAccountRead", this.workerFunction);
for (const st of [...modelPolicyStatements(cfg, this), publicUrlReadStatement(cfg, this), relaySendStatement(cfg, this.account)]) {
if (st) this.workerFunction.addToRolePolicy(st);
}
Expand Down
4 changes: 4 additions & 0 deletions infra/scripts/deploy-role-sim.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,10 @@ def targets(st, lid, r, action):
if action in ("iam:AttachRolePolicy", "iam:DetachRolePolicy"):
return [(f"arn:aws:iam::{ACCT}:role/{st.resolve(x)}", {}) for x in p.get("Roles", [])]
return [(arn, {})]
# A bulk operation is its own resource (bulk-operation/<id>), described only
# while one runs; the install's tables never start one (no import source).
if action == "dynamodb:DescribeBulkOperation" and not p.get("ImportSourceSpecification"):
return [("UNUSED:no bulk operation", {})]
if svc == "iam" and ty == "AWS::SNS::Topic":
return [("UNUSED:no delivery status logging role", {})]
if svc == "sns" and action in ("sns:Subscribe", "sns:Unsubscribe", "sns:ListSubscriptionsByTopic") and not p.get("Subscription"):
Expand Down
Loading
Loading