diff --git a/app/src/components/settings/HostsSettings.tsx b/app/src/components/settings/HostsSettings.tsx index b6713cd..1a6360d 100644 --- a/app/src/components/settings/HostsSettings.tsx +++ b/app/src/components/settings/HostsSettings.tsx @@ -5,50 +5,29 @@ import { addAwsProfileConnection, awsConnectionIdentity, awsConnectionSsoLogin, - awsPolicyDocument, checkAwsPermissions, listAwsProfiles, removeHostConnection, updateAwsConnection, } from "../../lib/tauri-commands"; -import { toAwsError } from "../../lib/aws-error"; +import { awsErrorMessage, toAwsError } from "../../lib/aws-error"; +import PolicyFiles from "./hosts/PolicyFiles"; +import EnvironmentsPanel from "./hosts/EnvironmentsPanel"; +import { COMMON_REGIONS } from "./hosts/environmentFormat"; import type { AwsError, HostConnection, PermissionReport, PermissionSummary, PolicyFile, - Tier, } from "../../lib/types"; import Button from "../ui/Button"; import SegmentedControl from "../ui/SegmentedControl"; import Field, { inputClass, selectClass } from "../ui/Field"; -const COMMON_REGIONS = [ - "us-east-1", "us-east-2", "us-west-1", "us-west-2", "ca-central-1", - "eu-west-1", "eu-west-2", "eu-west-3", "eu-central-1", "eu-north-1", - "ap-southeast-1", "ap-southeast-2", "ap-northeast-1", "ap-northeast-2", "ap-south-1", - "sa-east-1", -]; const OWN_PRINCIPAL_ACTIONS = ["iam:GetRole", "iam:SimulatePrincipalPolicy"]; -/** Human-readable copy for a failed AWS command; never raw JSON. */ -export function awsErrorMessage(e: AwsError): string { - switch (e.kind) { - case "sso_expired": - return `Your SSO session for profile ${e.profile} has expired.`; - case "profile_not_found": - return `Profile ${e.profile} was not found in your AWS config, or has no credentials.`; - case "keys_missing": - return "The access keys for this connection are missing from the keychain. Remove and re-add the connection."; - case "state_bucket_taken": - return `The state bucket name ${e.bucket} is already taken by another AWS account.`; - default: - return e.message; - } -} - const SUMMARY_LABEL: Record = { environment_admin: "Environment admin", workspace_user: "Workspace user", @@ -96,70 +75,6 @@ function ErrorLine({ ); } -/** A tier's policy files, loaded on demand: each one shown and copied on its own. */ -function PolicyFiles({ - tier, - label, - onCopy, -}: { - tier: Tier; - label: string; - onCopy: (file: PolicyFile) => void; -}) { - const [files, setFiles] = useState(null); - const [error, setError] = useState(null); - - const load = async () => { - setError(null); - try { - setFiles(await awsPolicyDocument(tier)); - } catch (e) { - setError(`Could not load the policy: ${awsErrorMessage(toAwsError(e))}`); - } - }; - - if (!files) { - return ( -
- - {error && ( -

- {error} -

- )} -
- ); - } - return ( -
-

- {tier === "workspace_user" ? "Workspace user" : "Environment admin"}:{" "} - {files.length === 1 - ? "attach this file as a customer managed policy." - : `Attach all ${files.length} files, each as its own customer managed policy.`} -

- {files.map((f) => ( -
-
- {f.name} - -
-
- Show JSON -
-              {f.json}
-            
-
-
- ))} -
- ); -} - function PermissionReportView({ report }: { report: PermissionReport }) { const [copyNote, setCopyNote] = useState(null); const probed = typeof report.method === "object"; @@ -399,6 +314,7 @@ function ConnectionRow({ host }: { host: HostConnection }) { {busy && !editing && !confirmRemove &&

Working…

} {failure && } {report && } + ); } @@ -591,7 +507,7 @@ export default function HostsSettings() { return (

- Where project environments run. AWS connections are used to check what your credentials can do. + Where project environments run. AWS connections check what your credentials can do, and find, deploy and join environments.

  • diff --git a/app/src/components/settings/hosts/AdminBundleModal.test.tsx b/app/src/components/settings/hosts/AdminBundleModal.test.tsx new file mode 100644 index 0000000..de5e1f5 --- /dev/null +++ b/app/src/components/settings/hosts/AdminBundleModal.test.tsx @@ -0,0 +1,70 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import AdminBundleModal from "./AdminBundleModal"; + +const invoke = vi.fn(); +vi.mock("@tauri-apps/api/core", () => ({ + invoke: (cmd: string, args?: unknown) => invoke(cmd, args), +})); + +describe("AdminBundleModal", () => { + beforeEach(() => vi.clearAllMocks()); + + it("saves the bundle and shows the folder and the two commands, with Copy", async () => { + invoke.mockResolvedValue("/home/me/triple-c-onboard-dev"); + const writeText = vi.fn().mockResolvedValue(undefined); + Object.assign(navigator, { clipboard: { writeText } }); + render( + , + ); + expect(screen.getByRole("dialog", { name: "Onboarding bundle" })).toBeInTheDocument(); + expect(screen.getByText(/environment admin/)).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Save bundle to folder…" })); + expect(await screen.findByText("/home/me/triple-c-onboard-dev")).toBeInTheDocument(); + expect(invoke).toHaveBeenCalledWith("save_aws_admin_bundle", { + connectionId: "h1", + region: "eu-west-1", + kind: "user_onboard", + environment: "dev", + ownerId: "AIDAEXAMPLE", + network: null, + }); + const commands = "tofu init -backend-config=backend.hcl\ntofu apply"; + expect(screen.getByText((_, el) => el?.tagName === "PRE" && el.textContent === commands)).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Copy commands" })); + await waitFor(() => expect(writeText).toHaveBeenCalledWith(commands)); + }); + + it("shows nothing new when the folder picker is dismissed", async () => { + invoke.mockResolvedValue(null); + render(); + fireEvent.click(screen.getByRole("button", { name: "Save bundle to folder…" })); + await waitFor(() => expect(invoke).toHaveBeenCalled()); + expect(screen.queryByRole("button", { name: "Copy commands" })).toBeNull(); + }); + + it("an environment bundle asks for the name and network", async () => { + invoke.mockResolvedValue("/tmp/env"); + render(); + fireEvent.change(screen.getByLabelText("Name"), { target: { value: "team" } }); + fireEvent.click(screen.getByRole("radio", { name: "Private + NAT" })); + fireEvent.click(screen.getByRole("button", { name: "Save bundle to folder…" })); + await waitFor(() => + expect(invoke).toHaveBeenCalledWith("save_aws_admin_bundle", { + connectionId: "h1", + region: "eu-west-1", + kind: "environment", + environment: "team", + ownerId: null, + network: { mode: "private-nat" }, + }), + ); + }); + + it("shows a save failure through the AWS error copy", async () => { + invoke.mockRejectedValue({ kind: "sso_expired", profile: "prod-sso" }); + render(); + fireEvent.click(screen.getByRole("button", { name: "Save bundle to folder…" })); + expect(await screen.findByText("Your SSO session for profile prod-sso has expired.")).toBeInTheDocument(); + }); +}); diff --git a/app/src/components/settings/hosts/AdminBundleModal.tsx b/app/src/components/settings/hosts/AdminBundleModal.tsx new file mode 100644 index 0000000..6630be5 --- /dev/null +++ b/app/src/components/settings/hosts/AdminBundleModal.tsx @@ -0,0 +1,152 @@ +import { useState } from "react"; +import { saveAwsAdminBundle } from "../../../lib/tauri-commands"; +import { awsErrorMessage, toAwsError } from "../../../lib/aws-error"; +import type { AwsError, ModuleKind, NetworkChoice } from "../../../lib/types"; +import Button from "../../ui/Button"; +import Field, { inputClass } from "../../ui/Field"; +import Modal from "../../ui/Modal"; +import NetworkFields from "./NetworkFields"; +import { DEFAULT_NETWORK, environmentNameError, networkFromDraft, type NetworkDraft } from "./environmentFormat"; + +const COMMANDS = "tofu init -backend-config=backend.hcl\ntofu apply"; + +const TITLE: Record = { + environment: "Environment bundle", + user_onboard: "Onboarding bundle", + permissions_boundary: "Permissions boundary bundle", +}; + +/** + * An admin request (D5): Triple-C writes the module, `backend.hcl`, + * `terraform.tfvars.json` and a README into a folder picked in Rust, and the + * admin runs the two commands from there. + */ +export default function AdminBundleModal({ + connectionId, + region, + kind, + environment, + ownerId, + network, + reason, + onClose, +}: { + connectionId: string; + region: string; + kind: ModuleKind; + /** Fixed environment; when absent for an environment bundle, the user picks it here. */ + environment?: string; + ownerId?: string; + network?: NetworkChoice; + /** Why the bundle is needed (e.g. the refusal that led here). */ + reason?: string; + onClose: () => void; +}) { + const askEnvironment = kind === "environment" && !environment; + const [name, setName] = useState("main"); + const [draft, setDraft] = useState(DEFAULT_NETWORK); + const [saving, setSaving] = useState(false); + const [saved, setSaved] = useState(null); + const [error, setError] = useState(null); + const [copyNote, setCopyNote] = useState(null); + + const nameError = askEnvironment ? environmentNameError(name) : null; + const picked = askEnvironment ? networkFromDraft(draft) : null; + const ready = !nameError && (!picked || "network" in picked); + + const save = async () => { + setSaving(true); + setError(null); + try { + const folder = await saveAwsAdminBundle(connectionId, region, kind, { + environment: askEnvironment ? name : environment, + ownerId, + network: picked && "network" in picked ? picked.network : network, + }); + if (folder) setSaved(folder); + } catch (e) { + setError(toAwsError(e)); + } finally { + setSaving(false); + } + }; + + const copy = async () => { + try { + await navigator.clipboard.writeText(COMMANDS); + setCopyNote("Commands copied."); + } catch (e) { + setCopyNote(`Could not copy: ${awsErrorMessage(toAwsError(e))}`); + } + }; + + return ( + + Close + + } + > +
    + {reason && ( +

    + Doing this from here was refused: {reason} +

    + )} + {kind === "environment" && ( +

    + Deploying an environment needs an environment admin. Triple-C writes the OpenTofu module with its + backend settings and variables into a folder; send it to an admin, who deploys it from there. +

    + )} + {kind === "user_onboard" && ( +

    + Joining {environment} needs your own task role and file system, which an environment admin creates + by applying this bundle. Send them the folder; once it's applied, Detect again shows you as joined. +

    + )} + {kind === "permissions_boundary" && ( +

    + Every role Triple-C creates is capped by the account's permissions boundary, and creating it needs an + account administrator. Send them this folder. +

    + )} +

    The bundle works with OpenTofu or Terraform 1.10 and later. Its README lists every step.

    + {askEnvironment && ( +
    + + {(id) => setName(e.target.value)} />} + + +
    + )} + + {error && ( +

    + {awsErrorMessage(error)} +

    + )} + {saved && ( +
    +

    + Saved to {saved} +

    +

    From that folder, run:

    +
    +              {COMMANDS}
    +            
    + + {copyNote &&

    {copyNote}

    } +
    + )} +
    +
    + ); +} diff --git a/app/src/components/settings/hosts/DeployEnvironmentModal.test.tsx b/app/src/components/settings/hosts/DeployEnvironmentModal.test.tsx new file mode 100644 index 0000000..6003815 --- /dev/null +++ b/app/src/components/settings/hosts/DeployEnvironmentModal.test.tsx @@ -0,0 +1,156 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import DeployEnvironmentModal from "./DeployEnvironmentModal"; +import type { DeployProgress } from "../../../lib/types"; +import { conn, env, progress, scan, tofuEvent } from "./testkit"; + +const invoke = vi.fn(); +vi.mock("@tauri-apps/api/core", () => ({ + invoke: (cmd: string, args?: unknown) => invoke(cmd, args), +})); + +type Handler = (e: { payload: DeployProgress }) => void; +const handlers = new Set(); +vi.mock("@tauri-apps/api/event", () => ({ + listen: vi.fn(async (_name: string, handler: Handler) => { + handlers.add(handler); + return () => handlers.delete(handler); + }), +})); +function emit(p: DeployProgress) { + act(() => { + for (const h of [...handlers]) h({ payload: p }); + }); +} + +const BOUNDARY_KEY = "boundary/terraform.tfstate"; + +function renderModal(over: Partial[0]> = {}) { + const props = { + connectionId: conn.id, + region: "eu-west-1", + scan: scan(), + onClose: vi.fn(), + onDeploy: vi.fn().mockResolvedValue(null), + onDetect: vi.fn(), + ...over, + }; + render(); + return props; +} + +describe("DeployEnvironmentModal", () => { + beforeEach(() => { + vi.clearAllMocks(); + handlers.clear(); + }); + + it("the public network mode is the default and says it costs nothing", () => { + const props = renderModal(); + expect(screen.getByRole("radio", { name: "Public" })).toHaveAttribute("aria-checked", "true"); + expect(screen.getByText("$0 — tasks get a public IP, no inbound access")).toBeInTheDocument(); + expect(screen.getByText("First deploy downloads OpenTofu (~30 MB) and the AWS provider (~150 MB).")).toBeInTheDocument(); + fireEvent.click(screen.getByRole("radio", { name: "Private + NAT" })); + expect(screen.getByText("about $33/month for the NAT gateway")).toBeInTheDocument(); + fireEvent.click(screen.getByRole("radio", { name: "Public" })); + expect(screen.getByLabelText("Name")).toHaveValue("main"); + fireEvent.click(screen.getByRole("button", { name: "Deploy" })); + expect(props.onDeploy).toHaveBeenCalledWith("main", { mode: "public" }); + }); + + it("validates the name with the backend's rule", () => { + const props = renderModal({ scan: scan({ environments: [env({ name: "main" })] }) }); + const deploy = screen.getByRole("button", { name: "Deploy" }); + expect(screen.getByText(/already exists/)).toBeInTheDocument(); + expect(deploy).toBeDisabled(); + for (const bad of ["Dev", "a--b", "dev-", "1dev", "a".repeat(21), ""]) { + fireEvent.change(screen.getByLabelText("Name"), { target: { value: bad } }); + expect(deploy).toBeDisabled(); + } + fireEvent.change(screen.getByLabelText("Name"), { target: { value: "team-2" } }); + expect(deploy).toBeEnabled(); + fireEvent.click(deploy); + expect(props.onDeploy).toHaveBeenCalledWith("team-2", { mode: "public" }); + }); + + it("an existing network needs a VPC and two distinct subnets", () => { + const props = renderModal(); + fireEvent.click(screen.getByRole("radio", { name: "Existing VPC" })); + const deploy = screen.getByRole("button", { name: "Deploy" }); + expect(deploy).toBeDisabled(); + fireEvent.change(screen.getByLabelText("VPC ID"), { target: { value: "vpc-0123abcd" } }); + fireEvent.change(screen.getByLabelText("Subnet ID 1"), { target: { value: "subnet-0123abcd" } }); + fireEvent.change(screen.getByLabelText("Subnet ID 2"), { target: { value: "subnet-0123abcd" } }); + expect(deploy).toBeDisabled(); + fireEvent.change(screen.getByLabelText("Subnet ID 2"), { target: { value: "subnet-4567abcd" } }); + fireEvent.click(screen.getByRole("switch", { name: "Assign a public IP" })); + fireEvent.click(deploy); + expect(props.onDeploy).toHaveBeenCalledWith("main", { + mode: "existing", + vpc_id: "vpc-0123abcd", + subnet_ids: ["subnet-0123abcd", "subnet-4567abcd"], + assign_public_ip: true, + }); + }); + + it("keeps the dialog open and shows the server's refusal", async () => { + const props = renderModal({ + onDeploy: vi.fn().mockResolvedValue({ kind: "other", message: "A deployment is starting for environment \"main\"; wait for it" }), + }); + fireEvent.click(screen.getByRole("button", { name: "Deploy" })); + expect(await screen.findByText(/A deployment is starting/)).toBeInTheDocument(); + expect(props.onClose).not.toHaveBeenCalled(); + }); + + it("deploy modal blocks on a missing boundary and offers to create it", async () => { + invoke.mockImplementation(async (cmd: string) => { + if (cmd === "deploy_aws_permissions_boundary") return "b1"; + throw new Error(`unexpected ${cmd}`); + }); + const props = renderModal({ scan: scan({ boundary: "no" }) }); + expect(screen.queryByLabelText("Name")).toBeNull(); + expect(screen.queryByRole("button", { name: "Deploy" })).toBeNull(); + fireEvent.click(screen.getByRole("button", { name: "Create the permissions boundary (needs an account administrator)" })); + await waitFor(() => + expect(invoke).toHaveBeenCalledWith("deploy_aws_permissions_boundary", { connectionId: "h1", region: "eu-west-1" }), + ); + emit(progress({ op_id: "b1", state_key: BOUNDARY_KEY, events: [tofuEvent("Creating boundary")] })); + expect(screen.getByText("Creating boundary")).toBeInTheDocument(); + emit(progress({ op_id: "b1", state_key: BOUNDARY_KEY, done: true, cancellable: false, result: { ok: true, exit_code: 0, summary: "Apply complete!" } })); + expect(await screen.findByLabelText("Name")).toBeInTheDocument(); + expect(props.onDetect).toHaveBeenCalled(); + }); + + it("opens the boundary bundle when creating the boundary is denied", async () => { + invoke.mockImplementation(async (cmd: string) => { + if (cmd === "deploy_aws_permissions_boundary") throw { kind: "access_denied", action: "iam:CreatePolicy", message: "denied iam:CreatePolicy" }; + if (cmd === "save_aws_admin_bundle") return "/tmp/b"; + throw new Error(`unexpected ${cmd}`); + }); + renderModal({ scan: scan({ boundary: "no" }) }); + fireEvent.click(screen.getByRole("button", { name: "Create the permissions boundary (needs an account administrator)" })); + const dialog = await screen.findByRole("dialog", { name: "Permissions boundary bundle" }); + expect(within(dialog).getByText(/denied iam:CreatePolicy/)).toBeInTheDocument(); + fireEvent.click(within(dialog).getByRole("button", { name: "Save bundle to folder…" })); + await waitFor(() => + expect(invoke).toHaveBeenCalledWith("save_aws_admin_bundle", { + connectionId: "h1", + region: "eu-west-1", + kind: "permissions_boundary", + environment: null, + ownerId: null, + network: null, + }), + ); + }); + + it("repairs a named environment and warns that a different network replaces it", () => { + const props = renderModal({ repair: "dev" }); + expect(screen.getByRole("dialog", { name: "Repair dev" })).toBeInTheDocument(); + expect(screen.queryByLabelText("Name")).toBeNull(); + expect(screen.getByText(/different network than the one it was deployed with replaces/)).toBeInTheDocument(); + fireEvent.click(screen.getByRole("radio", { name: "Private + NAT" })); + fireEvent.click(screen.getByRole("button", { name: "Repair" })); + expect(props.onDeploy).toHaveBeenCalledWith("dev", { mode: "private-nat" }); + }); +}); diff --git a/app/src/components/settings/hosts/DeployEnvironmentModal.tsx b/app/src/components/settings/hosts/DeployEnvironmentModal.tsx new file mode 100644 index 0000000..6fccbea --- /dev/null +++ b/app/src/components/settings/hosts/DeployEnvironmentModal.tsx @@ -0,0 +1,167 @@ +import { useState } from "react"; +import { deployAwsPermissionsBoundary } from "../../../lib/tauri-commands"; +import { awsErrorMessage } from "../../../lib/aws-error"; +import type { AwsError, EnvironmentScan, NetworkChoice } from "../../../lib/types"; +import Button from "../../ui/Button"; +import Field, { inputClass } from "../../ui/Field"; +import Modal from "../../ui/Modal"; +import AdminBundleModal from "./AdminBundleModal"; +import DeployProgress, { useDeployRuns } from "./DeployProgress"; +import NetworkFields from "./NetworkFields"; +import { + BOUNDARY_STATE_KEY, + DEFAULT_NETWORK, + environmentNameError, + networkFromDraft, + type NetworkDraft, +} from "./environmentFormat"; + +/** + * Deploy a new environment (name + D4 network), or — with `repair` — pick the + * network for an environment that has no record to take it from. A missing + * permissions boundary is a first step before the form. + */ +export default function DeployEnvironmentModal({ + connectionId, + region, + scan, + repair, + onClose, + onDeploy, + onDetect, +}: { + connectionId: string; + region: string; + scan: EnvironmentScan; + /** The environment to repair; absent for a new deploy. */ + repair?: string; + onClose: () => void; + /** Starts the run; resolves to the command's error, or null once started. */ + onDeploy: (name: string, network: NetworkChoice) => Promise; + onDetect: () => void; +}) { + const [name, setName] = useState("main"); + const [draft, setDraft] = useState(DEFAULT_NETWORK); + const [submitting, setSubmitting] = useState(false); + const [error, setError] = useState(null); + const [boundaryDone, setBoundaryDone] = useState(false); + const [boundaryError, setBoundaryError] = useState(null); + const [bundle, setBundle] = useState<{ reason?: string } | null>(null); + const boundary = useDeployRuns(({ result }) => { + if (result?.ok) setBoundaryDone(true); + onDetect(); + }); + const boundaryRun = boundary.runs[BOUNDARY_STATE_KEY]; + + if (bundle) { + return ( + setBundle(null)} + /> + ); + } + + const needsBoundary = !repair && scan.boundary === "no" && !boundaryDone; + const target = repair ?? name; + const nameError = repair + ? null + : environmentNameError(name) ?? + (scan.environments.some((e) => e.name === name) ? `An environment named ${name} already exists here.` : null); + const picked = networkFromDraft(draft); + const ready = !nameError && "network" in picked && !submitting; + + const createBoundary = async () => { + setBoundaryError(null); + const err = await boundary.start(BOUNDARY_STATE_KEY, region, "Permissions boundary", () => + deployAwsPermissionsBoundary(connectionId, region), + ); + if (err?.kind === "access_denied") setBundle({ reason: awsErrorMessage(err) }); + else if (err) setBoundaryError(err); + }; + + const submit = async () => { + if (!("network" in picked)) return; + setSubmitting(true); + setError(null); + const err = await onDeploy(target, picked.network); + setSubmitting(false); + if (err) setError(err); + else onClose(); + }; + + const verb = repair ? "Repair" : "Deploy"; + return ( + + + {!needsBoundary && ( + + )} + + } + > + {needsBoundary ? ( +
    +

    + This account has no Triple-C permissions boundary yet. Every role an environment creates is capped by + it, so it comes first. +

    +
    + + +
    + {boundaryError && ( +

    + {awsErrorMessage(boundaryError)} +

    + )} + {boundaryRun && } +
    + ) : ( +
    + {repair ? ( +

    + {repair} has no record, so Triple-C can't tell which network it was deployed with. Choose the same one: + a different network than the one it was deployed with replaces the network resources (VPC, subnets, + NAT gateway). +

    + ) : ( + + {(id) => setName(e.target.value)} />} + + )} + +

    + First deploy downloads OpenTofu (~30 MB) and the AWS provider (~150 MB). +

    + {error && ( +

    + {awsErrorMessage(error)} +

    + )} +
    + )} +
    + ); +} diff --git a/app/src/components/settings/hosts/DeployProgress.tsx b/app/src/components/settings/hosts/DeployProgress.tsx new file mode 100644 index 0000000..7f61ae6 --- /dev/null +++ b/app/src/components/settings/hosts/DeployProgress.tsx @@ -0,0 +1,281 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { listen } from "@tauri-apps/api/event"; +import { cancelAwsDeployment } from "../../../lib/tauri-commands"; +import { awsErrorMessage, toAwsError } from "../../../lib/aws-error"; +import { + AWS_DEPLOY_PROGRESS_EVENT, + type AwsError, + type DeployProgress as ProgressPayload, + type TofuEvent, + type TofuOutcome, +} from "../../../lib/types"; +import Button from "../../ui/Button"; +import Modal from "../../ui/Modal"; +import StatusIndicator from "../../ui/StatusIndicator"; + +/** One OpenTofu run this view is showing: a start, or a follow of one already running. */ +export interface DeployRun { + stateKey: string; + region: string; + label: string; + /** Null until the starting command resolves. */ + opId: string | null; + events: TofuEvent[]; + done: boolean; + cancellable: boolean; + result: TofuOutcome | null; +} + +type Subscription = { unlisten: (() => void) | null }; + +/** + * Runs keyed by state key. `start` subscribes to `aws-deploy-progress` before + * invoking, keeps every event for the state key it started until the op id + * is known (the backend may emit just before the invoke resolves), then keeps + * only that op's events. Resolves to the command's error, or null once started. + */ +export function useDeployRuns(onDone?: (run: { stateKey: string; result: TofuOutcome | null }) => void) { + const [runs, setRuns] = useState>({}); + const subs = useRef(new Map()); + const mounted = useRef(true); + const onDoneRef = useRef(onDone); + onDoneRef.current = onDone; + + useEffect(() => { + mounted.current = true; + const all = subs.current; + return () => { + mounted.current = false; + for (const s of all.values()) s.unlisten?.(); + all.clear(); + }; + }, []); + + const start = useCallback( + async (stateKey: string, region: string, label: string, run: () => Promise): Promise => { + subs.current.get(stateKey)?.unlisten?.(); + const sub: Subscription = { unlisten: null }; + subs.current.set(stateKey, sub); + const current = () => mounted.current && subs.current.get(stateKey) === sub; + const stop = () => { + sub.unlisten?.(); + sub.unlisten = null; + if (subs.current.get(stateKey) === sub) subs.current.delete(stateKey); + }; + + let opId: string | null = null; + const early: ProgressPayload[] = []; + const apply = (p: ProgressPayload) => { + setRuns((prev) => { + const r = prev[stateKey]; + if (!r || r.opId !== p.op_id || r.done) return prev; + return { + ...prev, + [stateKey]: { + ...r, + events: p.events.length ? [...r.events, ...p.events] : r.events, + done: p.done, + cancellable: p.done ? false : p.cancellable, + result: p.result ?? r.result, + }, + }; + }); + if (p.done) { + stop(); + onDoneRef.current?.({ stateKey, result: p.result ?? null }); + } + }; + + setRuns((prev) => ({ + ...prev, + [stateKey]: { stateKey, region, label, opId: null, events: [], done: false, cancellable: false, result: null }, + })); + + const unlisten = await listen(AWS_DEPLOY_PROGRESS_EVENT, ({ payload }) => { + if (!current() || payload.state_key !== stateKey) return; + if (opId === null) early.push(payload); + else if (payload.op_id === opId) apply(payload); + }); + if (!current()) { + unlisten(); + return null; + } + sub.unlisten = unlisten; + + try { + opId = await run(); + } catch (e) { + stop(); + if (mounted.current) { + setRuns((prev) => { + const { [stateKey]: _gone, ...rest } = prev; + return rest; + }); + } + return toAwsError(e); + } + if (!current()) return null; + const id = opId; + setRuns((prev) => (prev[stateKey] ? { ...prev, [stateKey]: { ...prev[stateKey], opId: id } } : prev)); + for (const p of early.splice(0)) if (p.op_id === id) apply(p); + return null; + }, + [], + ); + + const dismiss = useCallback((stateKey: string) => { + setRuns((prev) => { + if (!prev[stateKey]?.done) return prev; + const { [stateKey]: _gone, ...rest } = prev; + return rest; + }); + }, []); + + return { runs, start, dismiss }; +} + +function EventLine({ e }: { e: TofuEvent }) { + const isError = e.level === "error"; + return ( +
  • + {(e.resource || e.action) && ( + + {e.resource && {e.resource}} + {e.action && {e.action}} + + )} + {isError ? ( + <> + Error: +
    {e.message}
    + + ) : ( + {e.message} + )} +
  • + ); +} + +/** A run's events in order, its final result, and Cancel (after a confirmation). */ +export default function DeployProgress({ + run, + connectionId, + onDismiss, +}: { + run: DeployRun; + connectionId: string; + onDismiss?: () => void; +}) { + const [confirming, setConfirming] = useState(false); + const [cancelling, setCancelling] = useState(false); + const [cancelError, setCancelError] = useState(null); + const listRef = useRef(null); + + useEffect(() => { + const el = listRef.current; + if (el) el.scrollTop = el.scrollHeight; + }, [run.events.length]); + + const cancel = async () => { + setCancelling(true); + setCancelError(null); + try { + await cancelAwsDeployment(connectionId, run.region, run.stateKey); + setConfirming(false); + } catch (e) { + setCancelError(toAwsError(e)); + } finally { + setCancelling(false); + } + }; + + const status = run.done + ? null + : run.opId === null + ? { tone: "busy" as const, label: "Starting…" } + : { tone: "busy" as const, label: "Running" }; + + return ( +
    +
    +
    + {run.label} + {status && } +
    +
    + {!run.done && ( + + )} + {run.done && onDismiss && ( + + )} +
    +
    + {run.events.length > 0 && ( +
      + {run.events.map((e, i) => ( + + ))} +
    + )} + {run.done && run.result && ( +

    + {run.result.ok ? ( + + ) : ( + + )} +

    + )} + {cancelError && !confirming && ( +

    + {awsErrorMessage(cancelError)} +

    + )} + {confirming && ( + setConfirming(false)} + footer={ + <> + + + + } + > +
    +

    + OpenTofu stops gracefully and saves its state. Anything it already created stays; Repair or Update + finishes the job later. +

    + {cancelError && ( +

    + {awsErrorMessage(cancelError)} +

    + )} +
    +
    + )} +
    + ); +} diff --git a/app/src/components/settings/hosts/EnvironmentsPanel.test.tsx b/app/src/components/settings/hosts/EnvironmentsPanel.test.tsx new file mode 100644 index 0000000..937f8af --- /dev/null +++ b/app/src/components/settings/hosts/EnvironmentsPanel.test.tsx @@ -0,0 +1,329 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import EnvironmentsPanel from "./EnvironmentsPanel"; +import type { DeployProgress, EnvironmentScan } from "../../../lib/types"; +import { conn, env, progress, scan, tofuEvent } from "./testkit"; + +const invoke = vi.fn(); +vi.mock("@tauri-apps/api/core", () => ({ + invoke: (cmd: string, args?: unknown) => invoke(cmd, args), +})); + +type Handler = (e: { payload: DeployProgress }) => void; +const handlers = new Set(); +vi.mock("@tauri-apps/api/event", () => ({ + listen: vi.fn(async (_name: string, handler: Handler) => { + handlers.add(handler); + return () => handlers.delete(handler); + }), +})); +function emit(p: DeployProgress) { + act(() => { + for (const h of [...handlers]) h({ payload: p }); + }); +} + +/** Mock the backend: `detect` answers detection; `rest` answers everything else. */ +function backend(detect: () => EnvironmentScan, rest: (cmd: string, args: unknown) => unknown = () => { + throw new Error("unexpected"); +}) { + invoke.mockImplementation(async (cmd: string, args: unknown) => { + if (cmd === "detect_aws_environments") return detect(); + return rest(cmd, args); + }); +} + +const detectCalls = () => invoke.mock.calls.filter((c) => c[0] === "detect_aws_environments").length; + +async function open() { + fireEvent.click(screen.getByRole("button", { name: "Environments" })); + await waitFor(() => expect(detectCalls()).toBeGreaterThan(0)); +} + +describe("EnvironmentsPanel", () => { + beforeEach(() => { + vi.clearAllMocks(); + handlers.clear(); + }); + + it("detects in the connection's default region when opened, and again on a region change", async () => { + backend(() => scan()); + render(); + expect(detectCalls()).toBe(0); + await open(); + expect(invoke).toHaveBeenCalledWith("detect_aws_environments", { connectionId: "h1", region: "eu-west-1" }); + fireEvent.change(screen.getByLabelText("Region"), { target: { value: "us-east-1" } }); + await waitFor(() => + expect(invoke).toHaveBeenCalledWith("detect_aws_environments", { connectionId: "h1", region: "us-east-1" }), + ); + fireEvent.click(await screen.findByRole("button", { name: "Detect again" })); + await waitFor(() => expect(detectCalls()).toBe(3)); + }); + + it("shows deploy as primary when nothing is found and the user is an admin", async () => { + backend(() => scan()); + render(); + await open(); + const deploy = await screen.findByRole("button", { name: "Deploy a new environment" }); + expect(deploy.className).toContain("--accent-emphasis"); + expect(screen.getByText(/No Triple-C environment in eu-west-1/)).toBeInTheDocument(); + fireEvent.click(deploy); + expect(screen.getByRole("dialog", { name: "Deploy a new environment" })).toBeInTheDocument(); + }); + + it("deploy is secondary when environments exist", async () => { + backend(() => scan({ environments: [env({ onboarding: { state: "joined" }, actions: [] })] })); + render(); + await open(); + const deploy = await screen.findByRole("button", { name: "Deploy a new environment" }); + expect(deploy.className).not.toContain("--accent-emphasis"); + expect(within(screen.getByTestId("env-dev")).getByText("Joined")).toBeInTheDocument(); + }); + + it("offers an admin bundle instead of deploy for a workspace user with nothing found", async () => { + backend( + () => scan(), + (cmd) => { + if (cmd === "aws_policy_document") return [{ name: "environment-admin.json", json: "{}" }]; + throw new Error(`unexpected ${cmd}`); + }, + ); + render(); + await open(); + expect(await screen.findByText(/needs an environment admin/)).toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Deploy a new environment" })).toBeNull(); + fireEvent.click(screen.getByRole("button", { name: "Show the environment-admin policies" })); + expect(await screen.findByText("environment-admin.json")).toBeInTheDocument(); + expect(invoke).toHaveBeenCalledWith("aws_policy_document", { tier: "environment_admin" }); + fireEvent.click(screen.getByRole("button", { name: "Request an environment from an admin…" })); + const dialog = screen.getByRole("dialog"); + expect(within(dialog).getByRole("button", { name: "Save bundle to folder…" })).toBeInTheDocument(); + }); + + it("treats a connection with no permission report as not an admin", async () => { + backend(() => scan()); + render(); + await open(); + expect(await screen.findByRole("button", { name: "Request an environment from an admin…" })).toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Deploy a new environment" })).toBeNull(); + }); + + it("an incomplete environment offers repair and destroy, destroy only after typing its name", async () => { + backend( + () => scan({ environments: [env({ state: { state: "incomplete", lock: null }, actions: ["repair", "destroy"], info: null, onboarding: null, template_version: null })] }), + (cmd) => { + if (cmd === "destroy_incomplete_aws_environment") return "op9"; + throw new Error(`unexpected ${cmd}`); + }, + ); + render(); + await open(); + const row = await screen.findByTestId("env-dev"); + expect(within(row).getByText("Incomplete")).toBeInTheDocument(); + expect(within(row).getByRole("button", { name: "Repair dev" })).toBeInTheDocument(); + + // Repair without a record asks for the network and warns about a change. + fireEvent.click(within(row).getByRole("button", { name: "Repair dev" })); + const repair = screen.getByRole("dialog", { name: "Repair dev" }); + expect(within(repair).getByRole("radio", { name: "Public" })).toHaveAttribute("aria-checked", "true"); + expect(within(repair).getByText(/different network than the one it was deployed with replaces/)).toBeInTheDocument(); + fireEvent.click(within(repair).getByRole("button", { name: "Cancel" })); + + fireEvent.click(within(row).getByRole("button", { name: "Destroy dev" })); + const dialog = screen.getByRole("dialog", { name: "Destroy dev" }); + const confirm = within(dialog).getByRole("button", { name: "Destroy" }); + expect(confirm).toBeDisabled(); + fireEvent.change(within(dialog).getByLabelText(/Type dev to confirm/), { target: { value: "de" } }); + expect(confirm).toBeDisabled(); + fireEvent.change(within(dialog).getByLabelText(/Type dev to confirm/), { target: { value: "dev" } }); + expect(confirm).toBeEnabled(); + fireEvent.click(confirm); + await waitFor(() => + expect(invoke).toHaveBeenCalledWith("destroy_incomplete_aws_environment", { + connectionId: "h1", + region: "eu-west-1", + name: "dev", + }), + ); + }); + + it("a stale lock offers unlock with its owner and age", async () => { + const lock = { who: "alice@laptop", created: "2026-11-14T07:00:00Z", operation: "OperationTypeApply", age_secs: 3 * 3600 + 300, local_process: false }; + backend( + () => scan({ environments: [env({ state: { state: "incomplete", lock }, actions: ["repair", "unlock"], onboarding: null })] }), + (cmd) => { + if (cmd === "unlock_aws_state") return undefined; + throw new Error(`unexpected ${cmd}`); + }, + ); + render(); + await open(); + const row = await screen.findByTestId("env-dev"); + expect(within(row).getByText(/Locked by alice@laptop/)).toBeInTheDocument(); + expect(within(row).getByText(/3 h 5 min ago/)).toBeInTheDocument(); + expect(within(row).queryByRole("button", { name: "Destroy dev" })).toBeNull(); + + fireEvent.click(within(row).getByRole("button", { name: "Unlock dev" })); + const dialog = screen.getByRole("dialog", { name: "Unlock dev" }); + expect(within(dialog).getByText(/alice@laptop/)).toBeInTheDocument(); + expect(within(dialog).getByText(/3 h 5 min ago/)).toBeInTheDocument(); + const confirm = within(dialog).getByRole("button", { name: "Unlock" }); + expect(confirm).toBeDisabled(); + fireEvent.change(within(dialog).getByLabelText(/Type dev to confirm/), { target: { value: "dev" } }); + fireEvent.click(confirm); + await waitFor(() => + expect(invoke).toHaveBeenCalledWith("unlock_aws_state", { + connectionId: "h1", + region: "eu-west-1", + stateKey: "environments/dev/terraform.tfstate", + }), + ); + await waitFor(() => expect(detectCalls()).toBe(2)); + }); + + it("shows the server's refusal when a lock is still held", async () => { + backend( + () => scan({ environments: [env({ state: { state: "incomplete", lock: null }, actions: ["repair", "destroy"], onboarding: null })] }), + (cmd) => { + if (cmd === "repair_aws_environment") throw { kind: "other", message: "The state is locked; Unlock first" }; + throw new Error(`unexpected ${cmd}`); + }, + ); + render(); + await open(); + // With a record, Repair runs straight away on the recorded network. + fireEvent.click(await screen.findByRole("button", { name: "Repair dev" })); + expect(await screen.findByText("The state is locked; Unlock first")).toBeInTheDocument(); + expect(invoke).toHaveBeenCalledWith("repair_aws_environment", { connectionId: "h1", region: "eu-west-1", name: "dev", network: null }); + }); + + it("join onboards an admin and shows progress until done, then re-detects", async () => { + const key = "users/dev/abc123abc123/terraform.tfstate"; + let detects = 0; + backend( + () => { + detects += 1; + return scan({ environments: [env({ onboarding: detects > 1 ? { state: "joined" } : { state: "not_joined" } })] }); + }, + async (cmd) => { + if (cmd === "onboard_aws_user") { + // The backend can emit before the invoke resolves: an old follower's + // line (another op) and this run's first line. + emit(progress({ op_id: "old", state_key: key, events: [tofuEvent("stale line")] })); + emit(progress({ op_id: "op1", state_key: key, events: [tofuEvent("Planning")], cancellable: false })); + return "op1"; + } + throw new Error(`unexpected ${cmd}`); + }, + ); + render(); + await open(); + fireEvent.click(await screen.findByRole("button", { name: "Join dev" })); + expect(await screen.findByText("Planning")).toBeInTheDocument(); + expect(screen.queryByText("stale line")).toBeNull(); + expect(invoke).toHaveBeenCalledWith("onboard_aws_user", { connectionId: "h1", region: "eu-west-1", environment: "dev" }); + expect(screen.getByRole("button", { name: "Cancel deployment" })).toBeDisabled(); + + emit(progress({ op_id: "op1", state_key: key, events: [tofuEvent("Creating...", { resource: "aws_iam_role.task", action: "create" })] })); + expect(screen.getByText("aws_iam_role.task")).toBeInTheDocument(); + emit(progress({ op_id: "other", state_key: "environments/x/terraform.tfstate", events: [tofuEvent("unrelated")] })); + expect(screen.queryByText("unrelated")).toBeNull(); + expect(detectCalls()).toBe(1); + + emit(progress({ op_id: "op1", state_key: key, events: [], done: true, cancellable: false, result: { ok: true, exit_code: 0, summary: "Apply complete! Resources: 4 added" } })); + expect(await screen.findByText(/Apply complete! Resources: 4 added/)).toBeInTheDocument(); + await waitFor(() => expect(detectCalls()).toBe(2)); + expect(await within(screen.getByTestId("env-dev")).findByText("Joined")).toBeInTheDocument(); + }); + + it("a workspace user's join opens the onboarding bundle and waits for an admin", async () => { + backend( + () => scan({ environments: [env()] }), + (cmd) => { + if (cmd === "save_aws_admin_bundle") return "/home/me/onboard-dev"; + throw new Error(`unexpected ${cmd}`); + }, + ); + render(); + await open(); + fireEvent.click(await screen.findByRole("button", { name: "Join dev" })); + const dialog = screen.getByRole("dialog"); + fireEvent.click(within(dialog).getByRole("button", { name: "Save bundle to folder…" })); + await waitFor(() => + expect(invoke).toHaveBeenCalledWith("save_aws_admin_bundle", { + connectionId: "h1", + region: "eu-west-1", + kind: "user_onboard", + environment: "dev", + ownerId: "AIDAEXAMPLEEXAMPLE01", + network: null, + }), + ); + expect(invoke.mock.calls.some((c) => c[0] === "onboard_aws_user")).toBe(false); + fireEvent.click(within(dialog).getByRole("button", { name: "Close" })); + expect(within(screen.getByTestId("env-dev")).getByText("Waiting for an admin to onboard you")).toBeInTheDocument(); + }); + + it("follows a deployment running on this machine when opened, and cancels after confirming", async () => { + const lock = { who: "me@here", created: "x", operation: "OperationTypeApply", age_secs: 60, local_process: true }; + backend( + () => scan({ environments: [env({ state: { state: "deploying", lock }, actions: ["follow"], onboarding: null })] }), + async (cmd) => { + if (cmd === "follow_aws_deployment") { + emit(progress({ op_id: "f1", events: [tofuEvent("replayed line")] })); + return "f1"; + } + if (cmd === "cancel_aws_deployment") return undefined; + throw new Error(`unexpected ${cmd}`); + }, + ); + render(); + await open(); + expect(await screen.findByText("replayed line")).toBeInTheDocument(); + expect(invoke).toHaveBeenCalledWith("follow_aws_deployment", { + connectionId: "h1", + region: "eu-west-1", + stateKey: "environments/dev/terraform.tfstate", + }); + fireEvent.click(screen.getByRole("button", { name: "Cancel deployment" })); + const dialog = screen.getByRole("dialog", { name: "Cancel this deployment?" }); + fireEvent.click(within(dialog).getByRole("button", { name: "Cancel deployment" })); + await waitFor(() => + expect(invoke).toHaveBeenCalledWith("cancel_aws_deployment", { + connectionId: "h1", + region: "eu-west-1", + stateKey: "environments/dev/terraform.tfstate", + }), + ); + }); + + it("shows a failed run's errors in full", async () => { + backend( + () => scan({ environments: [env({ state: { state: "update_available" }, actions: ["join", "update"], onboarding: { state: "joined" } })] }), + async (cmd) => { + if (cmd === "update_aws_environment") return "u1"; + throw new Error(`unexpected ${cmd}`); + }, + ); + render(); + await open(); + fireEvent.click(await screen.findByRole("button", { name: "Update dev" })); + await waitFor(() => expect(invoke).toHaveBeenCalledWith("update_aws_environment", { connectionId: "h1", region: "eu-west-1", name: "dev" })); + const long = "Error: creating IAM Role (triple-c-dev-task): AccessDenied: User is not authorized to perform iam:CreateRole\n with aws_iam_role.task"; + emit(progress({ op_id: "u1", events: [tofuEvent(long, { level: "error", kind: "diagnostic" })] })); + emit(progress({ op_id: "u1", events: [], done: true, cancellable: false, result: { ok: false, exit_code: 1, summary: "Apply failed" } })); + expect(await screen.findByText(/Failed \(exit 1\): Apply failed/)).toBeInTheDocument(); + expect(screen.getByText((_, el) => el?.textContent === long && el.tagName === "PRE")).toBeInTheDocument(); + }); + + it("routes a detection failure through the AWS error copy", async () => { + backend(() => { + throw { kind: "state_bucket_taken", bucket: "triple-c-tfstate-123456789012-eu-west-1" }; + }); + render(); + await open(); + expect( + await screen.findByText("The state bucket name triple-c-tfstate-123456789012-eu-west-1 is already taken by another AWS account."), + ).toBeInTheDocument(); + }); +}); diff --git a/app/src/components/settings/hosts/EnvironmentsPanel.tsx b/app/src/components/settings/hosts/EnvironmentsPanel.tsx new file mode 100644 index 0000000..d2cb958 --- /dev/null +++ b/app/src/components/settings/hosts/EnvironmentsPanel.tsx @@ -0,0 +1,490 @@ +import { useCallback, useEffect, useRef, useState, type ReactNode } from "react"; +import { + deployAwsEnvironment, + destroyIncompleteAwsEnvironment, + detectAwsEnvironments, + followAwsDeployment, + onboardAwsUser, + repairAwsEnvironment, + unlockAwsState, + updateAwsEnvironment, +} from "../../../lib/tauri-commands"; +import { awsErrorMessage, toAwsError } from "../../../lib/aws-error"; +import type { + AwsError, + DetectedEnvironment, + EnvironmentScan, + HostConnection, + ModuleKind, + NetworkChoice, + PermissionSummary, + PolicyFile, +} from "../../../lib/types"; +import Button from "../../ui/Button"; +import Field, { inputClass, selectClass } from "../../ui/Field"; +import Modal from "../../ui/Modal"; +import StatusIndicator from "../../ui/StatusIndicator"; +import AdminBundleModal from "./AdminBundleModal"; +import DeployEnvironmentModal from "./DeployEnvironmentModal"; +import DeployProgress, { useDeployRuns, type DeployRun } from "./DeployProgress"; +import PolicyFiles from "./PolicyFiles"; +import { + COMMON_REGIONS, + environmentStateKey, + formatAge, + lockLine, + onboardingStateKey, + stateLock, + stateStatus, +} from "./environmentFormat"; + +/** A typed confirmation: the action runs only once the environment's name is typed. */ +function TypedConfirmModal({ + title, + name, + confirmLabel, + children, + onConfirm, + onClose, +}: { + title: string; + name: string; + confirmLabel: string; + children: ReactNode; + /** Resolves to the command's error, or null when done. */ + onConfirm: () => Promise; + onClose: () => void; +}) { + const [typed, setTyped] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const confirm = async () => { + setBusy(true); + setError(null); + const err = await onConfirm(); + setBusy(false); + if (err) setError(err); + else onClose(); + }; + return ( + + + + + } + > +
    + {children} + + {(id) => ( + setTyped(e.target.value)} /> + )} + + {error && ( +

    + {awsErrorMessage(error)} +

    + )} +
    +
    + ); +} + +type Bundle = { kind: ModuleKind; environment?: string; ownerId?: string }; + +/** The environment a run's state key belongs to, if any. */ +function runEnvironment(stateKey: string): string | null { + const m = /^(?:environments|users)\/([^/]+)\//.exec(stateKey); + return m ? m[1] : null; +} + +/** + * The environments a connection can reach in a region (spec §2): detection, + * each environment's state and actions, and deploy/join for this caller's tier. + */ +export default function EnvironmentsPanel({ + connection, + tier, +}: { + connection: HostConnection; + /** The connection's last permission report; absent means unknown, treated as not an admin. */ + tier?: PermissionSummary; +}) { + const isAdmin = tier === "environment_admin"; + const [open, setOpen] = useState(false); + const [region, setRegion] = useState(connection.kind.default_region); + const [scan, setScan] = useState(null); + const [detecting, setDetecting] = useState(false); + const [detectError, setDetectError] = useState(null); + const [rowErrors, setRowErrors] = useState>({}); + const [pending, setPending] = useState>({}); + const [waiting, setWaiting] = useState>(new Set()); + const [deployOpen, setDeployOpen] = useState(false); + const [repairOf, setRepairOf] = useState(null); + const [destroyOf, setDestroyOf] = useState(null); + const [unlockOf, setUnlockOf] = useState(null); + const [bundle, setBundle] = useState(null); + const [copyNote, setCopyNote] = useState(null); + const request = useRef(0); + const followed = useRef(new Set()); + + const detect = useCallback(async () => { + const id = ++request.current; + setDetecting(true); + setDetectError(null); + try { + const found = await detectAwsEnvironments(connection.id, region); + if (id === request.current) setScan(found); + } catch (e) { + if (id === request.current) { + setScan(null); + setDetectError(toAwsError(e)); + } + } finally { + if (id === request.current) setDetecting(false); + } + }, [connection.id, region]); + + // A finished run (its result line shown) re-detects. + const detectRef = useRef(detect); + detectRef.current = detect; + const { runs, start, dismiss } = useDeployRuns(() => void detectRef.current()); + + useEffect(() => { + if (open) void detect(); + }, [open, detect]); + + const launch = useCallback( + async (envName: string, stateKey: string, label: string, run: () => Promise) => { + setRowErrors(({ [envName]: _gone, ...rest }) => rest); + setPending((p) => ({ ...p, [envName]: true })); + const err = await start(stateKey, region, label, run); + setPending(({ [envName]: _gone, ...rest }) => rest); + if (err) setRowErrors((r) => ({ ...r, [envName]: err })); + return err; + }, + [start, region], + ); + + // Reattach to a deploy running on this machine (a re-follow replays its whole log). + useEffect(() => { + if (!scan) return; + for (const e of scan.environments) { + const key = environmentStateKey(e.name); + const seen = `${scan.region}:${key}`; + if (e.actions.includes("follow") && !runs[key] && !followed.current.has(seen)) { + followed.current.add(seen); + void launch(e.name, key, `Deploy of ${e.name}`, () => followAwsDeployment(connection.id, scan.region, key)); + } + } + }, [scan, runs, launch, connection.id]); + + const regions = COMMON_REGIONS.includes(connection.kind.default_region) + ? COMMON_REGIONS + : [connection.kind.default_region, ...COMMON_REGIONS]; + + const copy = async (file: PolicyFile) => { + try { + await navigator.clipboard.writeText(file.json); + setCopyNote(`${file.name} copied to clipboard.`); + } catch (e) { + setCopyNote(`Could not copy ${file.name}: ${awsErrorMessage(toAwsError(e))}`); + } + }; + + const deploy = (name: string, network: NetworkChoice) => + launch(name, environmentStateKey(name), `Deploy of ${name}`, () => + deployAwsEnvironment(connection.id, region, name, network), + ); + const repair = (name: string, network?: NetworkChoice) => + launch(name, environmentStateKey(name), `Repair of ${name}`, () => + repairAwsEnvironment(connection.id, region, name, network), + ); + + const join = (e: DetectedEnvironment) => { + if (!scan) return; + if (isAdmin) { + void launch(e.name, onboardingStateKey(e.name, scan.owner_key), `Joining ${e.name}`, () => + onboardAwsUser(connection.id, region, e.name), + ); + } else { + setWaiting((w) => new Set(w).add(e.name)); + setBundle({ kind: "user_onboard", environment: e.name, ownerId: scan.owner_id }); + } + }; + + const rowRuns = (name: string) => + Object.values(runs).filter((r) => r.region === region && runEnvironment(r.stateKey) === name); + const shown = new Set(scan?.environments.map((e) => e.name) ?? []); + const looseRuns = Object.values(runs).filter( + (r) => r.region !== region || !shown.has(runEnvironment(r.stateKey) ?? ""), + ); + const progress = (r: DeployRun) => ( + dismiss(r.stateKey)} + /> + ); + + const envRow = (e: DetectedEnvironment) => { + const status = stateStatus(e.state); + const lock = stateLock(e.state); + const has = (a: DetectedEnvironment["actions"][number]) => e.actions.includes(a); + const onboarding = e.onboarding?.state; + const busy = !!pending[e.name]; + const rowError = rowErrors[e.name]; + return ( +
  • +
    +
    +
    + {e.name} + + {onboarding === "joined" && } + {onboarding === "in_progress" && } + {onboarding === "incomplete" && } +
    +
    + {e.template_version !== null ? `Module version ${e.template_version}` : "Module version unknown"} + {e.info && ` · ${e.info.network_mode} network`} +
    + {lock && ( +
    + {lockLine(lock)} + {lock.local_process && " · running on this machine"} +
    + )} + {e.state.state === "unreadable_record" && ( +
    The environment's record can't be used: {e.state.reason}
    + )} + {!isAdmin && waiting.has(e.name) && onboarding !== "joined" && ( +
    Waiting for an admin to onboard you
    + )} +
    +
    + {has("join") && onboarding !== "joined" && onboarding !== "in_progress" && ( + + )} + {has("follow") && ( + + )} + {has("update") && ( + + )} + {has("repair") && ( + + )} + {has("unlock") && ( + + )} + {has("destroy") && ( + + )} +
    +
    + {rowError && ( +

    + {awsErrorMessage(rowError)} +

    + )} + {rowRuns(e.name).map(progress)} +
  • + ); + }; + + const nothingFound = !!scan && scan.environments.length === 0; + + return ( +
    + + {open && ( +
    +
    + + {(id) => ( + + )} + + +
    + {detecting && ( +

    + Detecting… +

    + )} + {detectError && ( +

    + {awsErrorMessage(detectError)} +

    + )} + {scan && isAdmin && scan.boundary === "no" && ( +

    + This account has no Triple-C permissions boundary yet; deploying creates it first. +

    + )} + {scan && scan.environments.length > 0 &&
      {scan.environments.map(envRow)}
    } + {nothingFound && ( +

    + No Triple-C environment in {scan.region}. + {!isAdmin && + " Deploying one needs an environment admin: attach the environment-admin policies to an identity, or send an admin a bundle to deploy."} + {!tier && " Run Check to find out whether you can deploy one yourself."} +

    + )} + {scan && isAdmin && ( + + )} + {nothingFound && !isAdmin && ( +
    + + + {copyNote && ( +

    + {copyNote} +

    + )} +
    + )} + {looseRuns.map(progress)} +
    + )} + {scan && (deployOpen || repairOf) && ( + { + setDeployOpen(false); + setRepairOf(null); + }} + onDeploy={repairOf ? (name, network) => repair(name, network) : deploy} + onDetect={() => void detect()} + /> + )} + {destroyOf && ( + setDestroyOf(null)} + onConfirm={() => + launch(destroyOf, environmentStateKey(destroyOf), `Destroy of ${destroyOf}`, () => + destroyIncompleteAwsEnvironment(connection.id, region, destroyOf), + ) + } + > +

    + {destroyOf} never finished deploying, so OpenTofu removes everything it created for it. This can't be + undone. +

    +
    + )} + {unlockOf && ( + setUnlockOf(null)} + onConfirm={async () => { + try { + await unlockAwsState(connection.id, region, environmentStateKey(unlockOf.name)); + } catch (e) { + return toAwsError(e); + } + void detect(); + return null; + }} + > + {(() => { + const lock = stateLock(unlockOf.state); + return lock ? ( +

    + Held by {lock.who || "unknown"} since{" "} + {formatAge(lock.age_secs)} ago ({lock.created} + {lock.operation && `, ${lock.operation}`}). +

    + ) : null; + })()} +

    + Unlock only if that deployment has stopped. Removing the lock of a run that is still going lets two runs + write the state at once. +

    +
    + )} + {bundle && ( + setBundle(null)} + /> + )} +
    + ); +} diff --git a/app/src/components/settings/hosts/NetworkFields.tsx b/app/src/components/settings/hosts/NetworkFields.tsx new file mode 100644 index 0000000..d4499b2 --- /dev/null +++ b/app/src/components/settings/hosts/NetworkFields.tsx @@ -0,0 +1,67 @@ +import type { NetworkChoice } from "../../../lib/types"; +import Field, { SwitchRow, monoInputClass } from "../../ui/Field"; +import SegmentedControl from "../../ui/SegmentedControl"; +import Toggle from "../../ui/Toggle"; +import type { NetworkDraft } from "./environmentFormat"; + +/** D4's modes and their cost lines. */ +const COST: Record = { + public: "$0 — tasks get a public IP, no inbound access", + "private-nat": "about $33/month for the NAT gateway", + existing: "No new network resources — tasks run in your VPC and two subnets in different availability zones", +}; + +/** The network picker shared by deploy, repair and the environment bundle. */ +export default function NetworkFields({ + value, + onChange, + error, +}: { + value: NetworkDraft; + onChange: (next: NetworkDraft) => void; + /** Why the existing-VPC fields aren't usable yet. */ + error?: string | null; +}) { + const set = (patch: Partial) => onChange({ ...value, ...patch }); + return ( +
    +
    Network
    + + label="Network" + value={value.mode} + onChange={(mode) => set({ mode })} + segments={[ + { value: "public", label: "Public" }, + { value: "private-nat", label: "Private + NAT" }, + { value: "existing", label: "Existing VPC" }, + ]} + /> +

    {COST[value.mode]}

    + {value.mode === "existing" && ( +
    + + {(id) => ( + set({ vpcId: e.target.value })} /> + )} + + + {(id) => ( + set({ subnet1: e.target.value })} /> + )} + + + {(id) => ( + set({ subnet2: e.target.value })} /> + )} + + set({ assignPublicIp: v })} />} + /> + {error &&

    {error}

    } +
    + )} +
    + ); +} diff --git a/app/src/components/settings/hosts/PolicyFiles.tsx b/app/src/components/settings/hosts/PolicyFiles.tsx new file mode 100644 index 0000000..703b2c7 --- /dev/null +++ b/app/src/components/settings/hosts/PolicyFiles.tsx @@ -0,0 +1,70 @@ +import { useState } from "react"; +import { awsPolicyDocument } from "../../../lib/tauri-commands"; +import { awsErrorMessage, toAwsError } from "../../../lib/aws-error"; +import type { PolicyFile, Tier } from "../../../lib/types"; +import Button from "../../ui/Button"; + +/** A tier's policy files, loaded on demand: each one shown and copied on its own. */ +export default function PolicyFiles({ + tier, + label, + onCopy, +}: { + tier: Tier; + label: string; + onCopy: (file: PolicyFile) => void; +}) { + const [files, setFiles] = useState(null); + const [error, setError] = useState(null); + + const load = async () => { + setError(null); + try { + setFiles(await awsPolicyDocument(tier)); + } catch (e) { + setError(`Could not load the policy: ${awsErrorMessage(toAwsError(e))}`); + } + }; + + if (!files) { + return ( +
    + + {error && ( +

    + {error} +

    + )} +
    + ); + } + return ( +
    +

    + {tier === "workspace_user" ? "Workspace user" : "Environment admin"}:{" "} + {files.length === 1 + ? "attach this file as a customer managed policy." + : `Attach all ${files.length} files, each as its own customer managed policy.`} +

    + {files.map((f) => ( +
    +
    + {f.name} + +
    +
    + Show JSON +
    +              {f.json}
    +            
    +
    +
    + ))} +
    + ); +} + diff --git a/app/src/components/settings/hosts/environmentFormat.ts b/app/src/components/settings/hosts/environmentFormat.ts new file mode 100644 index 0000000..ab1e49a --- /dev/null +++ b/app/src/components/settings/hosts/environmentFormat.ts @@ -0,0 +1,97 @@ +// Pure helpers shared by the environments UI. The name and id rules mirror +// `aws/tofu_modules.rs`; the server re-validates everything. +import type { EnvironmentState, LockInfo, NetworkChoice } from "../../../lib/types"; +import type { StatusTone } from "../../ui/StatusIndicator"; + +export const COMMON_REGIONS = [ + "us-east-1", "us-east-2", "us-west-1", "us-west-2", "ca-central-1", + "eu-west-1", "eu-west-2", "eu-west-3", "eu-central-1", "eu-north-1", + "ap-southeast-1", "ap-southeast-2", "ap-northeast-1", "ap-northeast-2", "ap-south-1", + "sa-east-1", +]; + +/** `validate_environment_name`: null when valid, else why not. */ +export function environmentNameError(name: string): string | null { + const ok = + /^[a-z][a-z0-9-]{0,19}$/.test(name) && !name.endsWith("-") && !name.includes("--"); + return ok + ? null + : "Use 1 to 20 lowercase letters, digits and single hyphens, starting with a letter and not ending in a hyphen."; +} + +/** `is_aws_id`: the prefix, then 8 or 17 lowercase hex characters. */ +export function isAwsId(id: string, prefix: "vpc-" | "subnet-"): boolean { + return new RegExp(`^${prefix}([0-9a-f]{8}|[0-9a-f]{17})$`).test(id); +} + +/** The fields behind the network picker, kept as text while the user types. */ +export interface NetworkDraft { + mode: NetworkChoice["mode"]; + vpcId: string; + subnet1: string; + subnet2: string; + assignPublicIp: boolean; +} + +export const DEFAULT_NETWORK: NetworkDraft = { + mode: "public", + vpcId: "", + subnet1: "", + subnet2: "", + assignPublicIp: false, +}; + +/** The draft as a `NetworkChoice`, or why it can't be one yet. */ +export function networkFromDraft(d: NetworkDraft): { network: NetworkChoice } | { error: string } { + if (d.mode === "public") return { network: { mode: "public" } }; + if (d.mode === "private-nat") return { network: { mode: "private-nat" } }; + const vpc = d.vpcId.trim(); + const subnets = [d.subnet1.trim(), d.subnet2.trim()]; + if (!isAwsId(vpc, "vpc-")) return { error: "Enter a VPC ID (vpc- and 8 or 17 hex characters)." }; + if (!subnets.every((s) => isAwsId(s, "subnet-"))) { + return { error: "Enter two subnet IDs (subnet- and 8 or 17 hex characters), in different availability zones." }; + } + if (subnets[0] === subnets[1]) return { error: "The two subnets must be different." }; + return { network: { mode: "existing", vpc_id: vpc, subnet_ids: subnets, assign_public_ip: d.assignPublicIp } }; +} + +export const environmentStateKey = (env: string) => `environments/${env}/terraform.tfstate`; +export const onboardingStateKey = (env: string, ownerKey: string) => `users/${env}/${ownerKey}/terraform.tfstate`; +export const BOUNDARY_STATE_KEY = "boundary/terraform.tfstate"; + +/** "45 s", "12 min", "3 h 5 min", "2 days". */ +export function formatAge(secs: number): string { + if (secs < 60) return `${Math.max(0, Math.floor(secs))} s`; + const mins = Math.floor(secs / 60); + if (mins < 60) return `${mins} min`; + const hours = Math.floor(mins / 60); + if (hours < 48) return mins % 60 ? `${hours} h ${mins % 60} min` : `${hours} h`; + return `${Math.floor(hours / 24)} days`; +} + +/** "Locked by · ago ()". */ +export function lockLine(lock: LockInfo): string { + const op = lock.operation ? ` (${lock.operation})` : ""; + return `Locked by ${lock.who || "unknown"} · ${formatAge(lock.age_secs)} ago${op}`; +} + +export function stateStatus(s: EnvironmentState): { tone: StatusTone; label: string } { + switch (s.state) { + case "ready": + return { tone: "ok", label: "Ready" }; + case "update_available": + return { tone: "ok", label: "Update available" }; + case "deploying": + return { tone: "busy", label: "Deploying" }; + case "incomplete": + return { tone: "error", label: "Incomplete" }; + case "externally_managed": + return { tone: "ok", label: "Available" }; + case "unreadable_record": + return { tone: "error", label: "Unreadable record" }; + } +} + +export function stateLock(s: EnvironmentState): LockInfo | null { + return s.state === "deploying" || s.state === "incomplete" ? s.lock : null; +} diff --git a/app/src/components/settings/hosts/testkit.ts b/app/src/components/settings/hosts/testkit.ts new file mode 100644 index 0000000..1532b68 --- /dev/null +++ b/app/src/components/settings/hosts/testkit.ts @@ -0,0 +1,64 @@ +// Shared fixtures for the environments UI tests (not a test file itself). +import type { + DeployProgress, + DetectedEnvironment, + EnvironmentInfo, + EnvironmentScan, + HostConnection, + TofuEvent, +} from "../../../lib/types"; + +export const conn: HostConnection = { + id: "h1", + name: "Prod", + kind: { type: "aws", auth: { method: "profile", name: "prod-sso" }, default_region: "eu-west-1" }, +}; + +export function scan(over: Partial = {}): EnvironmentScan { + return { + region: "eu-west-1", + account: "123456789012", + owner_id: "AIDAEXAMPLEEXAMPLE01", + owner_key: "abc123abc123", + state_bucket: "yes", + boundary: "yes", + environments: [], + ...over, + }; +} + +export function info(name = "dev"): EnvironmentInfo { + return { + schema: 1, + name, + template_version: 1, + cluster_arn: `arn:aws:ecs:eu-west-1:123456789012:cluster/triple-c-${name}`, + security_group_id: "sg-0123abcd", + subnet_ids: ["subnet-0123abcd", "subnet-4567abcd"], + assign_public_ip: true, + kms_key_arn: "arn:aws:kms:eu-west-1:123456789012:key/k", + log_group: `/triple-c/${name}`, + network_mode: "public", + tenancy: "strict", + }; +} + +export function env(over: Partial = {}): DetectedEnvironment { + return { + name: "dev", + template_version: 1, + state: { state: "ready" }, + actions: ["join"], + info: info(over.name ?? "dev"), + onboarding: { state: "not_joined" }, + ...over, + }; +} + +export function tofuEvent(message: string, over: Partial = {}): TofuEvent { + return { ts: "2026-11-14T10:00:00Z", level: "info", kind: "apply_progress", resource: null, action: null, message, ...over }; +} + +export function progress(over: Partial): DeployProgress { + return { op_id: "op1", state_key: "environments/dev/terraform.tfstate", events: [], done: false, cancellable: true, ...over }; +} diff --git a/app/src/lib/aws-error.ts b/app/src/lib/aws-error.ts index d4bbfe3..c55d627 100644 --- a/app/src/lib/aws-error.ts +++ b/app/src/lib/aws-error.ts @@ -21,3 +21,19 @@ export function toAwsError(e: unknown): AwsError { } return { kind: "other", message: typeof e === "string" ? e : e instanceof Error ? e.message : "Unknown error" }; } + +/** Human-readable copy for a failed AWS command; never raw JSON. */ +export function awsErrorMessage(e: AwsError): string { + switch (e.kind) { + case "sso_expired": + return `Your SSO session for profile ${e.profile} has expired.`; + case "profile_not_found": + return `Profile ${e.profile} was not found in your AWS config, or has no credentials.`; + case "keys_missing": + return "The access keys for this connection are missing from the keychain. Remove and re-add the connection."; + case "state_bucket_taken": + return `The state bucket name ${e.bucket} is already taken by another AWS account.`; + default: + return e.message; + } +}