diff --git a/server/src/app.module.ts b/server/src/app.module.ts index e3108d6..e3ccfcd 100644 --- a/server/src/app.module.ts +++ b/server/src/app.module.ts @@ -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, diff --git a/server/src/auth/auth.constants.ts b/server/src/auth/auth.constants.ts new file mode 100644 index 0000000..f57fba3 --- /dev/null +++ b/server/src/auth/auth.constants.ts @@ -0,0 +1 @@ +export const AUTH_COOKIE_NAME = "liqa_auth"; diff --git a/server/src/auth/auth.controller.ts b/server/src/auth/auth.controller.ts new file mode 100644 index 0000000..5b48d27 --- /dev/null +++ b/server/src/auth/auth.controller.ts @@ -0,0 +1,116 @@ +import { + Body, + Controller, + Get, + HttpCode, + NotFoundException, + Post, + Req, + Res, + UnauthorizedException, +} from "@nestjs/common"; +import { + ApiBearerAuth, + ApiOperation, + ApiResponse, + ApiTags, +} from "@nestjs/swagger"; +import { IsNotEmpty, IsString, MaxLength } from "class-validator"; +import type { Request, Response } from "express"; +import { AUTH_COOKIE_NAME } from "./auth.constants"; +import { AuthenticatedRequest } from "./auth.guard"; +import { AuthService } from "./auth.service"; +import { Public } from "./public.decorator"; + +export class LoginDto { + @IsString() + @IsNotEmpty() + @MaxLength(250) + username: string; + + @IsString() + @IsNotEmpty() + @MaxLength(1024) + password: string; +} + +function isHttps(request: Request): boolean { + const forwarded = request.get("x-forwarded-proto")?.split(",")[0].trim(); + return request.secure || forwarded === "https"; +} + +function cookieOptions(request: Request): string[] { + const options = ["Path=/", "HttpOnly", "SameSite=Strict"]; + if (isHttps(request)) options.push("Secure"); + return options; +} + +@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" }) + @ApiResponse({ status: 401, description: "Invalid username or password" }) + async login( + @Body() dto: LoginDto, + @Req() request: Request, + @Res({ passthrough: true }) response: Response, + ) { + const session = await this.auth.login(dto.username, dto.password); + const maxAge = Math.max( + 0, + Math.floor((session.expiresAt.getTime() - Date.now()) / 1000), + ); + response.setHeader( + "Set-Cookie", + `${AUTH_COOKIE_NAME}=${encodeURIComponent(session.token)}; ${[ + ...cookieOptions(request), + `Max-Age=${maxAge}`, + `Expires=${session.expiresAt.toUTCString()}`, + ].join("; ")}`, + ); + return { user: session.user }; + } + + @Get("me") + @ApiBearerAuth() + @ApiOperation({ summary: "Return the current authenticated user" }) + @ApiResponse({ status: 200, description: "Safe account identity" }) + @ApiResponse({ status: 401, description: "Missing or invalid credential" }) + me(@Req() request: AuthenticatedRequest) { + if (!this.auth.enabled) { + throw new NotFoundException("Authentication is disabled."); + } + if (!request.authSession) throw new UnauthorizedException(); + return request.authSession.user; + } + + @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 { + 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", + `${AUTH_COOKIE_NAME}=; ${[ + ...cookieOptions(request), + "Max-Age=0", + "Expires=Thu, 01 Jan 1970 00:00:00 GMT", + ].join("; ")}`, + ); + } +} diff --git a/server/src/auth/auth.guard.ts b/server/src/auth/auth.guard.ts new file mode 100644 index 0000000..7a129df --- /dev/null +++ b/server/src/auth/auth.guard.ts @@ -0,0 +1,63 @@ +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 { AUTH_COOKIE_NAME } from "./auth.constants"; +import { IS_PUBLIC_KEY } from "./public.decorator"; + +export interface AuthenticatedRequest extends Request { + authSession?: AuthSession; +} + +function cookieToken(header: string | undefined): string | undefined { + if (!header) return undefined; + for (const item of header.split(";")) { + const separator = item.indexOf("="); + if (separator < 0 || item.slice(0, separator).trim() !== AUTH_COOKIE_NAME) { + continue; + } + const value = item.slice(separator + 1).trim(); + try { + return decodeURIComponent(value); + } catch { + return undefined; + } + } + return undefined; +} + +function requestToken(request: Request): string | undefined { + const authorization = request.get("authorization"); + if (authorization) { + const match = /^Bearer\s+(.+)$/i.exec(authorization); + return match?.[1].trim(); + } + return cookieToken(request.get("cookie")); +} + +@Injectable() +export class AuthGuard implements CanActivate { + constructor( + private readonly reflector: Reflector, + private readonly auth: AuthService, + ) {} + + async canActivate(context: ExecutionContext): Promise { + const isPublic = this.reflector.getAllAndOverride(IS_PUBLIC_KEY, [ + context.getHandler(), + context.getClass(), + ]); + if (isPublic || !this.auth.enabled) return true; + + const request = context.switchToHttp().getRequest(); + const token = requestToken(request); + if (!token) throw new UnauthorizedException(); + request.authSession = await this.auth.authenticate(token); + return true; + } +} diff --git a/server/src/auth/auth.module.ts b/server/src/auth/auth.module.ts new file mode 100644 index 0000000..0d3b57a --- /dev/null +++ b/server/src/auth/auth.module.ts @@ -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 {} diff --git a/server/src/auth/auth.service.ts b/server/src/auth/auth.service.ts new file mode 100644 index 0000000..6e77eb5 --- /dev/null +++ b/server/src/auth/auth.service.ts @@ -0,0 +1,187 @@ +import { + Injectable, + NotFoundException, + UnauthorizedException, +} from "@nestjs/common"; +import { ConfigService } from "@nestjs/config"; +import { InjectRepository } from "@nestjs/typeorm"; +import { createHash, createHmac, timingSafeEqual } from "node:crypto"; +import { Repository } from "typeorm"; +import { AppConfig, authDurationSeconds } from "../config/app.config"; +import { PasswordService } from "./password.service"; +import { RevokedTokenEntity } from "./revoked-token.entity"; +import { UserEntity } from "./user.entity"; + +export interface SafeUser { + id: string; + username: string; + createdAt: Date; + updatedAt: Date; +} + +export interface AuthSession { + user: SafeUser; + token: string; + expiresAt: Date; +} + +interface JwtPayload { + sub: string; + iat: number; + exp: number; +} + +function base64UrlJson(value: unknown): string { + return Buffer.from(JSON.stringify(value)).toString("base64url"); +} + +export function tokenHash(token: string): string { + return createHash("sha256").update(token).digest("hex"); +} + +@Injectable() +export class AuthService { + constructor( + @InjectRepository(UserEntity) + private readonly users: Repository, + @InjectRepository(RevokedTokenEntity) + private readonly revokedTokens: Repository, + private readonly config: ConfigService, + private readonly passwords: PasswordService, + ) {} + + get enabled(): boolean { + return this.config.get("AUTH_ENABLED"); + } + + async login(username: string, password: string): Promise { + if (!this.enabled) { + throw new NotFoundException("Authentication is disabled."); + } + const user = await this.users.findOneBy({ username }); + const valid = user + ? await this.passwords.verify(password, user.passwordHash) + : false; + if (!user || !valid) { + throw new UnauthorizedException("Invalid username or password."); + } + return this.issueToken(user); + } + + issueToken( + user: Pick, + ): AuthSession { + if (!this.enabled) { + throw new NotFoundException("Authentication is disabled."); + } + const issuedAt = Math.floor(Date.now() / 1000); + const expiresIn = authDurationSeconds( + this.config.get("AUTH_JWT_EXPIRES_IN"), + ); + if (expiresIn === null) { + throw new Error("AUTH_JWT_EXPIRES_IN is not a valid positive duration."); + } + const payload: JwtPayload = { + sub: user.id, + iat: issuedAt, + exp: issuedAt + expiresIn, + }; + const unsigned = `${base64UrlJson({ alg: "HS256", typ: "JWT" })}.${base64UrlJson(payload)}`; + return { + user: this.safeUser(user as UserEntity), + token: `${unsigned}.${this.sign(unsigned)}`, + expiresAt: new Date(payload.exp * 1000), + }; + } + + async authenticate(token: string): Promise { + const payload = this.verify(token); + const digest = tokenHash(token); + if (await this.revokedTokens.findOneBy({ tokenHash: digest })) { + throw new UnauthorizedException(); + } + const user = await this.users.findOneBy({ id: payload.sub }); + if (!user) throw new UnauthorizedException(); + return { + user: this.safeUser(user), + token, + expiresAt: new Date(payload.exp * 1000), + }; + } + + async revoke(session: AuthSession): Promise { + await this.revokedTokens.save({ + tokenHash: tokenHash(session.token), + expiresAt: session.expiresAt, + }); + } + + private sign(unsigned: string): string { + return createHmac("sha256", this.config.get("AUTH_JWT_SECRET")) + .update(unsigned) + .digest("base64url"); + } + + private verify(token: string): JwtPayload { + const parts = token.split("."); + if (parts.length !== 3 || parts.some((part) => part.length === 0)) { + throw new UnauthorizedException(); + } + + 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 UnauthorizedException(); + } + if ( + !header || + typeof header !== "object" || + (header as { alg?: unknown }).alg !== "HS256" + ) { + throw new UnauthorizedException(); + } + + const unsigned = `${encodedHeader}.${encodedPayload}`; + const expected = Buffer.from(this.sign(unsigned), "base64url"); + if ( + expected.length !== supplied.length || + !timingSafeEqual(expected, supplied) + ) { + throw new UnauthorizedException(); + } + if (!payload || typeof payload !== "object") { + throw new UnauthorizedException(); + } + const claims = payload as Partial; + 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 UnauthorizedException(); + } + return claims as JwtPayload; + } + + private safeUser(user: UserEntity): SafeUser { + return { + id: user.id, + username: user.username, + createdAt: user.createdAt, + updatedAt: user.updatedAt, + }; + } +} diff --git a/server/src/auth/password.service.ts b/server/src/auth/password.service.ts new file mode 100644 index 0000000..7ebfe31 --- /dev/null +++ b/server/src/auth/password.service.ts @@ -0,0 +1,91 @@ +import { randomBytes, scrypt, timingSafeEqual } from "node:crypto"; +import { Injectable } from "@nestjs/common"; + +const SCRYPT_N = 16384; +const SCRYPT_R = 8; +const SCRYPT_P = 1; +const SALT_BYTES = 16; +const HASH_BYTES = 64; + +function derive( + password: string, + salt: Buffer, + length: number, + N: number, + r: number, + p: number, +): Promise { + 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 { + 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 { + 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); + } +} diff --git a/server/src/auth/public.decorator.ts b/server/src/auth/public.decorator.ts new file mode 100644 index 0000000..7beff6f --- /dev/null +++ b/server/src/auth/public.decorator.ts @@ -0,0 +1,4 @@ +import { SetMetadata } from "@nestjs/common"; + +export const IS_PUBLIC_KEY = "isPublic"; +export const Public = () => SetMetadata(IS_PUBLIC_KEY, true); diff --git a/server/src/auth/revoked-token.entity.ts b/server/src/auth/revoked-token.entity.ts new file mode 100644 index 0000000..3fa5d0f --- /dev/null +++ b/server/src/auth/revoked-token.entity.ts @@ -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; +} diff --git a/server/src/auth/user.entity.ts b/server/src/auth/user.entity.ts new file mode 100644 index 0000000..7b2b49f --- /dev/null +++ b/server/src/auth/user.entity.ts @@ -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; +} diff --git a/server/src/browser/browser.controller.ts b/server/src/browser/browser.controller.ts index 113e041..144f607 100644 --- a/server/src/browser/browser.controller.ts +++ b/server/src/browser/browser.controller.ts @@ -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( diff --git a/server/src/config/app.config.ts b/server/src/config/app.config.ts index 7227944..3d5f882 100644 --- a/server/src/config/app.config.ts +++ b/server/src/config/app.config.ts @@ -1,5 +1,7 @@ +import "reflect-metadata"; import { plainToInstance } from "class-transformer"; import { + IsBoolean, IsEnum, IsInt, IsString, @@ -10,6 +12,17 @@ import { import { appPackage } from "../common/app-package"; +export function authDurationSeconds(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; +} + export enum TraceMode { On = "on", RetainOnFailure = "retain-on-failure", @@ -74,15 +87,62 @@ 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 = ""; + + @IsString() + AUTH_JWT_EXPIRES_IN: string = "24h"; + + @IsString() + AUTH_REVOKED_TOKEN_CLEANUP_CRON: string = "0 3 * * *"; } export function validateAppConfig(config: Record): 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 && + authDurationSeconds(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; } diff --git a/server/src/credential/credential.controller.ts b/server/src/credential/credential.controller.ts index 9e21e18..c81ed03 100644 --- a/server/src/credential/credential.controller.ts +++ b/server/src/credential/credential.controller.ts @@ -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) {} diff --git a/server/src/database/entities.ts b/server/src/database/entities.ts index 8814555..d9500d1 100644 --- a/server/src/database/entities.ts +++ b/server/src/database/entities.ts @@ -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, diff --git a/server/src/database/migrations/1793823870652-AddAuthUsersAndRevokedTokens.ts b/server/src/database/migrations/1793823870652-AddAuthUsersAndRevokedTokens.ts new file mode 100644 index 0000000..91e99be --- /dev/null +++ b/server/src/database/migrations/1793823870652-AddAuthUsersAndRevokedTokens.ts @@ -0,0 +1,23 @@ +import { MigrationInterface, QueryRunner } from "typeorm"; + +export class AddAuthUsersAndRevokedTokens1793823870652 implements MigrationInterface { + name = "AddAuthUsersAndRevokedTokens1793823870652"; + + public async up(queryRunner: QueryRunner): Promise { + 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 { + await queryRunner.query(`DROP TABLE "revoked_tokens"`); + await queryRunner.query(`DROP TABLE "users"`); + } +} diff --git a/server/src/database/migrations/index.ts b/server/src/database/migrations/index.ts index 9450fc1..c9fff9a 100644 --- a/server/src/database/migrations/index.ts +++ b/server/src/database/migrations/index.ts @@ -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, ]; diff --git a/server/src/environment/environment.controller.ts b/server/src/environment/environment.controller.ts index a6dd6ba..4dc3c85 100644 --- a/server/src/environment/environment.controller.ts +++ b/server/src/environment/environment.controller.ts @@ -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) {} diff --git a/server/src/health/health.controller.ts b/server/src/health/health.controller.ts index f3f9700..b23b3fd 100644 --- a/server/src/health/health.controller.ts +++ b/server/src/health/health.controller.ts @@ -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 } { diff --git a/server/src/import/import.controller.ts b/server/src/import/import.controller.ts index 657ce1f..2603f76 100644 --- a/server/src/import/import.controller.ts +++ b/server/src/import/import.controller.ts @@ -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) {} diff --git a/server/src/interceptors/logging.interceptor.ts b/server/src/interceptors/logging.interceptor.ts index ba03c0e..9ad433b 100644 --- a/server/src/interceptors/logging.interceptor.ts +++ b/server/src/interceptors/logging.interceptor.ts @@ -8,6 +8,22 @@ 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 { + if ( + !/^(?:\/api\/v1)?\/auth\/login$/.test(path) || + !body || + typeof body !== "object" || + Array.isArray(body) + ) { + return body; + } + const requestBody = body as Record; + return { + ...requestBody, + password: requestBody.password ? "[REDACTED]" : requestBody.password, + }; +} + @Injectable() export class LoggingInterceptor implements NestInterceptor { private readonly logger = new TraceLogger(LoggingInterceptor.name); @@ -18,8 +34,11 @@ export class LoggingInterceptor implements NestInterceptor { const res = http.getResponse(); 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}`); diff --git a/server/src/main.ts b/server/src/main.ts index cc17762..06a7861 100644 --- a/server/src/main.ts +++ b/server/src/main.ts @@ -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); diff --git a/server/src/manifest/manifest.controller.ts b/server/src/manifest/manifest.controller.ts index 6d5ff51..5d6e990 100644 --- a/server/src/manifest/manifest.controller.ts +++ b/server/src/manifest/manifest.controller.ts @@ -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) {} @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"), diff --git a/server/src/manifest/manifest.dto.ts b/server/src/manifest/manifest.dto.ts index 0894dab..2ac738a 100644 --- a/server/src/manifest/manifest.dto.ts +++ b/server/src/manifest/manifest.dto.ts @@ -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 optional account authentication is enabled.", + type: "object", + properties: { enabled: { type: "boolean", example: false } }, + }) + auth!: { enabled: boolean }; + @ApiProperty({ type: RunLogsManifestDto }) runLogs!: RunLogsManifestDto; } diff --git a/server/src/mcp/mcp.controller.ts b/server/src/mcp/mcp.controller.ts index 8adf7b3..2c46950 100644 --- a/server/src/mcp/mcp.controller.ts +++ b/server/src/mcp/mcp.controller.ts @@ -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) {} diff --git a/server/src/scenario/scenario.controller.ts b/server/src/scenario/scenario.controller.ts index d2fd47a..a193356 100644 --- a/server/src/scenario/scenario.controller.ts +++ b/server/src/scenario/scenario.controller.ts @@ -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( diff --git a/server/src/session/session.controller.ts b/server/src/session/session.controller.ts index b6779ce..1ab3a17 100644 --- a/server/src/session/session.controller.ts +++ b/server/src/session/session.controller.ts @@ -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( diff --git a/server/src/snippet/snippet.controller.ts b/server/src/snippet/snippet.controller.ts index 5899bc9..83adcd3 100644 --- a/server/src/snippet/snippet.controller.ts +++ b/server/src/snippet/snippet.controller.ts @@ -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) {} diff --git a/server/test/app.harness.ts b/server/test/app.harness.ts index 27f4975..aa0e3b2 100644 --- a/server/test/app.harness.ts +++ b/server/test/app.harness.ts @@ -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 { // Each test app stores files in its own temp dir: suites run in parallel and @@ -69,6 +70,7 @@ export async function buildTestApp(): Promise { }), ScheduleModule.forRoot(), BrowserModule, + AuthModule, SessionModule, EnvironmentModule, ScenarioModule, diff --git a/server/test/auth-config.spec.ts b/server/test/auth-config.spec.ts new file mode 100644 index 0000000..83ab381 --- /dev/null +++ b/server/test/auth-config.spec.ts @@ -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(); + }); +}); diff --git a/server/test/auth-disabled.spec.ts b/server/test/auth-disabled.spec.ts new file mode 100644 index 0000000..262079a --- /dev/null +++ b/server/test/auth-disabled.spec.ts @@ -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(); + 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 }); + }); +}); diff --git a/server/test/auth.spec.ts b/server/test/auth.spec.ts new file mode 100644 index 0000000..8dd3c73 --- /dev/null +++ b/server/test/auth.spec.ts @@ -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 { + 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(); + let app: INestApplication; + let users: Repository; + let passwords: PasswordService; + let auth: AuthService; + let revokedTokens: Repository; + 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>(getRepositoryToken(UserEntity)); + passwords = app.get(PasswordService); + auth = app.get(AuthService); + revokedTokens = app.get>( + 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); + }); +}); diff --git a/server/test/logging.interceptor.spec.ts b/server/test/logging.interceptor.spec.ts new file mode 100644 index 0000000..cfe4671 --- /dev/null +++ b/server/test/logging.interceptor.spec.ts @@ -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); + }); +}); diff --git a/server/test/manifest.spec.ts b/server/test/manifest.spec.ts index 7526d45..3b12513 100644 --- a/server/test/manifest.spec.ts +++ b/server/test/manifest.spec.ts @@ -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");