This is an automated email from the ASF dual-hosted git repository. lahirujayathilake pushed a commit to branch signer-machine-api in repository https://gitbox.apache.org/repos/asf/airavata-custos.git
commit c52a2aa3486bda734c4041e308ff358264f1d61e Author: lahiruj <[email protected]> AuthorDate: Mon Nov 9 15:04:52 2026 -0500 Add the member SSH access page --- .../certificates/CertificateListContainer.tsx | 21 +-- web/src/app/(portal)/ssh-access/[serial]/page.tsx | 25 +++ web/src/app/(portal)/ssh-access/page.tsx | 22 +++ .../core/signer/__fixtures__/certificates.json | 16 +- .../signer/__tests__/CertificateDetail.test.tsx | 8 +- .../core/signer/__tests__/CertificateList.test.tsx | 3 +- .../__tests__/RevokeCertificateDialog.test.tsx | 24 +-- web/src/features/core/signer/__tests__/api.test.ts | 3 +- .../features/core/signer/__tests__/schemas.test.ts | 4 +- .../features/core/signer/__tests__/status.test.ts | 3 +- web/src/features/core/signer/api.ts | 38 +++- .../core/signer/components/CertificateDetail.tsx | 7 +- .../core/signer/components/CertificateList.tsx | 2 +- .../components/GenerateCertificateDialog.tsx | 176 +++++++++++++++++++ .../core/signer/components/MyCertificateDetail.tsx | 139 +++++++++++++++ .../core/signer/components/MyCertificates.tsx | 193 +++++++++++++++++++++ .../signer/components/RevokeCertificateDialog.tsx | 8 +- web/src/features/core/signer/queries.ts | 68 +++++++- web/src/features/core/signer/schemas.ts | 14 +- web/src/features/core/signer/status.ts | 5 + web/src/mocks/handlers/signer.ts | 43 ++++- web/src/shared/layout/Sidebar.tsx | 2 +- web/src/shared/layout/nav.ts | 10 +- web/tests/fixtures/signer-api.ts | 53 +++++- web/tests/signer-certificates.e2e.ts | 45 ++++- 25 files changed, 860 insertions(+), 72 deletions(-) diff --git a/web/src/app/(portal)/admin/signer/certificates/CertificateListContainer.tsx b/web/src/app/(portal)/admin/signer/certificates/CertificateListContainer.tsx index 53092a6a4..b75133065 100644 --- a/web/src/app/(portal)/admin/signer/certificates/CertificateListContainer.tsx +++ b/web/src/app/(portal)/admin/signer/certificates/CertificateListContainer.tsx @@ -23,7 +23,7 @@ import { useShallowSearchParams, } from "@/shared/hooks/useShallowSearchParams"; import { CertificateList } from "@/features/core/signer/components/CertificateList"; -import { useCertificates } from "@/features/core/signer/queries"; +import { useCertificates, useCursorPaging } from "@/features/core/signer/queries"; import type { CertificateStatus } from "@/features/core/signer/status"; function statusFilterFromUrl(raw: string | null): CertificateStatus | "all" { @@ -35,9 +35,7 @@ function statusFilterFromUrl(raw: string | null): CertificateStatus | "all" { export function CertificateListContainer() { const searchParams = useShallowSearchParams(); - // The cursor of each page after the first, so Previous can walk back. - const [cursors, setCursors] = React.useState<string[]>([]); - const [pageSize, setPageSize] = React.useState(20); + const { params: pageParams, paging } = useCursorPaging(); const search = searchParams.get("q") ?? ""; const statusFilter = statusFilterFromUrl(searchParams.get("status")); @@ -52,9 +50,8 @@ export function CertificateListContainer() { [searchParams], ); - const query = useCertificates({ limit: pageSize, cursor: cursors.at(-1) }); + const query = useCertificates(pageParams); const rows = query.data?.certificates ?? []; - const nextCursor = query.data?.next_cursor; return ( <CertificateList @@ -66,17 +63,7 @@ export function CertificateListContainer() { onSearchChange={(next) => updateParam("q", next)} statusFilter={statusFilter} onStatusFilterChange={(next) => updateParam("status", next === "all" ? null : next)} - paging={{ - page: cursors.length + 1, - pageSize, - hasNext: Boolean(nextCursor), - onNext: () => nextCursor && setCursors((prev) => [...prev, nextCursor]), - onPrevious: () => setCursors((prev) => prev.slice(0, -1)), - onPageSizeChange: (next) => { - setCursors([]); - setPageSize(next); - }, - }} + paging={paging(query.data?.next_cursor)} /> ); } diff --git a/web/src/app/(portal)/ssh-access/[serial]/page.tsx b/web/src/app/(portal)/ssh-access/[serial]/page.tsx new file mode 100644 index 000000000..1a41caf3f --- /dev/null +++ b/web/src/app/(portal)/ssh-access/[serial]/page.tsx @@ -0,0 +1,25 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import { MyCertificateDetail } from "@/features/core/signer/components/MyCertificateDetail"; + +export default async function MyCertificateDetailPage(props: { + params: Promise<{ serial: string }>; +}) { + const { serial } = await props.params; + return <MyCertificateDetail serial={serial} />; +} diff --git a/web/src/app/(portal)/ssh-access/page.tsx b/web/src/app/(portal)/ssh-access/page.tsx new file mode 100644 index 000000000..3e093de87 --- /dev/null +++ b/web/src/app/(portal)/ssh-access/page.tsx @@ -0,0 +1,22 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import { MyCertificates } from "@/features/core/signer/components/MyCertificates"; + +export default function SshAccessPage() { + return <MyCertificates />; +} diff --git a/web/src/features/core/signer/__fixtures__/certificates.json b/web/src/features/core/signer/__fixtures__/certificates.json index 026388e6c..c674cb4fb 100644 --- a/web/src/features/core/signer/__fixtures__/certificates.json +++ b/web/src/features/core/signer/__fixtures__/certificates.json @@ -1,7 +1,8 @@ [ { - "client_id": "airavata", + "requested_by": "app/airavata", "user_email": "[email protected]", + "user_sub": "sub-researcher", "serial_number": 42, "key_id": "[email protected]", "principal": "dev-admin", @@ -10,14 +11,14 @@ "valid_after": 1700000000, "valid_before": 4102444800, "issued_at": 1700000000, - "source_ip": "203.0.113.42", "granted_extensions": ["permit-pty", "permit-user-rc"], "force_command": null, "revoked": false }, { - "client_id": "airavata", + "requested_by": "app/airavata", "user_email": "[email protected]", + "user_sub": "sub-researcher", "serial_number": 43, "key_id": "[email protected]", "principal": "dev-admin", @@ -26,14 +27,14 @@ "valid_after": 1576800000, "valid_before": 1577836800, "issued_at": 1576800000, - "source_ip": "203.0.113.43", "granted_extensions": ["permit-pty"], "force_command": null, "revoked": false }, { - "client_id": "airavata", + "requested_by": "app/airavata", "user_email": "[email protected]", + "user_sub": "sub-researcher", "serial_number": 44, "key_id": "[email protected]", "principal": "dev-admin", @@ -42,7 +43,6 @@ "valid_after": 1690000000, "valid_before": 4102444800, "issued_at": 1690000000, - "source_ip": "203.0.113.44", "granted_extensions": ["permit-pty"], "force_command": null, "revoked": true, @@ -51,8 +51,9 @@ "revoked_by": "[email protected]" }, { - "client_id": "airavata", "user_email": "[email protected]", + "user_sub": "sub-future", + "requested_by": "user/future", "serial_number": 45, "key_id": "[email protected]", "principal": "future-user", @@ -61,7 +62,6 @@ "valid_after": 4102440000, "valid_before": 4102444800, "issued_at": 1700000000, - "source_ip": "203.0.113.45", "granted_extensions": ["permit-pty"], "force_command": null, "revoked": false diff --git a/web/src/features/core/signer/__tests__/CertificateDetail.test.tsx b/web/src/features/core/signer/__tests__/CertificateDetail.test.tsx index 9e61382f1..ea5786e57 100644 --- a/web/src/features/core/signer/__tests__/CertificateDetail.test.tsx +++ b/web/src/features/core/signer/__tests__/CertificateDetail.test.tsx @@ -9,7 +9,8 @@ import { ApiError } from "@/shared/api/client"; import type { Certificate } from "../schemas"; const baseCertificate: Certificate = { - client_id: "signer-client", + user_sub: "sub-admin", + requested_by: "user/1", serial_number: 42, key_id: "key-42", principal: "someone-else", @@ -19,7 +20,6 @@ const baseCertificate: Certificate = { valid_after: 1_700_000_000, valid_before: 4_102_444_800, issued_at: 1_700_000_000, - source_ip: "192.0.2.42", granted_extensions: ["permit-pty", "permit-user-rc"], force_command: "/usr/bin/id", revoked: false, @@ -77,12 +77,12 @@ describe("<CertificateDetail />", () => { it("renders complete issuance metadata", () => { render(<CertificateDetail serial="42" />); for (const value of [ - "signer-client", + "Self-service", "[email protected]", "key-42", "SHA256:pk", "SHA256:ca", - "192.0.2.42", + "sub-admin", "permit-pty, permit-user-rc", "/usr/bin/id", ]) { diff --git a/web/src/features/core/signer/__tests__/CertificateList.test.tsx b/web/src/features/core/signer/__tests__/CertificateList.test.tsx index da06e84d0..020b553df 100644 --- a/web/src/features/core/signer/__tests__/CertificateList.test.tsx +++ b/web/src/features/core/signer/__tests__/CertificateList.test.tsx @@ -21,7 +21,8 @@ import { CertificateList } from "../components/CertificateList"; import type { Certificate } from "../schemas"; const active: Certificate = { - client_id: "signer-client", + user_sub: "sub-1", + requested_by: "user/1", serial_number: 42, key_id: "k-active", principal: "dev-admin", diff --git a/web/src/features/core/signer/__tests__/RevokeCertificateDialog.test.tsx b/web/src/features/core/signer/__tests__/RevokeCertificateDialog.test.tsx index 56cabb273..f340814fb 100644 --- a/web/src/features/core/signer/__tests__/RevokeCertificateDialog.test.tsx +++ b/web/src/features/core/signer/__tests__/RevokeCertificateDialog.test.tsx @@ -34,18 +34,20 @@ function renderDialog( } describe("<RevokeCertificateDialog />", () => { - it("disables confirm until a reason is entered, then submits the trimmed reason", () => { + it("submits the trimmed reason", () => { const { props } = renderDialog(); - const confirm = screen.getByRole("button", { name: /confirm revoke/i }); - expect(confirm).toBeDisabled(); - fireEvent.change(screen.getByLabelText(/reason/i), { target: { value: " compromised " } }); - expect(confirm).toBeEnabled(); - - fireEvent.click(confirm); + fireEvent.click(screen.getByRole("button", { name: /confirm revoke/i })); expect(props.onSubmit).toHaveBeenCalledWith("compromised"); }); + // Make sure someone can revoke without giving a reason. + it("allows an empty reason", () => { + const { props } = renderDialog(); + fireEvent.click(screen.getByRole("button", { name: /confirm revoke/i })); + expect(props.onSubmit).toHaveBeenCalledWith(""); + }); + it("surfaces an error message", () => { renderDialog({ error: "You can only revoke your own certificates" }); expect(screen.getByText(/only revoke your own/i)).toBeInTheDocument(); @@ -64,14 +66,6 @@ describe("<RevokeCertificateDialog />", () => { expect(props.onSubmit).not.toHaveBeenCalled(); }); - it("shows remaining-length feedback and rejects whitespace-only reasons", () => { - renderDialog(); - const reason = screen.getByLabelText(/reason/i); - fireEvent.change(reason, { target: { value: " " } }); - expect(screen.getByText("255 remaining")).toBeInTheDocument(); - expect(screen.getByRole("button", { name: /confirm revoke/i })).toBeDisabled(); - }); - it("rejects reasons longer than 255 characters", () => { renderDialog(); fireEvent.change(screen.getByLabelText(/reason/i), { target: { value: "x".repeat(256) } }); diff --git a/web/src/features/core/signer/__tests__/api.test.ts b/web/src/features/core/signer/__tests__/api.test.ts index 43dcf856f..2bb14db3d 100644 --- a/web/src/features/core/signer/__tests__/api.test.ts +++ b/web/src/features/core/signer/__tests__/api.test.ts @@ -31,7 +31,8 @@ afterEach(() => { }); const certificate = { - client_id: "signer-client", + user_sub: "sub-1", + requested_by: "user/1", serial_number: 42, key_id: "k", principal: "dev-admin", diff --git a/web/src/features/core/signer/__tests__/schemas.test.ts b/web/src/features/core/signer/__tests__/schemas.test.ts index 94f766a7e..a203d2524 100644 --- a/web/src/features/core/signer/__tests__/schemas.test.ts +++ b/web/src/features/core/signer/__tests__/schemas.test.ts @@ -11,7 +11,8 @@ import { } from "../schemas"; const certificate = { - client_id: "signer-client", + user_sub: "sub-1", + requested_by: "user/1", serial_number: 42, key_id: "key-42", principal: "dev-admin", @@ -21,7 +22,6 @@ const certificate = { valid_after: 1_700_000_000, valid_before: 4_102_444_800, issued_at: 1_700_000_000, - source_ip: "192.0.2.4", granted_extensions: ["permit-pty"], force_command: null, revoked: false, diff --git a/web/src/features/core/signer/__tests__/status.test.ts b/web/src/features/core/signer/__tests__/status.test.ts index 9ab078a5c..f438a99f6 100644 --- a/web/src/features/core/signer/__tests__/status.test.ts +++ b/web/src/features/core/signer/__tests__/status.test.ts @@ -24,7 +24,8 @@ import { } from "../status"; const base: Certificate = { - client_id: "signer-client", + user_sub: "sub-1", + requested_by: "user/1", serial_number: 1, key_id: "k", principal: "p", diff --git a/web/src/features/core/signer/api.ts b/web/src/features/core/signer/api.ts index a71cee95b..b15d2dbe4 100644 --- a/web/src/features/core/signer/api.ts +++ b/web/src/features/core/signer/api.ts @@ -19,24 +19,56 @@ import { apiFetch } from "@/shared/api/client"; import { type Certificate, type CertificateList, + type GeneratedCertificate, type RevokeResponse, certificateListSchema, certificateSchema, + generatedCertificateSchema, revokeResponseSchema, } from "./schemas"; import type { CertificateListParams } from "./types"; -export async function listCertificates( - params: CertificateListParams = {}, +async function fetchCertificateList( + path: string, + params: CertificateListParams, ): Promise<CertificateList> { const search = new URLSearchParams(); if (typeof params.limit === "number") search.set("limit", String(params.limit)); if (params.cursor) search.set("cursor", params.cursor); const qs = search.toString(); - const raw = await apiFetch(`/connectors/signer/certificates${qs ? `?${qs}` : ""}`); + const raw = await apiFetch(`${path}${qs ? `?${qs}` : ""}`); return certificateListSchema.parse(raw); } +export function listCertificates(params: CertificateListParams = {}): Promise<CertificateList> { + return fetchCertificateList("/connectors/signer/certificates", params); +} + +export function listMyCertificates(params: CertificateListParams = {}): Promise<CertificateList> { + return fetchCertificateList("/connectors/signer/me/certificates", params); +} + +export async function getMyCertificate(serial: number | string): Promise<Certificate> { + const raw = await apiFetch(`/connectors/signer/me/certificates/${serial}`); + return certificateSchema.parse(raw); +} + +export async function generateCertificate(publicKey: string): Promise<GeneratedCertificate> { + const raw = await apiFetch("/connectors/signer/me/certificates", { + method: "POST", + body: { public_key: publicKey }, + }); + return generatedCertificateSchema.parse(raw); +} + +export async function revokeMyCertificate(serial: number, reason: string): Promise<RevokeResponse> { + const raw = await apiFetch(`/connectors/signer/me/certificates/${serial}/revoke`, { + method: "POST", + body: { reason }, + }); + return revokeResponseSchema.parse(raw); +} + export async function getCertificate(serial: number | string): Promise<Certificate> { const raw = await apiFetch(`/connectors/signer/certificates/${serial}`); return certificateSchema.parse(raw); diff --git a/web/src/features/core/signer/components/CertificateDetail.tsx b/web/src/features/core/signer/components/CertificateDetail.tsx index e2e0dd936..91cfeb369 100644 --- a/web/src/features/core/signer/components/CertificateDetail.tsx +++ b/web/src/features/core/signer/components/CertificateDetail.tsx @@ -34,6 +34,7 @@ import { formatCertificateLifetime, formatUnixSeconds, getCertificateStatus, + requestingApp, } from "../status"; import { RevokeCertificateDialog } from "./RevokeCertificateDialog"; @@ -135,8 +136,9 @@ export function CertificateDetail({ serial }: CertificateDetailProps) { function CertificateMetadata({ cert }: { cert: Certificate }) { const items: Array<{ label: string; value: React.ReactNode }> = [ - { label: "Signer client", value: cert.client_id }, + { label: "Generated by", value: requestingApp(cert) ?? "Self-service" }, { label: "User email", value: cert.user_email || "—" }, + { label: "Subject", value: <span className="break-all font-mono text-xs">{cert.user_sub}</span> }, { label: "Serial number", value: <span className="font-mono">{cert.serial_number}</span> }, { label: "Key ID", value: <span className="break-all font-mono text-xs">{cert.key_id}</span> }, { label: "Principal", value: cert.principal }, @@ -151,7 +153,6 @@ function CertificateMetadata({ cert }: { cert: Certificate }) { { label: "Issued at", value: formatUnixSeconds(cert.issued_at) }, { label: "Valid after", value: formatUnixSeconds(cert.valid_after) }, { label: "Valid before", value: formatUnixSeconds(cert.valid_before) }, - { label: "Source IP", value: cert.source_ip || "—" }, { label: "Granted extensions", value: cert.granted_extensions?.length ? cert.granted_extensions.join(", ") : "—", @@ -184,7 +185,7 @@ function CertificateMetadata({ cert }: { cert: Certificate }) { ); } -function revokeErrorMessage(error: unknown): string { +export function revokeErrorMessage(error: unknown): string { if (error instanceof ApiError) { if (error.status === 403) return "You no longer have permission to revoke certificates."; if (error.status === 409) return "This certificate is no longer active and cannot be revoked."; diff --git a/web/src/features/core/signer/components/CertificateList.tsx b/web/src/features/core/signer/components/CertificateList.tsx index 5b2e714a4..c3d21303f 100644 --- a/web/src/features/core/signer/components/CertificateList.tsx +++ b/web/src/features/core/signer/components/CertificateList.tsx @@ -176,7 +176,7 @@ export function CertificateList({ } // The DataTable pager needs a total. The signer sends none, so this one only goes forward and back. -function CursorPager({ page, pageSize, hasNext, onPrevious, onNext, onPageSizeChange }: CertificateListPaging) { +export function CursorPager({ page, pageSize, hasNext, onPrevious, onNext, onPageSizeChange }: CertificateListPaging) { return ( <div className="flex flex-col gap-3 text-sm text-muted-foreground sm:flex-row sm:items-center sm:justify-between"> <label className="flex items-center gap-2"> diff --git a/web/src/features/core/signer/components/GenerateCertificateDialog.tsx b/web/src/features/core/signer/components/GenerateCertificateDialog.tsx new file mode 100644 index 000000000..c085bfb49 --- /dev/null +++ b/web/src/features/core/signer/components/GenerateCertificateDialog.tsx @@ -0,0 +1,176 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +"use client"; + +import * as React from "react"; +import { ApiError } from "@/shared/api/client"; +import { Button } from "@/shared/ui/button"; +import { CopyValue } from "@/shared/ui/CopyValue"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/shared/ui/dialog"; +import { Label } from "@/shared/ui/label"; +import { useGenerateCertificate } from "../queries"; +import type { GeneratedCertificate } from "../schemas"; +import { formatUnixSeconds } from "../status"; + +const REFUSAL_MESSAGES: Record<string, string> = { + user_not_active: "Your account is not active. Contact your site admin.", + no_cluster_account: "You do not have an account on this cluster yet.", + cluster_account_not_ready: "Your cluster account is not ready yet. Try again once it is set up.", + no_active_allocation: "You need an active allocation to get a certificate.", + reserved_username: "Certificates cannot be issued for this username. Contact your site admin.", + invalid_public_key: "This does not look like an SSH public key. Paste the one line from your .pub file.", + key_type_not_allowed: "This site does not accept that key type.", + signer_unavailable: "Certificate service is not reachable. No certificate was issued. Try again in a minute.", +}; + +function refusalMessage(error: unknown): string { + const code = error instanceof ApiError ? (error.body as { error?: string } | null)?.error : undefined; + return (code && REFUSAL_MESSAGES[code]) || "Could not generate a certificate. Please try again."; +} + +function keyFile(certificate: string): string { + if (certificate.startsWith("ssh-rsa")) return "~/.ssh/id_rsa"; + if (certificate.startsWith("ecdsa")) return "~/.ssh/id_ecdsa"; + return "~/.ssh/id_ed25519"; +} + +function sshCommand(result: GeneratedCertificate): string { + const port = result.login_port === 22 ? "" : `-p ${result.login_port} `; + return `ssh -i ${keyFile(result.certificate)} ${port}${result.principal}@${result.login_host}`; +} + +export type GenerateCertificateDialogProps = { + open: boolean; + onOpenChange: (open: boolean) => void; +}; + +export function GenerateCertificateDialog({ open, onOpenChange }: GenerateCertificateDialogProps) { + const generate = useGenerateCertificate(); + const [publicKey, setPublicKey] = React.useState(""); + const { reset } = generate; + + React.useEffect(() => { + if (!open) { + setPublicKey(""); + reset(); + } + }, [open, reset]); + + // Checked here so a pasted private key is never sent anywhere. + const isPrivateKey = publicKey.includes("PRIVATE KEY") || publicKey.includes("PuTTY-User-Key-File"); + const result = generate.data; + + return ( + <Dialog + open={open} + onOpenChange={(next) => { + if (!generate.isPending) onOpenChange(next); + }} + > + <DialogContent> + {result ? ( + <> + <DialogHeader> + <DialogTitle>Your certificate is ready</DialogTitle> + <DialogDescription> + {result.principal}, valid until {formatUnixSeconds(result.valid_before)}. It is shown + only now. If you lose it, generate another. + </DialogDescription> + </DialogHeader> + <div className="space-y-4 text-sm"> + <div className="space-y-1"> + <p className="font-medium">Certificate</p> + <CopyValue value={result.certificate} label="certificate" explicit /> + </div> + <ol className="list-decimal space-y-2 pl-5"> + <li> + Save it next to your private key as{" "} + <code className="font-mono text-xs">{keyFile(result.certificate)}-cert.pub</code> + </li> + <li> + Run <CopyValue value={sshCommand(result)} label="ssh command" explicit /> + </li> + </ol> + </div> + <DialogFooter> + <Button onClick={() => onOpenChange(false)}>Done</Button> + </DialogFooter> + </> + ) : ( + <> + <DialogHeader> + <DialogTitle>Generate certificate</DialogTitle> + <DialogDescription>Logs in with your own cluster account.</DialogDescription> + </DialogHeader> + <form + className="space-y-4" + onSubmit={(e) => { + e.preventDefault(); + if (publicKey.trim() && !isPrivateKey) generate.mutate(publicKey.trim()); + }} + > + <div className="space-y-2"> + <Label htmlFor="public-key">Public key</Label> + <textarea + id="public-key" + value={publicKey} + onChange={(e) => setPublicKey(e.target.value)} + rows={4} + aria-invalid={isPrivateKey} + aria-describedby="public-key-help" + disabled={generate.isPending} + className="w-full rounded-md border border-border bg-background p-2 font-mono text-xs" + /> + <p id="public-key-help" className="text-xs text-muted-foreground"> + {isPrivateKey + ? "This is a private key. Keep it on your computer and paste the .pub file instead." + : "Paste your .pub file, for example ~/.ssh/id_ed25519.pub. Never your private key. No key yet? Run ssh-keygen -t ed25519 on your computer."} + </p> + </div> + {generate.error ? ( + <p className="text-sm text-[color:var(--custos-red-700)]"> + {refusalMessage(generate.error)} + </p> + ) : null} + <DialogFooter> + <Button + type="button" + variant="outline" + disabled={generate.isPending} + onClick={() => onOpenChange(false)} + > + Cancel + </Button> + <Button type="submit" disabled={generate.isPending || !publicKey.trim() || isPrivateKey}> + {generate.isPending ? "Generating…" : "Generate certificate"} + </Button> + </DialogFooter> + </form> + </> + )} + </DialogContent> + </Dialog> + ); +} diff --git a/web/src/features/core/signer/components/MyCertificateDetail.tsx b/web/src/features/core/signer/components/MyCertificateDetail.tsx new file mode 100644 index 000000000..d0994bbfa --- /dev/null +++ b/web/src/features/core/signer/components/MyCertificateDetail.tsx @@ -0,0 +1,139 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +"use client"; + +import * as React from "react"; +import { toast } from "sonner"; +import { ApiError } from "@/shared/api/client"; +import { Button } from "@/shared/ui/button"; +import { ErrorState } from "@/shared/ui/ErrorState"; +import { CardSkeleton } from "@/shared/ui/Loading"; +import { StatusBadge } from "@/shared/ui/StatusBadge"; +import { useMyCertificate, useRevokeMyCertificate } from "../queries"; +import { + CERTIFICATE_STATUS_LABELS, + formatCertificateLifetime, + formatUnixSeconds, + getCertificateStatus, + requestingApp, + statusBadgeVariantFromCertificateStatus, +} from "../status"; +import { revokeErrorMessage } from "./CertificateDetail"; +import { loadErrorMessage } from "./MyCertificates"; +import { RevokeCertificateDialog } from "./RevokeCertificateDialog"; + +export function MyCertificateDetail({ serial }: { serial: string }) { + const query = useMyCertificate(serial); + const revoke = useRevokeMyCertificate(); + const [dialogOpen, setDialogOpen] = React.useState(false); + const [revokeError, setRevokeError] = React.useState<string | null>(null); + + if (query.isLoading) return <CardSkeleton />; + if (query.error) { + if (query.error instanceof ApiError && query.error.status === 404) { + return <ErrorState heading="Certificate not found" message="You have no certificate with this serial." />; + } + return <ErrorState message={loadErrorMessage(query.error)} onRetry={() => query.refetch()} />; + } + const cert = query.data; + if (!cert) return null; + + const status = getCertificateStatus(cert); + const items: Array<[string, React.ReactNode]> = [ + ["Logs in as", <span key="principal" className="font-mono">{cert.principal}</span>], + ["Issued to", cert.user_email], + ["Generated by", requestingApp(cert) ?? "You"], + ["Key ID", <span key="key-id" className="break-all font-mono text-xs">{cert.key_id}</span>], + ["Key fingerprint", <span key="fingerprint" className="break-all font-mono text-xs">{cert.public_key_fingerprint}</span>], + ["Issued", formatUnixSeconds(cert.issued_at)], + ["Valid until", formatUnixSeconds(cert.valid_before)], + ["Lifetime", formatCertificateLifetime(cert)], + ["Options", cert.granted_extensions?.join(", ") || "None"], + ["Command", cert.force_command || "None"], + ]; + + return ( + <section className="space-y-6"> + <header className="flex flex-wrap items-start justify-between gap-3"> + <div className="space-y-2"> + <h1 className="font-display text-[28px] font-bold leading-tight"> + Certificate <span className="font-mono">{cert.serial_number}</span> + </h1> + <StatusBadge + variant={statusBadgeVariantFromCertificateStatus(status)} + label={CERTIFICATE_STATUS_LABELS[status]} + /> + </div> + {status === "active" ? ( + <Button + variant="destructive" + onClick={() => { + setRevokeError(null); + setDialogOpen(true); + }} + > + Revoke + </Button> + ) : null} + </header> + + {cert.revoked ? ( + <div className="rounded-md border border-[color:var(--custos-red-700)] p-3 text-sm"> + <p className="font-medium"> + Revoked {cert.revoked_at != null ? formatUnixSeconds(cert.revoked_at) : ""} by{" "} + {cert.revoked_by === "self" ? "you" : "your site"} + </p> + <p>{cert.revocation_reason ? `Reason: ${cert.revocation_reason}` : "No reason given."}</p> + <p className="text-muted-foreground"> + Login nodes still accept this certificate until it expires. + </p> + </div> + ) : null} + + <dl className="grid grid-cols-1 gap-x-8 gap-y-4 rounded-lg border bg-card p-5 sm:grid-cols-2"> + {items.map(([label, value]) => ( + <div key={label} className="space-y-1"> + <dt className="text-xs font-medium uppercase tracking-wide text-muted-foreground">{label}</dt> + <dd className="text-sm text-foreground">{value}</dd> + </div> + ))} + </dl> + + <RevokeCertificateDialog + serialNumber={cert.serial_number} + open={dialogOpen} + onOpenChange={setDialogOpen} + isPending={revoke.isPending} + error={revokeError} + onSubmit={(reason) => { + setRevokeError(null); + revoke.mutate( + { serial: cert.serial_number, reason }, + { + onSuccess: () => { + setDialogOpen(false); + toast.success("Certificate revoked"); + }, + onError: (err) => setRevokeError(revokeErrorMessage(err)), + }, + ); + }} + /> + </section> + ); +} diff --git a/web/src/features/core/signer/components/MyCertificates.tsx b/web/src/features/core/signer/components/MyCertificates.tsx new file mode 100644 index 000000000..3cc31f004 --- /dev/null +++ b/web/src/features/core/signer/components/MyCertificates.tsx @@ -0,0 +1,193 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +"use client"; + +import Link from "next/link"; +import * as React from "react"; +import { toast } from "sonner"; +import { ApiError } from "@/shared/api/client"; +import { Button } from "@/shared/ui/button"; +import { DataTable, type DataTableColumn } from "@/shared/ui/DataTable"; +import { EmptyState } from "@/shared/ui/EmptyState"; +import { ErrorState } from "@/shared/ui/ErrorState"; +import { TableSkeleton } from "@/shared/ui/Loading"; +import { StatusBadge } from "@/shared/ui/StatusBadge"; +import { useCursorPaging, useMyCertificates, useRevokeMyCertificate } from "../queries"; +import type { Certificate } from "../schemas"; +import { + CERTIFICATE_STATUS_LABELS, + type CertificateStatus, + formatUnixSeconds, + getCertificateStatus, + requestingApp, + statusBadgeVariantFromCertificateStatus, +} from "../status"; +import { revokeErrorMessage } from "./CertificateDetail"; +import { CursorPager } from "./CertificateList"; +import { GenerateCertificateDialog } from "./GenerateCertificateDialog"; +import { RevokeCertificateDialog } from "./RevokeCertificateDialog"; + +export function loadErrorMessage(error: unknown): string { + const message = error instanceof ApiError ? (error.body as { message?: string } | null)?.message : undefined; + return message || "Your certificates could not be loaded. Please try again."; +} + +export function MyCertificates() { + const { params, paging } = useCursorPaging(); + const query = useMyCertificates(params); + const revoke = useRevokeMyCertificate(); + const [generateOpen, setGenerateOpen] = React.useState(false); + const [statusFilter, setStatusFilter] = React.useState<CertificateStatus | "all">("all"); + const [revoking, setRevoking] = React.useState<Certificate | null>(null); + const [revokeError, setRevokeError] = React.useState<string | null>(null); + + const rows = query.data?.certificates ?? []; + const filtered = rows.filter( + (row) => statusFilter === "all" || getCertificateStatus(row) === statusFilter, + ); + + const columns: Array<DataTableColumn<Certificate>> = [ + { + key: "generatedBy", + header: "Generated by", + cell: (row) => ( + <Link href={`/ssh-access/${row.serial_number}`} className="font-medium hover:underline"> + {requestingApp(row) ?? "You"} + </Link> + ), + }, + { + key: "issued", + header: "Issued", + cell: (row) => <span className="text-sm">{formatUnixSeconds(row.issued_at)}</span>, + }, + { + key: "validBefore", + header: "Valid until", + cell: (row) => <span className="text-sm">{formatUnixSeconds(row.valid_before)}</span>, + }, + { + key: "status", + header: "Status", + cell: (row) => { + const status = getCertificateStatus(row); + return ( + <StatusBadge + variant={statusBadgeVariantFromCertificateStatus(status)} + label={CERTIFICATE_STATUS_LABELS[status]} + /> + ); + }, + }, + { + key: "actions", + header: "", + cell: (row) => + getCertificateStatus(row) === "active" ? ( + <Button + variant="outline" + size="sm" + onClick={() => { + setRevokeError(null); + setRevoking(row); + }} + > + Revoke + </Button> + ) : null, + }, + ]; + + return ( + <div className="space-y-6"> + <div className="flex flex-wrap items-start justify-between gap-3"> + <div> + <h1 className="font-display text-[28px] font-bold leading-tight">SSH access</h1> + <p className="mt-1 text-sm text-muted-foreground"> + Your SSH certificates for logging in to the cluster. + </p> + </div> + <Button onClick={() => setGenerateOpen(true)}>Generate certificate</Button> + </div> + + <p className="rounded-md border bg-card p-3 text-sm text-muted-foreground"> + A revoked certificate is still accepted by login nodes until it expires. + </p> + + <div className="flex items-center gap-3"> + <select + value={statusFilter} + onChange={(e) => setStatusFilter(e.target.value as CertificateStatus | "all")} + aria-label="Filter by status" + className="h-9 rounded-md border bg-background px-3 text-sm" + > + <option value="all">All statuses</option> + <option value="active">Active</option> + <option value="expired">Expired</option> + <option value="revoked">Revoked</option> + </select> + <span className="text-xs text-muted-foreground">Status filter applies to this page.</span> + </div> + + {query.isLoading ? ( + <TableSkeleton rows={4} columns={5} /> + ) : query.error ? ( + <ErrorState message={loadErrorMessage(query.error)} onRetry={() => query.refetch()} /> + ) : filtered.length === 0 ? ( + <EmptyState + heading={rows.length === 0 ? "No certificates yet" : "No matches on this page"} + description={ + rows.length === 0 + ? "Generate a certificate to log in to the cluster." + : "No certificates on this page have that status." + } + /> + ) : ( + <DataTable columns={columns} rows={filtered} rowKey={(row) => String(row.serial_number)} /> + )} + {!query.isLoading && (query.error || rows.length > 0) ? ( + <CursorPager {...paging(query.data?.next_cursor)} /> + ) : null} + + <GenerateCertificateDialog open={generateOpen} onOpenChange={setGenerateOpen} /> + <RevokeCertificateDialog + serialNumber={revoking?.serial_number ?? 0} + open={revoking !== null} + onOpenChange={(open) => { + if (!open) setRevoking(null); + }} + isPending={revoke.isPending} + error={revokeError} + onSubmit={(reason) => { + if (!revoking) return; + setRevokeError(null); + revoke.mutate( + { serial: revoking.serial_number, reason }, + { + onSuccess: () => { + setRevoking(null); + toast.success("Certificate revoked"); + }, + onError: (err) => setRevokeError(revokeErrorMessage(err)), + }, + ); + }} + /> + </div> + ); +} diff --git a/web/src/features/core/signer/components/RevokeCertificateDialog.tsx b/web/src/features/core/signer/components/RevokeCertificateDialog.tsx index 3b66aba68..896a72b22 100644 --- a/web/src/features/core/signer/components/RevokeCertificateDialog.tsx +++ b/web/src/features/core/signer/components/RevokeCertificateDialog.tsx @@ -50,7 +50,7 @@ export function RevokeCertificateDialog({ const [reason, setReason] = React.useState(""); const trimmedReason = reason.trim(); const reasonLength = Array.from(trimmedReason).length; - const reasonIsValid = reasonLength > 0 && reasonLength <= 255; + const reasonIsValid = reasonLength <= 255; React.useEffect(() => { if (!open) setReason(""); @@ -67,7 +67,8 @@ export function RevokeCertificateDialog({ <DialogHeader> <DialogTitle>Revoke certificate?</DialogTitle> <DialogDescription> - This revokes certificate serial {serialNumber}. This cannot be undone. + This revokes certificate serial {serialNumber} and cannot be undone. Login nodes still + accept it until it expires. </DialogDescription> </DialogHeader> <form @@ -88,7 +89,6 @@ export function RevokeCertificateDialog({ aria-describedby="revoke-reason-help" aria-invalid={reasonLength > 255} disabled={isPending} - required /> <div id="revoke-reason-help" @@ -97,7 +97,7 @@ export function RevokeCertificateDialog({ <span> {reasonLength > 255 ? "Reason must be 255 characters or fewer." - : "Required for the revocation audit record."} + : "Optional."} </span> <span>{Math.max(0, 255 - reasonLength)} remaining</span> </div> diff --git a/web/src/features/core/signer/queries.ts b/web/src/features/core/signer/queries.ts index b043e4d9b..3aad50a72 100644 --- a/web/src/features/core/signer/queries.ts +++ b/web/src/features/core/signer/queries.ts @@ -18,15 +18,46 @@ "use client"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { getCertificate, listCertificates, revokeCertificate } from "./api"; -import type { CertificateListParams } from "./types"; +import * as React from "react"; +import { + generateCertificate, + getCertificate, + getMyCertificate, + listCertificates, + listMyCertificates, + revokeCertificate, + revokeMyCertificate, +} from "./api"; +import type { CertificateListParams, CertificateListPaging } from "./types"; export const signerKeys = { all: ["signer-certificates"] as const, list: (params: CertificateListParams = {}) => [...signerKeys.all, "list", params] as const, detail: (serial: number | string) => [...signerKeys.all, "detail", String(serial)] as const, + myList: (params: CertificateListParams = {}) => [...signerKeys.all, "me", "list", params] as const, + myDetail: (serial: number | string) => [...signerKeys.all, "me", "detail", String(serial)] as const, }; +export function useCursorPaging() { + // The cursor of each page after the first, so Previous can walk back. + const [cursors, setCursors] = React.useState<string[]>([]); + const [pageSize, setPageSize] = React.useState(20); + const paging = (nextCursor: string | undefined): CertificateListPaging => ({ + page: cursors.length + 1, + pageSize, + hasNext: Boolean(nextCursor), + onNext: () => { + if (nextCursor) setCursors((prev) => [...prev, nextCursor]); + }, + onPrevious: () => setCursors((prev) => prev.slice(0, -1)), + onPageSizeChange: (next) => { + setCursors([]); + setPageSize(next); + }, + }); + return { params: { limit: pageSize, cursor: cursors.at(-1) }, paging }; +} + const DEFAULTS = { staleTime: 30_000, gcTime: 300_000, @@ -53,6 +84,39 @@ export function useCertificate(serial: number | string | undefined) { }); } +export function useMyCertificates(params: CertificateListParams = {}) { + return useQuery({ + queryKey: signerKeys.myList(params), + queryFn: () => listMyCertificates(params), + ...DEFAULTS, + }); +} + +export function useMyCertificate(serial: string) { + return useQuery({ + queryKey: signerKeys.myDetail(serial), + queryFn: () => getMyCertificate(serial), + ...DEFAULTS, + }); +} + +export function useGenerateCertificate() { + const client = useQueryClient(); + return useMutation({ + mutationFn: (publicKey: string) => generateCertificate(publicKey), + onSuccess: () => client.invalidateQueries({ queryKey: signerKeys.all }), + }); +} + +export function useRevokeMyCertificate() { + const client = useQueryClient(); + return useMutation({ + mutationFn: ({ serial, reason }: { serial: number; reason: string }) => + revokeMyCertificate(serial, reason), + onSuccess: () => client.invalidateQueries({ queryKey: signerKeys.all }), + }); +} + export function useRevokeCertificate() { const client = useQueryClient(); return useMutation({ diff --git a/web/src/features/core/signer/schemas.ts b/web/src/features/core/signer/schemas.ts index a08fb0223..9cc4dc3dd 100644 --- a/web/src/features/core/signer/schemas.ts +++ b/web/src/features/core/signer/schemas.ts @@ -22,17 +22,17 @@ import { z } from "zod"; // Mirrors extensions/SSH-Certificate-Signer CertificateResponse. Unix-second // timestamps are passed through as numbers and formatted in the UI layer. export const certificateSchema = z.object({ - client_id: z.string(), + requested_by: z.string(), serial_number: z.number().int(), key_id: z.string(), principal: z.string(), user_email: z.string(), + user_sub: z.string(), public_key_fingerprint: z.string(), ca_fingerprint: z.string(), valid_after: z.number().int(), valid_before: z.number().int(), issued_at: z.number().int(), - source_ip: z.string().optional(), granted_extensions: z.array(z.string()).optional(), force_command: z.string().nullable().optional(), revoked: z.boolean(), @@ -62,3 +62,13 @@ export const revokeResponseSchema = z.object({ already_revoked: z.boolean().optional(), }); export type RevokeResponse = z.infer<typeof revokeResponseSchema>; + +export const generatedCertificateSchema = z.object({ + certificate: z.string(), + serial_number: z.number().int(), + principal: z.string(), + valid_before: z.number().int(), + login_host: z.string(), + login_port: z.number().int(), +}); +export type GeneratedCertificate = z.infer<typeof generatedCertificateSchema>; diff --git a/web/src/features/core/signer/status.ts b/web/src/features/core/signer/status.ts index 23e810e6c..fef887fcf 100644 --- a/web/src/features/core/signer/status.ts +++ b/web/src/features/core/signer/status.ts @@ -20,6 +20,11 @@ import type { Certificate } from "./schemas"; export type CertificateStatus = "active" | "not-yet-valid" | "expired" | "revoked"; +// requested_by is "user/<id>" when the person generated it, or "app/<id>" for an app. +export function requestingApp(cert: Certificate): string | undefined { + return cert.requested_by.startsWith("app/") ? cert.requested_by.slice("app/".length) : undefined; +} + export const CERTIFICATE_STATUS_LABELS: Record<CertificateStatus, string> = { active: "Active", "not-yet-valid": "Not yet valid", diff --git a/web/src/mocks/handlers/signer.ts b/web/src/mocks/handlers/signer.ts index 7829c1461..c9e106c6f 100644 --- a/web/src/mocks/handlers/signer.ts +++ b/web/src/mocks/handlers/signer.ts @@ -53,6 +53,45 @@ function paginatedCertificates(): Certificate[] { } export const signerHandlers = [ + http.get("*/api/v1/connectors/signer/me/certificates", () => + HttpResponse.json({ certificates, limit: certificates.length }), + ), + + http.post("*/api/v1/connectors/signer/me/certificates", () => + HttpResponse.json({ + certificate: "[email protected] AAAAexample", + serial_number: 50, + principal: "dev-admin", + valid_before: Math.floor(Date.now() / 1000) + 28800, + login_host: "login.example.edu", + login_port: 22, + }), + ), + + http.get("*/api/v1/connectors/signer/me/certificates/:serial", ({ params }) => { + const found = certificates.find((c) => c.serial_number === Number(params["serial"])); + if (!found) return HttpResponse.json({ error: "not_found" }, { status: 404 }); + return HttpResponse.json(found); + }), + + http.post("*/api/v1/connectors/signer/me/certificates/:serial/revoke", ({ params }) => { + const serial = Number(params["serial"]); + const found = certificates.find((c) => c.serial_number === serial); + if (!found) return HttpResponse.json({ error: "not_found" }, { status: 404 }); + const now = Math.floor(Date.now() / 1000); + found.revoked = true; + found.revoked_at = now; + found.revoked_by = "self"; + return HttpResponse.json({ + success: true, + message: "Certificate revoked successfully", + serial_number: serial, + revoked: true, + revoked_at: now, + reason: "", + }); + }), + // The mock cursor is the index of the next row. http.get("*/api/v1/connectors/signer/certificates", ({ request }) => { const url = new URL(request.url); @@ -107,9 +146,9 @@ export const signerHandlers = [ const body = (await request.json().catch(() => ({}))) as { reason?: string }; const reason = (body.reason ?? "").trim(); - if (!reason || reason.length > 255) { + if (reason.length > 255) { return HttpResponse.json( - { error: "invalid_reason", message: "Reason must be between 1 and 255 characters" }, + { error: "invalid_reason", message: "Reason is limited to 255 characters" }, { status: 400 }, ); } diff --git a/web/src/shared/layout/Sidebar.tsx b/web/src/shared/layout/Sidebar.tsx index 58fb9682f..4f2ccdeb1 100644 --- a/web/src/shared/layout/Sidebar.tsx +++ b/web/src/shared/layout/Sidebar.tsx @@ -25,7 +25,7 @@ import Link from "next/link"; import { usePathname } from "next/navigation"; import { NAV_GROUP_LABELS, type NavGroup, type NavItem, portalNav } from "./nav"; -const GROUP_ORDER: NavGroup[] = ["allocations", "admin"]; +const GROUP_ORDER: NavGroup[] = ["allocations", "access", "admin"]; export function Sidebar() { const pathname = usePathname(); diff --git a/web/src/shared/layout/nav.ts b/web/src/shared/layout/nav.ts index e9dc58d97..22c84629c 100644 --- a/web/src/shared/layout/nav.ts +++ b/web/src/shared/layout/nav.ts @@ -26,12 +26,13 @@ import { type LucideIcon, ScrollText, Send, + SquareTerminal, UserCog, } from "lucide-react"; export type AbilityCheck = { action: string; subject: string }; -export type NavGroup = "allocations" | "admin"; +export type NavGroup = "allocations" | "access" | "admin"; export type NavItem = { href: string; @@ -44,6 +45,7 @@ export type NavItem = { export const NAV_GROUP_LABELS: Record<NavGroup, string> = { allocations: "My allocations", + access: "My access", admin: "Site administration", }; @@ -79,6 +81,12 @@ export const portalNav: NavItem[] = [ icon: ChartColumn, group: "allocations", }, + { + href: "/ssh-access", + label: "SSH access", + icon: SquareTerminal, + group: "access", + }, { href: "/admin/users", label: "Users & Permissions", diff --git a/web/tests/fixtures/signer-api.ts b/web/tests/fixtures/signer-api.ts index 79a2ab42d..7d140eedf 100644 --- a/web/tests/fixtures/signer-api.ts +++ b/web/tests/fixtures/signer-api.ts @@ -14,7 +14,8 @@ export type SignerScenario = | "already-revoked" | "inactive" | "forbidden" - | "server-error"; + | "server-error" + | "no-allocation"; type SignerApiController = { setScenario(scenario: SignerScenario): void; @@ -79,6 +80,52 @@ async function installSignerRoutes(context: BrowserContext) { return; } + if (url.pathname === "/api/v1/connectors/signer/me/certificates") { + if (request.method() === "GET") { + await json(route, { certificates, limit: certificates.length }); + return; + } + if (scenario === "no-allocation") { + await json(route, { error: "no_active_allocation", message: "refused" }, 403); + return; + } + await json(route, { + certificate: "[email protected] AAAA", + serial_number: 50, + principal: "dev-admin", + valid_before: 4_102_444_800, + login_host: "login.example.edu", + login_port: 22, + }); + return; + } + + const myDetailMatch = url.pathname.match(/^\/api\/v1\/connectors\/signer\/me\/certificates\/(\d+)$/); + if (request.method() === "GET" && myDetailMatch) { + const certificate = certificates.find((candidate) => candidate.serial_number === Number(myDetailMatch[1])); + await json(route, certificate ?? { error: "not_found" }, certificate ? 200 : 404); + return; + } + + const myRevokeMatch = url.pathname.match(/^\/api\/v1\/connectors\/signer\/me\/certificates\/(\d+)\/revoke$/); + if (request.method() === "POST" && myRevokeMatch) { + const certificate = certificates.find((candidate) => candidate.serial_number === Number(myRevokeMatch[1])); + if (certificate) { + certificate.revoked = true; + certificate.revoked_at = Math.floor(Date.now() / 1000); + certificate.revoked_by = "self"; + } + await json(route, { + success: true, + message: "Certificate revoked successfully", + serial_number: Number(myRevokeMatch[1]), + revoked: true, + revoked_at: Math.floor(Date.now() / 1000), + reason: "", + }); + return; + } + // The mock cursor is the index of the next row. if ( request.method() === "GET" && @@ -168,10 +215,10 @@ async function installSignerRoutes(context: BrowserContext) { // that the signer API would return for malformed JSON. } const reason = (body.reason ?? "").trim(); - if (!reason || reason.length > 255) { + if (reason.length > 255) { await json( route, - { error: "invalid_reason", message: "Reason must be between 1 and 255 characters" }, + { error: "invalid_reason", message: "Reason is limited to 255 characters" }, 400, ); return; diff --git a/web/tests/signer-certificates.e2e.ts b/web/tests/signer-certificates.e2e.ts index 7e6cd8217..a14c07138 100644 --- a/web/tests/signer-certificates.e2e.ts +++ b/web/tests/signer-certificates.e2e.ts @@ -40,7 +40,7 @@ test.describe("ssh certificates", () => { await expect(page).toHaveURL(/\/admin\/signer\/certificates\/42/); await expect(page.getByRole("heading", { name: /^Certificate 42$/ })).toBeVisible(); await expect(page.getByText("[email protected]")).toBeVisible(); - await expect(page.getByText("203.0.113.42")).toBeVisible(); + await expect(page.getByText("sub-researcher")).toBeVisible(); await expect(page.getByText(/permit-pty/)).toBeVisible(); }); @@ -197,4 +197,47 @@ test.describe("ssh certificates", () => { await expect(page.getByRole("dialog")).toBeVisible(); await expectNoSeriousAxeViolations(page, "[role=dialog]"); }); + + // Make sure a member with no privileges can generate and is told how to use the certificate. + test("member generates a certificate and gets the ssh command", async ({ page }) => { + await signInAs(page, "researcher"); + await page.goto("/ssh-access"); + await page.getByRole("button", { name: /^Generate certificate$/ }).click(); + await page.getByLabel(/public key/i).fill("ssh-ed25519 AAAA me@laptop"); + await page.getByRole("dialog").getByRole("button", { name: /^Generate certificate$/ }).click(); + await expect(page.getByText(/Your certificate is ready/)).toBeVisible(); + await expect(page.getByText("ssh -i ~/.ssh/id_ed25519 [email protected]")).toBeVisible(); + }); + + // Make sure a pasted private key cannot be submitted. + test("member cannot submit a private key", async ({ page }) => { + await signInAs(page, "researcher"); + await page.goto("/ssh-access"); + await page.getByRole("button", { name: /^Generate certificate$/ }).click(); + await page.getByLabel(/public key/i).fill("-----BEGIN OPENSSH PRIVATE KEY-----"); + await expect(page.getByText(/This is a private key/)).toBeVisible(); + await expect(page.getByRole("dialog").getByRole("button", { name: /^Generate certificate$/ })).toBeDisabled(); + }); + + // Make sure a refusal says why and keeps the pasted key. + test("member sees why a certificate was refused", async ({ page, signerApi }) => { + await signInAs(page, "researcher"); + signerApi.setScenario("no-allocation"); + await page.goto("/ssh-access"); + await page.getByRole("button", { name: /^Generate certificate$/ }).click(); + await page.getByLabel(/public key/i).fill("ssh-ed25519 AAAA me@laptop"); + await page.getByRole("dialog").getByRole("button", { name: /^Generate certificate$/ }).click(); + await expect(page.getByText("You need an active allocation to get a certificate.")).toBeVisible(); + await expect(page.getByLabel(/public key/i)).toHaveValue("ssh-ed25519 AAAA me@laptop"); + }); + + // Make sure a member can revoke their own certificate with no privilege, and no reason. + test("member revokes their own certificate", async ({ page }) => { + await signInAs(page, "researcher"); + await page.goto("/ssh-access/42"); + await page.getByRole("button", { name: /^Revoke$/ }).click(); + await page.getByRole("button", { name: /^Confirm revoke$/ }).click(); + await expect(page.getByText(/by you/)).toBeVisible(); + await expect(page.getByRole("button", { name: /^Revoke$/ })).toHaveCount(0); + }); });
