feat(auth): add optional authentication boundary
- Add account, JWT session, revocation, cookie and bearer handling. - Protect server surfaces while preserving public health, manifest and disabled mode. - Add SQLite migration and focused server regression coverage.
This commit is contained in:
1 parent
d4bb274982
commit
de41571b5c
33 files changed
+1083
-20
No files matched your search
@@ -0,0 +1,258 @@
|
||||
import { INestApplication } from "@nestjs/common";
|
||||
import { getRepositoryToken } from "@nestjs/typeorm";
|
||||
import request from "supertest";
|
||||
import { Repository } from "typeorm";
|
||||
import { filter, firstValueFrom, timeout } from "rxjs";
|
||||
import { AuthService } from "../src/auth/auth.service";
|
||||
import { tokenHash } from "../src/auth/auth.service";
|
||||
import { PasswordService } from "../src/auth/password.service";
|
||||
import { RevokedTokenEntity } from "../src/auth/revoked-token.entity";
|
||||
import { EnvironmentService } from "../src/environment/environment.service";
|
||||
import { RunEventsService } from "../src/scenario/run-events.service";
|
||||
import { ScenarioSchedulerService } from "../src/scenario/scenario-scheduler.service";
|
||||
import { ScenarioService } from "../src/scenario/scenario.service";
|
||||
import { UserEntity } from "../src/auth/user.entity";
|
||||
import { buildTestApp } from "./app.harness";
|
||||
|
||||
function firstSetCookie(response: {
|
||||
headers: Record<string, unknown>;
|
||||
}): string {
|
||||
const value = response.headers["set-cookie"];
|
||||
return Array.isArray(value) ? String(value[0]) : String(value);
|
||||
}
|
||||
|
||||
describe("optional authentication", () => {
|
||||
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 app: INestApplication;
|
||||
let users: Repository<UserEntity>;
|
||||
let passwords: PasswordService;
|
||||
let auth: AuthService;
|
||||
let revokedTokens: Repository<RevokedTokenEntity>;
|
||||
let user: UserEntity;
|
||||
|
||||
beforeAll(async () => {
|
||||
for (const key of envKeys) previousEnv.set(key, process.env[key]);
|
||||
process.env.AUTH_ENABLED = "true";
|
||||
process.env.AUTH_JWT_SECRET = "auth-test-secret-only";
|
||||
process.env.AUTH_JWT_EXPIRES_IN = "1h";
|
||||
app = await buildTestApp();
|
||||
users = app.get<Repository<UserEntity>>(getRepositoryToken(UserEntity));
|
||||
passwords = app.get(PasswordService);
|
||||
auth = app.get(AuthService);
|
||||
revokedTokens = app.get<Repository<RevokedTokenEntity>>(
|
||||
getRepositoryToken(RevokedTokenEntity),
|
||||
);
|
||||
user = await users.save(
|
||||
users.create({
|
||||
username: "alice",
|
||||
passwordHash: await passwords.hash("correct-test-password"),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app?.close();
|
||||
for (const key of envKeys) {
|
||||
const value = previousEnv.get(key);
|
||||
if (value === undefined) delete process.env[key];
|
||||
else process.env[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps health and the secret-free auth flag public while protecting REST, MCP, and run events", async () => {
|
||||
await request(app.getHttpServer()).get("/health").expect(200);
|
||||
const manifest = await request(app.getHttpServer())
|
||||
.get("/manifest.json")
|
||||
.expect(200);
|
||||
expect(manifest.body.auth).toEqual({ enabled: true });
|
||||
expect(JSON.stringify(manifest.body)).not.toContain("AUTH_JWT_SECRET");
|
||||
expect(JSON.stringify(manifest.body)).not.toContain(
|
||||
"auth-test-secret-only",
|
||||
);
|
||||
|
||||
await request(app.getHttpServer()).get("/scenarios").expect(401);
|
||||
await request(app.getHttpServer())
|
||||
.get("/scenarios/runs/events")
|
||||
.expect(401);
|
||||
await request(app.getHttpServer())
|
||||
.post("/mcp")
|
||||
.send({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} })
|
||||
.expect(401);
|
||||
});
|
||||
|
||||
it("continues processing scheduled scenarios without an HTTP credential", async () => {
|
||||
const environments = app.get(EnvironmentService);
|
||||
const scenarios = app.get(ScenarioService);
|
||||
const scheduler = app.get(ScenarioSchedulerService);
|
||||
const events = app.get(RunEventsService);
|
||||
const environment = await environments.create({
|
||||
name: "auth-scheduler-environment",
|
||||
data: {},
|
||||
});
|
||||
const scenario = await scenarios.create({
|
||||
name: "auth-scheduler-scenario",
|
||||
});
|
||||
await scenarios.createStep(scenario.id, {
|
||||
title: "Return a value",
|
||||
execCode: "return 1;",
|
||||
});
|
||||
const run = await scenarios.createRun(scenario.id, environment.id);
|
||||
const finished = firstValueFrom(
|
||||
events.stream().pipe(
|
||||
filter(
|
||||
(event) => event.type === "run.finished" && event.runId === run.id,
|
||||
),
|
||||
timeout({ first: 5000 }),
|
||||
),
|
||||
);
|
||||
|
||||
await scheduler.pickUpPendingRuns();
|
||||
await finished;
|
||||
expect((await scenarios.findRun(scenario.id, run.id)).status).toBe("pass");
|
||||
});
|
||||
|
||||
it("logs in with a strict HttpOnly cookie and returns only safe identity fields", async () => {
|
||||
const response = await request(app.getHttpServer())
|
||||
.post("/auth/login")
|
||||
.set("x-forwarded-proto", "https")
|
||||
.send({ username: "alice", password: "correct-test-password" })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.user).toMatchObject({
|
||||
id: user.id,
|
||||
username: "alice",
|
||||
});
|
||||
expect(response.body.user.passwordHash).toBeUndefined();
|
||||
expect(response.body.token).toBeUndefined();
|
||||
expect(JSON.stringify(response.body)).not.toContain(
|
||||
"correct-test-password",
|
||||
);
|
||||
const cookie = firstSetCookie(response);
|
||||
expect(cookie).toContain("HttpOnly");
|
||||
expect(cookie).toContain("SameSite=Strict");
|
||||
expect(cookie).toContain("Secure");
|
||||
expect(cookie).toContain("Max-Age=");
|
||||
});
|
||||
|
||||
it("rejects unknown or incorrect credentials without returning account data", async () => {
|
||||
for (const username of ["alice", "missing-user"]) {
|
||||
const response = await request(app.getHttpServer())
|
||||
.post("/auth/login")
|
||||
.send({ username, password: "wrong-test-password" })
|
||||
.expect(401);
|
||||
expect(JSON.stringify(response.body)).not.toContain("passwordHash");
|
||||
expect(JSON.stringify(response.body)).not.toContain(
|
||||
"wrong-test-password",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("accepts cookie and Bearer credentials and keeps the password hash private", async () => {
|
||||
const login = await request(app.getHttpServer())
|
||||
.post("/auth/login")
|
||||
.send({ username: "alice", password: "correct-test-password" })
|
||||
.expect(200);
|
||||
const cookiePair = firstSetCookie(login).split(";")[0];
|
||||
const token = decodeURIComponent(
|
||||
cookiePair.slice(cookiePair.indexOf("=") + 1),
|
||||
);
|
||||
|
||||
const cookieMe = await request(app.getHttpServer())
|
||||
.get("/auth/me")
|
||||
.set("Cookie", cookiePair)
|
||||
.expect(200);
|
||||
expect(cookieMe.body).toMatchObject({ id: user.id, username: "alice" });
|
||||
expect(cookieMe.body.passwordHash).toBeUndefined();
|
||||
await request(app.getHttpServer())
|
||||
.get("/scenarios")
|
||||
.set("Cookie", cookiePair)
|
||||
.expect(200);
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.get("/scenarios")
|
||||
.set("Authorization", `Bearer ${token}`)
|
||||
.expect(200);
|
||||
|
||||
const mcp = await request(app.getHttpServer())
|
||||
.post("/mcp")
|
||||
.set("Authorization", `Bearer ${token}`)
|
||||
.set("Content-Type", "application/json")
|
||||
.set("Accept", "application/json, text/event-stream")
|
||||
.send({
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
method: "initialize",
|
||||
params: {
|
||||
protocolVersion: "2024-11-05",
|
||||
capabilities: {},
|
||||
clientInfo: { name: "auth-test", version: "0" },
|
||||
},
|
||||
})
|
||||
.expect(200);
|
||||
expect(mcp.text).toContain("protocolVersion");
|
||||
});
|
||||
|
||||
it("rejects tampered and expired tokens and deleted users", async () => {
|
||||
const valid = auth.issueToken(user).token;
|
||||
const tampered = `${valid.slice(0, -2)}${valid.endsWith("A") ? "B" : "A"}A`;
|
||||
await request(app.getHttpServer())
|
||||
.get("/auth/me")
|
||||
.set("Authorization", `Bearer ${tampered}`)
|
||||
.expect(401);
|
||||
|
||||
const now = Date.now();
|
||||
const oldClock = jest
|
||||
.spyOn(Date, "now")
|
||||
.mockReturnValue(now - 2 * 3600_000);
|
||||
const expired = auth.issueToken(user).token;
|
||||
oldClock.mockRestore();
|
||||
await request(app.getHttpServer())
|
||||
.get("/auth/me")
|
||||
.set("Authorization", `Bearer ${expired}`)
|
||||
.expect(401);
|
||||
|
||||
const removedUser = await users.save(
|
||||
users.create({
|
||||
username: "deleted-user",
|
||||
passwordHash: await passwords.hash("temporary-test-password"),
|
||||
}),
|
||||
);
|
||||
const deletedUserToken = auth.issueToken(removedUser).token;
|
||||
await users.delete({ id: removedUser.id });
|
||||
await request(app.getHttpServer())
|
||||
.get("/auth/me")
|
||||
.set("Authorization", `Bearer ${deletedUserToken}`)
|
||||
.expect(401);
|
||||
});
|
||||
|
||||
it("persists only the token digest on logout and rejects token reuse", async () => {
|
||||
const login = await request(app.getHttpServer())
|
||||
.post("/auth/login")
|
||||
.send({ username: "alice", password: "correct-test-password" })
|
||||
.expect(200);
|
||||
const cookiePair = firstSetCookie(login).split(";")[0];
|
||||
const token = decodeURIComponent(
|
||||
cookiePair.slice(cookiePair.indexOf("=") + 1),
|
||||
);
|
||||
const logout = await request(app.getHttpServer())
|
||||
.post("/auth/logout")
|
||||
.set("Cookie", cookiePair)
|
||||
.expect(204);
|
||||
|
||||
expect(firstSetCookie(logout)).toContain("Max-Age=0");
|
||||
const storedRevocation = await revokedTokens.findOneBy({
|
||||
tokenHash: tokenHash(token),
|
||||
});
|
||||
expect(storedRevocation?.tokenHash).not.toBe(token);
|
||||
await request(app.getHttpServer())
|
||||
.get("/scenarios")
|
||||
.set("Authorization", `Bearer ${token}`)
|
||||
.expect(401);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user