This is an automated email from the ASF dual-hosted git repository. yasithdev pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/airavata-custos.git
commit 9d3feaafe3ca1986990ace95a4976a9e9aca50c7 Author: Lahiru Jayathilake <[email protected]> AuthorDate: Fri Nov 13 18:51:06 2026 -0500 Show serial, key and time left on the SSH access page (#747) * Show serial, key and time left on the SSH access page * Make the ssh-keygen command copyable in the certificate dialog * Return the login host and port with a certificate * Let user set lifetime and restrictions when generating a certificate * Let members choose certificate options and group the certificate page * Improve the generated certificate dialog layout * Show chosen restrictions and a download button, and open certificates by row * Improve the certificate detail page layout * Drop the serial link inside clickable rows --- config/custos.yaml | 2 +- connectors/Signer/README.md | 15 +- connectors/Signer/internal/handlers.go | 40 ++- connectors/Signer/internal/handlers_test.go | 29 ++ connectors/Signer/pkg/signer/loader.go | 2 +- extensions/SSH-Certificate-Signer/README.md | 2 +- .../internal/handler/certificates.go | 18 +- extensions/SSH-Certificate-Signer/main.go | 2 +- .../signer/__tests__/CertificateDetail.test.tsx | 3 +- .../core/signer/__tests__/CertificateList.test.tsx | 22 +- web/src/features/core/signer/api.ts | 7 +- .../core/signer/components/CertificateDetail.tsx | 128 +-------- .../core/signer/components/CertificateList.tsx | 19 +- .../core/signer/components/CertificateView.tsx | 245 +++++++++++++++++ .../components/GenerateCertificateDialog.tsx | 301 +++++++++++++++++++-- .../core/signer/components/MyCertificateDetail.tsx | 82 +----- .../core/signer/components/MyCertificates.tsx | 43 ++- .../signer/components/RevokeCertificateDialog.tsx | 2 +- web/src/features/core/signer/queries.ts | 3 +- web/src/features/core/signer/schemas.ts | 10 + web/src/features/core/signer/status.ts | 29 ++ web/src/mocks/handlers/signer.ts | 2 +- web/src/shared/ui/CopyValue.tsx | 18 +- web/tests/signer-certificates.e2e.ts | 14 +- 24 files changed, 775 insertions(+), 263 deletions(-) diff --git a/config/custos.yaml b/config/custos.yaml index 5aaff2055..f83bcfe74 100644 --- a/config/custos.yaml +++ b/config/custos.yaml @@ -223,5 +223,5 @@ connectors: base_url: "${SIGNER_BASE_URL}" service_token: "${SIGNER_SERVICE_TOKEN}" cluster_id: "${CUSTOS_CLUSTER_ID}" - certificate_ttl_seconds: 28800 + certificate_ttl_seconds: 14400 timeout_seconds: 10 diff --git a/connectors/Signer/README.md b/connectors/Signer/README.md index 922ed3e0f..a10a1183b 100644 --- a/connectors/Signer/README.md +++ b/connectors/Signer/README.md @@ -45,9 +45,18 @@ an active allocation on that cluster. The username comes from the cluster account, and the email and subject from the caller's verified token, never from the request. +Besides `public_key`, the caller may send options that only narrow the certificate: + +| Field | Effect | +|----------------------|--------------------------------------------------------------------------------------------| +| `ttl_seconds` | Shorter lifetime. Empty means `certificate_ttl_seconds`, which is also the longest allowed | +| `source_address` | Comma-separated IP addresses or CIDR blocks the certificate works from | +| `force_command` | The only command a login runs | +| `exclude_extensions` | Standard options to leave out, such as `permit-port-forwarding` | + A refusal has an `error` code: `user_not_active`, `no_cluster_account`, `cluster_account_not_ready`, -`no_active_allocation`, `signer_unavailable`, or from the signer `reserved_username`, `invalid_public_key`, -`key_type_not_allowed` and `too_many_certificates`. +`no_active_allocation`, `invalid_ttl`, `signer_unavailable`, or from the signer `reserved_username`, +`invalid_public_key`, `key_type_not_allowed`, `invalid_request` and `too_many_certificates`. Service accounts can't use these routes. A person generates a certificate and hands it to the tool that needs it. @@ -61,5 +70,5 @@ setting is empty the connector skips loading and reports the gap on `GET /connec | `base_url` | `SIGNER_BASE_URL` | yes | The signer's URL. Keep it off public networks. | | `service_token` | `SIGNER_SERVICE_TOKEN` | yes | The same token set on the signer | | `cluster_id` | `CUSTOS_CLUSTER_ID` | yes | The cluster certificates log in to | -| `certificate_ttl_seconds` | | no | Certificate lifetime, default `28800` | +| `certificate_ttl_seconds` | | no | Longest certificate lifetime, default `14400` | | `timeout_seconds` | | no | Request timeout, default `10` | diff --git a/connectors/Signer/internal/handlers.go b/connectors/Signer/internal/handlers.go index 3932bc095..8709f85cd 100644 --- a/connectors/Signer/internal/handlers.go +++ b/connectors/Signer/internal/handlers.go @@ -281,19 +281,37 @@ func (h *Handlers) generateCertificate(w http.ResponseWriter, r *http.Request) { } caller := identity.CallerFromContext(r.Context()) var req struct { - PublicKey string `json:"public_key"` - SourceAddress string `json:"source_address"` + PublicKey string `json:"public_key"` + TTLSeconds int `json:"ttl_seconds"` + SourceAddress string `json:"source_address"` + ForceCommand string `json:"force_command"` + ExcludeExtensions []string `json:"exclude_extensions"` } - if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxRequestBytes)).Decode(&req); err != nil || req.PublicKey == "" { + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxRequestBytes)).Decode(&req); err != nil { + refuse(w, http.StatusBadRequest, "invalid_request", "Invalid request body") + return + } + if req.PublicKey == "" { refuse(w, http.StatusBadRequest, "invalid_public_key", "A public key is required") return } + // The config value is the default and the longest a caller may ask for. + if req.TTLSeconds == 0 { + req.TTLSeconds = h.cfg.TTLSeconds + } + if req.TTLSeconds < 0 || req.TTLSeconds > h.cfg.TTLSeconds { + refuse(w, http.StatusBadRequest, "invalid_ttl", fmt.Sprintf("Lifetime must be between 1 and %d seconds", h.cfg.TTLSeconds)) + return + } h.issueCertificate(w, r, caller.UserID, map[string]any{ - "public_key": req.PublicKey, - "user_email": caller.Email, - "user_sub": claims.Sub, - "requested_by": caller.Requester(), - "source_address": req.SourceAddress, + "public_key": req.PublicKey, + "ttl_seconds": req.TTLSeconds, + "user_email": caller.Email, + "user_sub": claims.Sub, + "requested_by": caller.Requester(), + "source_address": req.SourceAddress, + "force_command": req.ForceCommand, + "exclude_extensions": req.ExcludeExtensions, }) } @@ -314,8 +332,10 @@ func (h *Handlers) issueCertificate(w http.ResponseWriter, r *http.Request, user return } sign["principal"] = username - sign["ttl_seconds"] = h.cfg.TTLSeconds - h.relayAndAudit(w, r, "/api/v1/sign", sign, AuditCertificateIssued, map[string]any{"user_id": userID, "principal": username, "requested_by": sign["requested_by"]}) + h.relayAndAudit(w, r, "/api/v1/sign", sign, AuditCertificateIssued, map[string]any{ + "user_id": userID, "principal": username, "requested_by": sign["requested_by"], "ttl_seconds": sign["ttl_seconds"], + "source_address": sign["source_address"], "force_command": sign["force_command"], "exclude_extensions": sign["exclude_extensions"], + }) } // loginName returns the username to sign for. diff --git a/connectors/Signer/internal/handlers_test.go b/connectors/Signer/internal/handlers_test.go index 94475d07d..933cd4d51 100644 --- a/connectors/Signer/internal/handlers_test.go +++ b/connectors/Signer/internal/handlers_test.go @@ -171,6 +171,35 @@ func TestGenerate_SignsForTheCallersOwnAccount(t *testing.T) { } } +// Make sure the options a member picks reach the signer: a shorter lifetime, addresses, a command, and dropped options. +func TestGenerate_PassesTheMembersRestrictions(t *testing.T) { + srv, seen := mockSignerServer(t, http.StatusOK, `{"serial_number":1}`) + + body := `{"public_key":"k","ttl_seconds":600,"source_address":"192.0.2.10","force_command":"rsync --server","exclude_extensions":["permit-port-forwarding"]}` + serve(srv.URL, httptest.NewRequest(http.MethodPost, "/connectors/signer/me/certificates", strings.NewReader(body))) + + var sent map[string]any + if err := json.Unmarshal([]byte(seen.body), &sent); err != nil { + t.Fatal(err) + } + excluded, _ := sent["exclude_extensions"].([]any) + if sent["ttl_seconds"] != float64(600) || sent["source_address"] != "192.0.2.10" || sent["force_command"] != "rsync --server" || + len(excluded) != 1 || excluded[0] != "permit-port-forwarding" { + t.Fatalf("signer got %v", sent) + } +} + +// Make sure a lifetime longer than the site's longest is refused and never reaches the signer. +func TestGenerate_LongerLifetimeIsRefused(t *testing.T) { + srv, seen := mockSignerServer(t, http.StatusOK, `{}`) + + rec := serve(srv.URL, httptest.NewRequest(http.MethodPost, "/connectors/signer/me/certificates", strings.NewReader(`{"public_key":"k","ttl_seconds":7200}`))) + + if rec.Code != http.StatusBadRequest || errorCode(t, rec) != "invalid_ttl" || seen.path != "" { + t.Fatalf("got %d %s, signer saw %q", rec.Code, rec.Body, seen.path) + } +} + // Make sure each issued certificate leaves an audit row under its serial, naming who asked. func TestGenerate_RecordsTheIssueInTheAuditLog(t *testing.T) { srv, _ := mockSignerServer(t, http.StatusOK, `{"serial_number":42}`) diff --git a/connectors/Signer/pkg/signer/loader.go b/connectors/Signer/pkg/signer/loader.go index 521c1f1bf..828992c9d 100644 --- a/connectors/Signer/pkg/signer/loader.go +++ b/connectors/Signer/pkg/signer/loader.go @@ -53,7 +53,7 @@ func LoadConnector(ctx context.Context, _ *sqlx.DB, _ *events.Bus, core *service } ttl, err := cfg.GetIntField("certificate_ttl_seconds") if err != nil { - ttl = 28800 + ttl = 14400 } handlers := internal.NewHandlers(internal.Config{ BaseURL: settings["base_url"], diff --git a/extensions/SSH-Certificate-Signer/README.md b/extensions/SSH-Certificate-Signer/README.md index 293faf415..2fc721798 100644 --- a/extensions/SSH-Certificate-Signer/README.md +++ b/extensions/SSH-Certificate-Signer/README.md @@ -245,7 +245,7 @@ The service handles SIGTERM and SIGINT for graceful shutdown: | `POST` | `/api/v1/sign` | Sign an SSH public key | | `GET` | `/api/v1/ca-public-key` | CA public key | | `GET` | `/api/v1/certificates` | List certificates. Filters: `user_sub`, `requested_by` | -| `GET` | `/api/v1/certificates/{serial}` | One certificate | +| `GET` | `/api/v1/certificates/{serial}` | One certificate, with the `login_host` and `login_port` to use it on | | `POST` | `/api/v1/certificates/{serial}/revoke` | Revoke an active certificate. `revoked_by` is required and `reason` can be empty | | `GET` | `/api/v1/health` | Health check, no token | diff --git a/extensions/SSH-Certificate-Signer/internal/handler/certificates.go b/extensions/SSH-Certificate-Signer/internal/handler/certificates.go index 905df99ab..c528c7a34 100644 --- a/extensions/SSH-Certificate-Signer/internal/handler/certificates.go +++ b/extensions/SSH-Certificate-Signer/internal/handler/certificates.go @@ -53,6 +53,8 @@ type CertificateResponse struct { RevokedAt *int64 `json:"revoked_at,omitempty"` RevocationReason string `json:"revocation_reason,omitempty"` RevokedBy string `json:"revoked_by,omitempty"` + LoginHost string `json:"login_host,omitempty"` + LoginPort int `json:"login_port,omitempty"` } type CertificateListResponse struct { @@ -86,13 +88,15 @@ type CertificateRevoker interface { } type CertificatesHandler struct { - db CertificateStore - revoker CertificateRevoker - logger *slog.Logger + db CertificateStore + revoker CertificateRevoker + loginHost string + loginPort int + logger *slog.Logger } -func NewCertificatesHandler(db CertificateStore, revoker CertificateRevoker, logger *slog.Logger) *CertificatesHandler { - return &CertificatesHandler{db: db, revoker: revoker, logger: logger} +func NewCertificatesHandler(db CertificateStore, revoker CertificateRevoker, loginHost string, loginPort int, logger *slog.Logger) *CertificatesHandler { + return &CertificatesHandler{db: db, revoker: revoker, loginHost: loginHost, loginPort: loginPort, logger: logger} } func (h *CertificatesHandler) HandleList(w http.ResponseWriter, r *http.Request) { @@ -141,7 +145,9 @@ func (h *CertificatesHandler) HandleGet(w http.ResponseWriter, r *http.Request) writeError(w, http.StatusInternalServerError, "internal_error", "Failed to get certificate") return } - writeJSON(w, http.StatusOK, toCertificateResponse(certificate)) + resp := toCertificateResponse(certificate) + resp.LoginHost, resp.LoginPort = h.loginHost, h.loginPort + writeJSON(w, http.StatusOK, resp) } func (h *CertificatesHandler) HandleRevoke(w http.ResponseWriter, r *http.Request) { diff --git a/extensions/SSH-Certificate-Signer/main.go b/extensions/SSH-Certificate-Signer/main.go index 9cc399171..e26ee72fb 100644 --- a/extensions/SSH-Certificate-Signer/main.go +++ b/extensions/SSH-Certificate-Signer/main.go @@ -181,7 +181,7 @@ func runServer(cfg *config.Config, logger *slog.Logger, autoMigrate bool) { }, logger) caPublicKeyHandler := handler.NewCAPublicKeyHandler(vaultClient, logger) healthHandler := handler.NewHealthHandler(db, vaultClient) - certificatesHandler := handler.NewCertificatesHandler(db, signerservice.NewRevocationService(db), logger) + certificatesHandler := handler.NewCertificatesHandler(db, signerservice.NewRevocationService(db), cfg.Signer.LoginHost, cfg.Signer.LoginPort, logger) handlers := server.Handlers{ Sign: signHandler.Handle, diff --git a/web/src/features/core/signer/__tests__/CertificateDetail.test.tsx b/web/src/features/core/signer/__tests__/CertificateDetail.test.tsx index ba4b56149..e67bbe901 100644 --- a/web/src/features/core/signer/__tests__/CertificateDetail.test.tsx +++ b/web/src/features/core/signer/__tests__/CertificateDetail.test.tsx @@ -82,12 +82,13 @@ describe("<CertificateDetail />", () => { "SHA256:pk", "SHA256:ca", "sub-admin", - "permit-pty, permit-user-rc", "/usr/bin/id", "[email protected]", ]) { expect(screen.getByText(value)).toBeInTheDocument(); } + expect(screen.getByLabelText("Allowed: Terminal sessions")).toBeInTheDocument(); + expect(screen.getByLabelText("Blocked: Port forwarding")).toBeInTheDocument(); }); it("renders a loading skeleton", () => { diff --git a/web/src/features/core/signer/__tests__/CertificateList.test.tsx b/web/src/features/core/signer/__tests__/CertificateList.test.tsx index 020b553df..4fd08e53c 100644 --- a/web/src/features/core/signer/__tests__/CertificateList.test.tsx +++ b/web/src/features/core/signer/__tests__/CertificateList.test.tsx @@ -20,6 +20,11 @@ import { describe, expect, it, vi } from "vitest"; import { CertificateList } from "../components/CertificateList"; import type { Certificate } from "../schemas"; +const push = vi.hoisted(() => vi.fn()); +vi.mock("next/navigation", () => ({ + useRouter: () => ({ push }), +})); + const active: Certificate = { user_sub: "sub-1", requested_by: "user/1", @@ -60,10 +65,11 @@ function renderList(overrides: Partial<React.ComponentProps<typeof CertificateLi } describe("<CertificateList />", () => { - it("renders the serial as a link to the detail page", () => { + // Make sure clicking a row opens that certificate's detail page. + it("opens the certificate when its row is clicked", () => { renderList(); - const link = screen.getByRole("link", { name: String(active.serial_number) }); - expect(link).toHaveAttribute("href", `/admin/signer/certificates/${active.serial_number}`); + fireEvent.click(screen.getByText("dev-admin")); + expect(push).toHaveBeenCalledWith(`/admin/signer/certificates/${active.serial_number}`); }); it("shows the empty state when no rows match the filters", () => { @@ -79,9 +85,9 @@ describe("<CertificateList />", () => { it("filters client-side by status", () => { renderList({ rows: [active, revoked], statusFilter: "revoked" }); expect( - screen.queryByRole("link", { name: String(active.serial_number) }), + screen.queryByRole("button", { name: String(active.serial_number) }), ).not.toBeInTheDocument(); - expect(screen.getByRole("link", { name: String(revoked.serial_number) })).toBeInTheDocument(); + expect(screen.getByRole("button", { name: String(revoked.serial_number) })).toBeInTheDocument(); }); it.each([ @@ -90,11 +96,11 @@ describe("<CertificateList />", () => { ])("filters the loaded page by %s", (_field, search) => { renderList({ rows: [active, revoked], search }); const expected = search === "44" ? revoked.serial_number : active.serial_number; - expect(screen.getByRole("link", { name: String(expected) })).toBeInTheDocument(); + expect(screen.getByRole("button", { name: String(expected) })).toBeInTheDocument(); if (search === "44") { - expect(screen.queryByRole("link", { name: String(active.serial_number) })).not.toBeInTheDocument(); + expect(screen.queryByRole("button", { name: String(active.serial_number) })).not.toBeInTheDocument(); } else { - expect(screen.queryByRole("link", { name: String(revoked.serial_number) })).not.toBeInTheDocument(); + expect(screen.queryByRole("button", { name: String(revoked.serial_number) })).not.toBeInTheDocument(); } }); diff --git a/web/src/features/core/signer/api.ts b/web/src/features/core/signer/api.ts index f3f608339..53aced339 100644 --- a/web/src/features/core/signer/api.ts +++ b/web/src/features/core/signer/api.ts @@ -20,6 +20,7 @@ import { apiFetch } from "@/shared/api/client"; import { type Certificate, type CertificateList, + type GenerateCertificateInput, type GeneratedCertificate, type RevokeResponse, certificateListSchema, @@ -61,10 +62,12 @@ export async function getMyCertificate(serial: number | string): Promise<Certifi return certificateSchema.parse(raw); } -export async function generateCertificate(publicKey: string): Promise<GeneratedCertificate> { +export async function generateCertificate( + input: GenerateCertificateInput, +): Promise<GeneratedCertificate> { const raw = await apiFetch("/connectors/signer/me/certificates", { method: "POST", - body: { public_key: publicKey }, + body: input, }); return generatedCertificateSchema.parse(raw); } diff --git a/web/src/features/core/signer/components/CertificateDetail.tsx b/web/src/features/core/signer/components/CertificateDetail.tsx index 7645846f9..16fd5980f 100644 --- a/web/src/features/core/signer/components/CertificateDetail.tsx +++ b/web/src/features/core/signer/components/CertificateDetail.tsx @@ -17,42 +17,26 @@ "use client"; -import { Calendar, Fingerprint, UserSquare } from "lucide-react"; import * as React from "react"; import { toast } from "sonner"; import { useAbility } from "@/shared/casl/AbilityProvider"; 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 { MetaItem, MetaRow } from "@/shared/ui/MetaRow"; import { useCertificate, useRevokeCertificate, useUserEmail } from "../queries"; -import type { Certificate } from "../schemas"; -import { - CERTIFICATE_STATUS_LABELS, - type CertificateStatus, - formatCertificateLifetime, - formatUnixSeconds, - getCertificateStatus, - userIdOf, -} from "../status"; +import { userIdOf } from "../status"; +import { CertificateView } from "./CertificateView"; import { RevokeCertificateDialog } from "./RevokeCertificateDialog"; export type CertificateDetailProps = { serial: string; }; -const STATUS_TONE: Record<CertificateStatus, "success" | "warning" | "danger"> = { - active: "success", - "not-yet-valid": "warning", - expired: "warning", - revoked: "danger", -}; - export function CertificateDetail({ serial }: CertificateDetailProps) { const ability = useAbility(); const query = useCertificate(serial); const revoke = useRevokeCertificate(); + const revokerEmail = useUserEmail(userIdOf(query.data?.revoked_by)); const [dialogOpen, setDialogOpen] = React.useState(false); const [revokeError, setRevokeError] = React.useState<string | null>(null); @@ -68,45 +52,19 @@ export function CertificateDetail({ serial }: CertificateDetailProps) { const cert = query.data; if (!cert) return null; - const status = getCertificateStatus(cert); - const canRevoke = ability.can("manage", "Signer") && status === "active"; + const openRevoke = () => { + setRevokeError(null); + setDialogOpen(true); + }; return ( - <section className="space-y-6"> - <header className="space-y-4"> - <div className="flex flex-wrap items-start justify-between gap-3"> - <h1 className="font-display text-[28px] font-bold leading-tight text-foreground"> - Certificate {cert.serial_number} - </h1> - {canRevoke ? ( - <Button - variant="destructive" - onClick={() => { - setRevokeError(null); - setDialogOpen(true); - }} - > - Revoke - </Button> - ) : null} - </div> - <MetaRow> - <MetaItem - variant="status" - tone={STATUS_TONE[status]} - value={CERTIFICATE_STATUS_LABELS[status]} - /> - <MetaItem icon={UserSquare} label="Principal" value={cert.principal} /> - <MetaItem - icon={Calendar} - label="Valid until" - value={formatUnixSeconds(cert.valid_before)} - /> - <MetaItem icon={Fingerprint} label="Lifetime" value={formatCertificateLifetime(cert)} /> - </MetaRow> - </header> - - <CertificateMetadata cert={cert} /> + <> + <CertificateView + cert={cert} + admin + revokedBy={revokerEmail ?? cert.revoked_by ?? "unknown"} + {...(ability.can("manage", "Signer") ? { onRevoke: openRevoke } : {})} + /> <RevokeCertificateDialog serialNumber={cert.serial_number} @@ -130,63 +88,7 @@ export function CertificateDetail({ serial }: CertificateDetailProps) { ); }} /> - </section> - ); -} - -function CertificateMetadata({ cert }: { cert: Certificate }) { - const revokerId = userIdOf(cert.revoked_by); - const revokerEmail = useUserEmail(revokerId); - const items: Array<{ label: string; value: React.ReactNode }> = [ - { 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 }, - { - label: "Public key fingerprint", - value: <span className="break-all font-mono text-xs">{cert.public_key_fingerprint}</span>, - }, - { - label: "CA fingerprint", - value: <span className="break-all font-mono text-xs">{cert.ca_fingerprint}</span>, - }, - { 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: "Granted extensions", - value: cert.granted_extensions?.length ? cert.granted_extensions.join(", ") : "—", - }, - { label: "Force command", value: cert.force_command || "—" }, - { label: "Source address", value: cert.source_address || "Any" }, - ]; - - if (cert.revoked) { - items.push( - { - label: "Revoked at", - value: cert.revoked_at != null ? formatUnixSeconds(cert.revoked_at) : "—", - }, - { label: "Revocation reason", value: cert.revocation_reason || "—" }, - { - label: "Revoked by", - value: revokerEmail ?? cert.revoked_by ?? "—", - }, - ); - } - - return ( - <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((item) => ( - <div key={item.label} className="space-y-1"> - <dt className="text-xs font-medium uppercase tracking-wide text-muted-foreground"> - {item.label} - </dt> - <dd className="text-sm text-foreground">{item.value}</dd> - </div> - ))} - </dl> + </> ); } diff --git a/web/src/features/core/signer/components/CertificateList.tsx b/web/src/features/core/signer/components/CertificateList.tsx index c3d21303f..8d95eb39c 100644 --- a/web/src/features/core/signer/components/CertificateList.tsx +++ b/web/src/features/core/signer/components/CertificateList.tsx @@ -17,7 +17,7 @@ "use client"; -import Link from "next/link"; +import { useRouter } from "next/navigation"; import * as React from "react"; import { Button } from "@/shared/ui/button"; import { DataTable, type DataTableColumn } from "@/shared/ui/DataTable"; @@ -59,6 +59,7 @@ export function CertificateList({ onStatusFilterChange, paging, }: CertificateListProps) { + const router = useRouter(); const filtered = React.useMemo(() => { const needle = search.trim().toLowerCase(); return rows.filter((row) => { @@ -77,14 +78,7 @@ export function CertificateList({ header: "Serial", sortable: true, sortValue: (row) => row.serial_number, - cell: (row) => ( - <Link - href={`/admin/signer/certificates/${row.serial_number}`} - className="font-mono font-medium text-foreground hover:underline" - > - {row.serial_number} - </Link> - ), + cell: (row) => <span className="font-mono font-medium">{row.serial_number}</span>, }, { key: "principal", @@ -168,7 +162,12 @@ export function CertificateList({ } /> ) : ( - <DataTable columns={columns} rows={filtered} rowKey={(row) => String(row.serial_number)} /> + <DataTable + columns={columns} + rows={filtered} + rowKey={(row) => String(row.serial_number)} + onRowClick={(row) => router.push(`/admin/signer/certificates/${row.serial_number}`)} + /> )} {paging && !isLoading && (error || rows.length > 0) && <CursorPager {...paging} />} </div> diff --git a/web/src/features/core/signer/components/CertificateView.tsx b/web/src/features/core/signer/components/CertificateView.tsx new file mode 100644 index 000000000..1ace6b958 --- /dev/null +++ b/web/src/features/core/signer/components/CertificateView.tsx @@ -0,0 +1,245 @@ +// 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 { Check, Clock, Hourglass, UserSquare, X } from "lucide-react"; +import type * as React from "react"; +import { cn } from "@/lib/utils"; +import { Button } from "@/shared/ui/button"; +import { Card } from "@/shared/ui/card"; +import { CopyValue } from "@/shared/ui/CopyValue"; +import { MetaItem, MetaRow } from "@/shared/ui/MetaRow"; +import { StatusBadge } from "@/shared/ui/StatusBadge"; +import type { Certificate } from "../schemas"; +import { + CERTIFICATE_OPTIONS, + CERTIFICATE_STATUS_LABELS, + formatCertificateLifetime, + formatUnixSeconds, + formatValidUntil, + getCertificateStatus, + sshLoginCommand, + statusBadgeVariantFromCertificateStatus, +} from "../status"; + +export type CertificateViewProps = { + cert: Certificate; + // Admins also see the subject, who asked and the CA. + admin?: boolean; + revokedBy: string; + onRevoke?: () => void; +}; + +export function CertificateView({ + cert, + admin = false, + revokedBy, + onRevoke, +}: CertificateViewProps) { + const status = getCertificateStatus(cert); + const granted = cert.granted_extensions ?? []; + const otherGranted = granted.filter((name) => !CERTIFICATE_OPTIONS.some((o) => o.name === name)); + + const command = cert.login_host + ? sshLoginCommand(cert.principal, cert.login_host, cert.login_port ?? 22) + : null; + + return ( + <section className="space-y-4"> + <header className="space-y-3"> + <div className="flex flex-wrap items-start justify-between gap-3"> + <h1 className="font-display text-[28px] font-bold leading-tight"> + Certificate <span className="font-mono">{cert.serial_number}</span> + </h1> + {status === "active" && onRevoke ? ( + <Button variant="destructive" onClick={onRevoke}> + Revoke + </Button> + ) : null} + </div> + <div className="flex flex-wrap items-center gap-3"> + <StatusBadge + variant={statusBadgeVariantFromCertificateStatus(status)} + label={CERTIFICATE_STATUS_LABELS[status]} + /> + <MetaRow> + <MetaItem + icon={UserSquare} + label="Logs in as" + value={<span className="font-mono">{cert.principal}</span>} + /> + <MetaItem + icon={Clock} + label={status === "active" ? "Expires" : "Valid until"} + value={formatValidUntil(cert)} + /> + <MetaItem icon={Hourglass} label="Lifetime" value={formatCertificateLifetime(cert)} /> + </MetaRow> + </div> + </header> + + {cert.revoked ? ( + <div className="space-y-1 rounded-lg border border-destructive p-4 text-sm"> + <p className="font-medium"> + Revoked + {cert.revoked_at != null ? ` ${formatUnixSeconds(cert.revoked_at)}` : ""} by{" "} + <span>{revokedBy}</span> + </p> + <p> + Reason: <span>{cert.revocation_reason || "None given"}</span> + </p> + <p className="text-muted-foreground"> + Login nodes still accept this certificate until it expires. + </p> + </div> + ) : status === "active" ? ( + <div className="space-y-2 rounded-lg border bg-card p-4 text-sm"> + {command ? <CopyValue value={command} label="ssh command" explicit wrap /> : null} + <p className="text-muted-foreground"> + A revoked certificate is still accepted by login nodes until it expires. + </p> + </div> + ) : ( + <p className="rounded-lg border bg-card p-4 text-sm text-muted-foreground"> + {status === "expired" + ? `Expired ${formatUnixSeconds(cert.valid_before)}. It no longer logs in.` + : `Works from ${formatUnixSeconds(cert.valid_after)}.`} + </p> + )} + + <div className="grid gap-4 lg:grid-cols-2"> + <InfoCard title="Validity"> + <dl className="divide-y"> + <Field label="Issued">{formatUnixSeconds(cert.issued_at)}</Field> + <Field label="Valid until">{formatUnixSeconds(cert.valid_before)}</Field> + {admin ? ( + <Field label="Valid after">{formatUnixSeconds(cert.valid_after)}</Field> + ) : null} + </dl> + </InfoCard> + + <InfoCard title="What this certificate allows"> + <ul + aria-label="Certificate options" + className="grid grid-cols-1 gap-x-6 gap-y-1.5 border-b py-2.5 text-sm sm:grid-cols-2" + > + {CERTIFICATE_OPTIONS.map((option) => { + const allowed = granted.includes(option.name); + return ( + <li + key={option.name} + aria-label={`${allowed ? "Allowed" : "Blocked"}: ${option.label}`} + className={ + allowed + ? "flex items-center gap-2" + : "flex items-center gap-2 text-muted-foreground" + } + > + {allowed ? ( + <Check className="h-4 w-4 text-custos-green-700" aria-hidden="true" /> + ) : ( + <X className="h-4 w-4" aria-hidden="true" /> + )} + {option.label} + </li> + ); + })} + {otherGranted.map((name) => ( + <li key={name} className="flex items-center gap-2 font-mono text-xs"> + <Check className="h-4 w-4 text-custos-green-700" aria-hidden="true" /> + {name} + </li> + ))} + </ul> + <dl className="divide-y"> + <Field label="Runs only"> + {cert.force_command ? ( + <span className="font-mono text-xs">{cert.force_command}</span> + ) : ( + "Any command" + )} + </Field> + <Field label="Log in from"> + {cert.source_address ? ( + <span className="font-mono text-xs">{cert.source_address}</span> + ) : ( + "Any address" + )} + </Field> + </dl> + </InfoCard> + + <InfoCard title="Key and identity" className="lg:col-span-2"> + <dl className="divide-y"> + <Field label="Issued to">{cert.user_email}</Field> + <Field label="Key fingerprint"> + <CopyValue + value={cert.public_key_fingerprint} + label="key fingerprint" + explicit + wrap + /> + </Field> + <Field label="Key ID"> + <CopyValue value={cert.key_id} label="key ID" explicit wrap /> + </Field> + {admin ? ( + <> + <Field label="Subject"> + <span className="break-all font-mono text-xs">{cert.user_sub}</span> + </Field> + <Field label="Requested by"> + <span className="font-mono text-xs">{cert.requested_by}</span> + </Field> + <Field label="CA fingerprint"> + <CopyValue value={cert.ca_fingerprint} label="CA fingerprint" explicit wrap /> + </Field> + </> + ) : null} + </dl> + </InfoCard> + </div> + </section> + ); +} + +function InfoCard({ + title, + className, + children, +}: { + title: string; + className?: string; + children: React.ReactNode; +}) { + return ( + <Card className={cn("gap-0 py-0", className)}> + <h2 className="border-b px-5 py-3 text-sm font-semibold">{title}</h2> + <div className="px-5 pb-1">{children}</div> + </Card> + ); +} + +function Field({ label, children }: { label: string; children: React.ReactNode }) { + return ( + <div className="grid grid-cols-1 gap-1 py-2.5 text-sm sm:grid-cols-[9rem_minmax(0,1fr)] sm:items-baseline sm:gap-4"> + <dt className="text-muted-foreground">{label}</dt> + <dd className="min-w-0 text-foreground">{children}</dd> + </div> + ); +} diff --git a/web/src/features/core/signer/components/GenerateCertificateDialog.tsx b/web/src/features/core/signer/components/GenerateCertificateDialog.tsx index e75f2655d..a98419f15 100644 --- a/web/src/features/core/signer/components/GenerateCertificateDialog.tsx +++ b/web/src/features/core/signer/components/GenerateCertificateDialog.tsx @@ -17,6 +17,7 @@ "use client"; +import { Download, Info } from "lucide-react"; import * as React from "react"; import { ApiError } from "@/shared/api/client"; import { Button } from "@/shared/ui/button"; @@ -30,9 +31,10 @@ import { DialogTitle, } from "@/shared/ui/dialog"; import { Label } from "@/shared/ui/label"; +import { Tooltip, TooltipContent, TooltipTrigger } from "@/shared/ui/tooltip"; import { useGenerateCertificate } from "../queries"; import type { GeneratedCertificate } from "../schemas"; -import { formatUnixSeconds } from "../status"; +import { CERTIFICATE_OPTIONS, LIFETIME_CHOICES, formatUnixSeconds } from "../status"; const REFUSAL_MESSAGES: Record<string, string> = { user_not_active: "Your account is not active. Contact your site admin.", @@ -44,8 +46,55 @@ const REFUSAL_MESSAGES: Record<string, string> = { key_type_not_allowed: "This site does not accept that key type.", too_many_certificates: "You have generated as many certificates as allowed for now. Use one you already have, or try again later.", signer_unavailable: "Certificate service is not reachable. No certificate was issued. Try again in a minute.", + invalid_ttl: "That lifetime is longer than this site allows.", + invalid_request: "Check the addresses. Use addresses like 192.0.2.10 or ranges like 192.0.2.0/24.", + principal_denied: "Your cluster account cannot log in yet. Contact your site admin.", }; +const LONGEST_LIFETIME = Math.max(...LIFETIME_CHOICES.map((choice) => choice.seconds)); + +// The signer takes a comma-separated list with no spaces. +function addressList(text: string): string { + return text + .split(/[\s,]+/) + .filter(Boolean) + .join(","); +} + +function OptionField({ + id, + label, + info, + children, +}: { + id: string; + label: string; + info: string; + children: React.ReactNode; +}) { + return ( + <div className="space-y-2"> + <div className="flex items-center gap-1"> + <span id={`${id}-label`} className="text-sm font-medium"> + {label} + </span> + <Tooltip> + <TooltipTrigger + aria-label={`About ${label.toLowerCase()}`} + className="inline-flex h-5 w-5 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" + > + <Info className="h-3.5 w-3.5" aria-hidden="true" /> + </TooltipTrigger> + <TooltipContent side="right">{info}</TooltipContent> + </Tooltip> + </div> + <fieldset aria-labelledby={`${id}-label`} className="min-w-0 space-y-2 text-sm"> + {children} + </fieldset> + </div> + ); +} + 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."; @@ -62,6 +111,15 @@ function sshCommand(result: GeneratedCertificate): string { return `ssh -i ${keyFile(result.certificate)} ${port}${result.principal}@${result.login_host}`; } +function downloadCertificate(certificate: string) { + const url = URL.createObjectURL(new Blob([`${certificate}\n`], { type: "text/plain" })); + const link = document.createElement("a"); + link.href = url; + link.download = `${keyFile(certificate).replace("~/.ssh/", "")}-cert.pub`; + link.click(); + URL.revokeObjectURL(url); +} + export type GenerateCertificateDialogProps = { open: boolean; onOpenChange: (open: boolean) => void; @@ -70,18 +128,44 @@ export type GenerateCertificateDialogProps = { export function GenerateCertificateDialog({ open, onOpenChange }: GenerateCertificateDialogProps) { const generate = useGenerateCertificate(); const [publicKey, setPublicKey] = React.useState(""); + const [lifetime, setLifetime] = React.useState(LONGEST_LIFETIME); + const [onlyAddresses, setOnlyAddresses] = React.useState(false); + const [addresses, setAddresses] = React.useState(""); + const [onlyCommand, setOnlyCommand] = React.useState(false); + const [command, setCommand] = React.useState(""); + const [blocked, setBlocked] = React.useState<string[]>([]); const { reset } = generate; React.useEffect(() => { if (!open) { setPublicKey(""); + setLifetime(LONGEST_LIFETIME); + setOnlyAddresses(false); + setAddresses(""); + setOnlyCommand(false); + setCommand(""); + setBlocked([]); 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 missingValue = + (onlyAddresses && !addressList(addresses)) || (onlyCommand && !command.trim()); const result = generate.data; + // What the member narrowed, shown back with the certificate. + const restrictions: Array<{ label: string; value: string; mono: boolean }> = []; + if (onlyAddresses) { + restrictions.push({ label: "Log in from", value: addressList(addresses), mono: true }); + } + if (onlyCommand) { + restrictions.push({ label: "Runs only", value: command.trim(), mono: true }); + } + if (blocked.length > 0) { + const labels = CERTIFICATE_OPTIONS.filter((o) => blocked.includes(o.name)).map((o) => o.label); + restrictions.push({ label: "Blocked", value: labels.join(", "), mono: false }); + } return ( <Dialog @@ -90,28 +174,82 @@ export function GenerateCertificateDialog({ open, onOpenChange }: GenerateCertif if (!generate.isPending) onOpenChange(next); }} > - <DialogContent> + <DialogContent + className={`max-h-[90vh] overflow-y-auto ${result ? "sm:max-w-2xl" : "sm:max-w-lg"}`} + > {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. + Certificate{" "} + <span className="font-medium text-foreground">{result.serial_number}</span> for{" "} + <span className="font-mono font-medium text-foreground">{result.principal}</span>, + valid until{" "} + <span className="font-medium text-foreground"> + {formatUnixSeconds(result.valid_before)} + </span> + . Shown once. </DialogDescription> </DialogHeader> - <div className="space-y-4 text-sm"> + <div className="min-w-0 space-y-4 text-sm"> + <div className="rounded-md border p-3"> + <p className="mb-2 font-medium">Restrictions</p> + {restrictions.length > 0 ? ( + <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1"> + {restrictions.map(({ label, value, mono }) => ( + <React.Fragment key={label}> + <dt className="text-muted-foreground">{label}</dt> + <dd + className={`min-w-0 break-all font-medium ${mono ? "font-mono text-xs" : ""}`} + > + {value} + </dd> + </React.Fragment> + ))} + </dl> + ) : ( + <p className="text-muted-foreground"> + No restrictions: any address, normal login, all options allowed. + </p> + )} + </div> <div className="space-y-1"> - <p className="font-medium">Certificate</p> - <CopyValue value={result.certificate} label="certificate" explicit /> + <div className="flex items-center justify-between"> + <p className="font-medium">Certificate</p> + <div className="flex items-center gap-3"> + <CopyValue value={result.certificate} label="certificate" explicit> + Copy + </CopyValue> + <Button + variant="outline" + size="sm" + onClick={() => downloadCertificate(result.certificate)} + > + <Download className="h-3.5 w-3.5" aria-hidden="true" /> + Download + </Button> + </div> + </div> + <pre className="max-h-56 overflow-y-auto whitespace-pre-wrap break-all rounded-md border bg-muted p-3 font-mono text-xs leading-relaxed"> + {result.certificate} + </pre> </div> <ol className="list-decimal space-y-2 pl-5"> <li> - Save it next to your private key as{" "} + Download it, or copy it, and 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 className="space-y-1"> + <div className="flex items-center justify-between"> + <span>Run</span> + <CopyValue value={sshCommand(result)} label="ssh command" explicit> + Copy + </CopyValue> + </div> + <pre className="whitespace-pre-wrap break-all rounded-md border bg-muted p-3 font-mono text-xs"> + {sshCommand(result)} + </pre> </li> </ol> </div> @@ -129,7 +267,14 @@ export function GenerateCertificateDialog({ open, onOpenChange }: GenerateCertif className="space-y-4" onSubmit={(e) => { e.preventDefault(); - if (publicKey.trim() && !isPrivateKey) generate.mutate(publicKey.trim()); + if (!publicKey.trim() || isPrivateKey || missingValue) return; + generate.mutate({ + public_key: publicKey.trim(), + ttl_seconds: lifetime, + exclude_extensions: blocked, + ...(onlyAddresses ? { source_address: addressList(addresses) } : {}), + ...(onlyCommand ? { force_command: command.trim() } : {}), + }); }} > <div className="space-y-2"> @@ -147,13 +292,134 @@ export function GenerateCertificateDialog({ open, onOpenChange }: GenerateCertif <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."} + : "Paste your .pub file, for example ~/.ssh/id_ed25519.pub. Never your private key."} </p> </div> + {isPrivateKey ? null : ( + <div className="space-y-1 text-xs text-muted-foreground"> + <p>No key yet? Run this on your computer:</p> + <div className="rounded-md border bg-muted px-3 py-2"> + <CopyValue + value="ssh-keygen -t ed25519" + label="ssh-keygen command" + explicit + className="w-full justify-between" + /> + </div> + </div> + )} + + <OptionField id="lifetime" label="Lifetime" info="How long the certificate works."> + <select + aria-labelledby="lifetime-label" + value={lifetime} + onChange={(e) => setLifetime(Number(e.target.value))} + disabled={generate.isPending} + className="h-9 w-full rounded-md border bg-background px-3 text-sm" + > + {LIFETIME_CHOICES.map((choice) => ( + <option key={choice.seconds} value={choice.seconds}> + {choice.label} + </option> + ))} + </select> + </OptionField> + + <OptionField + id="log-in-from" + label="Log in from" + info="Written into the certificate as source-address. Login nodes refuse the certificate from any other address." + > + <label className="flex items-center gap-2"> + <input + type="radio" + name="log-in-from" + checked={!onlyAddresses} + onChange={() => setOnlyAddresses(false)} + /> + Any address + </label> + <label className="flex items-center gap-2"> + <input + type="radio" + name="log-in-from" + checked={onlyAddresses} + onChange={() => setOnlyAddresses(true)} + /> + Only these addresses + </label> + {onlyAddresses ? ( + <input + aria-label="Addresses" + value={addresses} + onChange={(e) => setAddresses(e.target.value)} + placeholder="192.0.2.10, 198.51.100.0/24" + className="h-9 w-full rounded-md border bg-background px-3 font-mono text-xs" + /> + ) : null} + </OptionField> + + <OptionField + id="command" + label="Command" + info="Written into the certificate as force-command. Every login runs this command and nothing else." + > + <label className="flex items-center gap-2"> + <input + type="radio" + name="command" + checked={!onlyCommand} + onChange={() => setOnlyCommand(false)} + /> + Normal login + </label> + <label className="flex items-center gap-2"> + <input + type="radio" + name="command" + checked={onlyCommand} + onChange={() => setOnlyCommand(true)} + /> + Only this command + </label> + {onlyCommand ? ( + <input + aria-label="Command" + value={command} + onChange={(e) => setCommand(e.target.value)} + placeholder="/usr/bin/rsync --server ..." + className="h-9 w-full rounded-md border bg-background px-3 font-mono text-xs" + /> + ) : null} + </OptionField> + + <OptionField + id="allow" + label="Allow on this certificate" + info="Unticked options are left out of the certificate, so the login node blocks them." + > + <div className="grid grid-cols-1 gap-1 sm:grid-cols-2"> + {CERTIFICATE_OPTIONS.map((option) => ( + <label key={option.name} className="flex items-center gap-2"> + <input + type="checkbox" + checked={!blocked.includes(option.name)} + onChange={(e) => + setBlocked((current) => + e.target.checked + ? current.filter((n) => n !== option.name) + : [...current, option.name], + ) + } + /> + {option.label} + </label> + ))} + </div> + </OptionField> + {generate.error ? ( - <p className="text-sm text-[color:var(--custos-red-700)]"> - {refusalMessage(generate.error)} - </p> + <p className="text-sm text-destructive">{refusalMessage(generate.error)}</p> ) : null} <DialogFooter> <Button @@ -164,7 +430,10 @@ export function GenerateCertificateDialog({ open, onOpenChange }: GenerateCertif > Cancel </Button> - <Button type="submit" disabled={generate.isPending || !publicKey.trim() || isPrivateKey}> + <Button + type="submit" + disabled={generate.isPending || !publicKey.trim() || isPrivateKey || missingValue} + > {generate.isPending ? "Generating…" : "Generate certificate"} </Button> </DialogFooter> diff --git a/web/src/features/core/signer/components/MyCertificateDetail.tsx b/web/src/features/core/signer/components/MyCertificateDetail.tsx index 05278182a..db3f7e045 100644 --- a/web/src/features/core/signer/components/MyCertificateDetail.tsx +++ b/web/src/features/core/signer/components/MyCertificateDetail.tsx @@ -21,20 +21,12 @@ import * as React from "react"; import { toast } from "sonner"; import { useCurrentUser } from "@/features/core/identity/queries"; 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, - statusBadgeVariantFromCertificateStatus, - userIdOf, -} from "../status"; +import { userIdOf } from "../status"; import { revokeErrorMessage } from "./CertificateDetail"; +import { CertificateView } from "./CertificateView"; import { loadErrorMessage } from "./MyCertificates"; import { RevokeCertificateDialog } from "./RevokeCertificateDialog"; @@ -55,66 +47,16 @@ export function MyCertificateDetail({ serial }: { serial: string }) { 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], - ["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"], - ["Can log in from", cert.source_address || "Any address"], - ]; - 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{" "} - {userIdOf(cert.revoked_by) === user?.id ? "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> + <> + <CertificateView + cert={cert} + revokedBy={userIdOf(cert.revoked_by) === user?.id ? "you" : "your site"} + onRevoke={() => { + setRevokeError(null); + setDialogOpen(true); + }} + /> <RevokeCertificateDialog serialNumber={cert.serial_number} @@ -136,6 +78,6 @@ export function MyCertificateDetail({ serial }: { serial: string }) { ); }} /> - </section> + </> ); } diff --git a/web/src/features/core/signer/components/MyCertificates.tsx b/web/src/features/core/signer/components/MyCertificates.tsx index e1b5f4e73..dcf722b80 100644 --- a/web/src/features/core/signer/components/MyCertificates.tsx +++ b/web/src/features/core/signer/components/MyCertificates.tsx @@ -17,7 +17,7 @@ "use client"; -import Link from "next/link"; +import { useRouter } from "next/navigation"; import * as React from "react"; import { toast } from "sonner"; import { ApiError } from "@/shared/api/client"; @@ -32,7 +32,9 @@ import type { Certificate } from "../schemas"; import { CERTIFICATE_STATUS_LABELS, type CertificateStatus, + formatUnixDate, formatUnixSeconds, + formatValidUntil, getCertificateStatus, statusBadgeVariantFromCertificateStatus, } from "../status"; @@ -47,6 +49,7 @@ export function loadErrorMessage(error: unknown): string { } export function MyCertificates() { + const router = useRouter(); const { params, paging } = useCursorPaging(); const query = useMyCertificates(params); const revoke = useRevokeMyCertificate(); @@ -61,19 +64,37 @@ export function MyCertificates() { ); const columns: Array<DataTableColumn<Certificate>> = [ + { + key: "serial", + header: "Serial", + cell: (row) => <span className="font-mono font-medium">{row.serial_number}</span>, + }, + { + key: "key", + header: "Key", + cell: (row) => ( + <span className="font-mono text-xs text-muted-foreground" title={row.public_key_fingerprint}> + {row.public_key_fingerprint.slice(0, 14)}… + </span> + ), + }, { key: "issued", header: "Issued", cell: (row) => ( - <Link href={`/ssh-access/${row.serial_number}`} className="text-sm font-medium hover:underline"> - {formatUnixSeconds(row.issued_at)} - </Link> + <span className="text-sm" title={formatUnixSeconds(row.issued_at)}> + {formatUnixDate(row.issued_at)} + </span> ), }, { key: "validBefore", header: "Valid until", - cell: (row) => <span className="text-sm">{formatUnixSeconds(row.valid_before)}</span>, + cell: (row) => ( + <span className="text-sm" title={formatUnixSeconds(row.valid_before)}> + {formatValidUntil(row)} + </span> + ), }, { key: "status", @@ -91,11 +112,14 @@ export function MyCertificates() { { key: "actions", header: "", + align: "right", + interactive: true, cell: (row) => getCertificateStatus(row) === "active" ? ( <Button variant="outline" size="sm" + aria-label={`Revoke certificate ${row.serial_number}`} onClick={() => { setRevokeError(null); setRevoking(row); @@ -139,7 +163,7 @@ export function MyCertificates() { </div> {query.isLoading ? ( - <TableSkeleton rows={4} columns={5} /> + <TableSkeleton rows={4} columns={6} /> ) : query.error ? ( <ErrorState message={loadErrorMessage(query.error)} onRetry={() => query.refetch()} /> ) : filtered.length === 0 ? ( @@ -152,7 +176,12 @@ export function MyCertificates() { } /> ) : ( - <DataTable columns={columns} rows={filtered} rowKey={(row) => String(row.serial_number)} /> + <DataTable + columns={columns} + rows={filtered} + rowKey={(row) => String(row.serial_number)} + onRowClick={(row) => router.push(`/ssh-access/${row.serial_number}`)} + /> )} {!query.isLoading && (query.error || rows.length > 0) ? ( <CursorPager {...paging(query.data?.next_cursor)} /> diff --git a/web/src/features/core/signer/components/RevokeCertificateDialog.tsx b/web/src/features/core/signer/components/RevokeCertificateDialog.tsx index 896a72b22..eaedd948c 100644 --- a/web/src/features/core/signer/components/RevokeCertificateDialog.tsx +++ b/web/src/features/core/signer/components/RevokeCertificateDialog.tsx @@ -102,7 +102,7 @@ export function RevokeCertificateDialog({ <span>{Math.max(0, 255 - reasonLength)} remaining</span> </div> </div> - {error ? <p className="text-sm text-[color:var(--custos-red-700)]">{error}</p> : null} + {error ? <p className="text-sm text-destructive">{error}</p> : null} <DialogFooter> <Button type="button" diff --git a/web/src/features/core/signer/queries.ts b/web/src/features/core/signer/queries.ts index e91306744..ed78d85c9 100644 --- a/web/src/features/core/signer/queries.ts +++ b/web/src/features/core/signer/queries.ts @@ -29,6 +29,7 @@ import { revokeCertificate, revokeMyCertificate, } from "./api"; +import type { GenerateCertificateInput } from "./schemas"; import type { CertificateListParams, CertificateListPaging } from "./types"; export const signerKeys = { @@ -115,7 +116,7 @@ export function useMyCertificate(serial: string) { export function useGenerateCertificate() { const client = useQueryClient(); return useMutation({ - mutationFn: (publicKey: string) => generateCertificate(publicKey), + mutationFn: (input: GenerateCertificateInput) => generateCertificate(input), onSuccess: () => client.invalidateQueries({ queryKey: signerKeys.all }), }); } diff --git a/web/src/features/core/signer/schemas.ts b/web/src/features/core/signer/schemas.ts index b8efb3bd0..05f51ac6e 100644 --- a/web/src/features/core/signer/schemas.ts +++ b/web/src/features/core/signer/schemas.ts @@ -40,6 +40,8 @@ export const certificateSchema = z.object({ revoked_at: z.number().int().nullable().optional(), revocation_reason: z.string().optional(), revoked_by: z.string().optional(), + login_host: z.string().optional(), + login_port: z.number().int().optional(), }); export type Certificate = z.infer<typeof certificateSchema>; @@ -73,3 +75,11 @@ export const generatedCertificateSchema = z.object({ login_port: z.number().int(), }); export type GeneratedCertificate = z.infer<typeof generatedCertificateSchema>; + +export type GenerateCertificateInput = { + public_key: string; + ttl_seconds: number; + source_address?: string; + force_command?: string; + exclude_extensions?: string[]; +}; diff --git a/web/src/features/core/signer/status.ts b/web/src/features/core/signer/status.ts index 3b9350103..da328829a 100644 --- a/web/src/features/core/signer/status.ts +++ b/web/src/features/core/signer/status.ts @@ -61,6 +61,35 @@ export function formatUnixDate(seconds: number): string { }); } +// Time left on an active certificate, otherwise its end date. Certificates last at most a day. +export function formatValidUntil(cert: Certificate, now: Date = new Date()): string { + if (getCertificateStatus(cert, now) !== "active") return formatUnixDate(cert.valid_before); + const left = cert.valid_before - Math.floor(now.getTime() / 1000); + if (left < 60) return "in less than a minute"; + if (left < 3600) return `in ${Math.floor(left / 60)} min`; + return `in ${Math.floor(left / 3600)}h ${Math.floor((left % 3600) / 60)}m`; +} + +// The standard options a certificate can carry, in display order. +export const CERTIFICATE_OPTIONS: Array<{ name: string; label: string }> = [ + { name: "permit-pty", label: "Terminal sessions" }, + { name: "permit-port-forwarding", label: "Port forwarding" }, + { name: "permit-agent-forwarding", label: "Agent forwarding" }, + { name: "permit-X11-forwarding", label: "Graphical apps (X11)" }, + { name: "permit-user-rc", label: "Run ~/.ssh/rc at login" }, +]; + +// TODO: read the longest lifetime from the server. 4 hours matches the connector's default. +export const LIFETIME_CHOICES: Array<{ seconds: number; label: string }> = [ + { seconds: 3600, label: "1 hour" }, + { seconds: 7200, label: "2 hours" }, + { seconds: 14400, label: "4 hours" }, +]; + +export function sshLoginCommand(principal: string, host: string, port: number): string { + return `ssh ${port === 22 ? "" : `-p ${port} `}${principal}@${host}`; +} + export function formatCertificateLifetime(cert: Certificate): string { const seconds = Math.max(0, cert.valid_before - cert.valid_after); const hours = Math.floor(seconds / 3600); diff --git a/web/src/mocks/handlers/signer.ts b/web/src/mocks/handlers/signer.ts index 6dadd060b..0c9c57a66 100644 --- a/web/src/mocks/handlers/signer.ts +++ b/web/src/mocks/handlers/signer.ts @@ -62,7 +62,7 @@ export const signerHandlers = [ certificate: "[email protected] AAAAexample", serial_number: 50, principal: "dev-admin", - valid_before: Math.floor(Date.now() / 1000) + 28800, + valid_before: Math.floor(Date.now() / 1000) + 14400, login_host: "login.example.edu", login_port: 22, }), diff --git a/web/src/shared/ui/CopyValue.tsx b/web/src/shared/ui/CopyValue.tsx index 2732bc65d..12dd35e6c 100644 --- a/web/src/shared/ui/CopyValue.tsx +++ b/web/src/shared/ui/CopyValue.tsx @@ -27,11 +27,20 @@ export type CopyValueProps = { explicit?: boolean; className?: string; children?: React.ReactNode; + // Wrap a long value in full instead of cutting it off. + wrap?: boolean; }; const COPIED_RESET_MS = 1100; -export function CopyValue({ value, label, explicit = false, className, children }: CopyValueProps) { +export function CopyValue({ + value, + label, + explicit = false, + className, + children, + wrap = false, +}: CopyValueProps) { const [copied, setCopied] = React.useState(false); const timerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null); @@ -62,11 +71,14 @@ export function CopyValue({ value, label, explicit = false, className, children return ( <span className={cn( - "inline-flex max-w-full items-center gap-1.5 font-mono text-xs text-foreground", + "inline-flex max-w-full gap-1.5 font-mono text-xs text-foreground", + wrap ? "items-start" : "items-center", className, )} > - <span className="min-w-0 truncate">{children ?? value}</span> + <span className={cn("min-w-0", wrap ? "break-all" : "truncate")} title={value}> + {children ?? value} + </span> <button type="button" onClick={handleCopy} diff --git a/web/tests/signer-certificates.e2e.ts b/web/tests/signer-certificates.e2e.ts index dd730570b..ac84483a7 100644 --- a/web/tests/signer-certificates.e2e.ts +++ b/web/tests/signer-certificates.e2e.ts @@ -36,12 +36,12 @@ test.describe("ssh certificates", () => { await signInAs(page, "admin"); await page.goto("/admin/signer/certificates"); await expect(page.getByRole("heading", { name: /^SSH Certificates$/ })).toBeVisible(); - await page.getByRole("link", { name: "42" }).click(); + await page.getByRole("button", { name: "42" }).click(); 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("sub-researcher")).toBeVisible(); - await expect(page.getByText(/permit-pty/)).toBeVisible(); + await expect(page.getByLabel("Allowed: Terminal sessions")).toBeVisible(); }); test("search and status filters update URL state and filter the loaded page", async ({ page }) => { @@ -49,8 +49,8 @@ test.describe("ssh certificates", () => { await page.goto("/admin/signer/certificates"); await page.getByRole("searchbox", { name: /search certificates/i }).fill("44"); await expect(page).toHaveURL(/[?&]q=44/); - await expect(page.getByRole("link", { name: "44" })).toBeVisible(); - await expect(page.getByRole("link", { name: "42" })).toHaveCount(0); + await expect(page.getByRole("button", { name: "44" })).toBeVisible(); + await expect(page.getByRole("button", { name: "42" })).toHaveCount(0); await page.getByLabel(/filter by status/i).selectOption("revoked"); await expect(page).toHaveURL(/[?&]status=revoked/); }); @@ -67,14 +67,14 @@ test.describe("ssh certificates", () => { signerApi.setScenario("paginated"); await page.goto("/admin/signer/certificates"); await expect(page.getByText("Page 1")).toBeVisible(); - await expect(page.getByRole("link", { name: "100" })).toBeVisible(); + await expect(page.getByRole("button", { name: "100" })).toBeVisible(); await expect(page.getByRole("button", { name: /^Previous$/ })).toBeDisabled(); await page.getByRole("button", { name: /^Next$/ }).click(); await expect(page.getByText("Page 2")).toBeVisible(); - await expect(page.getByRole("link", { name: "120" })).toBeVisible(); + await expect(page.getByRole("button", { name: "120" })).toBeVisible(); await expect(page.getByRole("button", { name: /^Next$/ })).toBeDisabled(); await page.getByRole("button", { name: /^Previous$/ }).click(); - await expect(page.getByRole("link", { name: "100" })).toBeVisible(); + await expect(page.getByRole("button", { name: "100" })).toBeVisible(); }); test("distinguishes no matches on a loaded page", async ({ page }) => {
