~james/core

core/web/src/lib/api/settings.test.ts -rw-r--r-- 2.0 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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}).`);
	});
});