import { describe, expect, it } from "vitest"; import { ensureNewSshKey, isSshPublicKey, sshFingerprint } from "#lib/api/settings.ts"; const ed25519 = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHEisipfUi+zRyW1reo72Rt4+EUbM5mKZrI9/PkyHMpR qa"; const ecdsa = "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBPa17IfyrTk7DrKJLEhhFFDho8BE0v7Wk07xsmqWfoi+W6OuaFyPrSNJ2oYbmp1ZHIOOFSq9VY3Tu/eEk8VGhQY= qa"; const withBlob = (key: string, edit: (blob: string) => string) => { const [type, blob, ...rest] = key.split(" "); return [type, edit(blob), ...rest].join(" "); }; describe("isSshPublicKey", () => { it("accepts well-formed keys", () => { expect(isSshPublicKey(ed25519)).toBe(true); expect(isSshPublicKey(ecdsa)).toBe(true); expect(isSshPublicKey(ed25519.split(" ").slice(0, 2).join(" "))).toBe(true); }); it("rejects keys with characters removed", () => { expect(isSshPublicKey(withBlob(ed25519, (blob) => blob.slice(0, -4)))).toBe(false); expect( isSshPublicKey(withBlob(ed25519, (blob) => blob.slice(0, 20) + blob.slice(24))) ).toBe(false); expect(isSshPublicKey(withBlob(ecdsa, (blob) => blob.slice(0, -8) + "="))).toBe(false); }); it("rejects keys with trailing bytes", () => { expect(isSshPublicKey(withBlob(ed25519, (blob) => blob + "AAAA"))).toBe(false); }); it("rejects a type that does not match the blob", () => { expect(isSshPublicKey(ed25519.replace("ssh-ed25519", "ssh-rsa"))).toBe(false); expect(isSshPublicKey("ssh-ed25519 not-base64!")).toBe(false); expect(isSshPublicKey("ssh-ed25519")).toBe(false); }); }); describe("ensureNewSshKey", () => { it("returns the fingerprint of a key that is not added yet", async () => { await expect(ensureNewSshKey(ed25519, [])).resolves.toMatch(/^SHA256:/); }); it("rejects a key whose content is already added under any name", async () => { const fingerprint = await sshFingerprint(ed25519); await expect( ensureNewSshKey(ed25519.replace(" qa", " another name"), [fingerprint]) ).rejects.toThrow(`This key is already added (${fingerprint}).`); }); });