Merge pull request 'test(auth): cover integrated account journey' (#6) from feat/task-57-auth-integration into master
Reviewed-on: agent-codex/liqa#6
This commit is contained in:
commit
ff9a700c86
2 files changed
+294
-2
No files matched your search
@@ -50,7 +50,9 @@ import { LoggingInterceptor } from "../src/interceptors/logging.interceptor";
|
||||
import { validateAppConfig } from "../src/config/app.config";
|
||||
import { AuthModule } from "../src/auth/auth.module";
|
||||
|
||||
export async function buildTestApp(): Promise<INestApplication> {
|
||||
export async function buildTestApp(
|
||||
databasePath = ":memory:",
|
||||
): Promise<INestApplication> {
|
||||
// Each test app stores files in its own temp dir: suites run in parallel and
|
||||
// some clean up their files dir, which must not affect other suites.
|
||||
const filesDir = fs.mkdtempSync(path.join(os.tmpdir(), "liqa-test-files-"));
|
||||
@@ -65,7 +67,7 @@ export async function buildTestApp(): Promise<INestApplication> {
|
||||
}),
|
||||
// The real migrations, not synchronize, so tests use the schema production gets
|
||||
TypeOrmModule.forRoot({
|
||||
...dataSourceOptions(":memory:"),
|
||||
...dataSourceOptions(databasePath),
|
||||
migrationsRun: true,
|
||||
}),
|
||||
ScheduleModule.forRoot(),
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
import { INestApplication } from "@nestjs/common";
|
||||
import { getRepositoryToken } from "@nestjs/typeorm";
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
import { DataSource, Repository } from "typeorm";
|
||||
import request from "supertest";
|
||||
import { EnvironmentService } from "../src/environment/environment.service";
|
||||
import { ScenarioSchedulerService } from "../src/scenario/scenario-scheduler.service";
|
||||
import { ScenarioService } from "../src/scenario/scenario.service";
|
||||
import { PasswordService } from "../src/auth/password.service";
|
||||
import { UserEntity } from "../src/auth/user.entity";
|
||||
import {
|
||||
OperatorCliInput,
|
||||
runOperatorCommand,
|
||||
} from "../src/operator-cli/operator-cli";
|
||||
import { buildTestApp } from "./app.harness";
|
||||
|
||||
const AUTH_SECRET = "synthetic-integration-secret-for-tests";
|
||||
const USER_PASSWORD = "synthetic-integration-password";
|
||||
|
||||
function cookiePair(response: request.Response): string {
|
||||
const cookies = response.headers["set-cookie"];
|
||||
if (!Array.isArray(cookies) || typeof cookies[0] !== "string") {
|
||||
throw new Error("Login response did not set an auth cookie");
|
||||
}
|
||||
return cookies[0].split(";")[0];
|
||||
}
|
||||
|
||||
function cookieToken(cookie: string): string {
|
||||
return decodeURIComponent(cookie.slice(cookie.indexOf("=") + 1));
|
||||
}
|
||||
|
||||
function cliInput(): OperatorCliInput {
|
||||
const lines = ["integration-user"];
|
||||
const secrets = [USER_PASSWORD, USER_PASSWORD];
|
||||
return {
|
||||
line: async () => lines.shift() ?? "",
|
||||
secret: async () => secrets.shift() ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
describe("authentication integration journey", () => {
|
||||
const envKeys = [
|
||||
"AUTH_ENABLED",
|
||||
"AUTH_JWT_SECRET",
|
||||
"AUTH_JWT_EXPIRES_IN",
|
||||
"AUTH_REVOKED_TOKEN_CLEANUP_CRON",
|
||||
] as const;
|
||||
const previousEnv = new Map<string, string | undefined>();
|
||||
let directory: string;
|
||||
let databasePath: string;
|
||||
let app: INestApplication;
|
||||
|
||||
beforeAll(async () => {
|
||||
for (const key of envKeys) previousEnv.set(key, process.env[key]);
|
||||
process.env.AUTH_ENABLED = "true";
|
||||
process.env.AUTH_JWT_SECRET = AUTH_SECRET;
|
||||
process.env.AUTH_JWT_EXPIRES_IN = "1h";
|
||||
process.env.AUTH_REVOKED_TOKEN_CLEANUP_CRON = "0 3 * * *";
|
||||
directory = fs.mkdtempSync(path.join(os.tmpdir(), "liqa-auth-e2e-"));
|
||||
databasePath = path.join(directory, "liqa.db");
|
||||
app = await buildTestApp(databasePath);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app?.close();
|
||||
if (directory) fs.rmSync(directory, { recursive: true, force: true });
|
||||
for (const key of envKeys) {
|
||||
const value = previousEnv.get(key);
|
||||
if (value === undefined) delete process.env[key];
|
||||
else process.env[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
it("carries a CLI-created account through login, protected APIs, events, logout and deletion", async () => {
|
||||
const dataSource = app.get(DataSource);
|
||||
const passwords = app.get(PasswordService);
|
||||
await runOperatorCommand(["user:create"], {
|
||||
dataSource,
|
||||
config: {
|
||||
AUTH_ENABLED: true,
|
||||
AUTH_JWT_SECRET: AUTH_SECRET,
|
||||
AUTH_JWT_EXPIRES_IN: "1h",
|
||||
},
|
||||
passwords,
|
||||
input: cliInput(),
|
||||
output: { write: () => undefined },
|
||||
});
|
||||
|
||||
const users = app.get<Repository<UserEntity>>(
|
||||
getRepositoryToken(UserEntity),
|
||||
);
|
||||
const createdUser = await users.findOneByOrFail({
|
||||
username: "integration-user",
|
||||
});
|
||||
expect(createdUser.passwordHash).not.toBe(USER_PASSWORD);
|
||||
|
||||
const listener = await app.listen(0, "127.0.0.1");
|
||||
const address = listener.address();
|
||||
if (!address || typeof address === "string") {
|
||||
throw new Error("Could not determine ephemeral test server port");
|
||||
}
|
||||
|
||||
const login = await request(app.getHttpServer())
|
||||
.post("/auth/login")
|
||||
.send({ username: "integration-user", password: USER_PASSWORD })
|
||||
.expect(200);
|
||||
expect(login.body.user).toMatchObject({
|
||||
id: createdUser.id,
|
||||
username: "integration-user",
|
||||
});
|
||||
const cookie = cookiePair(login);
|
||||
const token = cookieToken(cookie);
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.get("/auth/me")
|
||||
.set("Cookie", cookie)
|
||||
.expect(200)
|
||||
.then(({ body }) => expect(body.id).toBe(createdUser.id));
|
||||
await request(app.getHttpServer())
|
||||
.get("/scenarios")
|
||||
.set("Authorization", `Bearer ${token}`)
|
||||
.expect(200);
|
||||
|
||||
const mcpRequest = {
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
method: "initialize",
|
||||
params: {
|
||||
protocolVersion: "2024-11-05",
|
||||
capabilities: {},
|
||||
clientInfo: { name: "auth-integration-test", version: "1" },
|
||||
},
|
||||
};
|
||||
for (const credential of [
|
||||
{ name: "Cookie", value: cookie },
|
||||
{ name: "Authorization", value: `Bearer ${token}` },
|
||||
]) {
|
||||
await request(app.getHttpServer())
|
||||
.post("/mcp")
|
||||
.set(credential.name, credential.value)
|
||||
.set("Content-Type", "application/json")
|
||||
.set("Accept", "application/json, text/event-stream")
|
||||
.send(mcpRequest)
|
||||
.expect(200);
|
||||
}
|
||||
|
||||
const abort = new AbortController();
|
||||
const eventResponse = await fetch(
|
||||
`http://127.0.0.1:${address.port}/scenarios/runs/events`,
|
||||
{
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
signal: abort.signal,
|
||||
},
|
||||
);
|
||||
expect(eventResponse.status).toBe(200);
|
||||
expect(eventResponse.headers.get("content-type")).toContain(
|
||||
"text/event-stream",
|
||||
);
|
||||
|
||||
const scenarios = app.get(ScenarioService);
|
||||
const environments = app.get(EnvironmentService);
|
||||
const scheduler = app.get(ScenarioSchedulerService);
|
||||
const scenario = await scenarios.create({ name: "auth integration run" });
|
||||
await scenarios.createStep(scenario.id, {
|
||||
title: "Return a deterministic result",
|
||||
execCode: "return 'integration-ok';",
|
||||
});
|
||||
const environment = await environments.create({
|
||||
name: "auth integration environment",
|
||||
data: {},
|
||||
});
|
||||
const run = await scenarios.createRun(scenario.id, environment.id);
|
||||
await scheduler.pickUpPendingRuns();
|
||||
|
||||
const reader = eventResponse.body?.getReader();
|
||||
if (!reader) throw new Error("Run events response has no readable body");
|
||||
let eventText = "";
|
||||
const readFinishedEvent = async () => {
|
||||
const decoder = new TextDecoder();
|
||||
while (
|
||||
!eventText.includes(`"runId":"${run.id}"`) ||
|
||||
!eventText.includes("event: run.finished")
|
||||
) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) throw new Error("Run events stream closed before completion");
|
||||
eventText += decoder.decode(value, { stream: true });
|
||||
}
|
||||
return eventText;
|
||||
};
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
const output = await Promise.race([
|
||||
readFinishedEvent(),
|
||||
new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(
|
||||
() => reject(new Error("Timed out waiting for run.finished SSE")),
|
||||
5000,
|
||||
);
|
||||
}),
|
||||
]);
|
||||
expect(output).toContain("event: run.started");
|
||||
expect(output).toContain("event: run.finished");
|
||||
expect(output).toContain(`"runId":"${run.id}"`);
|
||||
expect(output).toContain('"status":"pass"');
|
||||
} finally {
|
||||
if (timer) clearTimeout(timer);
|
||||
abort.abort();
|
||||
await reader.cancel().catch(() => undefined);
|
||||
}
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.post("/auth/logout")
|
||||
.set("Cookie", cookie)
|
||||
.expect(204);
|
||||
await request(app.getHttpServer())
|
||||
.get("/scenarios")
|
||||
.set("Cookie", cookie)
|
||||
.expect(401);
|
||||
await request(app.getHttpServer())
|
||||
.get("/scenarios")
|
||||
.set("Authorization", `Bearer ${token}`)
|
||||
.expect(401);
|
||||
|
||||
const deletionInput = {
|
||||
line: async () => "delete-user",
|
||||
secret: async () => USER_PASSWORD,
|
||||
};
|
||||
await runOperatorCommand(["user:create"], {
|
||||
dataSource,
|
||||
config: {
|
||||
AUTH_ENABLED: true,
|
||||
AUTH_JWT_SECRET: AUTH_SECRET,
|
||||
AUTH_JWT_EXPIRES_IN: "1h",
|
||||
},
|
||||
passwords,
|
||||
input: deletionInput,
|
||||
output: { write: () => undefined },
|
||||
});
|
||||
const deletionLogin = await request(app.getHttpServer())
|
||||
.post("/auth/login")
|
||||
.send({ username: "delete-user", password: USER_PASSWORD })
|
||||
.expect(200);
|
||||
const deletionCookie = cookiePair(deletionLogin);
|
||||
const deletionToken = cookieToken(deletionCookie);
|
||||
await runOperatorCommand(["user:delete", "delete-user"], {
|
||||
dataSource,
|
||||
config: {
|
||||
AUTH_ENABLED: true,
|
||||
AUTH_JWT_SECRET: AUTH_SECRET,
|
||||
AUTH_JWT_EXPIRES_IN: "1h",
|
||||
},
|
||||
passwords,
|
||||
input: deletionInput,
|
||||
output: { write: () => undefined },
|
||||
});
|
||||
await request(app.getHttpServer())
|
||||
.get("/scenarios")
|
||||
.set("Cookie", deletionCookie)
|
||||
.expect(401);
|
||||
await request(app.getHttpServer())
|
||||
.get("/scenarios")
|
||||
.set("Authorization", `Bearer ${deletionToken}`)
|
||||
.expect(401);
|
||||
|
||||
const migrationsBeforeRestart = await dataSource.query(
|
||||
"SELECT timestamp FROM migrations ORDER BY timestamp",
|
||||
);
|
||||
await app.close();
|
||||
app = await buildTestApp(databasePath);
|
||||
const reopenedDataSource = app.get(DataSource);
|
||||
expect(await reopenedDataSource.showMigrations()).toBe(false);
|
||||
await expect(
|
||||
reopenedDataSource.query(
|
||||
"SELECT timestamp FROM migrations ORDER BY timestamp",
|
||||
),
|
||||
).resolves.toEqual(migrationsBeforeRestart);
|
||||
await expect(
|
||||
reopenedDataSource
|
||||
.getRepository(UserEntity)
|
||||
.findOneBy({ username: "integration-user" }),
|
||||
).resolves.toMatchObject({ username: "integration-user" });
|
||||
await expect(
|
||||
reopenedDataSource
|
||||
.getRepository(UserEntity)
|
||||
.findOneBy({ username: "delete-user" }),
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user