diff --git a/packages/system/dashboard/images/console/CLAUDE.md b/packages/system/dashboard/images/console/CLAUDE.md index 036e527d6..c7b04a3b3 100644 --- a/packages/system/dashboard/images/console/CLAUDE.md +++ b/packages/system/dashboard/images/console/CLAUDE.md @@ -82,6 +82,7 @@ the apiserver checks that user's RBAC. poll. Don't add `refetchInterval`. If you need a one-shot, pass `{ watch: false }`. The one exception is the metrics panels in `components/observability`: the observability proxy serves the Prometheus query API, which has no watch, so they refresh on a fixed interval instead. Log lines stream through the tail endpoint and are not polled. + The Credentials tab is the other one: the `core.cozystack.io` Credential API serves no watch, so `use-app-credentials.ts` polls its list. Mint and revoke call `K8sClient.subresource` directly rather than through a mutation hook, because React Query keeps a mutation's result in its cache and a minted password must live only in the dialog's state. 4. **Tenant scoping.** Most resources live in `tenant-` namespaces. Pull the active tenant from `useTenantContext()` — never read the namespace from a URL param or guess it. diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.test.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.test.tsx index a0c3a6b84..7422205d4 100644 --- a/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.test.tsx +++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.test.tsx @@ -11,6 +11,7 @@ const h = vi.hoisted(() => ({ tabLabels: [] as string[], configMaps: [] as unknown[], configMapsError: undefined as unknown, + credentials: [] as unknown[], })) vi.mock("@cozystack/k8s-client", async (importOriginal) => ({ @@ -20,7 +21,9 @@ vi.mock("@cozystack/k8s-client", async (importOriginal) => ({ // Presence probes (use-resource-presence.ts) — report empty lists. useK8sList: (ref: { plural: string }) => ref.plural === "configmaps" ? { data: { items: h.configMaps }, error: h.configMapsError, isLoading: false } - : { data: { items: [] }, isLoading: false }, + : ref.plural === "credentials" + ? { data: { items: h.credentials }, isLoading: false } + : { data: { items: [] }, isLoading: false }, })) vi.mock("../../lib/app-definitions.ts", () => ({ useApplicationDefinitions: () => ({ @@ -61,6 +64,7 @@ vi.mock("./SerialTab.tsx", () => ({ SerialTab: () => null })) vi.mock("./VMPowerControls.tsx", () => ({ VMPowerControls: () => null })) vi.mock("./MetricsTab.tsx", () => ({ MetricsTab: () => null })) vi.mock("./LogsTab.tsx", () => ({ LogsTab: () => null })) +vi.mock("./CredentialsTab.tsx", () => ({ CredentialsTab: () => null })) const { ApplicationDetailPage } = await import("./ApplicationDetailPage.tsx") @@ -181,3 +185,36 @@ describe("ApplicationDetailPage configuration", () => { expect(h.tabLabels).not.toContain("ConfigMaps") }) }) + +describe("ApplicationDetailPage credentials", () => { + function showPostgres(credentials: unknown[]) { + h.appKind = "Postgres" + h.appPlural = "postgreses" + h.get = { + data: { kind: "Postgres", metadata: { name: "demo", namespace: "tenant-test" } }, + isLoading: false, + error: undefined, + } + h.configMaps = [] + h.configMapsError = undefined + h.credentials = credentials + h.tabLabels = [] + renderPage() + } + + it("offers Credentials ahead of Secrets once the application has an account", () => { + showPostgres([{ + metadata: { name: "demo.app" }, + spec: { application: { apiGroup: "apps.cozystack.io", kind: "Postgres", name: "demo" }, user: "app" }, + }]) + expect(h.tabLabels.slice(-5)).toEqual(["Credentials", "Secrets", "Metrics", "Logs", "Events"]) + }) + + it("leaves Credentials off while only other applications have accounts", () => { + showPostgres([{ + metadata: { name: "other.app" }, + spec: { application: { apiGroup: "apps.cozystack.io", kind: "Postgres", name: "other" }, user: "app" }, + }]) + expect(h.tabLabels).not.toContain("Credentials") + }) +}) diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.tsx index ab68f7c49..2cbf7d786 100644 --- a/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.tsx +++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.tsx @@ -44,6 +44,8 @@ import { useResourceBasePath } from "../../lib/portal.ts" import { useResourcePresence } from "./use-resource-presence.ts" import { useApplicationConfigMaps } from "./use-app-configmaps.ts" import { ConfigMapsTab } from "./ConfigMapsTab.tsx" +import { useApplicationCredentials } from "./use-app-credentials.ts" +import { CredentialsTab } from "./CredentialsTab.tsx" import { LogsTab } from "./LogsTab.tsx" export function ApplicationDetailPage() { @@ -82,6 +84,7 @@ export function ApplicationDetailPage() { const presence = useResourcePresence(ad, instance) const configMaps = useApplicationConfigMaps(ad, instance, tenantNamespace ?? undefined) + const credentials = useApplicationCredentials(ad, instance, tenantNamespace ?? undefined) if (!plural || !name) return // Check the fetch error before the loading guard: on a failed GET, isLoading @@ -166,6 +169,10 @@ export function ApplicationDetailPage() { if (configMaps.names.length > 0 || configMaps.error) { tabs.push({ to: `${base}/configmaps`, label: "ConfigMaps", end: false }) } + // Accounts appear seconds after the application is created, on a poll. + if (credentials.credentials.length > 0 || credentials.error) { + tabs.push({ to: `${base}/credentials`, label: "Credentials", end: false }) + } tabs.push( { to: `${base}/secrets`, label: "Secrets", end: false }, { to: `${base}/metrics`, label: "Metrics", end: false }, @@ -246,6 +253,18 @@ export function ApplicationDetailPage() { path="configmaps" element={} /> + { void credentials.refetch() }} + /> + } + /> } diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/CredentialActionDialog.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/detail/CredentialActionDialog.tsx new file mode 100644 index 000000000..5687d378c --- /dev/null +++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/CredentialActionDialog.tsx @@ -0,0 +1,158 @@ +import { useState } from "react" +import { K8sApiError, useK8sClient } from "@cozystack/k8s-client" +import { Button, Spinner } from "@cozystack/ui" +import { + DialogBackdrop, + DialogDescription, + DialogPopup, + DialogPortal, + DialogRoot, + DialogTitle, +} from "../../components/ui/dialog.tsx" +import { + runCredentialOperation, + type Credential, + type CredentialOperation, +} from "./use-app-credentials.ts" + +type Phase = + | { name: "confirm" } + | { name: "running" } + | { name: "failed"; message: string } + | { name: "minted"; username: string; password: string } + +function failureMessage(error: unknown, operation: CredentialOperation): string { + if (error instanceof K8sApiError && error.status === 409) { + return `${error.message}. The list has been refreshed: check the account and try again.` + } + if (error instanceof K8sApiError && error.status === 403) { + return `You are not allowed to ${operation} this password: ${error.message}` + } + return error instanceof Error ? error.message : "The request failed." +} + +function MintedPassword({ username, password }: { username: string; password: string }) { + const [copy, setCopy] = useState<"idle" | "ok" | "failed">("idle") + const handleCopy = async () => { + try { + await navigator.clipboard.writeText(password) + setCopy("ok") + } catch { + setCopy("failed") + } + } + return ( +
+

+ Save this password now. It cannot be shown again: the platform does not keep it. +

+
+
Username
{username}
+
+
Password
+
{password}
+
+
+
+ + {copy !== "idle" && ( + + {copy === "ok" ? "Copied." : "Could not copy. Select and copy the password manually."} + + )} +
+
+ ) +} + +export function CredentialActionDialog({ + namespace, + credential, + operation, + onChanged, + onClose, +}: { + namespace: string + credential: Credential + operation: CredentialOperation + onChanged: () => void + onClose: () => void +}) { + const client = useK8sClient() + const [phase, setPhase] = useState({ name: "confirm" }) + const user = credential.spec?.user ?? credential.metadata.name + const verb = operation === "mint" ? "Generate password" : "Revoke" + + const close = () => { + // Drop the password before the dialog goes away, not only on unmount. + setPhase({ name: "confirm" }) + onClose() + } + + const run = async () => { + setPhase({ name: "running" }) + try { + const result = await runCredentialOperation(client, namespace, credential, operation) + onChanged() + if (operation === "mint" && result?.status?.password) { + setPhase({ name: "minted", username: result.status.username ?? user, password: result.status.password }) + } else { + onClose() + } + } catch (error) { + if (error instanceof K8sApiError && error.status === 409) onChanged() + setPhase({ name: "failed", message: failureMessage(error, operation) }) + } + } + + return ( + { if (!open && phase.name !== "running") close() }} + > + + + + {phase.name === "minted" ? ( + <> + New password for {user} + +
+ +
+ + ) : ( + <> + {verb} for {user}? + + {operation === "mint" + ? "A new password is generated and shown to you once. The current password stops working for every client that uses it." + : "The current password stops working for every client that uses it, and nobody holds a working one until a new password is generated."} + + {phase.name === "failed" && ( +

{phase.message}

+ )} +
+ + {phase.name !== "failed" && ( + + )} +
+ + )} +
+
+
+ ) +} diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/CredentialsTab.test.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/detail/CredentialsTab.test.tsx new file mode 100644 index 000000000..a745cc14b --- /dev/null +++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/CredentialsTab.test.tsx @@ -0,0 +1,187 @@ +import { afterEach, describe, expect, it, vi } from "vitest" +import { fireEvent, screen, waitFor, within } from "@testing-library/react" +import { K8sApiError, K8sClient } from "@cozystack/k8s-client" +import type { ApplicationDefinition, ApplicationInstance } from "@cozystack/types" +import { renderWithK8sProvider } from "../../test-utils/render.tsx" +import { CredentialsTab } from "./CredentialsTab.tsx" +import { useApplicationCredentials, type Credential } from "./use-app-credentials.ts" + +const namespace = "tenant-test" +const secret = "s3cr3t-Pa55w0rd-only-once" +const ad: ApplicationDefinition = { + apiVersion: "cozystack.io/v1alpha1", kind: "ApplicationDefinition", + metadata: { name: "postgres" }, + spec: { application: { kind: "Postgres", plural: "postgreses", singular: "postgres", openAPISchema: "{}" } }, +} +const instance: ApplicationInstance = { + apiVersion: "apps.cozystack.io/v1alpha1", kind: "Postgres", + metadata: { name: "demo", namespace }, +} + +function credential(user: string, password: NonNullable["password"], extra: Partial = {}): Credential { + return { + apiVersion: "core.cozystack.io/v1alpha1", kind: "Credential", + metadata: { name: `demo.${user}`, namespace, resourceVersion: `rv-${user}` }, + spec: { application: { apiGroup: "apps.cozystack.io", kind: "Postgres", name: "demo" }, user }, + status: { password, history: [{ operation: "Create", at: "2026-11-20T10:00:00Z", by: "system:serviceaccount:cozy-system:cozystack-api" }] }, + ...extra, + } +} + +const items: Credential[] = [ + credential("alice", { origin: "Minted", at: "2026-11-20T12:00:00Z", by: "jane@example.org" }), + credential("bob", { origin: "Migrated" }), + credential("carol", { origin: "NotIssued" }), + credential("dave", { origin: "Revoked", at: "2026-11-20T13:00:00Z", by: "jane@example.org" }), + credential("eve", { origin: "Migrated" }, { + metadata: { name: "other.eve", namespace }, + spec: { application: { apiGroup: "apps.cozystack.io", kind: "Postgres", name: "other" }, user: "eve" }, + }), +] + +function Credentials() { + const result = useApplicationCredentials(ad, instance, namespace) + return { void result.refetch() }} /> +} + +function makeClient({ allowed = true, list = items }: { allowed?: boolean; list?: Credential[] } = {}) { + const client = new K8sClient() + vi.spyOn(client, "list").mockImplementation(async (group, _version, plural, ns) => { + expect([group, plural, ns]).toEqual(["core.cozystack.io", "credentials", namespace]) + return { apiVersion: "core.cozystack.io/v1alpha1", kind: "CredentialList", metadata: { resourceVersion: "1" }, items: list } + }) + vi.spyOn(client, "watch").mockReturnValue(() => {}) + vi.spyOn(client, "create").mockImplementation(async (_group, _version, _plural, body) => ({ + ...(body as object), status: { allowed }, + })) + return client +} + +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() +}) + +describe("application credentials", () => { + it("lists only this application's accounts with what each origin means", async () => { + renderWithK8sProvider(, { client: makeClient() }) + expect(await screen.findByText("alice")).toBeInTheDocument() + expect(screen.getByText(/Shown once to jane@example\.org at/)).toBeInTheDocument() + expect(screen.getByText(/password from before the conversion still works/)).toBeInTheDocument() + expect(screen.getByText(/Nobody holds a password yet/)).toBeInTheDocument() + expect(screen.getByText(/The password was revoked/)).toBeInTheDocument() + expect(screen.queryByText("eve")).not.toBeInTheDocument() + }) + + it("expands an account's history", async () => { + renderWithK8sProvider(, { client: makeClient({ list: [items[0]] }) }) + fireEvent.click(await screen.findByRole("button", { name: /History \(1\)/ })) + expect(screen.getByText("Created")).toBeInTheDocument() + expect(screen.getByText(/by the platform at/)).toBeInTheDocument() + }) + + it("hides the actions when the user may not mint or revoke", async () => { + const client = makeClient({ allowed: false }) + renderWithK8sProvider(, { client }) + expect(await screen.findByText("alice")).toBeInTheDocument() + await waitFor(() => expect(client.create).toHaveBeenCalledTimes(2)) + expect(client.create).toHaveBeenCalledWith("authorization.k8s.io", "v1", "selfsubjectaccessreviews", expect.objectContaining({ + spec: { resourceAttributes: { namespace, group: "core.cozystack.io", resource: "credentials", subresource: "mint", verb: "create" } }, + })) + expect(screen.queryByRole("button", { name: /Generate password/ })).not.toBeInTheDocument() + expect(screen.queryByRole("button", { name: /Revoke/ })).not.toBeInTheDocument() + }) + + it("shows a minted password once, with the precondition sent, and drops it on close", async () => { + const writeText = vi.fn().mockResolvedValue(undefined) + vi.stubGlobal("navigator", { clipboard: { writeText } }) + const client = makeClient() + const subresource = vi.spyOn(client, "subresource").mockResolvedValue({ + status: { username: "bob", password: secret, issuedAt: "2026-11-21T09:00:00Z" }, + }) + const { queryClient } = renderWithK8sProvider(, { client }) + fireEvent.click(await screen.findByRole("button", { name: "Generate password for bob" })) + const dialog = await screen.findByRole("dialog") + expect(dialog).toHaveTextContent("stops working for every client") + expect(subresource).not.toHaveBeenCalled() + + fireEvent.click(within(dialog).getByRole("button", { name: "Generate password" })) + expect(await screen.findByTestId("minted-password")).toHaveTextContent(secret) + expect(screen.getByText(/cannot be shown again/)).toBeInTheDocument() + expect(subresource).toHaveBeenCalledWith("core.cozystack.io", "v1alpha1", "credentials", "demo.bob", "mint", namespace, { + apiVersion: "core.cozystack.io/v1alpha1", + kind: "CredentialRequest", + spec: { preconditions: { resourceVersion: "rv-bob" } }, + }, "POST") + await waitFor(() => expect(client.list).toHaveBeenCalledTimes(2)) + + fireEvent.click(screen.getByRole("button", { name: "Copy password" })) + await waitFor(() => expect(writeText).toHaveBeenCalledWith(secret)) + + fireEvent.click(screen.getByRole("button", { name: "I have saved it, close" })) + await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()) + expect(document.body).not.toHaveTextContent(secret) + const cached = JSON.stringify([ + queryClient.getQueryCache().getAll().map((q) => q.state.data), + queryClient.getMutationCache().getAll().map((m) => m.state.data), + ]) + expect(cached).not.toContain(secret) + }) + + it("shows the server's conflict, refreshes the list and offers no blind retry", async () => { + const client = makeClient() + vi.spyOn(client, "subresource").mockRejectedValue( + new K8sApiError(409, { message: "credential demo.bob changed: password minted by john@example.org" }), + ) + renderWithK8sProvider(, { client }) + fireEvent.click(await screen.findByRole("button", { name: "Generate password for bob" })) + const dialog = await screen.findByRole("dialog") + fireEvent.click(within(dialog).getByRole("button", { name: "Generate password" })) + expect(await within(dialog).findByRole("alert")).toHaveTextContent("changed: password minted by john@example.org") + await waitFor(() => expect(client.list).toHaveBeenCalledTimes(2)) + expect(within(dialog).queryByRole("button", { name: "Generate password" })).not.toBeInTheDocument() + expect(screen.queryByTestId("minted-password")).not.toBeInTheDocument() + }) + + it("reports a denied action instead of failing silently", async () => { + const client = makeClient() + vi.spyOn(client, "subresource").mockRejectedValue(new K8sApiError(403, { message: "forbidden" })) + renderWithK8sProvider(, { client }) + fireEvent.click(await screen.findByRole("button", { name: "Revoke password for bob" })) + const dialog = await screen.findByRole("dialog") + fireEvent.click(within(dialog).getByRole("button", { name: "Revoke" })) + expect(await within(dialog).findByRole("alert")).toHaveTextContent("not allowed to revoke") + }) + + it("revokes without showing any secret", async () => { + const client = makeClient() + const subresource = vi.spyOn(client, "subresource").mockResolvedValue({ + status: { username: "alice", issuedAt: "2026-11-21T09:00:00Z" }, + }) + renderWithK8sProvider(, { client }) + fireEvent.click(await screen.findByRole("button", { name: "Revoke password for alice" })) + const dialog = await screen.findByRole("dialog") + expect(dialog).toHaveTextContent("stops working for every client") + fireEvent.click(within(dialog).getByRole("button", { name: "Revoke" })) + await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()) + expect(subresource).toHaveBeenCalledWith("core.cozystack.io", "v1alpha1", "credentials", "demo.alice", "revoke", namespace, + expect.objectContaining({ spec: { preconditions: { resourceVersion: "rv-alice" } } }), "POST") + expect(screen.queryByTestId("minted-password")).not.toBeInTheDocument() + }) + + it("offers no revoke where nobody holds a password", async () => { + renderWithK8sProvider(, { client: makeClient() }) + expect(await screen.findByRole("button", { name: "Generate password for carol" })).toBeInTheDocument() + expect(screen.queryByRole("button", { name: "Revoke password for carol" })).not.toBeInTheDocument() + expect(screen.queryByRole("button", { name: "Revoke password for dave" })).not.toBeInTheDocument() + }) + + it("treats a cluster without the Credential API as having no accounts", async () => { + const client = makeClient() + vi.mocked(client.list).mockRejectedValue(new K8sApiError(404, "not found")) + renderWithK8sProvider(, { client }) + expect(await screen.findByText("No accounts yet.")).toBeInTheDocument() + expect(screen.queryByRole("alert")).not.toBeInTheDocument() + }) +}) diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/CredentialsTab.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/detail/CredentialsTab.tsx new file mode 100644 index 000000000..3820e9e82 --- /dev/null +++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/CredentialsTab.tsx @@ -0,0 +1,151 @@ +import { useState } from "react" +import { ChevronDown, ChevronRight } from "lucide-react" +import { useSelfSubjectAccessReview } from "@cozystack/k8s-client" +import { Button, Section, Spinner } from "@cozystack/ui" +import { CredentialActionDialog } from "./CredentialActionDialog.tsx" +import { actorLabel, formatTime, operationLabel, originExplanation, originLabel } from "./credential-origin.ts" +import { + CREDENTIALS_GROUP, + type Credential, + type CredentialOperation, +} from "./use-app-credentials.ts" + +// Fail closed: while the review loads or errors the actions stay hidden. +function useOperationAllowed(namespace: string, operation: CredentialOperation): boolean { + const review = useSelfSubjectAccessReview({ + resourceAttributes: { + namespace, + group: CREDENTIALS_GROUP, + resource: "credentials", + subresource: operation, + verb: "create", + }, + }) + return !review.isLoading && !review.error && review.allowed +} + +function History({ credential }: { credential: Credential }) { + const [open, setOpen] = useState(false) + const entries = credential.status?.history ?? [] + if (entries.length === 0) return null + return ( +
+ + {open && ( +
    + {entries.map((entry, i) => ( +
  • + {operationLabel(entry.operation)} by {actorLabel(entry.by)} at {formatTime(entry.at)} +
  • + ))} +
+ )} +
+ ) +} + +function CredentialRow({ + credential, + canMint, + canRevoke, + onAction, +}: { + credential: Credential + canMint: boolean + canRevoke: boolean + onAction: (operation: CredentialOperation) => void +}) { + const user = credential.spec?.user ?? credential.metadata.name + const password = credential.status?.password + return ( +
+
+
+

{user} {originLabel(credential)}

+

{originExplanation(credential)}

+

+ Last change: {formatTime(password?.at)}{password?.by ? ` by ${actorLabel(password.by)}` : ""} +

+
+ {(canMint || canRevoke) && ( +
+ {canMint && ( + + )} + {canRevoke && password?.origin !== "Revoked" && password?.origin !== "NotIssued" && ( + + )} +
+ )} +
+ +
+ ) +} + +export function CredentialsTab({ + namespace, + credentials, + isLoading, + error, + onChanged, +}: { + namespace: string + credentials: Credential[] + isLoading: boolean + error: Error | null + onChanged: () => void +}) { + const canMint = useOperationAllowed(namespace, "mint") + const canRevoke = useOperationAllowed(namespace, "revoke") + const [action, setAction] = useState<{ credential: Credential; operation: CredentialOperation } | null>(null) + + return ( +
+
+ {error ?

{error.message}

+ : isLoading ?
Loading…
+ : credentials.length === 0 ?

No accounts yet.

+ : ( +
+ {credentials.map((credential) => ( + setAction({ credential, operation })} + /> + ))} +
+ )} +
+ {action && ( + setAction(null)} + /> + )} +
+ ) +} diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/credential-origin.test.ts b/packages/system/dashboard/images/console/apps/console/src/routes/detail/credential-origin.test.ts new file mode 100644 index 000000000..cb3916c55 --- /dev/null +++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/credential-origin.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from "vitest" + +import { actorLabel, formatTime, operationLabel, originLabel } from "./credential-origin.ts" +import type { Credential } from "./use-app-credentials.ts" + +describe("credential labels", () => { + it("names a mint the way the button does", () => { + expect(operationLabel("Mint")).toBe("Generated") + expect(operationLabel("Migrate")).toBe("Migrated") + expect(operationLabel("Revoke")).toBe("Revoked") + expect(originLabel({ status: { password: { origin: "Minted" } } } as Credential)).toBe("Generated") + }) + + it("shows the platform's service accounts as the platform", () => { + expect(actorLabel("system:serviceaccount:cozy-system:cozystack-migration-hook")).toBe("the platform") + expect(actorLabel("system:serviceaccount:tenant-foo:ci")).toBe("system:serviceaccount:tenant-foo:ci") + expect(actorLabel("jane@example.org")).toBe("jane@example.org") + expect(actorLabel(undefined)).toBe("unknown") + }) + + it("names the time zone", () => { + expect(formatTime("2026-11-20T12:00:00Z")).toMatch(/[A-Z]{2,}|GMT|UTC/) + }) +}) diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/credential-origin.ts b/packages/system/dashboard/images/console/apps/console/src/routes/detail/credential-origin.ts new file mode 100644 index 000000000..b04e7b883 --- /dev/null +++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/credential-origin.ts @@ -0,0 +1,55 @@ +import type { Credential } from "./use-app-credentials.ts" + +export function formatTime(at: string | undefined): string { + if (!at) return "—" + const date = new Date(at) + return Number.isNaN(date.getTime()) ? at : date.toLocaleString(undefined, { timeZoneName: "short" }) +} + +// The platform's own service accounts seed, migrate and adopt accounts; a +// tenant reads them as one actor rather than as Kubernetes identities. +const platformActorPrefix = "system:serviceaccount:cozy-system:" + +export function actorLabel(by: string | undefined): string { + if (!by) return "unknown" + return by.startsWith(platformActorPrefix) ? "the platform" : by +} + +// The API names the operations after its subresources; the console calls a +// mint "Generate password", so the history uses the same word. +export function operationLabel(operation: string): string { + switch (operation) { + case "Create": return "Created" + case "Migrate": return "Migrated" + case "Mint": return "Generated" + case "Revoke": return "Revoked" + default: return operation + } +} + +export function originLabel(credential: Credential): string { + const origin = credential.status?.password?.origin + switch (origin) { + case "NotIssued": return "Not issued" + case "Migrated": return "Migrated" + case "Minted": return "Generated" + case "Revoked": return "Revoked" + default: return "Unknown" + } +} + +export function originExplanation(credential: Credential): string { + const password = credential.status?.password + switch (password?.origin) { + case "NotIssued": + return "Nobody holds a password yet. Generate one to log in." + case "Migrated": + return "The password from before the conversion still works. Replace it by generating a new one." + case "Minted": + return `Shown once to ${actorLabel(password.by)} at ${formatTime(password.at)}.` + case "Revoked": + return "The password was revoked. Nobody holds a working one until a new one is generated." + default: + return "The account has no recorded password state yet." + } +} diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/use-app-credentials.ts b/packages/system/dashboard/images/console/apps/console/src/routes/detail/use-app-credentials.ts new file mode 100644 index 000000000..9c476b3a9 --- /dev/null +++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/use-app-credentials.ts @@ -0,0 +1,91 @@ +import { K8sApiError, useK8sList, type K8sClient, type K8sResource } from "@cozystack/k8s-client" +import { APPS_GROUP, type ApplicationDefinition, type ApplicationInstance } from "@cozystack/types" + +export const CREDENTIALS_GROUP = "core.cozystack.io" +export const CREDENTIALS_VERSION = "v1alpha1" + +export type CredentialOrigin = "NotIssued" | "Migrated" | "Minted" | "Revoked" +export type CredentialOperation = "mint" | "revoke" + +export interface CredentialHistoryEntry { + operation: string + at: string + by: string +} + +export type Credential = K8sResource< + { + application: { apiGroup: string; kind: string; name: string } + user: string + }, + { + password?: { origin?: CredentialOrigin; at?: string; by?: string } + history?: CredentialHistoryEntry[] + } +> + +export interface CredentialRequestResult { + status?: { username?: string; password?: string; issuedAt?: string } +} + +// The Credential API serves no watch, so the list is refreshed on a timer. +const POLL_INTERVAL_MS = 10_000 + +export function useApplicationCredentials( + ad: ApplicationDefinition | undefined, + instance: ApplicationInstance | undefined, + namespace: string | undefined, +) { + const kind = ad?.spec?.application.kind + const name = instance?.metadata.name + const query = useK8sList( + { apiGroup: CREDENTIALS_GROUP, apiVersion: CREDENTIALS_VERSION, plural: "credentials", namespace }, + { + enabled: !!namespace && !!kind && !!name, + watch: false, + refetchInterval: POLL_INTERVAL_MS, + retry: false, + }, + ) + // 404: the cluster predates the Credential API; 403: the user cannot list it. + const unavailable = query.error instanceof K8sApiError && [403, 404].includes(query.error.status) + const credentials = (query.data?.items ?? []) + .filter((c) => { + const app = c.spec?.application + return app?.apiGroup === APPS_GROUP && app.kind === kind && app.name === name + }) + .sort((a, b) => (a.spec?.user ?? "").localeCompare(b.spec?.user ?? "")) + return { + credentials: unavailable ? [] : credentials, + isLoading: query.isLoading, + error: unavailable ? null : query.error, + refetch: query.refetch, + } +} + +/** + * Mint or revoke through the Credential's subresource. Called on the client + * directly rather than through a mutation hook: React Query keeps a mutation's + * result in its cache, and a minted password must not outlive the dialog. + */ +export function runCredentialOperation( + client: K8sClient, + namespace: string, + credential: Credential, + operation: CredentialOperation, +): Promise { + return client.subresource( + CREDENTIALS_GROUP, + CREDENTIALS_VERSION, + "credentials", + credential.metadata.name, + operation, + namespace, + { + apiVersion: `${CREDENTIALS_GROUP}/${CREDENTIALS_VERSION}`, + kind: "CredentialRequest", + spec: { preconditions: { resourceVersion: credential.metadata.resourceVersion ?? "" } }, + }, + "POST", + ) +}