208 lines
8.4 KiB
TypeScript
208 lines
8.4 KiB
TypeScript
import {
|
|
chmodSync,
|
|
existsSync,
|
|
lstatSync,
|
|
mkdirSync,
|
|
renameSync,
|
|
realpathSync,
|
|
symlinkSync,
|
|
unlinkSync,
|
|
utimesSync,
|
|
writeFileSync,
|
|
linkSync,
|
|
} from "node:fs";
|
|
import { mkdtempSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import { afterEach, describe, expect, test } from "vitest";
|
|
import { createLocalUserRegistry } from "../src/auth/local-registry.js";
|
|
|
|
const password = "correct horse battery staple";
|
|
const passwordHash = "$argon2id$v=19$m=65536,t=3,p=1$AAECAwQFBgcICQoLDA0ODw$DRo8ZSPI8G5OCvnFFapbVEjP69aDjy1Sw9i2743cPC4";
|
|
const adminId = "6ba7b810-9dad-4ed1-80b4-00c04fd430c8";
|
|
const userId = "7ba7b810-9dad-4ed1-80b4-00c04fd430c8";
|
|
|
|
const createdRoots: string[] = [];
|
|
|
|
afterEach(() => {
|
|
for (const root of createdRoots.splice(0)) {
|
|
for (const name of ["users.yaml", "users-link.yaml", "users-target.yaml", "replacement.yaml"]) {
|
|
const path = join(root, name);
|
|
if (existsSync(path) || lstatMaybe(path)) unlinkSync(path);
|
|
}
|
|
}
|
|
});
|
|
|
|
function lstatMaybe(path: string): boolean {
|
|
try {
|
|
lstatSync(path);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function root(): string {
|
|
const path = mkdtempSync(join(realpathSync(tmpdir()), "thothii-local-registry-"));
|
|
chmodSync(path, 0o700);
|
|
if ((lstatSync(path).mode & 0o7777) !== 0o700) throw new Error("test root is not private");
|
|
createdRoots.push(path);
|
|
return path;
|
|
}
|
|
|
|
function userYaml(options: {
|
|
id?: string;
|
|
username?: string;
|
|
displayName?: string;
|
|
enabled?: boolean;
|
|
role?: "user" | "admin";
|
|
} = {}): string {
|
|
return [
|
|
` - id: ${options.id ?? adminId}`,
|
|
` username: ${options.username ?? "Admin"}`,
|
|
` displayName: ${options.displayName ?? "Admin"}`,
|
|
` passwordHash: ${passwordHash}`,
|
|
` roles:`,
|
|
` - ${options.role ?? "admin"}`,
|
|
` enabled: ${options.enabled ?? true}`,
|
|
` authRevision: 1`,
|
|
].join("\n") + "\n";
|
|
}
|
|
|
|
function registryYaml(users: string): string {
|
|
return `version: 1\nusers:\n${users}`;
|
|
}
|
|
|
|
function writeRegistry(contents: string, file = "users.yaml"): { root: string; path: string } {
|
|
const directory = root();
|
|
const path = join(directory, file);
|
|
writeFileSync(path, contents, { encoding: "utf8", mode: 0o600 });
|
|
chmodSync(path, 0o600);
|
|
return { root: directory, path };
|
|
}
|
|
|
|
async function expectInvalid(operation: Promise<unknown>, secrets: string[] = []): Promise<void> {
|
|
try {
|
|
await operation;
|
|
throw new Error("operation unexpectedly succeeded");
|
|
} catch (error) {
|
|
const message = error instanceof Error ? error.message : String(error);
|
|
expect(message).toBe("local_user_registry_invalid");
|
|
for (const secret of secrets) expect(message).not.toContain(secret);
|
|
}
|
|
}
|
|
|
|
describe("local user registry", () => {
|
|
test("reads known fields, performs case-insensitive lookup, and verifies passwords", async () => {
|
|
const fixture = writeRegistry(registryYaml(userYaml({ displayName: "Local administrator" })));
|
|
const registry = createLocalUserRegistry(fixture.path);
|
|
|
|
await expect(registry.findByUsername("aDmIn")).resolves.toMatchObject({
|
|
id: adminId,
|
|
username: "Admin",
|
|
normalizedUsername: "admin",
|
|
displayName: "Local administrator",
|
|
passwordHash,
|
|
roles: ["admin"],
|
|
enabled: true,
|
|
authRevision: 1,
|
|
});
|
|
await expect(registry.findBySubject(adminId)).resolves.toMatchObject({ username: "Admin" });
|
|
await expect(registry.verify(await registry.findByUsername("admin"), password)).resolves.toBe(true);
|
|
await expect(registry.verify(await registry.findByUsername("admin"), `${password}!`)).resolves.toBe(false);
|
|
});
|
|
|
|
test("uses a dummy verification path for unknown and disabled users", async () => {
|
|
const fixture = writeRegistry(registryYaml(userYaml() + userYaml({
|
|
id: userId,
|
|
username: "operator",
|
|
role: "user",
|
|
enabled: false,
|
|
})));
|
|
const registry = createLocalUserRegistry(fixture.path);
|
|
|
|
await expect(registry.verify(undefined, password)).resolves.toBe(false);
|
|
await expect(registry.verify(await registry.findByUsername("operator"), password)).resolves.toBe(false);
|
|
});
|
|
|
|
test("reports whether a structurally valid registry has an enabled administrator", async () => {
|
|
const admin = createLocalUserRegistry(writeRegistry(registryYaml(userYaml())).path);
|
|
const usersOnly = createLocalUserRegistry(writeRegistry(registryYaml(userYaml({ role: "user" }))).path);
|
|
const disabledAdmin = createLocalUserRegistry(writeRegistry(registryYaml(userYaml({ enabled: false }))).path);
|
|
|
|
await expect(admin.hasEnabledAdmin()).resolves.toBe(true);
|
|
await expect(usersOnly.hasEnabledAdmin()).resolves.toBe(false);
|
|
await expect(disabledAdmin.hasEnabledAdmin()).resolves.toBe(false);
|
|
await expectInvalid(usersOnly.findByUsername("admin"));
|
|
await expectInvalid(disabledAdmin.findBySubject(adminId));
|
|
});
|
|
|
|
test("rejects a valid registry under a non-private authentication directory", async () => {
|
|
const fixture = writeRegistry(registryYaml(userYaml()));
|
|
chmodSync(fixture.root, 0o750);
|
|
expect(lstatSync(fixture.root).mode & 0o7777).toBe(0o750);
|
|
|
|
await expectInvalid(createLocalUserRegistry(fixture.path).findByUsername("admin"), ["admin", passwordHash, fixture.path]);
|
|
});
|
|
|
|
test("rejects a valid registry under a symlinked authentication directory", async () => {
|
|
const outer = root();
|
|
const realDirectory = join(outer, "real-auth");
|
|
const linkedDirectory = join(outer, "linked-auth");
|
|
mkdirSync(realDirectory, { mode: 0o700 });
|
|
chmodSync(realDirectory, 0o700);
|
|
const path = join(realDirectory, "users.yaml");
|
|
writeFileSync(path, registryYaml(userYaml()), { encoding: "utf8", mode: 0o600 });
|
|
chmodSync(path, 0o600);
|
|
symlinkSync(realDirectory, linkedDirectory);
|
|
|
|
await expectInvalid(createLocalUserRegistry(join(linkedDirectory, "users.yaml")).findByUsername("admin"), ["admin", passwordHash]);
|
|
});
|
|
|
|
test.each([
|
|
["duplicate normalized usernames", registryYaml(userYaml() + userYaml({ id: userId, username: "admin" }))],
|
|
["duplicate IDs", registryYaml(userYaml() + userYaml({ username: "operator" }))],
|
|
["unknown YAML fields", `${registryYaml(userYaml())}unexpected: true\n`],
|
|
["duplicate roles", registryYaml(userYaml().replace(" - admin", " - admin\n - admin"))],
|
|
["invalid password hash", registryYaml(userYaml().replace(passwordHash, "not-a-password-hash"))],
|
|
["control character in display name", registryYaml(userYaml().replace("displayName: Admin", 'displayName: "Admin\\tUser"'))],
|
|
])("rejects %s", async (_name, contents) => {
|
|
const fixture = writeRegistry(contents);
|
|
await expectInvalid(createLocalUserRegistry(fixture.path).findByUsername("admin"), ["admin", passwordHash, fixture.path]);
|
|
});
|
|
|
|
test.each(["symlink", "hard link", "mode wider than 0600", "file larger than 1 MiB"])(
|
|
"rejects unsafe %s registry metadata",
|
|
async (kind) => {
|
|
const fixture = writeRegistry(registryYaml(userYaml()));
|
|
if (kind === "symlink") {
|
|
const target = join(fixture.root, "users-target.yaml");
|
|
renameSync(fixture.path, target);
|
|
symlinkSync(target, fixture.path);
|
|
} else if (kind === "hard link") {
|
|
linkSync(fixture.path, join(fixture.root, "users-link.yaml"));
|
|
} else if (kind === "mode wider than 0600") {
|
|
chmodSync(fixture.path, 0o640);
|
|
} else {
|
|
writeFileSync(fixture.path, "#".repeat((1 << 20) + 1), { encoding: "utf8", mode: 0o600 });
|
|
}
|
|
await expectInvalid(createLocalUserRegistry(fixture.path).findByUsername("admin"), ["admin", passwordHash, fixture.path]);
|
|
},
|
|
);
|
|
|
|
test("reloads a same-size atomic replacement with changed metadata", async () => {
|
|
const fixture = writeRegistry(registryYaml(userYaml({ displayName: "Admin" })));
|
|
const registry = createLocalUserRegistry(fixture.path);
|
|
await expect(registry.findByUsername("admin")).resolves.toMatchObject({ displayName: "Admin" });
|
|
|
|
const replacement = join(fixture.root, "replacement.yaml");
|
|
writeFileSync(replacement, registryYaml(userYaml({ displayName: "Owner" })), { encoding: "utf8", mode: 0o600 });
|
|
chmodSync(replacement, 0o600);
|
|
utimesSync(replacement, new Date("2035-01-01T00:00:00Z"), new Date("2035-01-01T00:00:00Z"));
|
|
expect(lstatSync(replacement).size).toBe(lstatSync(fixture.path).size);
|
|
renameSync(replacement, fixture.path);
|
|
|
|
await expect(registry.findByUsername("admin")).resolves.toMatchObject({ displayName: "Owner" });
|
|
});
|
|
});
|