diff --git a/src/util/HeaderUtil.ts b/src/util/HeaderUtil.ts index e411a36f3..fa1bc5f74 100644 --- a/src/util/HeaderUtil.ts +++ b/src/util/HeaderUtil.ts @@ -362,6 +362,9 @@ export const parseAcceptLanguage = (input: string): AcceptLanguage[] => { return results; }; +// eslint-disable-next-line max-len +const rfc1123Date = /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT$/u; + /** * Parses an Accept-DateTime header string. * @@ -369,8 +372,22 @@ export const parseAcceptLanguage = (input: string): AcceptLanguage[] => { * * @returns An array with a single {@link AcceptDatetime} object. */ -export const parseAcceptDateTime = (input: string): AcceptDatetime[] => - [{ range: input, weight: 1 }]; +export const parseAcceptDateTime = (input: string): AcceptDatetime[] => { + const results: AcceptDatetime[] = []; + const range = input.trim(); + if (range) { + if (!rfc1123Date.test(range)) { + logger.warn( + `Invalid Accept-DateTime range: ${range}`, + ); + throw new BadRequestHttpError( + `Invalid Accept-DateTime range: ${range} does not match the RFC1123 format`, + ); + } + results.push({ range, weight: 1 }); + } + return results; +}; /** * Adds a header value without overriding previous values. diff --git a/test/unit/util/HeaderUtil.test.ts b/test/unit/util/HeaderUtil.test.ts index 865e9f643..f6884f5fc 100644 --- a/test/unit/util/HeaderUtil.test.ts +++ b/test/unit/util/HeaderUtil.test.ts @@ -3,6 +3,7 @@ import { addHeader, parseAccept, parseAcceptCharset, + parseAcceptDateTime, parseAcceptEncoding, parseAcceptLanguage, parseForwarded, @@ -131,6 +132,24 @@ describe('HeaderUtil', (): void => { }); }); + describe('#parseAcceptDateTime', (): void => { + it('parses valid Accept-DateTime Headers.', async(): Promise => { + expect(parseAcceptDateTime('Wed, 30 May 2007 18:47:52 GMT')).toEqual([ + { range: 'Wed, 30 May 2007 18:47:52 GMT', weight: 1 }, + ]); + }); + + it('parses empty Accept-DateTime headers.', async(): Promise => { + expect(parseAcceptDateTime('')).toEqual([]); + expect(parseAcceptDateTime(' ')).toEqual([]); + }); + + it('rejects invalid Accept-DateTime Headers.', async(): Promise => { + expect((): any => parseAcceptDateTime('a/b')).toThrow('Invalid Accept-DateTime range:'); + expect((): any => parseAcceptDateTime('30 May 2007')).toThrow('Invalid Accept-DateTime range:'); + }); + }); + describe('#addHeader', (): void => { let response: HttpResponse; @@ -168,7 +187,7 @@ describe('HeaderUtil', (): void => { }); }); - describe('parseForwarded', (): void => { + describe('#parseForwarded', (): void => { it('parses an undefined value.', (): void => { expect(parseForwarded()).toEqual({}); });