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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions dashboard/e2e/staging-cms.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { expect, test, type Page, type Route } from "@playwright/test";

// A repository's staging CMS write connection, from Settings > Repositories.
// Every API call is answered here; nothing reaches a real backend.

interface Backend {
role: string;
saved: Record<string, unknown> | null;
calls: { method: string; path: string; body: Record<string, unknown> | null }[];
}

async function mockApi(page: Page, init: Partial<Backend> = {}): Promise<Backend> {
const db: Backend = { role: "admin", saved: null, calls: [], ...init };
const json = (route: Route, body: unknown, status = 200) =>
route.fulfill({ status, 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) => {
const req = route.request();
const p = new URL(req.url()).pathname;
const method = req.method();
const body = req.postData() ? (JSON.parse(req.postData() as string) as Record<string, unknown>) : null;
db.calls.push({ method, path: p, body });
if (p === "/api/me")
return json(route, { user_id: "u_1", team_id: "t_1", github_login: null, email: "person@example.com", avatar_url: "", role: db.role, auth_provider: "email", mfa_enabled: false });
if (p === "/api/banners") return json(route, { banners: [] });
if (p === "/api/teams") return json(route, { teams: [{ team_id: "t_1", org: "your-team", status: "active", current: true }] });
if (p === "/api/repos")
return json(route, { repos: [{ name: "your-team/web", enabled: true, ticket_source: "github", onboard_status: "ready" }, { name: "your-team/api", enabled: false, ticket_source: "github" }] });
if (p === "/api/github/installation-status") return json(route, { status: "connected", github_org: "your-team", installation_id: 7 });
if (p === "/api/repos/your-team/web/staging-cms") {
if (method === "GET") return json(route, db.saved ?? { configured: false, repo: "your-team/web", providers: ["sanity"] });
if (method === "PUT") {
db.saved = { configured: true, repo: "your-team/web", provider: "sanity", project_id: body?.project_id, dataset: body?.dataset, production_dataset: body?.production_dataset, token_set: true };
return json(route, db.saved);
}
if (method === "DELETE") {
db.saved = null;
return json(route, { configured: false, repo: "your-team/web" });
}
}
return json(route, { error: `not mocked: ${method} ${p}` }, 404);
},
);
return db;
}

test("an admin saves a staging-only connection; production names are refused", async ({ page }) => {
const db = await mockApi(page);
await page.goto("/settings/repos/");
await page.getByRole("button", { name: "Staging content connection for your-team/web" }).click();
const dialog = page.getByTestId("staging-cms-dialog");
await expect(dialog).toBeVisible();
await dialog.getByLabel("Project id").fill("abc123");
await dialog.getByLabel("Staging dataset", { exact: true }).fill("production");
await expect(dialog.getByText("This looks like production.")).toBeVisible();
await expect(dialog.getByRole("button", { name: "Save" })).toBeDisabled();
await dialog.getByLabel("Staging dataset", { exact: true }).fill("staging");
await dialog.getByLabel("Token with write access to the staging dataset").fill("sk-test");
await dialog.getByRole("button", { name: "Save" }).click();
await expect(dialog).toBeHidden();
const put = db.calls.find((c) => c.method === "PUT");
expect(put?.body).toMatchObject({ provider: "sanity", project_id: "abc123", dataset: "staging", token: "sk-test" });
// The token is never shown again; a saved one keeps its place.
await page.getByRole("button", { name: "Staging content connection for your-team/web" }).click();
await expect(dialog.getByLabel("Token with write access to the staging dataset")).toHaveValue("");
await expect(dialog.getByRole("button", { name: "Remove connection" })).toBeVisible();
});

test("a turned-off repository and a member see no staging content button", async ({ page }) => {
await mockApi(page, { role: "member" });
await page.goto("/settings/repos/");
await expect(page.getByRole("list", { name: "Repositories" }).getByRole("listitem")).toHaveCount(2);
await expect(page.getByRole("button", { name: /Staging content connection/ })).toHaveCount(0);
});

for (const width of [375, 1440]) {
test(`the dialog has no horizontal scroll at ${width}px`, async ({ page }) => {
await page.setViewportSize({ width, height: 900 });
await mockApi(page);
await page.goto("/settings/repos/");
await page.getByRole("button", { name: "Staging content connection for your-team/web" }).click();
await expect(page.getByTestId("staging-cms-dialog")).toBeVisible();
const overflow = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
expect(overflow).toBeLessThanOrEqual(0);
});
}
21 changes: 21 additions & 0 deletions dashboard/src/app/settings/repos/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { Suspense, useCallback, useEffect, useState } from "react";
import { api, type Repo } from "@/lib/api";
import { githubAppUrl } from "@/lib/runtime-config";
import { RoleGuard } from "@/components/role-guard";
import { StagingCmsDialog } from "@/components/staging-cms-dialog";
import { useToast } from "@/components/toast";
import { Page, PageHeader } from "@/components/page";
import { buttonClass, secondaryButton } from "@/components/ui";
Expand Down Expand Up @@ -75,6 +76,8 @@ function ReposPage() {
const [toggling, setToggling] = useState<string | null>(null);
const [syncing, setSyncing] = useState(false);
const [savingRole, setSavingRole] = useState<string | null>(null);
// The repository whose staging CMS connection is open, if any.
const [stagingRepo, setStagingRepo] = useState<string | null>(null);
// Turning repos on or off, syncing and routing roles need `repos`.
const { ready, can } = useCan();
const canManage = can("repos");
Expand Down Expand Up @@ -295,6 +298,17 @@ function ReposPage() {
))}
</Select>
) : undefined}
{repo.enabled && canManage && (
<button
type="button"
onClick={() => setStagingRepo(repo.name)}
className={buttonClass("secondary", "sm")}
aria-label={`Staging content connection for ${repo.name}`}
title="Let Coderhelm update the staging CMS content your end-to-end tests read"
>
Staging content
</button>
)}
</>
}
/>
Expand All @@ -304,6 +318,13 @@ function ReposPage() {
)}
<LoadMore hasMore={!loading && filtered.length > shownCount} loading={false} onClick={() => setShownCount((n) => n + PAGE_SIZE)} />
</div>
{stagingRepo && (
<StagingCmsDialog
repo={stagingRepo}
open={!!stagingRepo}
onOpenChange={(v) => !v && setStagingRepo(null)}
/>
)}
</Page>
);
}
190 changes: 190 additions & 0 deletions dashboard/src/components/staging-cms-dialog.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
"use client";

import { useEffect, useId, useState } from "react";
import { api, type StagingCms } from "@/lib/api";
import { SecretInput } from "./field";
import { Modal, ModalFooter } from "./modal";
import { inputClass, primaryButton, secondaryButton } from "./ui";

// A repository's staging CMS write connection. When a feature changes the CMS
// schema and the end-to-end tests read pages from the CMS, Coderhelm updates
// the staging content those tests read through this connection, never
// production. Without one, the run stops and lists the content to change.

/** Dataset names Coderhelm refuses: they look like production. */
const PRODUCTION_WORDS = ["production", "prod", "prd", "live", "master", "main"];

export function looksLikeProduction(dataset: string): boolean {
return dataset
.toLowerCase()
.split(/[^a-z0-9]+/)
.some((w) => PRODUCTION_WORDS.includes(w));
}

export function StagingCmsDialog({
repo,
open,
onOpenChange,
}: {
repo: string;
open: boolean;
onOpenChange: (open: boolean) => void;
}) {
const [conn, setConn] = useState<StagingCms | null>(null);
const [projectId, setProjectId] = useState("");
const [dataset, setDataset] = useState("");
const [prodDataset, setProdDataset] = useState("");
const [token, setToken] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const ids = { project: useId(), dataset: useId(), prod: useId(), token: useId() };

// Each opening reads the saved connection; the token is never sent back.
useEffect(() => {
if (!open) return;
setError("");
setToken("");
setConn(null);
api
.getStagingCms(repo)
.then((c) => {
setConn(c);
setProjectId(c.project_id ?? "");
setDataset(c.dataset ?? "");
setProdDataset(c.production_dataset ?? "");
})
.catch(() => setError("Couldn't load the connection. Try again."));
}, [open, repo]);

const production = looksLikeProduction(dataset) || (!!prodDataset && prodDataset === dataset);

const save = async () => {
setBusy(true);
setError("");
try {
const c = await api.saveStagingCms(repo, {
provider: "sanity",
project_id: projectId.trim(),
dataset: dataset.trim(),
production_dataset: prodDataset.trim(),
token: token.trim() || undefined,
});
setConn(c);
onOpenChange(false);
} catch (e) {
setError(e instanceof Error && e.message ? e.message : "Couldn't save. Try again.");
}
setBusy(false);
};

const remove = async () => {
setBusy(true);
setError("");
try {
await api.deleteStagingCms(repo);
onOpenChange(false);
} catch {
setError("Couldn't remove the connection. Try again.");
}
setBusy(false);
};

return (
<Modal
open={open}
onOpenChange={(v) => !busy && onOpenChange(v)}
testId="staging-cms-dialog"
title={`Staging content for ${repo}`}
description="When a new feature changes the CMS schema and the end-to-end tests read pages from the CMS, Coderhelm updates the staging content those tests read. It never writes to production. Without a connection, the run stops and lists the content to change."
>
<form
id="staging-cms-form"
className="space-y-4"
onSubmit={(e) => {
e.preventDefault();
if (!production) void save();
}}
>
<p className="text-sm text-zinc-300">CMS: Sanity</p>
<div>
<label htmlFor={ids.project} className="mb-1 block text-sm font-medium text-zinc-200">
Project id
</label>
<input
id={ids.project}
type="text"
value={projectId}
onChange={(e) => setProjectId(e.target.value)}
className={inputClass}
autoComplete="off"
required
/>
</div>
<div>
<label htmlFor={ids.dataset} className="mb-1 block text-sm font-medium text-zinc-200">
Staging dataset
</label>
<input
id={ids.dataset}
type="text"
value={dataset}
onChange={(e) => setDataset(e.target.value)}
className={inputClass}
autoComplete="off"
aria-invalid={production || undefined}
aria-describedby={`${ids.dataset}-help`}
required
/>
<p id={`${ids.dataset}-help`} className={`mt-1 text-xs ${production ? "text-red-400" : "text-zinc-400"}`}>
{production
? "This looks like production. Coderhelm writes only to staging; enter the staging dataset."
: "The dataset your end-to-end tests read on staging."}
</p>
</div>
<div>
<label htmlFor={ids.prod} className="mb-1 block text-sm font-medium text-zinc-200">
Production dataset <span className="font-normal text-zinc-500">(optional)</span>
</label>
<input
id={ids.prod}
type="text"
value={prodDataset}
onChange={(e) => setProdDataset(e.target.value)}
className={inputClass}
autoComplete="off"
/>
<p className="mt-1 text-xs text-zinc-400">Named so Coderhelm refuses it, whatever it is called.</p>
</div>
<div>
<label htmlFor={ids.token} className="mb-1 block text-sm font-medium text-zinc-200">
Token with write access to the staging dataset
</label>
<SecretInput
id={ids.token}
value={token}
onChange={(e) => setToken(e.target.value)}
placeholder={conn?.token_set ? "Saved. Enter a new one to replace it." : ""}
/>
</div>
{error && (
<p role="alert" className="text-sm text-red-400">
{error}
</p>
)}
<ModalFooter>
{conn?.configured && (
<button type="button" onClick={remove} disabled={busy} className={secondaryButton}>
Remove connection
</button>
)}
<button type="button" onClick={() => onOpenChange(false)} disabled={busy} className={secondaryButton}>
Cancel
</button>
<button type="submit" form="staging-cms-form" disabled={busy || production} className={primaryButton}>
{busy ? "Saving…" : "Save"}
</button>
</ModalFooter>
</form>
</Modal>
);
}
30 changes: 30 additions & 0 deletions dashboard/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,15 @@ export const api = {
}),
deleteRepo: (repo: string) =>
request<void>(`/api/repos/${repo}`, { method: "DELETE" }),
/** The repository's staging-only CMS write connection (never its token). */
getStagingCms: (repo: string) => request<StagingCms>(`/api/repos/${repo}/staging-cms`),
saveStagingCms: (repo: string, body: StagingCmsInput) =>
request<StagingCms>(`/api/repos/${repo}/staging-cms`, {
method: "PUT",
body: JSON.stringify(body),
}),
deleteStagingCms: (repo: string) =>
request<StagingCms>(`/api/repos/${repo}/staging-cms`, { method: "DELETE" }),

// Stats
getStats: () => request<{ month: Stats; all_time: Stats }>("/api/stats"),
Expand Down Expand Up @@ -1982,6 +1991,27 @@ export interface Repo {
role?: string;
}

/** A repository's staging CMS write connection, as the gateway shows it. */
export interface StagingCms {
configured: boolean;
repo: string;
provider?: string;
project_id?: string;
dataset?: string;
production_dataset?: string;
/** Whether a token is saved; the token itself is never returned. */
token_set?: boolean;
}

export interface StagingCmsInput {
provider: "sanity";
project_id: string;
dataset: string;
production_dataset?: string;
/** Left out to keep the saved token. */
token?: string;
}

export interface Stats {
total_runs: number;
completed: number;
Expand Down
Loading