diff --git a/dashboard/e2e/infra-aws-switch.spec.ts b/dashboard/e2e/infra-aws-switch.spec.ts index a5f2e522..6fdac097 100644 --- a/dashboard/e2e/infra-aws-switch.spec.ts +++ b/dashboard/e2e/infra-aws-switch.spec.ts @@ -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) => { @@ -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); }); @@ -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); +}); diff --git a/dashboard/e2e/infra-security.spec.ts b/dashboard/e2e/infra-security.spec.ts index 2f68f7d4..058dd7fb 100644 --- a/dashboard/e2e/infra-security.spec.ts +++ b/dashboard/e2e/infra-security.spec.ts @@ -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 @@ -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 | null; } async function mockApi(page: Page, init: Partial = {}): Promise { - 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) => { @@ -30,7 +35,16 @@ async function mockApi(page: Page, init: Partial = {}): Promise { } 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: [] }); @@ -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((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"); diff --git a/dashboard/e2e/integrations-page.spec.ts b/dashboard/e2e/integrations-page.spec.ts index 5fdeb71e..ef81f8f9 100644 --- a/dashboard/e2e/integrations-page.spec.ts +++ b/dashboard/e2e/integrations-page.spec.ts @@ -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((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}` diff --git a/dashboard/src/app/security/infrastructure/parts.tsx b/dashboard/src/app/security/infrastructure/parts.tsx index ef93d60b..0af42716 100644 --- a/dashboard/src/app/security/infrastructure/parts.tsx +++ b/dashboard/src/app/security/infrastructure/parts.tsx @@ -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"; @@ -57,24 +62,42 @@ export function LocationLink({ fix }: { fix: InfraFix }) { return href ? {words} : {words}; } +/** 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 (
- {short.map((a) => ( + {shown.map(({ a, s, missing }) => ( {a.update_url && ( - + perms.pressed(a.account)}> Update the role in AWS )} @@ -86,13 +109,14 @@ export function MissingReads({ accounts }: { accounts: InfraAccount[] }) { >

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) => ( {m} - {i < a.missing.length - 1 ? ", " : "."} + {i < missing.length - 1 ? ", " : "."} ))}

+
))}
diff --git a/dashboard/src/app/settings/integrations/aws/page.tsx b/dashboard/src/app/settings/integrations/aws/page.tsx index ab32122d..2a5753a4 100644 --- a/dashboard/src/app/settings/integrations/aws/page.tsx +++ b/dashboard/src/app/settings/integrations/aws/page.tsx @@ -541,7 +541,7 @@ function AccountSettings({ label="Infrastructure vulnerabilities" layout="toggle" unsaved={dirty("infrastructure")} - help={} + help={} control={(ids) => ( >({}); - const stateRef = useRef(state); - stateRef.current = state; - const accounts = connections.map(accountOf).join(","); - - const patch = useCallback((account: string, p: Partial) => { - setState((s) => ({ ...s, [account]: { ...EMPTY, ...s[account], ...p } })); - }, []); - - const check = useCallback( - async (account: string, pressed = false) => { - patch(account, { checking: true, error: null }); - try { - const r = await api.checkAwsPermissions(account, pressed); - const before = stateRef.current[account]; - const view = r.permissions; - const landed = !!before?.pressedAt && before.view?.status === "update_needed" && view?.status === "up_to_date"; - patch(account, { - view, - checking: false, - updated: before?.updated || landed, - pressedAt: view?.status === "up_to_date" ? null : before?.pressedAt ?? null, - }); - } catch (e) { - patch(account, { checking: false, error: e instanceof Error && e.message ? e.message : "The check didn't run." }); - } - }, - [patch], - ); - - // The stored check shows at once; a live check of each account follows. - useEffect(() => { - for (const c of connections) { - const a = accountOf(c); - if (!stateRef.current[a]) patch(a, { view: c.abilities?.permissions ?? null }); - check(a); - } + const key = connections.map(accountOf).join(","); + const targets = useMemo( + () => connections.map((c) => ({ account: accountOf(c), saved: c.abilities?.permissions ?? null })), // Only when the set of accounts changes. // eslint-disable-next-line react-hooks/exhaustive-deps - }, [accounts]); - - // After Update: check again when the person comes back to this tab, and - // every POLL_MS while the update is outstanding. - const watching = Object.entries(state).filter(([, s]) => s.pressedAt && Date.now() - s.pressedAt < WATCH_MS).map(([a]) => a); - const watchKey = watching.join(","); - useEffect(() => { - if (!watchKey) return; - const list = watchKey.split(","); - const again = () => { - for (const a of list) if (!stateRef.current[a]?.checking) check(a, true); - }; - const onVisible = () => { - if (document.visibilityState === "visible") again(); - }; - document.addEventListener("visibilitychange", onVisible); - window.addEventListener("focus", again); - const t = window.setInterval(again, POLL_MS); - return () => { - document.removeEventListener("visibilitychange", onVisible); - window.removeEventListener("focus", again); - window.clearInterval(t); - }; - }, [watchKey, check]); - - const pressed = useCallback((account: string) => patch(account, { pressedAt: Date.now(), updated: false }), [patch]); - - return { state, check, pressed, of: (account: string) => state[account] ?? EMPTY }; + [key], + ); + return usePermissionChecks(targets); } export type AwsPermissionsApi = ReturnType; diff --git a/dashboard/src/components/connections.tsx b/dashboard/src/components/connections.tsx index d0233774..1efb5ddc 100644 --- a/dashboard/src/components/connections.tsx +++ b/dashboard/src/components/connections.tsx @@ -1,10 +1,12 @@ "use client"; import Link from "next/link"; -import { useState, type ReactNode } from "react"; +import { useMemo, useState, type ReactNode } from "react"; import { api, type AwsAccountAbilities, type AwsAbilityReply, type Connector, type ConnectorId, type KeyConnectorKind } from "@/lib/api"; import { errorMessage, timeAgo } from "@/lib/data-sources"; +import { infraMissingOf, usePermissionChecks } from "@/hooks/use-permission-checks"; import { Callout } from "./callout"; +import { PermissionCheckNote } from "./permission-check-note"; import { Field, SecretInput } from "./field"; import { MarkdownEditor } from "./markdown-editor"; import { Switch } from "./teams-webhook"; @@ -360,6 +362,17 @@ export function AwsAbilitiesPanel({ const set = (body: Parameters[1]) => run(() => api.setAwsAbilities(a.account, body), "Saved"); const ABILITY: Record = { metrics: "CloudWatch metrics", airflow: "Airflow", infra: "the Infrastructure vulnerabilities reads" }; const missing = (a.missing ?? []).map((m) => ABILITY[m] ?? m); + // The warning below comes from the last saved check, which can be a day + // old: while it shows, check the role live (and again after Update), and + // take the fresh account the check answers with. + const warned = !a.install_account && (missing.length > 0 || a.permissions?.status === "update_needed") && !!a.update_url; + const infraOn = !!a.infrastructure?.on; + const targets = useMemo(() => (warned ? [{ account: a.account }] : []), [warned, a.account]); + const perms = usePermissionChecks(targets, { + enabled: canEdit, + settled: (v) => v.status === "up_to_date" && (!infraOn || infraMissingOf(v)?.length === 0), + onReply: (_, r) => onChange(r), + }); return (
@@ -428,7 +441,7 @@ export function AwsAbilitiesPanel({

Nothing to do. Each version update brings this release's read-only permissions to this account's read role by itself.

)} - {!a.install_account && (missing.length > 0 || a.permissions?.status === "update_needed") && a.update_url && ( + {warned && a.update_url && ( {canEdit && (

- + perms.pressed(a.account)}> Update in AWS

)} + {canEdit && }
)} {error && ( diff --git a/dashboard/src/components/infra-reads.tsx b/dashboard/src/components/infra-reads.tsx index 24cdfdbe..2ad44bab 100644 --- a/dashboard/src/components/infra-reads.tsx +++ b/dashboard/src/components/infra-reads.tsx @@ -7,7 +7,8 @@ import { Code } from "@/components/settings"; import { linkButton } from "@/components/ui"; -import type { AwsAccountAbilities } from "@/lib/api"; +import { infraMissingOf } from "@/hooks/use-permission-checks"; +import type { AwsAccountAbilities, AwsPermissions } from "@/lib/api"; /** Every action the option adds, as the role templates grant them. */ export const INFRA_ACTIONS = [ @@ -32,11 +33,15 @@ export const INFRA_ACTIONS = [ "ssm:GetParameters", ]; -export function InfraReadsHelp({ a, on }: { a: AwsAccountAbilities; on: boolean }) { +/** `live`: the page's live check of the role, which wins over the saved one on `a` when it is newer. */ +export function InfraReadsHelp({ a, on, live }: { a: AwsAccountAbilities; on: boolean; live?: AwsPermissions | null }) { const infra = a.infrastructure; const row = a.permissions?.abilities.find((x) => x.key === "infra"); - const missing = infra?.missing?.length ? infra.missing : on && infra?.available === false ? (row?.missing.length ? row.missing : INFRA_ACTIONS) : []; - const update = a.permissions?.update ?? null; + const newer = live && (!a.permissions || live.checked_at > a.permissions.checked_at) ? live : null; + const fresh = infraMissingOf(newer); + const saved = infra?.missing?.length ? infra.missing : on && infra?.available === false ? (row?.missing.length ? row.missing : INFRA_ACTIONS) : []; + const missing = fresh ? (on ? fresh : []) : saved; + const update = (newer ?? a.permissions)?.update ?? null; return ( <> Reads which AMIs, node groups, databases and caches run here, once a day, so Security can say what you have to fix and what AWS patches for you. diff --git a/dashboard/src/components/permission-check-note.tsx b/dashboard/src/components/permission-check-note.tsx new file mode 100644 index 00000000..ffd8ecbb --- /dev/null +++ b/dashboard/src/components/permission-check-note.tsx @@ -0,0 +1,21 @@ +"use client"; + +import type { AccountPermissions } from "@/hooks/use-permission-checks"; + +/** + * One quiet line under a saved permission warning while the page checks the + * role live, or while it waits for an update someone pressed. + */ +export function PermissionCheckNote({ s }: { s: AccountPermissions }) { + const text = s.checking ? "Checking the role now…" : s.pressedAt ? "Waiting for the update. This checks again by itself." : null; + return ( +

+ {text && ( + <> +

+ ); +} diff --git a/dashboard/src/hooks/use-permission-checks.ts b/dashboard/src/hooks/use-permission-checks.ts new file mode 100644 index 00000000..2625ab7a --- /dev/null +++ b/dashboard/src/hooks/use-permission-checks.ts @@ -0,0 +1,137 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; +import { api, type AwsAbilityReply, type AwsPermissions } from "@/lib/api"; + +// Live checks of AWS roles' permissions, for every page that shows a saved +// permission warning with an update link. The saved check can be a day old +// (the worker checks once a day), so a page that shows the warning checks +// the role again at once (POST /api/aws-connections/:id/permissions/check, +// which also saves the result). After someone presses the update link the +// page checks again by itself: when they come back to the tab, and every +// POLL_MS for WATCH_MS, until the check says the update landed. + +export const POLL_MS = 15_000; +/** How long after pressing Update the page keeps checking by itself. */ +export const WATCH_MS = 15 * 60_000; + +export type PermissionCheckReply = AwsAbilityReply & { permissions: AwsPermissions | null }; + +export interface AccountPermissions { + view: AwsPermissions | null; + checking: boolean; + /** When someone pressed Update for this account (this page view). */ + pressedAt: number | null; + /** The update landed while this page watched. */ + updated: boolean; + error: string | null; +} + +export const EMPTY_PERMISSIONS: AccountPermissions = { view: null, checking: false, pressedAt: null, updated: false, error: null }; + +/** An account to check, with the check the page already has (if any). */ +export interface PermissionTarget { + account: string; + saved?: AwsPermissions | null; +} + +export interface PermissionCheckOptions { + /** False: show nothing live and never call (the person can't run the check). */ + enabled?: boolean; + /** Whether a check says nothing is left to do for what this page warns about (default: up to date). */ + settled?: (view: AwsPermissions) => boolean; + /** Every live answer, for pages that keep the account itself. */ + onReply?: (account: string, reply: PermissionCheckReply) => void; +} + +const upToDate = (v: AwsPermissions) => v.status === "up_to_date"; + +/** The infrastructure reads a check says the role lacks, or null when the check doesn't say. */ +export function infraMissingOf(view: AwsPermissions | null | undefined): string[] | null { + if (!view || view.status === "error") return null; + const g = view.abilities.find((a) => a.key === "infra"); + return g ? g.missing : null; +} + +/** Live permission state for each account, and the actions on it. */ +export function usePermissionChecks(targets: PermissionTarget[], opts: PermissionCheckOptions = {}) { + const enabled = opts.enabled ?? true; + const [state, setState] = useState>({}); + const stateRef = useRef(state); + stateRef.current = state; + const optsRef = useRef(opts); + optsRef.current = opts; + const targetsRef = useRef(targets); + targetsRef.current = targets; + const accounts = enabled ? targets.map((t) => t.account).join(",") : ""; + + const settled = useCallback((v: AwsPermissions | null | undefined) => !!v && v.status !== "error" && (optsRef.current.settled ?? upToDate)(v), []); + + const patch = useCallback((account: string, p: Partial) => { + setState((s) => ({ ...s, [account]: { ...EMPTY_PERMISSIONS, ...s[account], ...p } })); + }, []); + + const check = useCallback( + async (account: string, pressed = false) => { + patch(account, { checking: true, error: null }); + try { + const r = await api.checkAwsPermissions(account, pressed); + const before = stateRef.current[account]; + const view = r.permissions; + const done = settled(view); + const landed = !!before?.pressedAt && !!before.view && !settled(before.view) && done; + patch(account, { + view, + checking: false, + updated: before?.updated || landed, + pressedAt: done ? null : before?.pressedAt ?? null, + }); + optsRef.current.onReply?.(account, r); + } catch (e) { + patch(account, { checking: false, error: e instanceof Error && e.message ? e.message : "The check didn't run." }); + } + }, + [patch, settled], + ); + + // The saved check shows at once; a live check of each account follows. + useEffect(() => { + if (!accounts) return; + for (const t of targetsRef.current) { + if (!stateRef.current[t.account]) patch(t.account, { view: t.saved ?? null }); + check(t.account); + } + }, [accounts, check, patch]); + + // After Update: check again when the person comes back to this tab, and + // every POLL_MS while the update is outstanding. + const watching = Object.entries(state) + .filter(([, s]) => s.pressedAt && Date.now() - s.pressedAt < WATCH_MS) + .map(([a]) => a); + const watchKey = enabled ? watching.join(",") : ""; + useEffect(() => { + if (!watchKey) return; + const list = watchKey.split(","); + const again = () => { + for (const a of list) if (!stateRef.current[a]?.checking) check(a, true); + }; + const onVisible = () => { + if (document.visibilityState === "visible") again(); + }; + document.addEventListener("visibilitychange", onVisible); + window.addEventListener("focus", again); + const t = window.setInterval(again, POLL_MS); + return () => { + document.removeEventListener("visibilitychange", onVisible); + window.removeEventListener("focus", again); + window.clearInterval(t); + }; + }, [watchKey, check]); + + const pressed = useCallback((account: string) => patch(account, { pressedAt: Date.now(), updated: false }), [patch]); + const of = useCallback((account: string) => state[account] ?? EMPTY_PERMISSIONS, [state]); + + return { state, check, pressed, of, settled }; +} + +export type PermissionChecks = ReturnType;