Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import {
BadRequestException,
createParamDecorator,
ExecutionContext,
} from "@nestjs/common";
import { ETAPE_DOSSIER_COMPLET, ETAPE_ETAT_CIVIL } from "@domifa/common";
import { parseStrictInt } from "./ParseStrictInt.pipe";

export function parseEtapeDemande(value: unknown): number | null {
return parseStrictInt(value, {
min: ETAPE_ETAT_CIVIL,
max: ETAPE_DOSSIER_COMPLET,
});
}

// Custom decorator, not a pipe: see ParseStrictInt.pipe
export const EtapeDemandeParam = createParamDecorator(
(_data: unknown, context: ExecutionContext): number => {
const etape = parseEtapeDemande(
context.switchToHttp().getRequest().params?.etapeDemande
);
if (etape === null) {
throw new BadRequestException("ETAPE_DEMANDE_INVALID");
}
return etape;
}
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import {
BadRequestException,
createParamDecorator,
ExecutionContext,
} from "@nestjs/common";

export type StrictIntBounds = { min?: number; max?: number };

// Digits only, no sign, no leading zero, no exponent / hex / decimal: one writing per number
const STRICT_INT_FORMAT = /^(0|[1-9]\d{0,14})$/;

export function parseStrictInt(
value: unknown,
{ min = 0, max = Number.MAX_SAFE_INTEGER }: StrictIntBounds = {}
): number | null {
if (typeof value !== "string" || !STRICT_INT_FORMAT.test(value)) {
return null;
}
const num = Number(value);
return num >= min && num <= max ? num : null;
}

// Custom decorator, not a pipe: the global ValidationPipe would convert the raw param ("1e3", "0x10") first
export const IntParam = createParamDecorator(
(
{ name, ...bounds }: StrictIntBounds & { name: string },
context: ExecutionContext
): number => {
const num = parseStrictInt(
context.switchToHttp().getRequest().params?.[name],
bounds
);
if (num === null) {
throw new BadRequestException(`${name.toUpperCase()}_INVALID`);
}
return num;
}
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import {
BadRequestException,
createParamDecorator,
ExecutionContext,
} from "@nestjs/common";
import { parseStrictInt } from "./ParseStrictInt.pipe";

export const USAGER_REF_MAX = 100_000;

export function parseUsagerRef(value: unknown): number | null {
return parseStrictInt(value, { min: 1, max: USAGER_REF_MAX });
}

// Custom decorator, not a pipe: see ParseStrictInt.pipe
export const UsagerRefParam = createParamDecorator(
(_data: unknown, context: ExecutionContext): number => {
const ref = parseUsagerRef(
context.switchToHttp().getRequest().params?.usagerRef
);
if (ref === null) {
throw new BadRequestException("USAGER_REF_INVALID");
}
return ref;
}
);
3 changes: 3 additions & 0 deletions packages/backend/src/_common/decorators/parse-pipes/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
//@index('./*.ts', f => `export * from '${f.path}'`)
export * from "./parse-token.pipe";
export * from "./ParseEtapeDemande.pipe";
export * from "./ParseRegion.pipe";
export * from "./ParseStrictInt.pipe";
export * from "./ParseString.pipe";
export * from "./ParseUsagerRef.pipe";
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { parseEtapeDemande } from "../parse-pipes/ParseEtapeDemande.pipe";

describe("parseEtapeDemande", () => {
it.each(["0", "1", "2", "3", "4", "5"])("accepts %s", (value) => {
expect(parseEtapeDemande(value)).toEqual(Number(value));
});

it.each(["-1", "6", "999", "03", "1.0", "", "a", undefined, 3])(
"rejects %p",
(value) => {
expect(parseEtapeDemande(value)).toBeNull();
}
);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { parseStrictInt } from "../parse-pipes/ParseStrictInt.pipe";
import { toStrictInt } from "../transformers/StrictIntDecorator";

describe("parseStrictInt", () => {
it.each([
["0", 0],
["3", 3],
["42", 42],
])("accepts %s", (value, expected) => {
expect(parseStrictInt(value)).toEqual(expected);
});

it.each([
"3X3",
"1e3",
"0x10",
"007",
"-1",
"+1",
"1.5",
" 1",
"1 ",
"",
"1234567890123456",
undefined,
null,
1,
["1"],
])("rejects %p", (value) => {
expect(parseStrictInt(value)).toBeNull();
});

it("applies the bounds", () => {
expect(parseStrictInt("0", { min: 1 })).toBeNull();
expect(parseStrictInt("11", { max: 10 })).toBeNull();
expect(parseStrictInt("10", { min: 1, max: 10 })).toEqual(10);
});
});

describe("toStrictInt", () => {
it("converts a plain integer string", () => {
expect(toStrictInt("3")).toEqual(3);
});

it.each(["3X3", "1e3", "0x10", "007", 1.5, null, undefined])(
"leaves %p untouched",
(value) => {
expect(toStrictInt(value)).toEqual(value);
}
);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { parseUsagerRef } from "../parse-pipes/ParseUsagerRef.pipe";

describe("parseUsagerRef", () => {
it.each([
["1", 1],
["42", 42],
["100000", 100000],
])("accepts %s", (value, expected) => {
expect(parseUsagerRef(value)).toEqual(expected);
});

it.each([
"0",
"-1",
"007",
"100001",
"99999999999",
"1e3",
"0x10",
"1.5",
" 1",
"1 ",
"",
"abc",
undefined,
null,
1,
["1"],
])("rejects %p", (value) => {
expect(parseUsagerRef(value)).toBeNull();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Transform, TransformFnParams } from "class-transformer";
import { parseStrictInt } from "../parse-pipes/ParseStrictInt.pipe";

// Strings that are not a plain integer are left untouched so that @IsInt rejects them
export function toStrictInt(value: unknown): unknown {
return typeof value === "string" ? parseStrictInt(value) ?? value : value;
}

export function StrictIntTransform(): PropertyDecorator {
return Transform(({ value }: TransformFnParams) => toStrictInt(value));
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//@index('./*.ts', f => `export * from '${f.path}'`)
export * from "./isSiretDecorator";
export * from "./LowerCaseDecorator";
export * from "./StrictIntDecorator";
export * from "./StripTagsDecorator";
export * from "./TrimDecorator";
export * from "./TrimOrNullDecorator";
Expand Down
10 changes: 6 additions & 4 deletions packages/backend/src/auth/guards/usager-access.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,22 @@ import {
import { isInt } from "class-validator";

import { appLogger } from "../../util";
import { parseUsagerRef } from "../../_common/decorators/parse-pipes/ParseUsagerRef.pipe";
import { usagerRepository } from "../../database";

@Injectable()
export class UsagerAccessGuard implements CanActivate {
public async canActivate(context: ExecutionContext) {
const r = context.switchToHttp().getRequest();

const usagerRef = Number(r.params?.usagerRef);
const usagerRef = parseUsagerRef(r.params?.usagerRef);
const structureId = Number(r.user?.structureId);

if (!isInt(usagerRef) || usagerRef < 0) {
appLogger.error("[UsagerAccessGuard] invalid usagerRef", {
sentry: true,
if (usagerRef === null) {
// Malformed refs come from scans: log only, no Sentry
appLogger.warn("[UsagerAccessGuard] invalid usagerRef", {
context: {
url: r.url,
usagerRef: r.params?.usagerRef,
user: r.user?.id,
},
Expand Down
9 changes: 5 additions & 4 deletions packages/backend/src/auth/guards/usager-note-access.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
} from "@nestjs/common";

import { appLogger } from "../../util";
import { parseUsagerRef } from "../../_common/decorators/parse-pipes/ParseUsagerRef.pipe";
import { isInt, isUUID } from "class-validator";
import { usagerNotesRepository } from "../../database";

Expand All @@ -15,12 +16,12 @@ export class UsagerNoteAccessGuard implements CanActivate {
public async canActivate(context: ExecutionContext) {
const r = context.switchToHttp().getRequest();

const usagerRef = Number(r.params?.usagerRef);
const usagerRef = parseUsagerRef(r.params?.usagerRef);
const structureId = Number(r.user?.structureId);

if (!isInt(usagerRef) || usagerRef < 0) {
appLogger.error("[UsagerNoteAccessGuard] invalid usagerRef", {
sentry: true,
if (usagerRef === null) {
// Malformed refs come from scans: log only, no Sentry
appLogger.warn("[UsagerNoteAccessGuard] invalid usagerRef", {
context: {
url: r.url,
usagerRef: r.params?.usagerRef,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
Delete,
Param,
ParseArrayPipe,
ParseIntPipe,
ParseUUIDPipe,
Post,
UseGuards,
Expand Down Expand Up @@ -40,6 +39,7 @@ import {
SUPPORT_READ_ROLES,
} from "@domifa/common";
import { MessageSmsService } from "../sms/services/message-sms.service";
import { UsagerRefParam } from "../../_common/decorators";

@UseGuards(AuthGuard("jwt"), AppUserGuard)
@AllowUserProfiles("structure")
Expand Down Expand Up @@ -83,7 +83,7 @@ export class InteractionsController {
@UseGuards(UsagerAccessGuard)
@AllowUserStructureRoles(...SUPPORT_READ_ROLES)
public async getInteractions(
@Param("usagerRef", new ParseIntPipe()) _usagerRef: number,
@UsagerRefParam() _usagerRef: number,
@CurrentUser() user: UserStructureAuthenticated,
@CurrentUsager() currentUsager: Usager,
@Body() pageOptionsDto: PageOptionsDto
Expand All @@ -99,7 +99,7 @@ export class InteractionsController {
@UseGuards(UsagerAccessGuard)
@AllowUserStructureRoles(...SUPPORT_READ_ROLES)
public async getLoginPortailHistory(
@Param("usagerRef", new ParseIntPipe()) _usagerRef: number,
@UsagerRefParam() _usagerRef: number,
@CurrentUser() user: UserStructureAuthenticated,
@CurrentUsager() currentUsager: Usager,
@Body() pageOptionsDto: PageOptionsDto
Expand Down Expand Up @@ -127,7 +127,7 @@ export class InteractionsController {
@CurrentUser() user: UserStructureAuthenticated,
@CurrentUsager() usager: Usager,
@Param("interactionUuid", new ParseUUIDPipe()) _interactionUuid: string,
@Param("usagerRef", new ParseIntPipe()) _usagerRef: number,
@UsagerRefParam() _usagerRef: number,
@CurrentInteraction() interaction: CommonInteraction
) {
return await this.interactionDeletor.deleteInteraction({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ const buildParams = (
[METABASE_PARAM_KEYS.structureType]: dto.structureType
? [dto.structureType]
: [],
[METABASE_PARAM_KEYS.structureId]: dto.structureId ? [dto.structureId] : [],
[METABASE_PARAM_KEYS.structureId]: dto.structureId
? [String(dto.structureId)]
: [],
});

// Cache key combines (userId, role, hash-of-resolved-params).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@ import {
STRUCTURE_TYPE_MAP,
StructureType,
} from "@domifa/common";
import { Transform } from "class-transformer";
import { StrictIntTransform } from "../../../_common/decorators";
import {
IsIn,
IsNotEmpty,
IsNumber,
IsNumberString,
IsInt,
IsOptional,
IsString,
Max,
Expand All @@ -18,8 +17,8 @@ import {

export class MetabaseStatsDto {
@IsNotEmpty()
@IsNumber()
@Transform(({ value }) => Number(value), { toClassOnly: true })
@IsInt()
@StrictIntTransform()
@Min(2020)
@Max(2048)
year: number;
Expand All @@ -35,7 +34,9 @@ export class MetabaseStatsDto {
department?: string;

@IsOptional()
@IsNumberString()
@IsInt()
@Min(1)
@StrictIntTransform()
structureId?: number;

@IsOptional()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import { BREVO_EMAIL_EVENT_TYPES, BrevoEmailEventType } from "@domifa/common";
import { Type } from "class-transformer";
import { IsIn, IsInt, IsOptional, Max, Min } from "class-validator";
import { StrictIntTransform } from "../../../_common/decorators";

export class BrevoEmailEventsQueryDto {
@IsOptional()
@Type(() => Number)
@StrictIntTransform()
@IsInt()
@Min(1)
@Max(100)
public readonly limit: number = 50;

@IsOptional()
@Type(() => Number)
@StrictIntTransform()
@IsInt()
@Min(0)
public readonly offset: number = 0;
Expand All @@ -21,7 +21,7 @@ export class BrevoEmailEventsQueryDto {
public readonly event?: BrevoEmailEventType;

@IsOptional()
@Type(() => Number)
@StrictIntTransform()
@IsInt()
@Min(1)
@Max(90)
Expand Down
Loading
Loading