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:
agent committed 2026-11-04 15:43:33 -05:00
1 parent d4bb274982
commit de41571b5c
33 files changed
+1083 -20

No files matched your search

+2
View File
@@ -48,6 +48,7 @@ import { ManifestController } from "../src/manifest/manifest.controller";
import { HttpExceptionFilter } from "../src/filters/http-exception.filter";
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> {
// Each test app stores files in its own temp dir: suites run in parallel and
@@ -69,6 +70,7 @@ export async function buildTestApp(): Promise<INestApplication> {
}),
ScheduleModule.forRoot(),
BrowserModule,
AuthModule,
SessionModule,
EnvironmentModule,
ScenarioModule,
+54
View File
@@ -0,0 +1,54 @@
import "reflect-metadata";
import {
authDurationSeconds,
validateAppConfig,
} from "../src/config/app.config";
describe("Authentication configuration", () => {
it("defaults authentication off with a 24-hour token lifetime and cleanup schedule", () => {
const config = validateAppConfig({});
expect(config.AUTH_ENABLED).toBe(false);
expect(config.AUTH_JWT_EXPIRES_IN).toBe("24h");
expect(config.AUTH_REVOKED_TOKEN_CLEANUP_CRON).toBe("0 3 * * *");
});
it("parses explicit true and false values without JavaScript truthiness", () => {
expect(validateAppConfig({ AUTH_ENABLED: "false" }).AUTH_ENABLED).toBe(
false,
);
expect(
validateAppConfig({ AUTH_ENABLED: "true", AUTH_JWT_SECRET: "test" })
.AUTH_ENABLED,
).toBe(true);
});
it("requires a signing secret and usable token lifetime only when enabled", () => {
expect(() => validateAppConfig({ AUTH_ENABLED: "true" })).toThrow(
"AUTH_JWT_SECRET must be set when AUTH_ENABLED=true",
);
expect(() =>
validateAppConfig({
AUTH_ENABLED: "true",
AUTH_JWT_SECRET: "test",
AUTH_JWT_EXPIRES_IN: "0h",
}),
).toThrow("AUTH_JWT_EXPIRES_IN must be a positive duration");
expect(
validateAppConfig({
AUTH_ENABLED: "false",
AUTH_JWT_EXPIRES_IN: "invalid",
}).AUTH_ENABLED,
).toBe(false);
});
it("rejects non-boolean auth settings and parses common positive durations", () => {
expect(() => validateAppConfig({ AUTH_ENABLED: "yes" })).toThrow(
"AUTH_ENABLED must be either true or false",
);
expect(authDurationSeconds("30m")).toBe(1800);
expect(authDurationSeconds("24h")).toBe(86400);
expect(authDurationSeconds("2d")).toBe(172800);
expect(authDurationSeconds("0s")).toBeNull();
});
});
+34
View File
@@ -0,0 +1,34 @@
import { INestApplication } from "@nestjs/common";
import request from "supertest";
import { buildTestApp } from "./app.harness";
describe("authentication disabled", () => {
const envKeys = ["AUTH_ENABLED", "AUTH_JWT_SECRET"] as const;
const previousEnv = new Map<string, string | undefined>();
let app: INestApplication;
beforeAll(async () => {
for (const key of envKeys) previousEnv.set(key, process.env[key]);
process.env.AUTH_ENABLED = "false";
delete process.env.AUTH_JWT_SECRET;
app = await buildTestApp();
});
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("starts without a secret and leaves existing REST behavior public", async () => {
await request(app.getHttpServer()).get("/scenarios").expect(200);
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: false });
});
});
+258
View File
@@ -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);
});
});
+16
View File
@@ -0,0 +1,16 @@
import { redactAuthRequestBody } from "../src/interceptors/logging.interceptor";
describe("redactAuthRequestBody", () => {
it("redacts login passwords on local and API-prefixed route paths", () => {
const body = { username: "operator", password: "synthetic-secret" };
expect(redactAuthRequestBody("/auth/login", body)).toEqual({
username: "operator",
password: "[REDACTED]",
});
expect(redactAuthRequestBody("/api/v1/auth/login", body)).toEqual({
username: "operator",
password: "[REDACTED]",
});
expect(redactAuthRequestBody("/api/v1/scenarios", body)).toBe(body);
});
});
+1
View File
@@ -21,6 +21,7 @@ describe("GET /manifest.json", () => {
expect(res.body).toEqual({
name: appPackage().name,
version: appPackage().version,
auth: { enabled: false },
runLogs: { dataLimits: { bytes: 256, lines: 5 } },
});
expect(res.headers["cache-control"]).toBe("no-cache");