|
| 1 | +/* |
| 2 | +Copyright The CryptOS Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +import "reflect-metadata"; |
| 18 | +import { Code, ConnectError } from "@connectrpc/connect"; |
| 19 | +import { X509CertificateGenerator } from "@peculiar/x509"; |
| 20 | +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; |
| 21 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
| 22 | + |
| 23 | +import type { CredentialRequestRow } from "@/lib/operators"; |
| 24 | + |
| 25 | +import { CredentialCompleteDialog } from "@/components/credential-complete-dialog"; |
| 26 | +import { generateBackupPassphrase, keyBackupPem } from "@/lib/crypto/key-backup"; |
| 27 | +import { base64 } from "@/lib/crypto/leaf-key"; |
| 28 | +import * as modeMod from "@/lib/fleet/mode"; |
| 29 | +import * as operators from "@/lib/operators"; |
| 30 | + |
| 31 | +const { buildCredentialPkcs12, downloadBytes } = vi.hoisted(() => ({ |
| 32 | + buildCredentialPkcs12: vi.fn(), |
| 33 | + downloadBytes: vi.fn(), |
| 34 | +})); |
| 35 | +vi.mock("@/lib/download", async (importOriginal) => ({ |
| 36 | + ...(await importOriginal<typeof import("@/lib/download")>()), |
| 37 | + downloadBytes: (...a: unknown[]) => downloadBytes(...a), |
| 38 | +})); |
| 39 | + |
| 40 | +vi.mock("@/lib/crypto/key-backup", async (importOriginal) => { |
| 41 | + const actual = await importOriginal<typeof import("@/lib/crypto/key-backup")>(); |
| 42 | + buildCredentialPkcs12.mockImplementation(actual.buildCredentialPkcs12); |
| 43 | + return { ...actual, buildCredentialPkcs12: (...a: unknown[]) => buildCredentialPkcs12(...a) }; |
| 44 | +}); |
| 45 | + |
| 46 | +const EMAIL = "new-hire@example.org"; |
| 47 | + |
| 48 | +const request: CredentialRequestRow = { |
| 49 | + completedSerial: "", |
| 50 | + createdAt: "2026-09-29T14:00:00Z", |
| 51 | + createdByCn: "admin@example.org", |
| 52 | + csrPem: "", |
| 53 | + email: EMAIL, |
| 54 | + expiresAt: "2026-10-29T14:00:00Z", |
| 55 | + fullName: "New Hire", |
| 56 | + id: "req-1", |
| 57 | + level: "operator", |
| 58 | + state: "pending", |
| 59 | +}; |
| 60 | + |
| 61 | +const material = async () => { |
| 62 | + const keys = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-384" }, true, [ |
| 63 | + "sign", |
| 64 | + "verify", |
| 65 | + ])) as CryptoKeyPair; |
| 66 | + const passphrase = generateBackupPassphrase(); |
| 67 | + const backup = new TextEncoder().encode(await keyBackupPem(keys.privateKey, passphrase)); |
| 68 | + const cert = await X509CertificateGenerator.createSelfSigned({ |
| 69 | + keys, |
| 70 | + name: `CN=${EMAIL}`, |
| 71 | + notAfter: new Date(Date.now() + 86_400_000), |
| 72 | + notBefore: new Date(Date.now() - 60_000), |
| 73 | + serialNumber: "0a", |
| 74 | + signingAlgorithm: { hash: "SHA-384", name: "ECDSA" }, |
| 75 | + }); |
| 76 | + return { backup, certPem: cert.toString("pem"), keys, passphrase }; |
| 77 | +}; |
| 78 | + |
| 79 | +const fill = (label: RegExp, value: string) => |
| 80 | + fireEvent.change(screen.getByLabelText(label), { target: { value } }); |
| 81 | + |
| 82 | +beforeEach(() => { |
| 83 | + downloadBytes.mockReset(); |
| 84 | + buildCredentialPkcs12.mockClear(); |
| 85 | + operators.__resetOperators(); |
| 86 | +}); |
| 87 | +afterEach(() => { |
| 88 | + vi.restoreAllMocks(); |
| 89 | + vi.unstubAllGlobals(); |
| 90 | +}); |
| 91 | + |
| 92 | +describe("CredentialCompleteDialog", () => { |
| 93 | + it("records the certificate, then builds the PKCS#12 with the key backup's passphrase", async () => { |
| 94 | + const { backup, certPem, passphrase } = await material(); |
| 95 | + const record = vi.spyOn(operators, "recordOperatorCredential"); |
| 96 | + const onRecorded = vi.fn(); |
| 97 | + render( |
| 98 | + <CredentialCompleteDialog |
| 99 | + heldBackup={backup} |
| 100 | + onClose={vi.fn()} |
| 101 | + onRecorded={onRecorded} |
| 102 | + request={request} |
| 103 | + />, |
| 104 | + ); |
| 105 | + |
| 106 | + fill(/signed certificate/i, certPem); |
| 107 | + fill(/backup passphrase/i, passphrase); |
| 108 | + fireEvent.click(screen.getByRole("button", { name: /record/i })); |
| 109 | + |
| 110 | + await waitFor(() => expect(downloadBytes).toHaveBeenCalled(), { timeout: 15_000 }); |
| 111 | + expect(record).toHaveBeenCalledWith(expect.objectContaining({ requestId: "req-1" })); |
| 112 | + const [args] = buildCredentialPkcs12.mock.calls[0] as [ |
| 113 | + { backup: Uint8Array; friendlyName: string; passphrase: string }, |
| 114 | + ]; |
| 115 | + expect(args.backup).toBe(backup); |
| 116 | + expect(args.passphrase).toBe(passphrase); |
| 117 | + expect(args.friendlyName).toBe(`FleetOS operator (${EMAIL})`); |
| 118 | + expect(downloadBytes.mock.calls[0][0]).toBe(`${EMAIL}.p12`); |
| 119 | + expect(onRecorded).toHaveBeenCalled(); |
| 120 | + expect(screen.getByText(/PKCS#12 downloaded/i)).toBeInTheDocument(); |
| 121 | + }, 30_000); |
| 122 | + |
| 123 | + it("stops before recording when the passphrase doesn't open the backup", async () => { |
| 124 | + const { backup, certPem } = await material(); |
| 125 | + const record = vi.spyOn(operators, "recordOperatorCredential"); |
| 126 | + render( |
| 127 | + <CredentialCompleteDialog |
| 128 | + heldBackup={backup} |
| 129 | + onClose={vi.fn()} |
| 130 | + onRecorded={vi.fn()} |
| 131 | + request={request} |
| 132 | + />, |
| 133 | + ); |
| 134 | + fill(/signed certificate/i, certPem); |
| 135 | + fill(/backup passphrase/i, "wrong-passphrase-wrong-pass"); |
| 136 | + fireEvent.click(screen.getByRole("button", { name: /record/i })); |
| 137 | + |
| 138 | + await screen.findByText(/passphrase is wrong/i, {}, { timeout: 15_000 }); |
| 139 | + expect(record).not.toHaveBeenCalled(); |
| 140 | + expect(downloadBytes).not.toHaveBeenCalled(); |
| 141 | + }, 30_000); |
| 142 | + |
| 143 | + it("takes a key backup file when the browser holds none", async () => { |
| 144 | + const { backup, certPem, passphrase } = await material(); |
| 145 | + render(<CredentialCompleteDialog onClose={vi.fn()} onRecorded={vi.fn()} request={request} />); |
| 146 | + expect(screen.queryByLabelText(/held in this browser/i)).not.toBeInTheDocument(); |
| 147 | + fill(/signed certificate/i, certPem); |
| 148 | + fireEvent.change(screen.getByLabelText(/^key backup file/i), { |
| 149 | + target: { files: [new File([new TextDecoder().decode(backup)], "k.key.pem")] }, |
| 150 | + }); |
| 151 | + fill(/backup passphrase/i, passphrase); |
| 152 | + await waitFor(() => expect(screen.getByRole("button", { name: /record/i })).toBeEnabled()); |
| 153 | + fireEvent.click(screen.getByRole("button", { name: /record/i })); |
| 154 | + await waitFor(() => expect(downloadBytes).toHaveBeenCalled(), { timeout: 15_000 }); |
| 155 | + }, 30_000); |
| 156 | + |
| 157 | + it("only records when the holder keeps the key", async () => { |
| 158 | + const { certPem } = await material(); |
| 159 | + const record = vi.spyOn(operators, "recordOperatorCredential"); |
| 160 | + render(<CredentialCompleteDialog onClose={vi.fn()} onRecorded={vi.fn()} request={request} />); |
| 161 | + fill(/signed certificate/i, certPem); |
| 162 | + fireEvent.click(screen.getByLabelText(/holder has the key/i)); |
| 163 | + fireEvent.click(screen.getByRole("button", { name: /record/i })); |
| 164 | + await screen.findByText(/recorded/i, { selector: "[role=status]" }); |
| 165 | + expect(record).toHaveBeenCalled(); |
| 166 | + expect(downloadBytes).not.toHaveBeenCalled(); |
| 167 | + expect(screen.getByText(/openssl pkcs12 -export/)).toBeInTheDocument(); |
| 168 | + }, 30_000); |
| 169 | + |
| 170 | + it("explains a refusal by its reason code", async () => { |
| 171 | + const { certPem } = await material(); |
| 172 | + vi.spyOn(operators, "recordOperatorCredential").mockRejectedValue( |
| 173 | + new ConnectError("refused", Code.InvalidArgument, { |
| 174 | + "x-cryptos-error-code": "1610", |
| 175 | + "x-cryptos-error-reason": "LEVEL_EXT_CRITICAL", |
| 176 | + }), |
| 177 | + ); |
| 178 | + render(<CredentialCompleteDialog onClose={vi.fn()} onRecorded={vi.fn()} request={request} />); |
| 179 | + fill(/signed certificate/i, certPem); |
| 180 | + fireEvent.click(screen.getByLabelText(/holder has the key/i)); |
| 181 | + fireEvent.click(screen.getByRole("button", { name: /record/i })); |
| 182 | + await screen.findByText(/marked critical/i); |
| 183 | + }, 30_000); |
| 184 | + |
| 185 | + it("asks for the holder's name when recording without a request", async () => { |
| 186 | + const { certPem } = await material(); |
| 187 | + const record = vi.spyOn(operators, "recordOperatorCredential"); |
| 188 | + render(<CredentialCompleteDialog onClose={vi.fn()} onRecorded={vi.fn()} request={null} />); |
| 189 | + fill(/signed certificate/i, certPem); |
| 190 | + fill(/holder's full name/i, "Out Of Band"); |
| 191 | + fireEvent.click(screen.getByLabelText(/holder has the key/i)); |
| 192 | + fireEvent.click(screen.getByRole("button", { name: /record/i })); |
| 193 | + await waitFor(() => |
| 194 | + expect(record).toHaveBeenCalledWith( |
| 195 | + expect.objectContaining({ fullName: "Out Of Band", requestId: undefined }), |
| 196 | + ), |
| 197 | + ); |
| 198 | + }, 30_000); |
| 199 | + |
| 200 | + it("never puts the key or the passphrase in a request body (live)", async () => { |
| 201 | + const { backup, certPem, keys, passphrase } = await material(); |
| 202 | + vi.spyOn(modeMod, "fleetMode").mockReturnValue("live"); |
| 203 | + const bodies: string[] = []; |
| 204 | + vi.stubGlobal( |
| 205 | + "fetch", |
| 206 | + vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => { |
| 207 | + const raw = init?.body; |
| 208 | + bodies.push(ArrayBuffer.isView(raw) ? new TextDecoder().decode(raw) : String(raw ?? "")); |
| 209 | + return Response.json( |
| 210 | + { |
| 211 | + credential: { commonName: EMAIL, email: EMAIL, level: "operator", serialHex: "0A" }, |
| 212 | + }, |
| 213 | + { headers: { "content-type": "application/json" }, status: 200 }, |
| 214 | + ); |
| 215 | + }), |
| 216 | + ); |
| 217 | + render( |
| 218 | + <CredentialCompleteDialog |
| 219 | + heldBackup={backup} |
| 220 | + onClose={vi.fn()} |
| 221 | + onRecorded={vi.fn()} |
| 222 | + request={request} |
| 223 | + />, |
| 224 | + ); |
| 225 | + fill(/signed certificate/i, certPem); |
| 226 | + fill(/backup passphrase/i, passphrase); |
| 227 | + fireEvent.click(screen.getByRole("button", { name: /record/i })); |
| 228 | + await waitFor(() => expect(downloadBytes).toHaveBeenCalled(), { timeout: 15_000 }); |
| 229 | + |
| 230 | + expect(bodies).toHaveLength(1); |
| 231 | + const pkcs8 = base64(new Uint8Array(await crypto.subtle.exportKey("pkcs8", keys.privateKey))); |
| 232 | + const jwk = await crypto.subtle.exportKey("jwk", keys.privateKey); |
| 233 | + const backupB64 = base64(backup); |
| 234 | + for (const secret of [pkcs8, jwk.d ?? "unset", passphrase, backupB64]) { |
| 235 | + expect(bodies[0]).not.toContain(secret); |
| 236 | + } |
| 237 | + }, 30_000); |
| 238 | +}); |
0 commit comments