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
21 changes: 18 additions & 3 deletions dashboard/e2e/infra-aws-switch.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ function account(on: boolean, available: boolean | null) {
};
}

async function mockApi(page: Page) {
const db = { on: false, puts: [] as unknown[] };
async function mockApi(page: Page, init: { on?: boolean; liveHasReads?: boolean } = {}) {
const db = { on: init.on ?? false, puts: [] as unknown[] };
const json = (r: Route, body: unknown, status = 200) => r.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) });
await page.route((url) => url.hostname !== "localhost", (r) => r.abort());
await page.route((url) => url.hostname === "localhost" && /^\/(api|auth)\//.test(url.pathname), async (r) => {
Expand All @@ -59,7 +59,14 @@ async function mockApi(page: Page) {
if (typeof body.infrastructure === "boolean") db.on = body.infrastructure;
return json(r, { account: conn().abilities, status: "connected", reason: "", last_check: new Date().toISOString() });
}
if (/permissions\/check$/.test(p)) return json(r, { account: conn().abilities, status: "connected", reason: "", last_check: new Date().toISOString(), permissions: conn().abilities.permissions });
if (/permissions\/check$/.test(p)) {
if (init.liveHasReads) {
// The role has the reads now: a check newer than the saved one.
const now = permissionsView(A, { optionalOff: [] });
return json(r, { account: conn().abilities, status: "connected", reason: "", last_check: new Date().toISOString(), permissions: { ...now, checked_at: new Date(Date.now() + 60_000).toISOString() } });
}
return json(r, { account: conn().abilities, status: "connected", reason: "", last_check: new Date().toISOString(), permissions: conn().abilities.permissions });
}
if (/\/log-groups$/.test(p)) return json(r, { log_groups: [] });
return json(r, { error: `not mocked: ${p}` }, 404);
});
Expand All @@ -83,3 +90,11 @@ test("switching on Infrastructure vulnerabilities names what it reads and the up
await missing.scrollIntoViewIfNeeded();
await shoot(page, "aws-infrastructure-switch");
});

test("a saved warning about the reads goes away when the page's live check finds them", async ({ page }) => {
await mockApi(page, { on: true, liveHasReads: true });
await page.goto("/settings/integrations/aws/");
await expect(page.getByRole("switch", { name: "Infrastructure vulnerabilities" })).toBeChecked();
await expect(page.getByTestId(`aws-perms-${A}`)).toContainText("Permissions up to date");
await expect(page.getByTestId("infra-reads-missing")).toHaveCount(0);
});
73 changes: 71 additions & 2 deletions dashboard/e2e/infra-security.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { expect, test, type Page, type Route } from "@playwright/test";
import { shoot } from "./infra-shots";
import { permissionsView } from "./aws-permissions-data";
import { ACCOUNT_MISSING, INFRA_FEEDS, INFRA_INSIGHTS, INFRA_RESOURCES, infraFinding, infraOverview, iso } from "./infra-data";

// Infrastructure vulnerabilities: Security › Infrastructure grouped by fix
Expand All @@ -14,10 +15,14 @@ interface Db {
overview: unknown;
overviewCode: number;
calls: { call: string; body: unknown }[];
/** The live permission check's answer for an account (infra reads it lacks), or null for a failed check. */
live: (account: string) => string[] | null;
/** Holds the live check's answer until it resolves. */
hold: Promise<void> | null;
}

async function mockApi(page: Page, init: Partial<Db> = {}): Promise<Db> {
const db: Db = { role: "admin", overview: infraOverview(), overviewCode: 200, calls: [], ...init };
const db: Db = { role: "admin", overview: infraOverview(), overviewCode: 200, calls: [], live: () => null, hold: null, ...init };
const json = (route: Route, body: unknown, code = 200) => route.fulfill({ status: code, contentType: "application/json", body: JSON.stringify(body) });
await page.route((url) => url.hostname !== "localhost", (route) => route.abort());
await page.route((url) => url.hostname === "localhost" && /^\/(api|auth)\//.test(url.pathname), async (route) => {
Expand All @@ -30,7 +35,16 @@ async function mockApi(page: Page, init: Partial<Db> = {}): Promise<Db> {
} catch {
body = null;
}
if (p.startsWith("/api/security")) db.calls.push({ call: `${method} ${p}`, body });
if (p.startsWith("/api/security") || p.startsWith("/api/aws-connections")) db.calls.push({ call: `${method} ${p}`, body });
const live = p.match(/^\/api\/aws-connections\/(\d{12})\/permissions\/check$/);
if (live && method === "POST") {
if (db.hold) await db.hold;
const infra = db.live(live[1]);
if (!infra) return json(route, { error: "Coderhelm couldn't take on the role." }, 502);
const view = permissionsView(live[1], { optionalOff: [] });
view.abilities = view.abilities.map((g) => (g.key === "infra" ? { ...g, missing: infra } : g));
return json(route, { account: { account: live[1] }, status: "connected", reason: "", last_check: iso(0), permissions: view });
}
if (p === "/api/me") return json(route, { user_id: "u_1", team_id: "t_1", github_login: null, email: "admin@example.com", avatar_url: "", role: db.role });
if (p === "/api/usage") return json(route, { month: "2026-11", total_tokens: 0, tokens_in: 0, tokens_out: 0, total_runs: 0, max_tokens: 0 });
if (p === "/api/banners") return json(route, { banners: [] });
Expand Down Expand Up @@ -253,6 +267,61 @@ test.describe("Infrastructure vulnerabilities", () => {
await shoot(page, "security-infrastructure-missing");
});

test("the warning goes away when the live check finds the reads (the saved check was a day old)", async ({ page }) => {
let release = () => {};
const db = await mockApi(page, {
overview: infraOverview({ accounts: [...infraOverview().accounts, ACCOUNT_MISSING] }),
live: () => [],
hold: new Promise<void>((r) => (release = r)),
});
await page.goto("/security/infrastructure");
const warn = page.getByTestId("missing-reads");
// The saved check shows at once, and says quietly that it is checking.
await expect(warn).toContainText("needs 4 more read-only permissions in account 444455556666");
await expect(warn.getByTestId("permission-check-note")).toHaveText("Checking the role now…");
release();
await expect(warn).toHaveCount(0);
// Only the warned account is checked.
expect(call(db, "POST /api/aws-connections/444455556666/permissions/check").length).toBeGreaterThan(0);
expect(call(db, "POST /api/aws-connections/111122223333/permissions/check")).toHaveLength(0);
});

test("the live check's list replaces the saved one; after Update the page checks again on focus and drops the warning", async ({ page }) => {
let fixed = false;
const db = await mockApi(page, {
overview: infraOverview({ accounts: [...infraOverview().accounts, ACCOUNT_MISSING] }),
live: () => (fixed ? [] : ["ec2:DescribeInstances"]),
});
await page.goto("/security/infrastructure");
const warn = page.getByTestId("missing-reads");
await expect(warn).toContainText("needs 1 more read-only permission in account 444455556666");
await expect(warn).not.toContainText("eks:DescribeNodegroup");

// The AWS console tab opens on the context, where nothing leaves this machine.
await page.context().route((url) => url.hostname !== "localhost", (route) => route.abort());
const [popup] = await Promise.all([page.waitForEvent("popup"), warn.getByRole("link", { name: "Update the role in AWS" }).click()]);
await popup.close();
await expect(warn.getByTestId("permission-check-note")).toContainText("Waiting for the update");
fixed = true;
await page.evaluate(() => window.dispatchEvent(new Event("focus")));
await expect(warn).toHaveCount(0);
expect(call(db, "POST /api/aws-connections/444455556666/permissions/check").some((c) => (c.body as { pressed?: boolean } | null)?.pressed === true)).toBe(true);
});

test("a check that fails keeps the saved warning; a member never runs the check", async ({ page }) => {
const db = await mockApi(page, { overview: infraOverview({ accounts: [...infraOverview().accounts, ACCOUNT_MISSING] }), live: () => null });
await page.goto("/security/infrastructure");
const warn = page.getByTestId("missing-reads");
await expect.poll(() => call(db, "POST /api/aws-connections/444455556666/permissions/check").length).toBeGreaterThan(0);
await expect(warn).toContainText("needs 4 more read-only permissions");
await expect(warn.getByTestId("permission-check-note")).toHaveText("");

const member = await mockApi(page, { role: "member", overview: infraOverview({ accounts: [...infraOverview().accounts, ACCOUNT_MISSING] }), live: () => [] });
await page.goto("/security/infrastructure");
await expect(page.getByTestId("missing-reads")).toContainText("needs 4 more read-only permissions");
expect(call(member, "POST /api/aws-connections/444455556666/permissions/check")).toHaveLength(0);
});

test("with no account switched on, the page says how to start; a member sees no buttons", async ({ page }) => {
const db = await mockApi(page, { role: "member", overview: infraOverview({ accounts: [], findings: [] }) });
await page.goto("/security/infrastructure");
Expand Down
31 changes: 31 additions & 0 deletions dashboard/e2e/integrations-page.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,37 @@ test("an AWS role without the permissions offers the one-click stack", async ({
await expect(aws.getByRole("switch", { name: "Let agents read Airflow" })).toBeDisabled();
});

test("an AWS account's saved update warning is checked live and goes away when the role is up to date", async ({ page }) => {
const update = "https://console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/quickcreate?stackName=CoderHelmLogReaderOps";
const list = items().map((i) =>
i.id === `aws-${ACCOUNT}`
? { ...i, detail: awsDetail({ update_url: update, permissions: { status: "update_needed", missing_count: 20 } }) }
: i,
);
const db = await mockApi(page, { items: list });
let release = () => {};
const held = new Promise<void>((r) => (release = r));
await page.context().route(`**/api/aws-connections/${ACCOUNT}/permissions/check`, async (r) => {
db.calls.push({ method: r.request().method(), path: new URL(r.request().url()).pathname, body: null });
await held;
await r.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({ account: awsDetail({ permissions: { status: "up_to_date", missing_count: 0 } }), status: "connected", reason: "", last_check: ago(0), permissions: { status: "up_to_date", missing_count: 0, abilities: [] } }),
});
});
await page.goto("/settings/integrations");
const aws = row(page, `aws-${ACCOUNT}`);
await control(page, `aws-${ACCOUNT}`, `AWS account ${ACCOUNT}`).click();
const panel = aws.getByTestId(`aws-panel-${ACCOUNT}`);
await expect(panel.getByText("Update needed: 20 new read-only permissions")).toBeVisible();
await expect(panel.getByTestId("permission-check-note")).toHaveText("Checking the role now…");
release();
await expect(panel.getByText("Update needed: 20 new read-only permissions")).toHaveCount(0);
await expect(aws.getByRole("link", { name: "Update in AWS" })).toHaveCount(0);
expect(db.calls.some((c) => c.method === "POST" && c.path === `/api/aws-connections/${ACCOUNT}/permissions/check`)).toBe(true);
});

test("a self-hosted install's own account never asks for anything: the release brings the permissions", async ({ page }) => {
const list = items().map((i) =>
i.id === `aws-${ACCOUNT}`
Expand Down
38 changes: 31 additions & 7 deletions dashboard/src/app/security/infrastructure/parts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@
// runbook when a person applies it.

import Link from "next/link";
import { useMemo } from "react";
import { Callout } from "@/components/callout";
import { PermissionCheckNote } from "@/components/permission-check-note";
import { useCan } from "@/hooks/use-can";
import { infraMissingOf, usePermissionChecks } from "@/hooks/use-permission-checks";
import type { AwsPermissions } from "@/lib/api";
import { CodeBlock } from "@/components/code-block";
import { Chip, DetailBlock, Time } from "@/components/list";
import { Code } from "@/components/settings";
Expand Down Expand Up @@ -57,24 +62,42 @@ export function LocationLink({ fix }: { fix: InfraFix }) {
return href ? <OutLink href={href}>{words}</OutLink> : <span className="text-zinc-300 [overflow-wrap:anywhere]">{words}</span>;
}

/** A check says nothing is left for Infrastructure vulnerabilities: the role has its reads. */
const infraSettled = (v: AwsPermissions) => infraMissingOf(v)?.length === 0;

/**
* Accounts where Infrastructure vulnerabilities is on but the role lacks the
* reads: a warning that names the feature, and the one-click update.
* reads: a warning that names the feature, and the one-click update. The
* list comes from the last saved check (once a day), so the page checks
* each warned account live and drops the warning when the role has the
* reads; after Update it keeps checking, like Settings › AWS.
*/
export function MissingReads({ accounts }: { accounts: InfraAccount[] }) {
const { ready, can } = useCan();
const short = accounts.filter((a) => a.on && a.missing.length > 0);
if (short.length === 0) return null;
const key = short.map((a) => a.account).join(",");
// Only when the set of warned accounts changes.
// eslint-disable-next-line react-hooks/exhaustive-deps
const targets = useMemo(() => short.map((a) => ({ account: a.account })), [key]);
const perms = usePermissionChecks(targets, { enabled: ready && can("integrations"), settled: infraSettled });
const shown = short
.map((a) => {
const s = perms.of(a.account);
return { a, s, missing: infraMissingOf(s.view) ?? a.missing };
})
.filter((x) => x.missing.length > 0);
if (shown.length === 0) return null;
return (
<div className="space-y-3" data-testid="missing-reads">
{short.map((a) => (
{shown.map(({ a, s, missing }) => (
<Callout
key={a.account}
variant="warning"
title={`Infrastructure vulnerabilities needs ${a.missing.length} more read-only permission${a.missing.length === 1 ? "" : "s"} in account ${a.account}`}
title={`Infrastructure vulnerabilities needs ${missing.length} more read-only permission${missing.length === 1 ? "" : "s"} in account ${a.account}`}
actions={
<>
{a.update_url && (
<a href={a.update_url} target="_blank" rel="noreferrer" className={linkButton}>
<a href={a.update_url} target="_blank" rel="noreferrer" className={linkButton} onClick={() => perms.pressed(a.account)}>
Update the role in AWS
</a>
)}
Expand All @@ -86,13 +109,14 @@ export function MissingReads({ accounts }: { accounts: InfraAccount[] }) {
>
<p>
An AWS admin signs in to account {a.account} and creates the update stack. It adds only describe and list calls:{" "}
{a.missing.map((m, i) => (
{missing.map((m, i) => (
<span key={m}>
<Code>{m}</Code>
{i < a.missing.length - 1 ? ", " : "."}
{i < missing.length - 1 ? ", " : "."}
</span>
))}
</p>
<PermissionCheckNote s={s} />
</Callout>
))}
</div>
Expand Down
2 changes: 1 addition & 1 deletion dashboard/src/app/settings/integrations/aws/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -541,7 +541,7 @@ function AccountSettings({
label="Infrastructure vulnerabilities"
layout="toggle"
unsaved={dirty("infrastructure")}
help={<InfraReadsHelp a={a} on={v.infrastructure} />}
help={<InfraReadsHelp a={a} on={v.infrastructure} live={perms.of(a.account).view} />}
control={(ids) => (
<Switch
id={ids.inputId}
Expand Down
Loading
Loading