mirror of
https://github.com/cozystack/cozystack.git
synced 2026-11-30 04:06:34 +09:00
feat(dashboard): manage application credentials from the console
Converted applications no longer let tenants read their passwords from a Secret: the API mints a password on request and shows it once. Without a console path, tenants who only use the dashboard would have no way to log in to a fresh database or to replace a migrated password. The Credentials tab lists an application's accounts with where the live password came from and its history, and offers mint and revoke behind a confirmation. Every request carries the resourceVersion the user saw, so a concurrent mint surfaces as a conflict instead of silently killing the password someone else just received. Actions are gated on a SelfSubjectAccessReview so viewers see the record without the buttons. The Credential API serves no watch, so the tab polls, the one exception to the console's no-polling rule besides the metrics panels. Mint and revoke bypass the mutation hooks because React Query keeps a mutation's result in its cache, and a minted password must live only in the dialog's state. The console's agent notes record both, since either would otherwise look like a mistake. Assisted-by: LLM Signed-off-by: Andrei Kvapil <kvapss@gmail.com>
This commit is contained in:
9 files changed
+724
-1
No files matched your search
@@ -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-<name>` namespaces.
|
||||
Pull the active tenant from `useTenantContext()` — never read the
|
||||
namespace from a URL param or guess it.
|
||||
|
||||
+38
-1
@@ -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")
|
||||
})
|
||||
})
|
||||
+19
@@ -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 <Navigate to="/console" replace />
|
||||
// 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={<ConfigMapsTab namespace={tenantNamespace ?? ""} names={configMaps.names} error={configMaps.error} />}
|
||||
/>
|
||||
<Route
|
||||
path="credentials"
|
||||
element={
|
||||
<CredentialsTab
|
||||
namespace={tenantNamespace ?? ""}
|
||||
credentials={credentials.credentials}
|
||||
isLoading={credentials.isLoading}
|
||||
error={credentials.error}
|
||||
onChanged={() => { void credentials.refetch() }}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="secrets"
|
||||
element={<SecretsTab ad={ad} instance={instance} />}
|
||||
|
||||
+158
@@ -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 (
|
||||
<div className="space-y-3">
|
||||
<p role="alert" className="rounded-md bg-amber-50 p-3 text-sm text-amber-900">
|
||||
Save this password now. It cannot be shown again: the platform does not keep it.
|
||||
</p>
|
||||
<dl className="space-y-2 text-sm">
|
||||
<div className="flex gap-2"><dt className="w-20 text-slate-500">Username</dt><dd><code>{username}</code></dd></div>
|
||||
<div className="flex items-start gap-2">
|
||||
<dt className="w-20 pt-1 text-slate-500">Password</dt>
|
||||
<dd className="flex-1"><code data-testid="minted-password" className="block break-all rounded bg-slate-900 p-2 text-xs text-slate-100">{password}</code></dd>
|
||||
</div>
|
||||
</dl>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button size="sm" variant="outline" disabled={!navigator.clipboard} onClick={handleCopy}>Copy password</Button>
|
||||
{copy !== "idle" && (
|
||||
<span role="status" className="text-xs">
|
||||
{copy === "ok" ? "Copied." : "Could not copy. Select and copy the password manually."}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
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<Phase>({ 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 (
|
||||
<DialogRoot
|
||||
open
|
||||
modal
|
||||
disablePointerDismissal={phase.name === "minted" || phase.name === "running"}
|
||||
onOpenChange={(open) => { if (!open && phase.name !== "running") close() }}
|
||||
>
|
||||
<DialogPortal>
|
||||
<DialogBackdrop />
|
||||
<DialogPopup className="w-[min(32rem,calc(100vw-2rem))] space-y-4 p-5">
|
||||
{phase.name === "minted" ? (
|
||||
<>
|
||||
<DialogTitle>New password for {user}</DialogTitle>
|
||||
<MintedPassword username={phase.username} password={phase.password} />
|
||||
<div className="flex justify-end">
|
||||
<Button size="sm" onClick={close}>I have saved it, close</Button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<DialogTitle>{verb} for {user}?</DialogTitle>
|
||||
<DialogDescription>
|
||||
{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."}
|
||||
</DialogDescription>
|
||||
{phase.name === "failed" && (
|
||||
<p role="alert" className="rounded-md bg-red-50 p-3 text-sm text-red-700">{phase.message}</p>
|
||||
)}
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button size="sm" variant="outline" disabled={phase.name === "running"} onClick={close}>
|
||||
{phase.name === "failed" ? "Close" : "Cancel"}
|
||||
</Button>
|
||||
{phase.name !== "failed" && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant={operation === "revoke" ? "destructive" : "default"}
|
||||
disabled={phase.name === "running"}
|
||||
onClick={run}
|
||||
>
|
||||
{phase.name === "running" && <Spinner />} {verb}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</DialogPopup>
|
||||
</DialogPortal>
|
||||
</DialogRoot>
|
||||
)
|
||||
}
|
||||
+187
@@ -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<Credential["status"]>["password"], extra: Partial<Credential> = {}): 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 <CredentialsTab namespace={namespace} credentials={result.credentials} isLoading={result.isLoading}
|
||||
error={result.error} onChanged={() => { 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(<Credentials />, { 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(<Credentials />, { 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(<Credentials />, { 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(<Credentials />, { 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(<Credentials />, { 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(<Credentials />, { 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(<Credentials />, { 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(<Credentials />, { 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(<Credentials />, { client })
|
||||
expect(await screen.findByText("No accounts yet.")).toBeInTheDocument()
|
||||
expect(screen.queryByRole("alert")).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
+151
@@ -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 (
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className="flex items-center gap-1 text-xs text-slate-500 hover:text-slate-800"
|
||||
>
|
||||
{open ? <ChevronDown className="size-3.5" /> : <ChevronRight className="size-3.5" />}
|
||||
History ({entries.length})
|
||||
</button>
|
||||
{open && (
|
||||
<ul className="mt-2 space-y-1 text-xs text-slate-600">
|
||||
{entries.map((entry, i) => (
|
||||
<li key={`${entry.at}-${i}`}>
|
||||
<span className="font-medium">{operationLabel(entry.operation)}</span> by {actorLabel(entry.by)} at {formatTime(entry.at)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<div className="space-y-2 px-5 py-3 text-sm">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="space-y-1">
|
||||
<p><code className="font-medium">{user}</code> <span className="ml-2 text-xs text-slate-500">{originLabel(credential)}</span></p>
|
||||
<p className="text-slate-600">{originExplanation(credential)}</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Last change: {formatTime(password?.at)}{password?.by ? ` by ${actorLabel(password.by)}` : ""}
|
||||
</p>
|
||||
</div>
|
||||
{(canMint || canRevoke) && (
|
||||
<div className="flex shrink-0 gap-2">
|
||||
{canMint && (
|
||||
<Button size="sm" variant="outline" onClick={() => onAction("mint")} aria-label={`Generate password for ${user}`}>
|
||||
Generate password
|
||||
</Button>
|
||||
)}
|
||||
{canRevoke && password?.origin !== "Revoked" && password?.origin !== "NotIssued" && (
|
||||
<Button size="sm" variant="outline" onClick={() => onAction("revoke")} aria-label={`Revoke password for ${user}`}>
|
||||
Revoke
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<History credential={credential} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<div className="space-y-6 p-6">
|
||||
<Section
|
||||
title="Credentials"
|
||||
description="Passwords are never stored by the console. A generated password is shown once, to you."
|
||||
bodyClassName="p-0"
|
||||
>
|
||||
{error ? <p role="alert" className="p-4 text-red-600">{error.message}</p>
|
||||
: isLoading ? <div className="flex items-center gap-2 p-4"><Spinner /> Loading…</div>
|
||||
: credentials.length === 0 ? <p className="p-4">No accounts yet.</p>
|
||||
: (
|
||||
<div className="divide-y divide-slate-100">
|
||||
{credentials.map((credential) => (
|
||||
<CredentialRow
|
||||
key={credential.metadata.name}
|
||||
credential={credential}
|
||||
canMint={canMint}
|
||||
canRevoke={canRevoke}
|
||||
onAction={(operation) => setAction({ credential, operation })}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
{action && (
|
||||
<CredentialActionDialog
|
||||
key={`${action.credential.metadata.name}/${action.operation}`}
|
||||
namespace={namespace}
|
||||
credential={action.credential}
|
||||
operation={action.operation}
|
||||
onChanged={onChanged}
|
||||
onClose={() => setAction(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+24
@@ -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/)
|
||||
})
|
||||
})
|
||||
+55
@@ -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."
|
||||
}
|
||||
}
|
||||
+91
@@ -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<Credential>(
|
||||
{ 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<CredentialRequestResult> {
|
||||
return client.subresource<CredentialRequestResult>(
|
||||
CREDENTIALS_GROUP,
|
||||
CREDENTIALS_VERSION,
|
||||
"credentials",
|
||||
credential.metadata.name,
|
||||
operation,
|
||||
namespace,
|
||||
{
|
||||
apiVersion: `${CREDENTIALS_GROUP}/${CREDENTIALS_VERSION}`,
|
||||
kind: "CredentialRequest",
|
||||
spec: { preconditions: { resourceVersion: credential.metadata.resourceVersion ?? "" } },
|
||||
},
|
||||
"POST",
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user