Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#2926 - Détection de code HTML entrant dans nos APIs #2949

Merged
merged 2 commits into from
Feb 11, 2025
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
115 changes: 115 additions & 0 deletions back/src/adapters/primary/routers/security.e2e.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import {
AgencyDtoBuilder,
ConventionDtoBuilder,
UnauthenticatedConventionRoutes,
expectHttpResponseToEqual,
unauthenticatedConventionRoutes,
} from "shared";
import { HttpClient } from "shared-routes";
import { createSupertestSharedClient } from "shared-routes/supertest";
import { AppConfigBuilder } from "../../../utils/AppConfigBuilder";
import { InMemoryGateways, buildTestApp } from "../../../utils/buildTestApp";

describe("security e2e", () => {
const peAgency = new AgencyDtoBuilder().withKind("pole-emploi").build();

const convention = new ConventionDtoBuilder()
.withAgencyId(peAgency.id)
.withFederatedIdentity({ provider: "peConnect", token: "some-id" })
.build();

let unauthenticatedRequest: HttpClient<UnauthenticatedConventionRoutes>;
let gateways: InMemoryGateways;

beforeEach(async () => {
const testApp = await buildTestApp(new AppConfigBuilder().build());
const request = testApp.request;

({ gateways } = testApp);

unauthenticatedRequest = createSupertestSharedClient(
unauthenticatedConventionRoutes,
request,
);

gateways.timeGateway.defaultDate = new Date();
});

describe("check request body for HTML", () => {
it("400 - should throw an error if a request (POST) body parameter contains HTML", async () => {
const response = await unauthenticatedRequest.createConvention({
body: {
convention: {
...convention,
businessName: "<script>alert('XSS')</script>",
},
},
});

expectHttpResponseToEqual(response, {
body: {
status: 400,
message: "Invalid request body",
},
status: 400,
});
});

it("200 - should not throw an error if a request (POST) body parameter does not contain HTML", async () => {
const response = await unauthenticatedRequest.createConvention({
body: {
convention: {
...convention,
businessName: "L'amie > caline !",
},
},
});

expectHttpResponseToEqual(response, {
body: {
id: convention.id,
},
status: 200,
});
});

it("400 - should throw an error if a request (GET) query parameter contains HTML", async () => {
const response = await unauthenticatedRequest.findSimilarConventions({
queryParams: {
beneficiaryBirthdate: "1990-01-01",
beneficiaryLastName: "<script>alert('XSS')</script>",
codeAppellation: "1234567890",
dateStart: "2021-01-01",
siret: "12345678901234",
},
});

expectHttpResponseToEqual(response, {
body: {
status: 400,
message: "Invalid request body",
},
status: 400,
});
});

it("200 - should not throw an error if a request (GET) query parameter does not contain HTML", async () => {
const response = await unauthenticatedRequest.findSimilarConventions({
queryParams: {
beneficiaryBirthdate: "1990-01-01",
beneficiaryLastName: "Bon<<eau",
codeAppellation: "11573",
dateStart: "2021-01-01",
siret: "12345678901234",
},
});

expectHttpResponseToEqual(response, {
body: {
similarConventionIds: [],
},
status: 200,
});
});
});
});
26 changes: 26 additions & 0 deletions back/src/config/bootstrap/detectHtmlInParamsMiddleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { NextFunction, Request, Response } from "express";
import { doesObjectContainsHTML, technicalRoutes } from "shared";

const excludedRoutes: string[] = [
technicalRoutes.htmlToPdf.url,
technicalRoutes.inboundEmailParsing.url,
];

export const detectHtmlInParamsMiddleware = (
req: Request,
res: Response,
next: NextFunction,
) => {
if (!excludedRoutes.includes(req.originalUrl)) {
if (
(req.body && doesObjectContainsHTML(req.body)) ||
(req.query && doesObjectContainsHTML(req.query))
) {
return res.status(400).json({
status: 400,
message: "Invalid request body",
});
}
}
next();
};
3 changes: 2 additions & 1 deletion back/src/config/bootstrap/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import { legacyCreateLogger } from "../../utils/logger";
import { AppConfig } from "./appConfig";
import { createAppDependencies } from "./createAppDependencies";
import { Gateways } from "./createGateways";
import { detectHtmlInParamsMiddleware } from "./detectHtmlInParamsMiddleware";
import { startCrawler } from "./startCrawler";

const logger = legacyCreateLogger(__filename);
Expand Down Expand Up @@ -74,7 +75,7 @@ export const createApp = async (
} else next();
});
});

app.use(detectHtmlInParamsMiddleware);
const deps = await createAppDependencies(config);

app.use(createSearchRouter(deps));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ export class HttpConventionGateway implements ConventionGateway {
.then((response) =>
match(response)
.with({ status: 200 }, ({ body }) => body.similarConventionIds)
.with({ status: 400 }, throwBadRequestWithExplicitMessage)
.otherwise(otherwiseThrow),
),
);
Expand Down
1 change: 1 addition & 0 deletions shared/src/convention/convention.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ export const unauthenticatedConventionRoutes = defineRoutes({
queryParamsSchema: findSimilarConventionsParamsSchema,
responses: {
200: findSimilarConventionsResponseSchema,
400: httpErrorSchema,
},
}),
});
Expand Down
20 changes: 20 additions & 0 deletions shared/src/utils/string.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { values } from "ramda";

export const capitalize = (str: string): string =>
str[0].toUpperCase() + str.slice(1);

Expand Down Expand Up @@ -45,3 +47,21 @@ export const removeSpaces = (str: string) => str.replace(/\s/g, "");

export const isStringEmpty = (str: string) =>
str !== "" && str.trim().length === 0;

export const doesStringContainsHTML = (possiblyHtmlString: string): boolean => {
const htmlRegex =
/(?:<[!]?(?:(?:[a-z][a-z0-9-]{0,1000})|(?:!--[\s\S]{0,1000}?--))(?:\s{0,1000}[^>]{0,1000})?>\s{0,1000})|(?:<!--)/i;
return htmlRegex.test(possiblyHtmlString);
};

export const doesObjectContainsHTML = (obj: object): boolean => {
const browseObjectProps = (hasHtml: boolean, value: unknown): boolean => {
if (hasHtml) return true;
if (typeof value === "string") return doesStringContainsHTML(value);
if (typeof value === "object" && value !== null) {
return values(value).reduce(browseObjectProps, false);
}
return false;
};
return values(obj).reduce(browseObjectProps, false);
};
15 changes: 15 additions & 0 deletions shared/src/utils/string.unit.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
cleanStringToHTMLAttribute,
doesStringContainsHTML,
looksLikeSiret,
removeDiacritics,
slugify,
Expand Down Expand Up @@ -111,4 +112,18 @@ describe("string utils", () => {
},
);
});

describe("doesStringContainsHTML", () => {
it.each([
["<script>alert('XSS')</script>", true],
["some content with a <a href='example.com'>link</a>", true],
["some content with a <!-- beginning of html comment", true],
["some content with a <!-- html comment -->", true],
["some content with an --> ending of html comment", false],
["some content with an < open tag", false],
["> < emoji ?", false],
])(`should return true for "%s"`, (input, expected) => {
expect(doesStringContainsHTML(input)).toBe(expected);
});
});
});
Loading