Files
liqa/server/test/operator-cli.spec.ts
T
agent 768a799db0 feat(auth): add operator account CLI
- Add local and container-ready user management and token commands.
- Document setup and verify commands against an isolated database.
2026-11-09 14:31:29 -05:00

244 lines
8.0 KiB
TypeScript

import { EventEmitter } from "node:events";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { DataSource } from "typeorm";
import { AuthService } from "../src/auth/auth.service";
import { AuthFailure } from "../src/auth/auth.error";
import { PasswordService } from "../src/auth/password.service";
import { UserEntity } from "../src/auth/user.entity";
import { RevokedTokenEntity } from "../src/auth/revoked-token.entity";
import { verifyJwt } from "../src/auth/jwt.helpers";
import { dataSourceOptions } from "../src/database/data-source";
import {
OperatorCliContext,
OperatorCliInput,
OperatorCliOutput,
runOperatorCommand,
} from "../src/operator-cli/operator-cli";
import { RawInput, readHiddenInput } from "../src/operator-cli/hidden-input";
const SECRET = "operator-cli-test-secret";
describe("operator account CLI", () => {
let directory: string;
let dataSource: DataSource;
let passwords: PasswordService;
const output: string[] = [];
const config = {
AUTH_ENABLED: true,
AUTH_JWT_SECRET: SECRET,
AUTH_JWT_EXPIRES_IN: "24h",
} as const;
function context(input: OperatorCliInput): OperatorCliContext {
const outputWriter: OperatorCliOutput = {
write: (message) => output.push(message),
};
return { dataSource, config, passwords, input, output: outputWriter };
}
function prompts(
lines: string[] = [],
secrets: string[] = [],
): OperatorCliInput {
return {
line: jest.fn(async () => lines.shift() ?? ""),
secret: jest.fn(async () => secrets.shift() ?? ""),
};
}
beforeAll(async () => {
directory = fs.mkdtempSync(path.join(os.tmpdir(), "liqa-operator-cli-"));
dataSource = new DataSource({
...dataSourceOptions(path.join(directory, "custom.db")),
migrationsRun: true,
});
await dataSource.initialize();
passwords = new PasswordService();
});
afterAll(async () => {
await dataSource?.destroy();
fs.rmSync(directory, { recursive: true, force: true });
});
beforeEach(() => output.splice(0));
it("creates an account with matching hidden passwords and prints only safe identity data", async () => {
const input = prompts(
[" alice "],
["correct horse battery staple", "correct horse battery staple"],
);
await runOperatorCommand(["user:create"], context(input));
const user = await dataSource
.getRepository(UserEntity)
.findOneBy({ username: "alice" });
expect(user).not.toBeNull();
expect(user?.passwordHash).not.toContain("correct horse battery staple");
expect(output.join("")).toContain('Created user "alice".');
output.splice(0);
await runOperatorCommand(["user:get", "alice"], context(prompts()));
const details = JSON.parse(output.join("")) as Record<string, unknown>;
expect(details).toMatchObject({ id: user?.id, username: "alice" });
expect(details.passwordHash).toBeUndefined();
expect(JSON.stringify(details)).not.toContain(
"correct horse battery staple",
);
});
it("rejects duplicate, empty and mismatched credentials without creating accounts", async () => {
const users = dataSource.getRepository(UserEntity);
const initialCount = await users.count();
await expect(
runOperatorCommand(["user:create"], context(prompts(["alice"], []))),
).rejects.toThrow("already exists");
await expect(
runOperatorCommand(["user:create"], context(prompts([" "], []))),
).rejects.toThrow("Username cannot be empty");
await expect(
runOperatorCommand(["user:create"], context(prompts(["bob"], ["", ""]))),
).rejects.toThrow("Password cannot be empty");
await expect(
runOperatorCommand(
["user:create"],
context(prompts(["bob"], ["first secret", "different secret"])),
),
).rejects.toThrow("Passwords do not match");
expect(await users.count()).toBe(initialCount);
expect(output.join("")).not.toContain("first secret");
expect(output.join("")).not.toContain("different secret");
});
it("issues default and custom duration JWTs accepted by the auth service, then deletion invalidates them", async () => {
const users = dataSource.getRepository(UserEntity);
const user = await users.findOneByOrFail({ username: "alice" });
await runOperatorCommand(["user:token", "alice"], context(prompts()));
const defaultLines = output.join("").trim().split("\n");
const defaultToken = defaultLines[defaultLines.length - 1];
const defaultClaims = verifyJwt(defaultToken, SECRET);
expect(defaultClaims.sub).toBe(user.id);
expect(defaultClaims.exp - defaultClaims.iat).toBe(86400);
output.splice(0);
await runOperatorCommand(
["user:token", "alice", "30m"],
context(prompts()),
);
const customLines = output.join("").trim().split("\n");
const customToken = customLines[customLines.length - 1];
const customClaims = verifyJwt(customToken, SECRET);
expect(customClaims.exp - customClaims.iat).toBe(1800);
const auth = new AuthService(
users,
dataSource.getRepository(RevokedTokenEntity),
{
get: (key: string) =>
({
AUTH_ENABLED: true,
AUTH_COOKIE_NAME: "liqa_auth",
AUTH_JWT_EXPIRES_IN: "24h",
AUTH_JWT_SECRET: SECRET,
})[key],
} as never,
passwords,
);
expect((await auth.authenticate(customToken)).user.id).toBe(user.id);
await runOperatorCommand(["user:delete", "alice"], context(prompts()));
expect(await users.findOneBy({ id: user.id })).toBeNull();
await expect(auth.authenticate(customToken)).rejects.toMatchObject({
reason: "invalid-token",
} satisfies Partial<AuthFailure>);
});
it("rejects unknown targets, bad durations, and disabled account management", async () => {
for (const command of ["user:get", "user:delete", "user:token"]) {
await expect(
runOperatorCommand([command, "missing"], context(prompts())),
).rejects.toThrow("No account found");
}
await expect(
runOperatorCommand(["user:token", "missing", "30m"], context(prompts())),
).rejects.toThrow("No account found");
const user = await dataSource.getRepository(UserEntity).save(
dataSource.getRepository(UserEntity).create({
username: "duration-check",
passwordHash: await passwords.hash("test password"),
}),
);
await expect(
runOperatorCommand(
["user:token", user.username, "0h"],
context(prompts()),
),
).rejects.toThrow("Duration must be a positive number");
await expect(
runOperatorCommand(["user:get", user.username], {
...context(prompts()),
config: { ...config, AUTH_ENABLED: false },
}),
).rejects.toThrow("require AUTH_ENABLED=true");
});
});
describe("hidden password input", () => {
class FakeRawInput extends EventEmitter {
isTTY = true;
isRaw = false;
modes: boolean[] = [];
setRawMode(mode: boolean): this {
this.isRaw = mode;
this.modes.push(mode);
return this;
}
pause(): this {
return this;
}
resume(): this {
return this;
}
}
it("collects input without echoing the password and restores terminal mode", async () => {
const input = new FakeRawInput();
let shown = "";
const read = readHiddenInput(
input as unknown as RawInput,
{
write: (value: string) => {
shown += value;
return true;
},
},
"Password: ",
);
input.emit("data", Buffer.from("private-password\r"));
await expect(read).resolves.toBe("private-password");
expect(shown).toBe("Password: \n");
expect(shown).not.toContain("private-password");
expect(input.modes).toEqual([true, false]);
});
it("rejects secret prompts without a terminal", async () => {
const input = new FakeRawInput();
input.isTTY = false;
await expect(
readHiddenInput(
input as unknown as RawInput,
{ write: () => true },
"Password: ",
),
).rejects.toThrow("requires an interactive terminal");
});
});