feat(auth): add optional authentication boundary
- Add account, JWT session, revocation, cookie and bearer handling. - Protect server surfaces while preserving public health, manifest and disabled mode. - Add SQLite migration and focused server regression coverage.
This commit is contained in:
1 parent
d4bb274982
commit
de41571b5c
33 files changed
+1083
-20
No files matched your search
@@ -4,6 +4,7 @@ import { ScheduleModule } from "@nestjs/schedule";
|
|||||||
import { ServeStaticModule } from "@nestjs/serve-static";
|
import { ServeStaticModule } from "@nestjs/serve-static";
|
||||||
import { TypeOrmModule } from "@nestjs/typeorm";
|
import { TypeOrmModule } from "@nestjs/typeorm";
|
||||||
import { BrowserModule } from "./browser/browser.module";
|
import { BrowserModule } from "./browser/browser.module";
|
||||||
|
import { AuthModule } from "./auth/auth.module";
|
||||||
import { clientStaticOptions } from "./common/client-static";
|
import { clientStaticOptions } from "./common/client-static";
|
||||||
import { dataSourceOptions } from "./database/data-source";
|
import { dataSourceOptions } from "./database/data-source";
|
||||||
import { AppConfig, validateAppConfig } from "./config/app.config";
|
import { AppConfig, validateAppConfig } from "./config/app.config";
|
||||||
@@ -36,6 +37,7 @@ import { SnippetModule } from "./snippet/snippet.module";
|
|||||||
dataSourceOptions(config.get("DB_PATH")),
|
dataSourceOptions(config.get("DB_PATH")),
|
||||||
}),
|
}),
|
||||||
BrowserModule,
|
BrowserModule,
|
||||||
|
AuthModule,
|
||||||
EnvironmentModule,
|
EnvironmentModule,
|
||||||
CredentialModule,
|
CredentialModule,
|
||||||
ScenarioModule,
|
ScenarioModule,
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
export const AUTH_COOKIE_NAME = "liqa_auth";
|
||||||
@@ -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<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",
|
||||||
|
`${AUTH_COOKIE_NAME}=; ${[
|
||||||
|
...cookieOptions(request),
|
||||||
|
"Max-Age=0",
|
||||||
|
"Expires=Thu, 01 Jan 1970 00:00:00 GMT",
|
||||||
|
].join("; ")}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<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);
|
||||||
|
if (!token) throw new UnauthorizedException();
|
||||||
|
request.authSession = await this.auth.authenticate(token);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 {}
|
||||||
@@ -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<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");
|
||||||
|
}
|
||||||
|
|
||||||
|
async login(username: string, password: string): Promise<AuthSession> {
|
||||||
|
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<UserEntity, "id" | "username" | "createdAt" | "updatedAt">,
|
||||||
|
): 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<AuthSession> {
|
||||||
|
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<void> {
|
||||||
|
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<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 UnauthorizedException();
|
||||||
|
}
|
||||||
|
return claims as JwtPayload;
|
||||||
|
}
|
||||||
|
|
||||||
|
private safeUser(user: UserEntity): SafeUser {
|
||||||
|
return {
|
||||||
|
id: user.id,
|
||||||
|
username: user.username,
|
||||||
|
createdAt: user.createdAt,
|
||||||
|
updatedAt: user.updatedAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
import { SetMetadata } from "@nestjs/common";
|
||||||
|
|
||||||
|
export const IS_PUBLIC_KEY = "isPublic";
|
||||||
|
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -1,5 +1,10 @@
|
|||||||
import { Body, Controller, Post } from "@nestjs/common";
|
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 { CodeExecutorService } from "../code-executor/code-executor.service";
|
||||||
import { CredentialService } from "../credential/credential.service";
|
import { CredentialService } from "../credential/credential.service";
|
||||||
import { EnvironmentService } from "../environment/environment.service";
|
import { EnvironmentService } from "../environment/environment.service";
|
||||||
@@ -8,6 +13,7 @@ import { ExecDto } from "./dto/exec.dto";
|
|||||||
import { OpenDto } from "./dto/open.dto";
|
import { OpenDto } from "./dto/open.dto";
|
||||||
|
|
||||||
@ApiTags("browser")
|
@ApiTags("browser")
|
||||||
|
@ApiBearerAuth()
|
||||||
@Controller()
|
@Controller()
|
||||||
export class BrowserController {
|
export class BrowserController {
|
||||||
constructor(
|
constructor(
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
|
import "reflect-metadata";
|
||||||
import { plainToInstance } from "class-transformer";
|
import { plainToInstance } from "class-transformer";
|
||||||
import {
|
import {
|
||||||
|
IsBoolean,
|
||||||
IsEnum,
|
IsEnum,
|
||||||
IsInt,
|
IsInt,
|
||||||
IsString,
|
IsString,
|
||||||
@@ -10,6 +12,17 @@ import {
|
|||||||
|
|
||||||
import { appPackage } from "../common/app-package";
|
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 {
|
export enum TraceMode {
|
||||||
On = "on",
|
On = "on",
|
||||||
RetainOnFailure = "retain-on-failure",
|
RetainOnFailure = "retain-on-failure",
|
||||||
@@ -74,15 +87,62 @@ export class AppConfig {
|
|||||||
@IsInt()
|
@IsInt()
|
||||||
@Min(0)
|
@Min(0)
|
||||||
RUN_LOG_DATA_COLLAPSE_LINES: number = 5;
|
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<string, unknown>): AppConfig {
|
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,
|
enableImplicitConversion: true,
|
||||||
});
|
});
|
||||||
const errors = validateSync(validated, { skipMissingProperties: false });
|
const errors = validateSync(validated, { skipMissingProperties: false });
|
||||||
if (errors.length > 0) {
|
if (errors.length > 0) {
|
||||||
throw new Error(errors.toString());
|
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;
|
return validated;
|
||||||
}
|
}
|
||||||
@@ -10,7 +10,12 @@ import {
|
|||||||
Post,
|
Post,
|
||||||
Query,
|
Query,
|
||||||
} from "@nestjs/common";
|
} 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 { CredentialQueryDto } from "./dto/credential-query.dto";
|
||||||
import { CredentialService } from "./credential.service";
|
import { CredentialService } from "./credential.service";
|
||||||
import { CreateCredentialDto } from "./dto/create-credential.dto";
|
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";
|
import { UpdateCredentialDto } from "./dto/update-credential.dto";
|
||||||
|
|
||||||
@ApiTags("credentials")
|
@ApiTags("credentials")
|
||||||
|
@ApiBearerAuth()
|
||||||
@Controller("credentials")
|
@Controller("credentials")
|
||||||
export class CredentialController {
|
export class CredentialController {
|
||||||
constructor(private readonly credentialService: CredentialService) {}
|
constructor(private readonly credentialService: CredentialService) {}
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import { CredentialEntity } from "../credential/credential.entity";
|
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 { EnvironmentEntity } from "../environment/environment.entity";
|
||||||
import { FileEntity } from "../file/file.entity";
|
import { FileEntity } from "../file/file.entity";
|
||||||
import { ScenarioFileEntity } from "../file/scenario-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). */
|
/** Every TypeORM entity of the app (used by the app, the migrations CLI and tests). */
|
||||||
export const ENTITIES = [
|
export const ENTITIES = [
|
||||||
|
UserEntity,
|
||||||
|
RevokedTokenEntity,
|
||||||
SessionEntity,
|
SessionEntity,
|
||||||
EnvironmentEntity,
|
EnvironmentEntity,
|
||||||
CredentialEntity,
|
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"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Initial1790793447827 } from "./1790793447827-Initial";
|
import { Initial1790793447827 } from "./1790793447827-Initial";
|
||||||
import { AddRunLogContext1790848194828 } from "./1790848194828-AddRunLogContext";
|
import { AddRunLogContext1790848194828 } from "./1790848194828-AddRunLogContext";
|
||||||
import { AddRunLogData1790850734763 } from "./1790850734763-AddRunLogData";
|
import { AddRunLogData1790850734763 } from "./1790850734763-AddRunLogData";
|
||||||
|
import { AddAuthUsersAndRevokedTokens1793823870652 } from "./1793823870652-AddAuthUsersAndRevokedTokens";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* All migrations, oldest first. Listed explicitly (instead of a glob) so the
|
* All migrations, oldest first. Listed explicitly (instead of a glob) so the
|
||||||
@@ -10,4 +11,5 @@ export const MIGRATIONS = [
|
|||||||
Initial1790793447827,
|
Initial1790793447827,
|
||||||
AddRunLogContext1790848194828,
|
AddRunLogContext1790848194828,
|
||||||
AddRunLogData1790850734763,
|
AddRunLogData1790850734763,
|
||||||
|
AddAuthUsersAndRevokedTokens1793823870652,
|
||||||
];
|
];
|
||||||
@@ -10,7 +10,12 @@ import {
|
|||||||
Post,
|
Post,
|
||||||
Query,
|
Query,
|
||||||
} from "@nestjs/common";
|
} 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 { EnvironmentQueryDto } from "./dto/environment-query.dto";
|
||||||
import { CreateEnvironmentDto } from "./dto/create-environment.dto";
|
import { CreateEnvironmentDto } from "./dto/create-environment.dto";
|
||||||
import { EnvironmentExportDto } from "./dto/environment-export.dto";
|
import { EnvironmentExportDto } from "./dto/environment-export.dto";
|
||||||
@@ -18,6 +23,7 @@ import { UpdateEnvironmentDto } from "./dto/update-environment.dto";
|
|||||||
import { EnvironmentService } from "./environment.service";
|
import { EnvironmentService } from "./environment.service";
|
||||||
|
|
||||||
@ApiTags("environments")
|
@ApiTags("environments")
|
||||||
|
@ApiBearerAuth()
|
||||||
@Controller("environments")
|
@Controller("environments")
|
||||||
export class EnvironmentController {
|
export class EnvironmentController {
|
||||||
constructor(private readonly environmentService: EnvironmentService) {}
|
constructor(private readonly environmentService: EnvironmentService) {}
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import { Controller, Get } from "@nestjs/common";
|
import { Controller, Get } from "@nestjs/common";
|
||||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
||||||
|
import { Public } from "../auth/public.decorator";
|
||||||
|
|
||||||
@ApiTags("health")
|
@ApiTags("health")
|
||||||
@Controller()
|
@Controller()
|
||||||
export class HealthController {
|
export class HealthController {
|
||||||
@Get("health")
|
@Get("health")
|
||||||
|
@Public()
|
||||||
@ApiOperation({ summary: "Health check" })
|
@ApiOperation({ summary: "Health check" })
|
||||||
@ApiResponse({ status: 200, description: "Service is healthy" })
|
@ApiResponse({ status: 200, description: "Service is healthy" })
|
||||||
health(): { status: string } {
|
health(): { status: string } {
|
||||||
@@ -12,6 +14,7 @@ export class HealthController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Get("healthz")
|
@Get("healthz")
|
||||||
|
@Public()
|
||||||
@ApiOperation({ summary: "Health check" })
|
@ApiOperation({ summary: "Health check" })
|
||||||
@ApiResponse({ status: 200, description: "Service is healthy" })
|
@ApiResponse({ status: 200, description: "Service is healthy" })
|
||||||
healthz(): { status: string } {
|
healthz(): { status: string } {
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { BadRequestException, Body, Controller, Post } from "@nestjs/common";
|
import { BadRequestException, Body, Controller, Post } from "@nestjs/common";
|
||||||
import {
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
ApiBody,
|
ApiBody,
|
||||||
ApiConsumes,
|
ApiConsumes,
|
||||||
ApiOperation,
|
ApiOperation,
|
||||||
@@ -10,6 +11,7 @@ import { YAML_CONTENT_TYPES } from "../common/body-parsers";
|
|||||||
import { ImportService } from "./import.service";
|
import { ImportService } from "./import.service";
|
||||||
|
|
||||||
@ApiTags("import")
|
@ApiTags("import")
|
||||||
|
@ApiBearerAuth()
|
||||||
@Controller("import")
|
@Controller("import")
|
||||||
export class ImportController {
|
export class ImportController {
|
||||||
constructor(private readonly importService: ImportService) {}
|
constructor(private readonly importService: ImportService) {}
|
||||||
|
|||||||
@@ -8,6 +8,22 @@ import type { Request, Response } from "express";
|
|||||||
import { Observable, tap } from "rxjs";
|
import { Observable, tap } from "rxjs";
|
||||||
import { TraceLogger } from "../common/trace-logger";
|
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<string, unknown>;
|
||||||
|
return {
|
||||||
|
...requestBody,
|
||||||
|
password: requestBody.password ? "[REDACTED]" : requestBody.password,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class LoggingInterceptor implements NestInterceptor {
|
export class LoggingInterceptor implements NestInterceptor {
|
||||||
private readonly logger = new TraceLogger(LoggingInterceptor.name);
|
private readonly logger = new TraceLogger(LoggingInterceptor.name);
|
||||||
@@ -18,8 +34,11 @@ export class LoggingInterceptor implements NestInterceptor {
|
|||||||
const res = http.getResponse<Response>();
|
const res = http.getResponse<Response>();
|
||||||
const { method, url, body } = req;
|
const { method, url, body } = req;
|
||||||
const start = Date.now();
|
const start = Date.now();
|
||||||
|
const safeBody = redactAuthRequestBody(req.path, body);
|
||||||
const bodyStr =
|
const bodyStr =
|
||||||
body && Object.keys(body).length ? ` ${JSON.stringify(body)}` : "";
|
safeBody && Object.keys(safeBody).length
|
||||||
|
? ` ${JSON.stringify(safeBody)}`
|
||||||
|
: "";
|
||||||
|
|
||||||
this.logger.debug(`→ ${method} ${url}${bodyStr}`);
|
this.logger.debug(`→ ${method} ${url}${bodyStr}`);
|
||||||
|
|
||||||
|
|||||||
+5
-1
@@ -19,7 +19,10 @@ import { TraceInterceptor } from "./interceptors/trace.interceptor";
|
|||||||
// crashes the process on any unhandled rejection or uncaught exception.
|
// crashes the process on any unhandled rejection or uncaught exception.
|
||||||
const processLogger = new TraceLogger("Process");
|
const processLogger = new TraceLogger("Process");
|
||||||
process.on("uncaughtException", (err) => {
|
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) => {
|
process.on("unhandledRejection", (reason) => {
|
||||||
processLogger.error(
|
processLogger.error(
|
||||||
@@ -74,6 +77,7 @@ async function bootstrap() {
|
|||||||
.setTitle(pkgName)
|
.setTitle(pkgName)
|
||||||
.setDescription(`${pkgName} API`)
|
.setDescription(`${pkgName} API`)
|
||||||
.setVersion(pkgVersion)
|
.setVersion(pkgVersion)
|
||||||
|
.addBearerAuth()
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
const document = SwaggerModule.createDocument(app, swaggerConfig);
|
const document = SwaggerModule.createDocument(app, swaggerConfig);
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { Controller, Get, Header } from "@nestjs/common";
|
|||||||
import { ConfigService } from "@nestjs/config";
|
import { ConfigService } from "@nestjs/config";
|
||||||
import { ApiOkResponse, ApiOperation, ApiTags } from "@nestjs/swagger";
|
import { ApiOkResponse, ApiOperation, ApiTags } from "@nestjs/swagger";
|
||||||
import { AppConfig } from "../config/app.config";
|
import { AppConfig } from "../config/app.config";
|
||||||
|
import { Public } from "../auth/public.decorator";
|
||||||
import { ManifestDto } from "./manifest.dto";
|
import { ManifestDto } from "./manifest.dto";
|
||||||
|
|
||||||
@ApiTags("manifest")
|
@ApiTags("manifest")
|
||||||
@@ -10,6 +11,7 @@ export class ManifestController {
|
|||||||
constructor(private readonly config: ConfigService<AppConfig, true>) {}
|
constructor(private readonly config: ConfigService<AppConfig, true>) {}
|
||||||
|
|
||||||
@Get("manifest.json")
|
@Get("manifest.json")
|
||||||
|
@Public()
|
||||||
// Clients cache the manifest themselves; the browser just revalidates it (ETag)
|
// Clients cache the manifest themselves; the browser just revalidates it (ETag)
|
||||||
@Header("Cache-Control", "no-cache")
|
@Header("Cache-Control", "no-cache")
|
||||||
@ApiOperation({ summary: "Public client configuration and app version" })
|
@ApiOperation({ summary: "Public client configuration and app version" })
|
||||||
@@ -18,6 +20,7 @@ export class ManifestController {
|
|||||||
return {
|
return {
|
||||||
name: this.config.get("APP_NAME"),
|
name: this.config.get("APP_NAME"),
|
||||||
version: this.config.get("APP_VERSION"),
|
version: this.config.get("APP_VERSION"),
|
||||||
|
auth: { enabled: this.config.get("AUTH_ENABLED") },
|
||||||
runLogs: {
|
runLogs: {
|
||||||
dataLimits: {
|
dataLimits: {
|
||||||
bytes: this.config.get("RUN_LOG_DATA_COLLAPSE_BYTES"),
|
bytes: this.config.get("RUN_LOG_DATA_COLLAPSE_BYTES"),
|
||||||
|
|||||||
@@ -2,13 +2,15 @@ import { ApiProperty } from "@nestjs/swagger";
|
|||||||
|
|
||||||
export class RunLogDataLimitsDto {
|
export class RunLogDataLimitsDto {
|
||||||
@ApiProperty({
|
@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,
|
example: 256,
|
||||||
})
|
})
|
||||||
bytes!: number;
|
bytes!: number;
|
||||||
|
|
||||||
@ApiProperty({
|
@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,
|
example: 5,
|
||||||
})
|
})
|
||||||
lines!: number;
|
lines!: number;
|
||||||
@@ -26,6 +28,13 @@ export class ManifestDto {
|
|||||||
@ApiProperty({ example: "1.4.0" })
|
@ApiProperty({ example: "1.4.0" })
|
||||||
version!: string;
|
version!: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
description: "Whether optional account authentication is enabled.",
|
||||||
|
type: "object",
|
||||||
|
properties: { enabled: { type: "boolean", example: false } },
|
||||||
|
})
|
||||||
|
auth!: { enabled: boolean };
|
||||||
|
|
||||||
@ApiProperty({ type: RunLogsManifestDto })
|
@ApiProperty({ type: RunLogsManifestDto })
|
||||||
runLogs!: RunLogsManifestDto;
|
runLogs!: RunLogsManifestDto;
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,15 @@
|
|||||||
import { Controller, Delete, Get, Post, Req, Res } from "@nestjs/common";
|
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 type { Request, Response } from "express";
|
||||||
import { McpService } from "./mcp.service";
|
import { McpService } from "./mcp.service";
|
||||||
|
|
||||||
@ApiTags("mcp")
|
@ApiTags("mcp")
|
||||||
|
@ApiBearerAuth()
|
||||||
@Controller("mcp")
|
@Controller("mcp")
|
||||||
export class McpController {
|
export class McpController {
|
||||||
constructor(private readonly mcpService: McpService) {}
|
constructor(private readonly mcpService: McpService) {}
|
||||||
|
|||||||
@@ -16,7 +16,12 @@ import {
|
|||||||
UploadedFile,
|
UploadedFile,
|
||||||
} from "@nestjs/common";
|
} from "@nestjs/common";
|
||||||
import { FileInterceptor } from "@nestjs/platform-express";
|
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 { Response } from "express";
|
||||||
import { interval, map, merge, type Observable } from "rxjs";
|
import { interval, map, merge, type Observable } from "rxjs";
|
||||||
import type { File as MulterFile } from "multer";
|
import type { File as MulterFile } from "multer";
|
||||||
@@ -40,6 +45,7 @@ interface SseMessage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@ApiTags("scenarios")
|
@ApiTags("scenarios")
|
||||||
|
@ApiBearerAuth()
|
||||||
@Controller("scenarios")
|
@Controller("scenarios")
|
||||||
export class ScenarioController {
|
export class ScenarioController {
|
||||||
private static readonly HEARTBEAT_MS = 25_000;
|
private static readonly HEARTBEAT_MS = 25_000;
|
||||||
@@ -60,7 +66,10 @@ export class ScenarioController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Post("import")
|
@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" })
|
@ApiResponse({ status: 201, description: "Scenario imported" })
|
||||||
importScenario(@Body() payload: unknown) {
|
importScenario(@Body() payload: unknown) {
|
||||||
return this.scenarioService.importScenario(
|
return this.scenarioService.importScenario(
|
||||||
@@ -200,7 +209,8 @@ export class ScenarioController {
|
|||||||
|
|
||||||
@Get(":id/export-e2e")
|
@Get(":id/export-e2e")
|
||||||
@ApiOperation({
|
@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: 200, description: "Zip archive" })
|
||||||
@ApiResponse({ status: 404, description: "Scenario or version not found" })
|
@ApiResponse({ status: 404, description: "Scenario or version not found" })
|
||||||
@@ -210,10 +220,8 @@ export class ScenarioController {
|
|||||||
version: number | undefined,
|
version: number | undefined,
|
||||||
@Res() res: Response,
|
@Res() res: Response,
|
||||||
) {
|
) {
|
||||||
const { filename, buffer } = await this.e2eExportService.buildE2eTestPackage(
|
const { filename, buffer } =
|
||||||
id,
|
await this.e2eExportService.buildE2eTestPackage(id, version);
|
||||||
version,
|
|
||||||
);
|
|
||||||
res.setHeader("Content-Type", "application/zip");
|
res.setHeader("Content-Type", "application/zip");
|
||||||
res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
|
res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
|
||||||
res.setHeader("Content-Length", buffer.length);
|
res.setHeader("Content-Length", buffer.length);
|
||||||
@@ -270,7 +278,8 @@ export class ScenarioController {
|
|||||||
|
|
||||||
@Get(":id/used-snippets")
|
@Get(":id/used-snippets")
|
||||||
@ApiOperation({
|
@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: 200 })
|
||||||
@ApiResponse({ status: 404, description: "Scenario not found" })
|
@ApiResponse({ status: 404, description: "Scenario not found" })
|
||||||
@@ -375,7 +384,9 @@ export class ScenarioController {
|
|||||||
const fmt = format === "csv" ? "csv" : "md";
|
const fmt = format === "csv" ? "csv" : "md";
|
||||||
const content = await this.scenarioService.exportRunLogs(id, runId, fmt);
|
const content = await this.scenarioService.exportRunLogs(id, runId, fmt);
|
||||||
const contentType =
|
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";
|
const ext = fmt === "csv" ? "csv" : "md";
|
||||||
res.setHeader("Content-Type", contentType);
|
res.setHeader("Content-Type", contentType);
|
||||||
res.setHeader(
|
res.setHeader(
|
||||||
|
|||||||
@@ -8,7 +8,12 @@ import {
|
|||||||
ParseUUIDPipe,
|
ParseUUIDPipe,
|
||||||
Query,
|
Query,
|
||||||
} from "@nestjs/common";
|
} 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 { SessionQueryDto } from "./session-query.dto";
|
||||||
import { SessionContextService } from "./session-context.service";
|
import { SessionContextService } from "./session-context.service";
|
||||||
import { SessionService } from "./session.service";
|
import { SessionService } from "./session.service";
|
||||||
@@ -19,6 +24,7 @@ function maskToken(token: string, head = 6, tail = 4): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@ApiTags("sessions")
|
@ApiTags("sessions")
|
||||||
|
@ApiBearerAuth()
|
||||||
@Controller("sessions")
|
@Controller("sessions")
|
||||||
export class SessionController {
|
export class SessionController {
|
||||||
constructor(
|
constructor(
|
||||||
|
|||||||
@@ -11,7 +11,12 @@ import {
|
|||||||
Post,
|
Post,
|
||||||
Query,
|
Query,
|
||||||
} from "@nestjs/common";
|
} 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 { SnippetQueryDto } from "./dto/snippet-query.dto";
|
||||||
import { CreateSnippetDto } from "./dto/create-snippet.dto";
|
import { CreateSnippetDto } from "./dto/create-snippet.dto";
|
||||||
import { SnippetExportDto } from "./dto/snippet-export.dto";
|
import { SnippetExportDto } from "./dto/snippet-export.dto";
|
||||||
@@ -19,6 +24,7 @@ import { UpdateSnippetDto } from "./dto/update-snippet.dto";
|
|||||||
import { SnippetService } from "./snippet.service";
|
import { SnippetService } from "./snippet.service";
|
||||||
|
|
||||||
@ApiTags("snippets")
|
@ApiTags("snippets")
|
||||||
|
@ApiBearerAuth()
|
||||||
@Controller("snippets")
|
@Controller("snippets")
|
||||||
export class SnippetController {
|
export class SnippetController {
|
||||||
constructor(private readonly snippetService: SnippetService) {}
|
constructor(private readonly snippetService: SnippetService) {}
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ import { ManifestController } from "../src/manifest/manifest.controller";
|
|||||||
import { HttpExceptionFilter } from "../src/filters/http-exception.filter";
|
import { HttpExceptionFilter } from "../src/filters/http-exception.filter";
|
||||||
import { LoggingInterceptor } from "../src/interceptors/logging.interceptor";
|
import { LoggingInterceptor } from "../src/interceptors/logging.interceptor";
|
||||||
import { validateAppConfig } from "../src/config/app.config";
|
import { validateAppConfig } from "../src/config/app.config";
|
||||||
|
import { AuthModule } from "../src/auth/auth.module";
|
||||||
|
|
||||||
export async function buildTestApp(): Promise<INestApplication> {
|
export async function buildTestApp(): Promise<INestApplication> {
|
||||||
// Each test app stores files in its own temp dir: suites run in parallel and
|
// 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(),
|
ScheduleModule.forRoot(),
|
||||||
BrowserModule,
|
BrowserModule,
|
||||||
|
AuthModule,
|
||||||
SessionModule,
|
SessionModule,
|
||||||
EnvironmentModule,
|
EnvironmentModule,
|
||||||
ScenarioModule,
|
ScenarioModule,
|
||||||
|
|||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { INestApplication } from "@nestjs/common";
|
||||||
|
import request from "supertest";
|
||||||
|
import { buildTestApp } from "./app.harness";
|
||||||
|
|
||||||
|
describe("authentication disabled", () => {
|
||||||
|
const envKeys = ["AUTH_ENABLED", "AUTH_JWT_SECRET"] as const;
|
||||||
|
const previousEnv = new Map<string, string | undefined>();
|
||||||
|
let app: INestApplication;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
for (const key of envKeys) previousEnv.set(key, process.env[key]);
|
||||||
|
process.env.AUTH_ENABLED = "false";
|
||||||
|
delete process.env.AUTH_JWT_SECRET;
|
||||||
|
app = await buildTestApp();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await app?.close();
|
||||||
|
for (const key of envKeys) {
|
||||||
|
const value = previousEnv.get(key);
|
||||||
|
if (value === undefined) delete process.env[key];
|
||||||
|
else process.env[key] = value;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("starts without a secret and leaves existing REST behavior public", async () => {
|
||||||
|
await request(app.getHttpServer()).get("/scenarios").expect(200);
|
||||||
|
await request(app.getHttpServer()).get("/health").expect(200);
|
||||||
|
const manifest = await request(app.getHttpServer())
|
||||||
|
.get("/manifest.json")
|
||||||
|
.expect(200);
|
||||||
|
expect(manifest.body.auth).toEqual({ enabled: false });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,258 @@
|
|||||||
|
import { INestApplication } from "@nestjs/common";
|
||||||
|
import { getRepositoryToken } from "@nestjs/typeorm";
|
||||||
|
import request from "supertest";
|
||||||
|
import { Repository } from "typeorm";
|
||||||
|
import { filter, firstValueFrom, timeout } from "rxjs";
|
||||||
|
import { AuthService } from "../src/auth/auth.service";
|
||||||
|
import { tokenHash } from "../src/auth/auth.service";
|
||||||
|
import { PasswordService } from "../src/auth/password.service";
|
||||||
|
import { RevokedTokenEntity } from "../src/auth/revoked-token.entity";
|
||||||
|
import { EnvironmentService } from "../src/environment/environment.service";
|
||||||
|
import { RunEventsService } from "../src/scenario/run-events.service";
|
||||||
|
import { ScenarioSchedulerService } from "../src/scenario/scenario-scheduler.service";
|
||||||
|
import { ScenarioService } from "../src/scenario/scenario.service";
|
||||||
|
import { UserEntity } from "../src/auth/user.entity";
|
||||||
|
import { buildTestApp } from "./app.harness";
|
||||||
|
|
||||||
|
function firstSetCookie(response: {
|
||||||
|
headers: Record<string, unknown>;
|
||||||
|
}): string {
|
||||||
|
const value = response.headers["set-cookie"];
|
||||||
|
return Array.isArray(value) ? String(value[0]) : String(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("optional authentication", () => {
|
||||||
|
const envKeys = [
|
||||||
|
"AUTH_ENABLED",
|
||||||
|
"AUTH_JWT_SECRET",
|
||||||
|
"AUTH_JWT_EXPIRES_IN",
|
||||||
|
"AUTH_REVOKED_TOKEN_CLEANUP_CRON",
|
||||||
|
] as const;
|
||||||
|
const previousEnv = new Map<string, string | undefined>();
|
||||||
|
let app: INestApplication;
|
||||||
|
let users: Repository<UserEntity>;
|
||||||
|
let passwords: PasswordService;
|
||||||
|
let auth: AuthService;
|
||||||
|
let revokedTokens: Repository<RevokedTokenEntity>;
|
||||||
|
let user: UserEntity;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
for (const key of envKeys) previousEnv.set(key, process.env[key]);
|
||||||
|
process.env.AUTH_ENABLED = "true";
|
||||||
|
process.env.AUTH_JWT_SECRET = "auth-test-secret-only";
|
||||||
|
process.env.AUTH_JWT_EXPIRES_IN = "1h";
|
||||||
|
app = await buildTestApp();
|
||||||
|
users = app.get<Repository<UserEntity>>(getRepositoryToken(UserEntity));
|
||||||
|
passwords = app.get(PasswordService);
|
||||||
|
auth = app.get(AuthService);
|
||||||
|
revokedTokens = app.get<Repository<RevokedTokenEntity>>(
|
||||||
|
getRepositoryToken(RevokedTokenEntity),
|
||||||
|
);
|
||||||
|
user = await users.save(
|
||||||
|
users.create({
|
||||||
|
username: "alice",
|
||||||
|
passwordHash: await passwords.hash("correct-test-password"),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await app?.close();
|
||||||
|
for (const key of envKeys) {
|
||||||
|
const value = previousEnv.get(key);
|
||||||
|
if (value === undefined) delete process.env[key];
|
||||||
|
else process.env[key] = value;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps health and the secret-free auth flag public while protecting REST, MCP, and run events", async () => {
|
||||||
|
await request(app.getHttpServer()).get("/health").expect(200);
|
||||||
|
const manifest = await request(app.getHttpServer())
|
||||||
|
.get("/manifest.json")
|
||||||
|
.expect(200);
|
||||||
|
expect(manifest.body.auth).toEqual({ enabled: true });
|
||||||
|
expect(JSON.stringify(manifest.body)).not.toContain("AUTH_JWT_SECRET");
|
||||||
|
expect(JSON.stringify(manifest.body)).not.toContain(
|
||||||
|
"auth-test-secret-only",
|
||||||
|
);
|
||||||
|
|
||||||
|
await request(app.getHttpServer()).get("/scenarios").expect(401);
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get("/scenarios/runs/events")
|
||||||
|
.expect(401);
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post("/mcp")
|
||||||
|
.send({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} })
|
||||||
|
.expect(401);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("continues processing scheduled scenarios without an HTTP credential", async () => {
|
||||||
|
const environments = app.get(EnvironmentService);
|
||||||
|
const scenarios = app.get(ScenarioService);
|
||||||
|
const scheduler = app.get(ScenarioSchedulerService);
|
||||||
|
const events = app.get(RunEventsService);
|
||||||
|
const environment = await environments.create({
|
||||||
|
name: "auth-scheduler-environment",
|
||||||
|
data: {},
|
||||||
|
});
|
||||||
|
const scenario = await scenarios.create({
|
||||||
|
name: "auth-scheduler-scenario",
|
||||||
|
});
|
||||||
|
await scenarios.createStep(scenario.id, {
|
||||||
|
title: "Return a value",
|
||||||
|
execCode: "return 1;",
|
||||||
|
});
|
||||||
|
const run = await scenarios.createRun(scenario.id, environment.id);
|
||||||
|
const finished = firstValueFrom(
|
||||||
|
events.stream().pipe(
|
||||||
|
filter(
|
||||||
|
(event) => event.type === "run.finished" && event.runId === run.id,
|
||||||
|
),
|
||||||
|
timeout({ first: 5000 }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
await scheduler.pickUpPendingRuns();
|
||||||
|
await finished;
|
||||||
|
expect((await scenarios.findRun(scenario.id, run.id)).status).toBe("pass");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("logs in with a strict HttpOnly cookie and returns only safe identity fields", async () => {
|
||||||
|
const response = await request(app.getHttpServer())
|
||||||
|
.post("/auth/login")
|
||||||
|
.set("x-forwarded-proto", "https")
|
||||||
|
.send({ username: "alice", password: "correct-test-password" })
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(response.body.user).toMatchObject({
|
||||||
|
id: user.id,
|
||||||
|
username: "alice",
|
||||||
|
});
|
||||||
|
expect(response.body.user.passwordHash).toBeUndefined();
|
||||||
|
expect(response.body.token).toBeUndefined();
|
||||||
|
expect(JSON.stringify(response.body)).not.toContain(
|
||||||
|
"correct-test-password",
|
||||||
|
);
|
||||||
|
const cookie = firstSetCookie(response);
|
||||||
|
expect(cookie).toContain("HttpOnly");
|
||||||
|
expect(cookie).toContain("SameSite=Strict");
|
||||||
|
expect(cookie).toContain("Secure");
|
||||||
|
expect(cookie).toContain("Max-Age=");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects unknown or incorrect credentials without returning account data", async () => {
|
||||||
|
for (const username of ["alice", "missing-user"]) {
|
||||||
|
const response = await request(app.getHttpServer())
|
||||||
|
.post("/auth/login")
|
||||||
|
.send({ username, password: "wrong-test-password" })
|
||||||
|
.expect(401);
|
||||||
|
expect(JSON.stringify(response.body)).not.toContain("passwordHash");
|
||||||
|
expect(JSON.stringify(response.body)).not.toContain(
|
||||||
|
"wrong-test-password",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("accepts cookie and Bearer credentials and keeps the password hash private", async () => {
|
||||||
|
const login = await request(app.getHttpServer())
|
||||||
|
.post("/auth/login")
|
||||||
|
.send({ username: "alice", password: "correct-test-password" })
|
||||||
|
.expect(200);
|
||||||
|
const cookiePair = firstSetCookie(login).split(";")[0];
|
||||||
|
const token = decodeURIComponent(
|
||||||
|
cookiePair.slice(cookiePair.indexOf("=") + 1),
|
||||||
|
);
|
||||||
|
|
||||||
|
const cookieMe = await request(app.getHttpServer())
|
||||||
|
.get("/auth/me")
|
||||||
|
.set("Cookie", cookiePair)
|
||||||
|
.expect(200);
|
||||||
|
expect(cookieMe.body).toMatchObject({ id: user.id, username: "alice" });
|
||||||
|
expect(cookieMe.body.passwordHash).toBeUndefined();
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get("/scenarios")
|
||||||
|
.set("Cookie", cookiePair)
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get("/scenarios")
|
||||||
|
.set("Authorization", `Bearer ${token}`)
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
const mcp = await request(app.getHttpServer())
|
||||||
|
.post("/mcp")
|
||||||
|
.set("Authorization", `Bearer ${token}`)
|
||||||
|
.set("Content-Type", "application/json")
|
||||||
|
.set("Accept", "application/json, text/event-stream")
|
||||||
|
.send({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
id: 1,
|
||||||
|
method: "initialize",
|
||||||
|
params: {
|
||||||
|
protocolVersion: "2024-11-05",
|
||||||
|
capabilities: {},
|
||||||
|
clientInfo: { name: "auth-test", version: "0" },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.expect(200);
|
||||||
|
expect(mcp.text).toContain("protocolVersion");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects tampered and expired tokens and deleted users", async () => {
|
||||||
|
const valid = auth.issueToken(user).token;
|
||||||
|
const tampered = `${valid.slice(0, -2)}${valid.endsWith("A") ? "B" : "A"}A`;
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get("/auth/me")
|
||||||
|
.set("Authorization", `Bearer ${tampered}`)
|
||||||
|
.expect(401);
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
const oldClock = jest
|
||||||
|
.spyOn(Date, "now")
|
||||||
|
.mockReturnValue(now - 2 * 3600_000);
|
||||||
|
const expired = auth.issueToken(user).token;
|
||||||
|
oldClock.mockRestore();
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get("/auth/me")
|
||||||
|
.set("Authorization", `Bearer ${expired}`)
|
||||||
|
.expect(401);
|
||||||
|
|
||||||
|
const removedUser = await users.save(
|
||||||
|
users.create({
|
||||||
|
username: "deleted-user",
|
||||||
|
passwordHash: await passwords.hash("temporary-test-password"),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const deletedUserToken = auth.issueToken(removedUser).token;
|
||||||
|
await users.delete({ id: removedUser.id });
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get("/auth/me")
|
||||||
|
.set("Authorization", `Bearer ${deletedUserToken}`)
|
||||||
|
.expect(401);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("persists only the token digest on logout and rejects token reuse", async () => {
|
||||||
|
const login = await request(app.getHttpServer())
|
||||||
|
.post("/auth/login")
|
||||||
|
.send({ username: "alice", password: "correct-test-password" })
|
||||||
|
.expect(200);
|
||||||
|
const cookiePair = firstSetCookie(login).split(";")[0];
|
||||||
|
const token = decodeURIComponent(
|
||||||
|
cookiePair.slice(cookiePair.indexOf("=") + 1),
|
||||||
|
);
|
||||||
|
const logout = await request(app.getHttpServer())
|
||||||
|
.post("/auth/logout")
|
||||||
|
.set("Cookie", cookiePair)
|
||||||
|
.expect(204);
|
||||||
|
|
||||||
|
expect(firstSetCookie(logout)).toContain("Max-Age=0");
|
||||||
|
const storedRevocation = await revokedTokens.findOneBy({
|
||||||
|
tokenHash: tokenHash(token),
|
||||||
|
});
|
||||||
|
expect(storedRevocation?.tokenHash).not.toBe(token);
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get("/scenarios")
|
||||||
|
.set("Authorization", `Bearer ${token}`)
|
||||||
|
.expect(401);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -21,6 +21,7 @@ describe("GET /manifest.json", () => {
|
|||||||
expect(res.body).toEqual({
|
expect(res.body).toEqual({
|
||||||
name: appPackage().name,
|
name: appPackage().name,
|
||||||
version: appPackage().version,
|
version: appPackage().version,
|
||||||
|
auth: { enabled: false },
|
||||||
runLogs: { dataLimits: { bytes: 256, lines: 5 } },
|
runLogs: { dataLimits: { bytes: 256, lines: 5 } },
|
||||||
});
|
});
|
||||||
expect(res.headers["cache-control"]).toBe("no-cache");
|
expect(res.headers["cache-control"]).toBe("no-cache");
|
||||||
|
|||||||
Reference in new issue
Block a user