From 09c9b25178cf2445b044b24efac46380ae2e8fc5 Mon Sep 17 00:00:00 2001 From: Nanobyte Date: Thu, 25 Feb 2021 19:08:29 +0100 Subject: [PATCH] Fix getSkipSegmentsByHash requires valid json The categories parameter has to be a valid array with strings in JSON format --- src/routes/getSkipSegmentsByHash.ts | 22 +++++++++++++++++----- test/cases/getSegmentsByHash.ts | 6 +++--- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/src/routes/getSkipSegmentsByHash.ts b/src/routes/getSkipSegmentsByHash.ts index 5c557ac..399400b 100644 --- a/src/routes/getSkipSegmentsByHash.ts +++ b/src/routes/getSkipSegmentsByHash.ts @@ -10,11 +10,23 @@ export async function getSkipSegmentsByHash(req: Request, res: Response) { return; } - const categories: Category[] = req.query.categories - ? JSON.parse(req.query.categories as string) - : req.query.category - ? [req.query.category] - : ['sponsor']; + let categories: Category[] = []; + try { + categories = req.query.categories + ? JSON.parse(req.query.categories as string) + : req.query.category + ? [req.query.category] + : ["sponsor"]; + if (!Array.isArray(categories)) { + return res.status(400).send("Categories parameter does not match format requirements."); + } + } + catch(error) { + return res.status(400).send("Bad parameter: categories (invalid JSON)"); + } + + // filter out none string elements, only flat array with strings is valid + categories = categories.filter((item: any) => typeof item === "string"); // Get all video id's that match hash prefix const segments = getSegmentsByHash(req, hashPrefix, categories); diff --git a/test/cases/getSegmentsByHash.ts b/test/cases/getSegmentsByHash.ts index a76861a..1d0975f 100644 --- a/test/cases/getSegmentsByHash.ts +++ b/test/cases/getSegmentsByHash.ts @@ -96,10 +96,10 @@ describe('getSegmentsByHash', () => { .catch(err => done("Couldn't call endpoint")); }); - it('Should return 500 for bad format categories', (done: Done) => { // should probably be 400 - fetch(getbaseURL() + '/api/skipSegments/?categories=shilling') + it('Should return 400 for bad format categories', (done: Done) => { + fetch(getbaseURL() + '/api/skipSegments/fdaf?categories=shilling') .then(res => { - if (res.status !== 500) done("expected 500 got " + res.status); + if (res.status !== 400) done("expected 400 got " + res.status); else done(); // pass }) .catch(err => done("Couldn't call endpoint"));