feat(auth): deliver optional authentication across Liqa #24

Merged
ars9 merged 16 commits from agent-codex/liqa:master into master 2026-11-11 19:35:12 +02:00
40 changed files with 1322 additions and 20 deletions
Showing only changes of commit c3e8670515 - Show all commits

No files matched your search

+2
View File
@@ -4,6 +4,7 @@ import { ScheduleModule } from "@nestjs/schedule";
import { ServeStaticModule } from "@nestjs/serve-static";
import { TypeOrmModule } from "@nestjs/typeorm";
import { BrowserModule } from "./browser/browser.module";
import { AuthModule } from "./auth/auth.module";
import { clientStaticOptions } from "./common/client-static";
import { dataSourceOptions } from "./database/data-source";
import { AppConfig, validateAppConfig } from "./config/app.config";
@@ -36,6 +37,7 @@ import { SnippetModule } from "./snippet/snippet.module";
dataSourceOptions(config.get("DB_PATH")),
}),
BrowserModule,
AuthModule,
EnvironmentModule,
CredentialModule,
ScenarioModule,
+1
View File
@@ -0,0 +1 @@
export const AUTH_COOKIE_NAME = "liqa_auth";
+112
View File
@@ -0,0 +1,112 @@
import {
Body,
Controller,
Get,
HttpCode,
NotFoundException,
Post,
Req,
Res,
UnauthorizedException,
} from "@nestjs/common";
import {
ApiBearerAuth,
ApiOperation,
ApiResponse,
ApiTags,
} from "@nestjs/swagger";
import type { Request, Response } from "express";
import { AuthenticatedRequest } from "./auth.guard";
import { AuthService, AuthSession, SafeUser } from "./auth.service";
import { Public } from "./public.decorator";
import { LoginDto } from "./dto/login.dto";
import {
clearedSessionCookie,
loginResponse,
sessionCookie,
sessionUser,
} from "./auth.helpers";
import { AuthFailure } from "./auth.error";
import { LoginResponseDto, SafeUserDto } from "./dto/auth-response.dto";
@ApiTags("auth")
@Controller("auth")
export class AuthController {
constructor(private readonly auth: AuthService) {}
@Post("login")
@HttpCode(200)
@Public()
@ApiOperation({ summary: "Sign in and start a browser session" })
@ApiResponse({
status: 200,
description: "Signed in; session cookie set",
type: LoginResponseDto,
})
@ApiResponse({ status: 401, description: "Invalid username or password" })
async login(
@Body() dto: LoginDto,
@Req() request: Request,
@Res({ passthrough: true }) response: Response,
): Promise<{ user: SafeUser }> {
if (!this.auth.enabled)
throw new NotFoundException("Authentication is disabled.");
let session: AuthSession;
try {
session = await this.auth.login(dto.username, dto.password);
} catch (error) {
if (error instanceof AuthFailure && error.reason === "disabled") {
throw new NotFoundException("Authentication is disabled.");
}
if (
error instanceof AuthFailure &&
error.reason === "invalid-credentials"
) {
throw new UnauthorizedException("Invalid username or password.");
}
throw error;
}
response.setHeader(
"Set-Cookie",
sessionCookie(request, session, this.auth.cookieName),
);
return loginResponse(session.user);
}
@Get("me")
@ApiBearerAuth()
@ApiOperation({ summary: "Return the current authenticated user" })
@ApiResponse({
status: 200,
description: "Safe account identity",
type: SafeUserDto,
})
@ApiResponse({ status: 401, description: "Missing or invalid credential" })
me(@Req() request: AuthenticatedRequest): SafeUser {
if (!this.auth.enabled) {
throw new NotFoundException("Authentication is disabled.");
}
if (!request.authSession) throw new UnauthorizedException();
return sessionUser(request.authSession);
}
@Post("logout")
@HttpCode(204)
@ApiBearerAuth()
@ApiOperation({ summary: "Revoke the current session and clear its cookie" })
@ApiResponse({ status: 204, description: "Session revoked" })
async logout(
@Req() request: AuthenticatedRequest,
@Res({ passthrough: true }) response: Response,
): Promise<void> {
if (!this.auth.enabled) {
throw new NotFoundException("Authentication is disabled.");
}
if (!request.authSession) throw new UnauthorizedException();
await this.auth.revoke(request.authSession);
response.setHeader(
"Set-Cookie",
clearedSessionCookie(request, this.auth.cookieName),
);
}
}
+9
View File
@@ -0,0 +1,9 @@
export type AuthFailureReason =
"disabled" | "invalid-credentials" | "invalid-token";
export class AuthFailure extends Error {
constructor(readonly reason: AuthFailureReason) {
super(reason);
this.name = "AuthFailure";
}
}
+43
View File
@@ -0,0 +1,43 @@
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import type { Request } from "express";
import { AuthService, AuthSession } from "./auth.service";
import { requestToken } from "./auth.helpers";
import { IS_PUBLIC_KEY } from "./public.decorator";
import { AuthFailure } from "./auth.error";
export interface AuthenticatedRequest extends Request {
authSession?: AuthSession;
}
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private readonly reflector: Reflector,
private readonly auth: AuthService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
]);
if (isPublic || !this.auth.enabled) return true;
const request = context.switchToHttp().getRequest<AuthenticatedRequest>();
const token = requestToken(request, this.auth.cookieName);
if (!token) throw new UnauthorizedException();
try {
request.authSession = await this.auth.authenticate(token);
} catch (error) {
if (error instanceof AuthFailure) throw new UnauthorizedException();
throw error;
}
return true;
}
}
+74
View File
@@ -0,0 +1,74 @@
import type { Request } from "express";
import { AUTH_COOKIE_NAME } from "./auth.constants";
import type { AuthSession, SafeUser } from "./auth.service";
export function isHttps(request: Request): boolean {
const forwarded = request.get("x-forwarded-proto")?.split(",")[0].trim();
return request.secure || forwarded === "https";
}
export function sessionCookie(
request: Request,
session: AuthSession,
cookieName = AUTH_COOKIE_NAME,
): string {
const maxAge = Math.max(
0,
Math.floor((session.expiresAt.getTime() - Date.now()) / 1000),
);
const options = ["Path=/", "HttpOnly", "SameSite=Strict"];
if (isHttps(request)) options.push("Secure");
options.push(
`Max-Age=${maxAge}`,
`Expires=${session.expiresAt.toUTCString()}`,
);
return `${cookieName}=${encodeURIComponent(session.token)}; ${options.join("; ")}`;
}
export function clearedSessionCookie(
request: Request,
cookieName = AUTH_COOKIE_NAME,
): string {
const options = ["Path=/", "HttpOnly", "SameSite=Strict"];
if (isHttps(request)) options.push("Secure");
options.push("Max-Age=0", "Expires=Thu, 01 Jan 1970 00:00:00 GMT");
return `${cookieName}=; ${options.join("; ")}`;
}
export function loginResponse(user: SafeUser): { user: SafeUser } {
return { user };
}
export function sessionUser(session: AuthSession): SafeUser {
return session.user;
}
export function cookieToken(
header: string | undefined,
cookieName = AUTH_COOKIE_NAME,
): string | undefined {
if (!header) return undefined;
for (const item of header.split(";")) {
const separator = item.indexOf("=");
if (separator < 0 || item.slice(0, separator).trim() !== cookieName) {
continue;
}
try {
return decodeURIComponent(item.slice(separator + 1).trim());
} catch {
return undefined;
}
}
return undefined;
}
export function requestToken(
request: Request,
cookieName = AUTH_COOKIE_NAME,
): string | undefined {
const authorization = request.get("authorization");
if (authorization) {
return /^Bearer\s+(.+)$/i.exec(authorization)?.[1].trim();
}
return cookieToken(request.get("cookie"), cookieName);
}
+21
View File
@@ -0,0 +1,21 @@
import { Module } from "@nestjs/common";
import { APP_GUARD } from "@nestjs/core";
import { TypeOrmModule } from "@nestjs/typeorm";
import { AuthController } from "./auth.controller";
import { AuthGuard } from "./auth.guard";
import { AuthService } from "./auth.service";
import { PasswordService } from "./password.service";
import { RevokedTokenEntity } from "./revoked-token.entity";
import { UserEntity } from "./user.entity";
@Module({
imports: [TypeOrmModule.forFeature([UserEntity, RevokedTokenEntity])],
controllers: [AuthController],
providers: [
AuthService,
PasswordService,
{ provide: APP_GUARD, useClass: AuthGuard },
],
exports: [AuthService, PasswordService],
})
export class AuthModule {}
+102
View File
@@ -0,0 +1,102 @@
import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { AppConfig } from "../config/app.config";
import { durationSeconds } from "../common/interval";
import { PasswordService } from "./password.service";
import { RevokedTokenEntity } from "./revoked-token.entity";
import { UserEntity } from "./user.entity";
import { AuthFailure } from "./auth.error";
import { issueJwt, safeUser, tokenHash, verifyJwt } from "./jwt.helpers";
export interface SafeUser {
id: string;
username: string;
createdAt: Date;
updatedAt: Date;
}
export interface AuthSession {
user: SafeUser;
token: string;
expiresAt: Date;
}
@Injectable()
export class AuthService {
constructor(
@InjectRepository(UserEntity)
private readonly users: Repository<UserEntity>,
@InjectRepository(RevokedTokenEntity)
private readonly revokedTokens: Repository<RevokedTokenEntity>,
private readonly config: ConfigService<AppConfig, true>,
private readonly passwords: PasswordService,
) {}
get enabled(): boolean {
return this.config.get("AUTH_ENABLED");
}
get cookieName(): string {
return this.config.get("AUTH_COOKIE_NAME");
}
async login(username: string, password: string): Promise<AuthSession> {
if (!this.enabled) {
throw new AuthFailure("disabled");
}
const user = await this.users.findOneBy({ username });
const valid = user
? await this.passwords.verify(password, user.passwordHash)
: false;
if (!user || !valid) {
throw new AuthFailure("invalid-credentials");
}
return this.issueToken(user);
}
issueToken(
user: Pick<UserEntity, "id" | "username" | "createdAt" | "updatedAt">,
): AuthSession {
if (!this.enabled) {
throw new AuthFailure("disabled");
}
const expiresIn = durationSeconds(this.config.get("AUTH_JWT_EXPIRES_IN"));
if (expiresIn === null) {
throw new Error("AUTH_JWT_EXPIRES_IN is not a valid positive duration.");
}
const { token, expiresAt } = issueJwt(
user.id,
expiresIn,
this.config.get("AUTH_JWT_SECRET"),
);
return {
user: safeUser(user),
token,
expiresAt,
};
}
async authenticate(token: string): Promise<AuthSession> {
const payload = verifyJwt(token, this.config.get("AUTH_JWT_SECRET"));
const digest = tokenHash(token);
if (await this.revokedTokens.findOneBy({ tokenHash: digest })) {
throw new AuthFailure("invalid-token");
}
const user = await this.users.findOneBy({ id: payload.sub });
if (!user) throw new AuthFailure("invalid-token");
return {
user: safeUser(user),
token,
expiresAt: new Date(payload.exp * 1000),
};
}
async revoke(session: AuthSession): Promise<void> {
await this.revokedTokens.save({
tokenHash: tokenHash(session.token),
expiresAt: session.expiresAt,
});
}
}
+20
View File
@@ -0,0 +1,20 @@
import { ApiProperty } from "@nestjs/swagger";
export class SafeUserDto {
@ApiProperty()
id!: string;
@ApiProperty()
username!: string;
@ApiProperty({ type: String, format: "date-time" })
createdAt!: Date;
@ApiProperty({ type: String, format: "date-time" })
updatedAt!: Date;
}
export class LoginResponseDto {
@ApiProperty({ type: SafeUserDto })
user!: SafeUserDto;
}
+13
View File
@@ -0,0 +1,13 @@
import { IsNotEmpty, IsString, MaxLength } from "class-validator";
export class LoginDto {
@IsString()
@IsNotEmpty()
@MaxLength(250)
username!: string;
@IsString()
@IsNotEmpty()
@MaxLength(1024)
password!: string;
}
+98
View File
@@ -0,0 +1,98 @@
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
import { AuthFailure } from "./auth.error";
import { SafeUser } from "./auth.service";
import { UserEntity } from "./user.entity";
export interface JwtPayload {
sub: string;
iat: number;
exp: number;
}
export function safeUser(
user: Pick<UserEntity, "id" | "username" | "createdAt" | "updatedAt">,
): SafeUser {
return {
id: user.id,
username: user.username,
createdAt: user.createdAt,
updatedAt: user.updatedAt,
};
}
export function tokenHash(token: string): string {
return createHash("sha256").update(token).digest("hex");
}
function base64UrlJson(value: unknown): string {
return Buffer.from(JSON.stringify(value)).toString("base64url");
}
function sign(unsigned: string, secret: string): string {
return createHmac("sha256", secret).update(unsigned).digest("base64url");
}
export function issueJwt(
userId: string,
expiresIn: number,
secret: string,
): { token: string; expiresAt: Date } {
const issuedAt = Math.floor(Date.now() / 1000);
const payload: JwtPayload = {
sub: userId,
iat: issuedAt,
exp: issuedAt + expiresIn,
};
const unsigned = `${base64UrlJson({ alg: "HS256", typ: "JWT" })}.${base64UrlJson(payload)}`;
return {
token: `${unsigned}.${sign(unsigned, secret)}`,
expiresAt: new Date(payload.exp * 1000),
};
}
export function verifyJwt(token: string, secret: string): JwtPayload {
const parts = token.split(".");
if (parts.length !== 3 || parts.some((part) => part.length === 0))
throw new AuthFailure("invalid-token");
const [encodedHeader, encodedPayload, encodedSignature] = parts;
let header: unknown;
let payload: unknown;
let supplied: Buffer;
try {
header = JSON.parse(
Buffer.from(encodedHeader, "base64url").toString("utf8"),
);
payload = JSON.parse(
Buffer.from(encodedPayload, "base64url").toString("utf8"),
);
supplied = Buffer.from(encodedSignature, "base64url");
} catch {
throw new AuthFailure("invalid-token");
}
if (
!header ||
typeof header !== "object" ||
(header as { alg?: unknown }).alg !== "HS256"
)
throw new AuthFailure("invalid-token");
const unsigned = `${encodedHeader}.${encodedPayload}`;
const expected = Buffer.from(sign(unsigned, secret), "base64url");
if (
expected.length !== supplied.length ||
!timingSafeEqual(expected, supplied)
)
throw new AuthFailure("invalid-token");
if (!payload || typeof payload !== "object")
throw new AuthFailure("invalid-token");
const claims = payload as Partial<JwtPayload>;
const now = Math.floor(Date.now() / 1000);
if (
typeof claims.sub !== "string" ||
!claims.sub ||
!Number.isSafeInteger(claims.iat) ||
!Number.isSafeInteger(claims.exp) ||
(claims.exp as number) <= now
)
throw new AuthFailure("invalid-token");
return claims as JwtPayload;
}
+95
View File
@@ -0,0 +1,95 @@
import { randomBytes, scrypt, timingSafeEqual } from "node:crypto";
import { Injectable } from "@nestjs/common";
// N=2^14 is the baseline scrypt CPU/memory cost; verify permits bounded future upgrades.
const SCRYPT_N = 16384;
// r=8 and p=1 are the standard scrypt block size and parallelization for this cost.
const SCRYPT_R = 8;
const SCRYPT_P = 1;
// A 128-bit random salt prevents practical salt collisions across stored passwords.
const SALT_BYTES = 16;
// 512-bit output gives ample margin for password verification.
const HASH_BYTES = 64;
function derive(
password: string,
salt: Buffer,
length: number,
N: number,
r: number,
p: number,
): Promise<Buffer> {
const maxmem = 128 * N * r + 2 * 1024 * 1024;
return new Promise((resolve, reject) => {
scrypt(password, salt, length, { N, r, p, maxmem }, (error, key) => {
if (error) reject(error);
else resolve(key as Buffer);
});
});
}
@Injectable()
export class PasswordService {
async hash(password: string): Promise<string> {
const salt = randomBytes(SALT_BYTES);
const hash = await derive(
password,
salt,
HASH_BYTES,
SCRYPT_N,
SCRYPT_R,
SCRYPT_P,
);
return [
"scrypt",
SCRYPT_N,
SCRYPT_R,
SCRYPT_P,
salt.toString("base64url"),
hash.toString("base64url"),
].join("$");
}
async verify(password: string, encodedHash: string): Promise<boolean> {
const [algorithm, rawN, rawR, rawP, rawSalt, rawHash, ...extra] =
encodedHash.split("$");
if (
algorithm !== "scrypt" ||
extra.length > 0 ||
!rawN ||
!rawR ||
!rawP ||
!rawSalt ||
!rawHash
) {
return false;
}
const N = Number(rawN);
const r = Number(rawR);
const p = Number(rawP);
const salt = Buffer.from(rawSalt, "base64url");
const expected = Buffer.from(rawHash, "base64url");
if (
!Number.isSafeInteger(N) ||
N < 16384 ||
N > 65536 ||
(N & (N - 1)) !== 0 ||
!Number.isSafeInteger(r) ||
r < 1 ||
r > 16 ||
!Number.isSafeInteger(p) ||
p < 1 ||
p > 4 ||
salt.length < 16 ||
salt.length > 64 ||
expected.length < 32 ||
expected.length > 128
) {
return false;
}
const actual = await derive(password, salt, expected.length, N, r, p);
return timingSafeEqual(actual, expected);
}
}
+4
View File
@@ -0,0 +1,4 @@
import { SetMetadata } from "@nestjs/common";
export const IS_PUBLIC_KEY = Symbol("isPublic");
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
+11
View File
@@ -0,0 +1,11 @@
import { Column, Entity, PrimaryColumn } from "typeorm";
/** A SHA-256 digest of a JWT that has been logged out. */
@Entity("revoked_tokens")
export class RevokedTokenEntity {
@PrimaryColumn({ length: 64 })
tokenHash: string;
@Column({ type: "datetime" })
expiresAt: Date;
}
+26
View File
@@ -0,0 +1,26 @@
import {
Column,
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from "typeorm";
/** Local operator-managed account. Password hashes are never returned by the API. */
@Entity("users")
export class UserEntity {
@PrimaryGeneratedColumn("uuid")
id: string;
@Column({ unique: true })
username: string;
@Column("text")
passwordHash: string;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}
+7 -1
View File
@@ -1,5 +1,10 @@
import { Body, Controller, Post } from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import {
ApiBearerAuth,
ApiOperation,
ApiResponse,
ApiTags,
} from "@nestjs/swagger";
import { CodeExecutorService } from "../code-executor/code-executor.service";
import { CredentialService } from "../credential/credential.service";
import { EnvironmentService } from "../environment/environment.service";
@@ -8,6 +13,7 @@ import { ExecDto } from "./dto/exec.dto";
import { OpenDto } from "./dto/open.dto";
@ApiTags("browser")
@ApiBearerAuth()
@Controller()
export class BrowserController {
constructor(
+11
View File
@@ -0,0 +1,11 @@
/** Parse a positive duration (seconds, minutes, hours, or days) into seconds. */
export function durationSeconds(value: string): number | null {
const match = /^(\d+)(s|m|h|d)$/.exec(value);
if (!match) return null;
const amount = Number(match[1]);
const multiplier = { s: 1, m: 60, h: 3600, d: 86400 }[
match[2] as "s" | "m" | "h" | "d"
];
const seconds = amount * multiplier;
return Number.isSafeInteger(seconds) && seconds > 0 ? seconds : null;
}
+56 -1
View File
@@ -1,5 +1,7 @@
import "reflect-metadata";
import { plainToInstance } from "class-transformer";
import {
IsBoolean,
IsEnum,
IsInt,
IsString,
@@ -10,6 +12,8 @@ import {
import { appPackage } from "../common/app-package";
import { durationSeconds } from "../common/interval";
export enum TraceMode {
On = "on",
RetainOnFailure = "retain-on-failure",
@@ -74,15 +78,66 @@ export class AppConfig {
@IsInt()
@Min(0)
RUN_LOG_DATA_COLLAPSE_LINES: number = 5;
/** Authentication is opt-in so existing deployments remain unchanged. */
@IsBoolean()
AUTH_ENABLED: boolean = false;
/** Required only when AUTH_ENABLED is true. */
@IsString()
AUTH_JWT_SECRET: string = "";
/** Cookie name used for browser sessions. */
@IsString()
AUTH_COOKIE_NAME: string = "liqa_auth";
@IsString()
AUTH_JWT_EXPIRES_IN: string = "24h";
@IsString()
AUTH_REVOKED_TOKEN_CLEANUP_CRON: string = "0 3 * * *";
}
export function validateAppConfig(config: Record<string, unknown>): AppConfig {
const validated = plainToInstance(AppConfig, config, {
const authEnabled = config.AUTH_ENABLED;
if (
authEnabled !== undefined &&
authEnabled !== true &&
authEnabled !== false &&
authEnabled !== "true" &&
authEnabled !== "false"
) {
throw new Error("AUTH_ENABLED must be either true or false.");
}
const normalized = {
...config,
AUTH_ENABLED: authEnabled === true || authEnabled === "true",
};
const validated = plainToInstance(AppConfig, normalized, {
enableImplicitConversion: true,
});
const errors = validateSync(validated, { skipMissingProperties: false });
if (errors.length > 0) {
throw new Error(errors.toString());
}
if (validated.AUTH_ENABLED && !validated.AUTH_JWT_SECRET.trim()) {
throw new Error("AUTH_JWT_SECRET must be set when AUTH_ENABLED=true.");
}
if (
validated.AUTH_ENABLED &&
durationSeconds(validated.AUTH_JWT_EXPIRES_IN) === null
) {
throw new Error(
"AUTH_JWT_EXPIRES_IN must be a positive duration such as 30m, 1h, or 24h.",
);
}
if (
validated.AUTH_ENABLED &&
!validated.AUTH_REVOKED_TOKEN_CLEANUP_CRON.trim()
) {
throw new Error(
"AUTH_REVOKED_TOKEN_CLEANUP_CRON must be set when AUTH_ENABLED=true.",
);
}
return validated;
}
@@ -10,7 +10,12 @@ import {
Post,
Query,
} from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import {
ApiBearerAuth,
ApiOperation,
ApiResponse,
ApiTags,
} from "@nestjs/swagger";
import { CredentialQueryDto } from "./dto/credential-query.dto";
import { CredentialService } from "./credential.service";
import { CreateCredentialDto } from "./dto/create-credential.dto";
@@ -18,6 +23,7 @@ import { CredentialExportDto } from "./dto/credential-export.dto";
import { UpdateCredentialDto } from "./dto/update-credential.dto";
@ApiTags("credentials")
@ApiBearerAuth()
@Controller("credentials")
export class CredentialController {
constructor(private readonly credentialService: CredentialService) {}
+4
View File
@@ -1,4 +1,6 @@
import { CredentialEntity } from "../credential/credential.entity";
import { RevokedTokenEntity } from "../auth/revoked-token.entity";
import { UserEntity } from "../auth/user.entity";
import { EnvironmentEntity } from "../environment/environment.entity";
import { FileEntity } from "../file/file.entity";
import { ScenarioFileEntity } from "../file/scenario-file.entity";
@@ -16,6 +18,8 @@ import { SnippetEntity } from "../snippet/snippet.entity";
/** Every TypeORM entity of the app (used by the app, the migrations CLI and tests). */
export const ENTITIES = [
UserEntity,
RevokedTokenEntity,
SessionEntity,
EnvironmentEntity,
CredentialEntity,
@@ -0,0 +1,23 @@
import { MigrationInterface, QueryRunner } from "typeorm";
export class AddAuthUsersAndRevokedTokens1793823870652 implements MigrationInterface {
name = "AddAuthUsersAndRevokedTokens1793823870652";
public async up(queryRunner: QueryRunner): Promise<void> {
if (!(await queryRunner.hasTable("users"))) {
await queryRunner.query(
`CREATE TABLE "users" ("id" varchar PRIMARY KEY NOT NULL, "username" varchar NOT NULL, "passwordHash" text NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_fe0bb3f6520ee0469504521e710" UNIQUE ("username"))`,
);
}
if (!(await queryRunner.hasTable("revoked_tokens"))) {
await queryRunner.query(
`CREATE TABLE "revoked_tokens" ("tokenHash" varchar(64) PRIMARY KEY NOT NULL, "expiresAt" datetime NOT NULL)`,
);
}
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP TABLE "revoked_tokens"`);
await queryRunner.query(`DROP TABLE "users"`);
}
}
+2
View File
@@ -1,6 +1,7 @@
import { Initial1790793447827 } from "./1790793447827-Initial";
import { AddRunLogContext1790848194828 } from "./1790848194828-AddRunLogContext";
import { AddRunLogData1790850734763 } from "./1790850734763-AddRunLogData";
import { AddAuthUsersAndRevokedTokens1793823870652 } from "./1793823870652-AddAuthUsersAndRevokedTokens";
/**
* All migrations, oldest first. Listed explicitly (instead of a glob) so the
@@ -10,4 +11,5 @@ export const MIGRATIONS = [
Initial1790793447827,
AddRunLogContext1790848194828,
AddRunLogData1790850734763,
AddAuthUsersAndRevokedTokens1793823870652,
];
@@ -10,7 +10,12 @@ import {
Post,
Query,
} from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import {
ApiBearerAuth,
ApiOperation,
ApiResponse,
ApiTags,
} from "@nestjs/swagger";
import { EnvironmentQueryDto } from "./dto/environment-query.dto";
import { CreateEnvironmentDto } from "./dto/create-environment.dto";
import { EnvironmentExportDto } from "./dto/environment-export.dto";
@@ -18,6 +23,7 @@ import { UpdateEnvironmentDto } from "./dto/update-environment.dto";
import { EnvironmentService } from "./environment.service";
@ApiTags("environments")
@ApiBearerAuth()
@Controller("environments")
export class EnvironmentController {
constructor(private readonly environmentService: EnvironmentService) {}
+3
View File
@@ -1,10 +1,12 @@
import { Controller, Get } from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import { Public } from "../auth/public.decorator";
@ApiTags("health")
@Controller()
export class HealthController {
@Get("health")
@Public()
@ApiOperation({ summary: "Health check" })
@ApiResponse({ status: 200, description: "Service is healthy" })
health(): { status: string } {
@@ -12,6 +14,7 @@ export class HealthController {
}
@Get("healthz")
@Public()
@ApiOperation({ summary: "Health check" })
@ApiResponse({ status: 200, description: "Service is healthy" })
healthz(): { status: string } {
+2
View File
@@ -1,5 +1,6 @@
import { BadRequestException, Body, Controller, Post } from "@nestjs/common";
import {
ApiBearerAuth,
ApiBody,
ApiConsumes,
ApiOperation,
@@ -10,6 +11,7 @@ import { YAML_CONTENT_TYPES } from "../common/body-parsers";
import { ImportService } from "./import.service";
@ApiTags("import")
@ApiBearerAuth()
@Controller("import")
export class ImportController {
constructor(private readonly importService: ImportService) {}
+22 -1
View File
@@ -8,6 +8,24 @@ import type { Request, Response } from "express";
import { Observable, tap } from "rxjs";
import { TraceLogger } from "../common/trace-logger";
export function redactAuthRequestBody(path: string, body: unknown): unknown {
const normalizedPath = path.toLowerCase().replace(/\/+$/, "");
if (
(normalizedPath !== "/auth/login" &&
normalizedPath !== "/api/v1/auth/login") ||
!body ||
typeof body !== "object" ||
Array.isArray(body)
) {
return body;
}
const requestBody = body as Record<string, unknown>;
return {
...requestBody,
password: requestBody.password ? "[REDACTED]" : requestBody.password,
};
}
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
private readonly logger = new TraceLogger(LoggingInterceptor.name);
@@ -18,8 +36,11 @@ export class LoggingInterceptor implements NestInterceptor {
const res = http.getResponse<Response>();
const { method, url, body } = req;
const start = Date.now();
const safeBody = redactAuthRequestBody(req.path, body);
const bodyStr =
body && Object.keys(body).length ? ` ${JSON.stringify(body)}` : "";
safeBody && Object.keys(safeBody).length
? ` ${JSON.stringify(safeBody)}`
: "";
this.logger.debug(`→ ${method} ${url}${bodyStr}`);
+5 -1
View File
@@ -19,7 +19,10 @@ import { TraceInterceptor } from "./interceptors/trace.interceptor";
// crashes the process on any unhandled rejection or uncaught exception.
const processLogger = new TraceLogger("Process");
process.on("uncaughtException", (err) => {
processLogger.error(`Uncaught exception (process kept alive): ${err.message}`, err.stack);
processLogger.error(
`Uncaught exception (process kept alive): ${err.message}`,
err.stack,
);
});
process.on("unhandledRejection", (reason) => {
processLogger.error(
@@ -74,6 +77,7 @@ async function bootstrap() {
.setTitle(pkgName)
.setDescription(`${pkgName} API`)
.setVersion(pkgVersion)
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, swaggerConfig);
@@ -2,6 +2,7 @@ import { Controller, Get, Header } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { ApiOkResponse, ApiOperation, ApiTags } from "@nestjs/swagger";
import { AppConfig } from "../config/app.config";
import { Public } from "../auth/public.decorator";
import { ManifestDto } from "./manifest.dto";
@ApiTags("manifest")
@@ -10,6 +11,7 @@ export class ManifestController {
constructor(private readonly config: ConfigService<AppConfig, true>) {}
@Get("manifest.json")
@Public()
// Clients cache the manifest themselves; the browser just revalidates it (ETag)
@Header("Cache-Control", "no-cache")
@ApiOperation({ summary: "Public client configuration and app version" })
@@ -18,6 +20,7 @@ export class ManifestController {
return {
name: this.config.get("APP_NAME"),
version: this.config.get("APP_VERSION"),
auth: { enabled: this.config.get("AUTH_ENABLED") },
runLogs: {
dataLimits: {
bytes: this.config.get("RUN_LOG_DATA_COLLAPSE_BYTES"),
+11 -2
View File
@@ -2,13 +2,15 @@ import { ApiProperty } from "@nestjs/swagger";
export class RunLogDataLimitsDto {
@ApiProperty({
description: "Data blocks over this many bytes (pretty-printed) start collapsed",
description:
"Data blocks over this many bytes (pretty-printed) start collapsed",
example: 256,
})
bytes!: number;
@ApiProperty({
description: "Data blocks over this many lines (pretty-printed) start collapsed",
description:
"Data blocks over this many lines (pretty-printed) start collapsed",
example: 5,
})
lines!: number;
@@ -26,6 +28,13 @@ export class ManifestDto {
@ApiProperty({ example: "1.4.0" })
version!: string;
@ApiProperty({
description: "Whether account authentication is enabled.",
type: "object",
properties: { enabled: { type: "boolean", example: false } },
})
auth!: { enabled: boolean };
@ApiProperty({ type: RunLogsManifestDto })
runLogs!: RunLogsManifestDto;
}
+7 -1
View File
@@ -1,9 +1,15 @@
import { Controller, Delete, Get, Post, Req, Res } from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import {
ApiBearerAuth,
ApiOperation,
ApiResponse,
ApiTags,
} from "@nestjs/swagger";
import type { Request, Response } from "express";
import { McpService } from "./mcp.service";
@ApiTags("mcp")
@ApiBearerAuth()
@Controller("mcp")
export class McpController {
constructor(private readonly mcpService: McpService) {}
+20 -9
View File
@@ -16,7 +16,12 @@ import {
UploadedFile,
} from "@nestjs/common";
import { FileInterceptor } from "@nestjs/platform-express";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import {
ApiBearerAuth,
ApiOperation,
ApiResponse,
ApiTags,
} from "@nestjs/swagger";
import { Response } from "express";
import { interval, map, merge, type Observable } from "rxjs";
import type { File as MulterFile } from "multer";
@@ -40,6 +45,7 @@ interface SseMessage {
}
@ApiTags("scenarios")
@ApiBearerAuth()
@Controller("scenarios")
export class ScenarioController {
private static readonly HEARTBEAT_MS = 25_000;
@@ -60,7 +66,10 @@ export class ScenarioController {
}
@Post("import")
@ApiOperation({ summary: "Import a scenario from an export payload (single object or array)" })
@ApiOperation({
summary:
"Import a scenario from an export payload (single object or array)",
})
@ApiResponse({ status: 201, description: "Scenario imported" })
importScenario(@Body() payload: unknown) {
return this.scenarioService.importScenario(
@@ -200,7 +209,8 @@ export class ScenarioController {
@Get(":id/export-e2e")
@ApiOperation({
summary: "Export a scenario as a standalone, plug-and-play Playwright e2e test (zip)",
summary:
"Export a scenario as a standalone, plug-and-play Playwright e2e test (zip)",
})
@ApiResponse({ status: 200, description: "Zip archive" })
@ApiResponse({ status: 404, description: "Scenario or version not found" })
@@ -210,10 +220,8 @@ export class ScenarioController {
version: number | undefined,
@Res() res: Response,
) {
const { filename, buffer } = await this.e2eExportService.buildE2eTestPackage(
id,
version,
);
const { filename, buffer } =
await this.e2eExportService.buildE2eTestPackage(id, version);
res.setHeader("Content-Type", "application/zip");
res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
res.setHeader("Content-Length", buffer.length);
@@ -270,7 +278,8 @@ export class ScenarioController {
@Get(":id/used-snippets")
@ApiOperation({
summary: "List snippets referenced (directly or transitively) by this scenario's steps",
summary:
"List snippets referenced (directly or transitively) by this scenario's steps",
})
@ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario not found" })
@@ -375,7 +384,9 @@ export class ScenarioController {
const fmt = format === "csv" ? "csv" : "md";
const content = await this.scenarioService.exportRunLogs(id, runId, fmt);
const contentType =
fmt === "csv" ? "text/csv; charset=utf-8" : "text/markdown; charset=utf-8";
fmt === "csv"
? "text/csv; charset=utf-8"
: "text/markdown; charset=utf-8";
const ext = fmt === "csv" ? "csv" : "md";
res.setHeader("Content-Type", contentType);
res.setHeader(
+7 -1
View File
@@ -8,7 +8,12 @@ import {
ParseUUIDPipe,
Query,
} from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import {
ApiBearerAuth,
ApiOperation,
ApiResponse,
ApiTags,
} from "@nestjs/swagger";
import { SessionQueryDto } from "./session-query.dto";
import { SessionContextService } from "./session-context.service";
import { SessionService } from "./session.service";
@@ -19,6 +24,7 @@ function maskToken(token: string, head = 6, tail = 4): string {
}
@ApiTags("sessions")
@ApiBearerAuth()
@Controller("sessions")
export class SessionController {
constructor(
+7 -1
View File
@@ -11,7 +11,12 @@ import {
Post,
Query,
} from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import {
ApiBearerAuth,
ApiOperation,
ApiResponse,
ApiTags,
} from "@nestjs/swagger";
import { SnippetQueryDto } from "./dto/snippet-query.dto";
import { CreateSnippetDto } from "./dto/create-snippet.dto";
import { SnippetExportDto } from "./dto/snippet-export.dto";
@@ -19,6 +24,7 @@ import { UpdateSnippetDto } from "./dto/update-snippet.dto";
import { SnippetService } from "./snippet.service";
@ApiTags("snippets")
@ApiBearerAuth()
@Controller("snippets")
export class SnippetController {
constructor(private readonly snippetService: SnippetService) {}
+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,
+53
View File
@@ -0,0 +1,53 @@
import "reflect-metadata";
import { validateAppConfig } from "../src/config/app.config";
import { durationSeconds } from "../src/common/interval";
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_COOKIE_NAME).toBe("liqa_auth");
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(durationSeconds("30m")).toBe(1800);
expect(durationSeconds("24h")).toBe(86400);
expect(durationSeconds("2d")).toBe(172800);
expect(durationSeconds("0s")).toBeNull();
});
});
+41
View File
@@ -0,0 +1,41 @@
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 });
});
it("returns not found for login while authentication is disabled", async () => {
await request(app.getHttpServer())
.post("/auth/login")
.send({ username: "nobody", password: "synthetic" })
.expect(404);
});
});
+57
View File
@@ -0,0 +1,57 @@
import { AuthSession } from "../src/auth/auth.service";
import {
clearedSessionCookie,
cookieToken,
requestToken,
sessionCookie,
} from "../src/auth/auth.helpers";
import { Public, IS_PUBLIC_KEY } from "../src/auth/public.decorator";
describe("authentication helpers", () => {
const request = {
secure: false,
get: (name: string) =>
name === "x-forwarded-proto" ? undefined : undefined,
} as never;
const session: AuthSession = {
user: {
id: "u",
username: "user",
createdAt: new Date(0),
updatedAt: new Date(0),
},
token: "a.token.value",
expiresAt: new Date(Date.now() + 60_000),
};
it("sets and clears a configurable cookie name", () => {
expect(sessionCookie(request, session, "custom_session")).toContain(
"custom_session=a.token.value",
);
expect(clearedSessionCookie(request, "custom_session")).toContain(
"custom_session=;",
);
});
it("reads only the selected cookie and supports bearer credentials", () => {
expect(
cookieToken("other=x; custom_session=encoded%20value", "custom_session"),
).toBe("encoded value");
expect(
requestToken(
{
get: (name: string) =>
name === "authorization" ? "Bearer token" : undefined,
} as never,
"x",
),
).toBe("token");
});
it("stores public-route metadata under a Symbol key", () => {
class PublicController {}
Public()(PublicController);
expect(typeof IS_PUBLIC_KEY).toBe("symbol");
expect(Reflect.getMetadata(IS_PUBLIC_KEY, PublicController)).toBe(true);
});
});
+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/jwt.helpers";
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);
});
});
+62
View File
@@ -0,0 +1,62 @@
import { CallHandler, ExecutionContext } from "@nestjs/common";
import { of } from "rxjs";
import { TraceLogger } from "../src/common/trace-logger";
import {
LoggingInterceptor,
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/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);
});
it("never logs a password received on the accepted trailing-slash login path", () => {
const loggedMessages: unknown[][] = [];
const debug = jest
.spyOn(TraceLogger.prototype, "debug")
.mockImplementation((...args: unknown[]) => {
loggedMessages.push(args);
});
const context = {
switchToHttp: () => ({
getRequest: () => ({
method: "POST",
url: "/api/v1/auth/login/",
path: "/api/v1/auth/login/",
body: { username: "operator", password: "synthetic-login-secret" },
}),
getResponse: () => ({ statusCode: 200 }),
}),
} as unknown as ExecutionContext;
const handler = {
handle: () => of({ user: { username: "operator" } }),
} as CallHandler;
try {
new LoggingInterceptor().intercept(context, handler).subscribe();
const output = JSON.stringify(loggedMessages);
expect(output).toContain("[REDACTED]");
expect(output).not.toContain("synthetic-login-secret");
} finally {
debug.mockRestore();
}
});
});
+14
View File
@@ -1,9 +1,22 @@
import { INestApplication } from "@nestjs/common";
import request from "supertest";
import { appPackage } from "../src/common/app-package";
import { ManifestDto } from "../src/manifest/manifest.dto";
import { buildTestApp } from "./app.harness";
describe("GET /manifest.json", () => {
it("describes the manifest auth flag without describing authentication as optional", () => {
const authProperty = Reflect.getMetadata(
"swagger/apiModelProperties",
ManifestDto.prototype,
"auth",
) as { description: string };
expect(authProperty.description).toBe(
"Whether account authentication is enabled.",
);
expect(authProperty.description).not.toContain("optional");
});
let app: INestApplication;
afterEach(async () => {
@@ -21,6 +34,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");