72 lines
2.3 KiB
TypeScript
72 lines
2.3 KiB
TypeScript
import { afterEach, describe, expect, test } from "bun:test";
|
|
import { mkdtemp, readFile, rm, stat } from "node:fs/promises";
|
|
import { join } from "node:path";
|
|
import { tmpdir } from "node:os";
|
|
import {
|
|
getSessionPath,
|
|
readSession,
|
|
removeSessions,
|
|
writeSession,
|
|
type KuberSession,
|
|
} from "../../lib/session";
|
|
|
|
const originalRuntimeDirectory = process.env.XDG_RUNTIME_DIR;
|
|
const originalConfigDirectory = process.env.XDG_CONFIG_HOME;
|
|
const directories: string[] = [];
|
|
|
|
async function setupDirectories(): Promise<void> {
|
|
const root = await mkdtemp(join(tmpdir(), "kuber-session-test-"));
|
|
directories.push(root);
|
|
process.env.XDG_RUNTIME_DIR = join(root, "runtime");
|
|
process.env.XDG_CONFIG_HOME = join(root, "config");
|
|
}
|
|
|
|
afterEach(async () => {
|
|
if (originalRuntimeDirectory === undefined)
|
|
delete process.env.XDG_RUNTIME_DIR;
|
|
else process.env.XDG_RUNTIME_DIR = originalRuntimeDirectory;
|
|
if (originalConfigDirectory === undefined) delete process.env.XDG_CONFIG_HOME;
|
|
else process.env.XDG_CONFIG_HOME = originalConfigDirectory;
|
|
await Promise.all(
|
|
directories
|
|
.splice(0)
|
|
.map((path) => rm(path, { recursive: true, force: true })),
|
|
);
|
|
});
|
|
|
|
describe("API sessions", () => {
|
|
const session: KuberSession = {
|
|
token: "token",
|
|
expiresAt: "2999-01-01T00:00:00.000Z",
|
|
user: { username: "dmgnr", roles: ["admin"] },
|
|
};
|
|
|
|
test("writes runtime sessions with private permissions", async () => {
|
|
await setupDirectories();
|
|
const path = await writeSession(session, false);
|
|
expect(path).toBe(getSessionPath(false));
|
|
expect((await stat(path)).mode & 0o777).toBe(0o600);
|
|
expect(JSON.parse(await readFile(path, "utf8"))).toEqual(session);
|
|
expect(await readSession()).toEqual(session);
|
|
});
|
|
|
|
test("selects persistent storage and removes the other session", async () => {
|
|
await setupDirectories();
|
|
await writeSession(session, false);
|
|
const path = await writeSession(session, true);
|
|
expect(path).toBe(getSessionPath(true));
|
|
expect(await readSession()).toEqual(session);
|
|
await removeSessions();
|
|
expect(await readSession()).toBeUndefined();
|
|
});
|
|
|
|
test("discards expired sessions", async () => {
|
|
await setupDirectories();
|
|
await writeSession(
|
|
{ ...session, expiresAt: "2000-01-01T00:00:00.000Z" },
|
|
false,
|
|
);
|
|
expect(await readSession()).toBeUndefined();
|
|
});
|
|
});
|