Skip to content

Commit

Permalink
Enhance Value utility to support multiple QUERY patterns with sanitiz…
Browse files Browse the repository at this point in the history
…ation and validation
  • Loading branch information
dharmesh-hemaram committed Nov 10, 2024
1 parent 200ea3b commit d2714e1
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
13 changes: 13 additions & 0 deletions libs/acf/util/src/lib/value.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,17 @@ describe('getValue', () => {

window.history.replaceState({}, '', `${window.location.pathname}${originalSearch}`);
});

it('should handle multiple QUERY patterns correctly with sanitization and validation', async () => {
const searchParams = new URLSearchParams();
searchParams.set('param1', 'value1');
searchParams.set('param2', 'value2<script>alert(1)</script>');
const originalSearch = window.location.search;
window.history.replaceState({}, '', `${window.location.pathname}?${searchParams.toString()}`);

const result = await Value.getValue('<query::param1> and <query::param2>');
expect(result).toBe('value1 and value2&lt;script&gt;alert(1)&lt;/script&gt;');

window.history.replaceState({}, '', `${window.location.pathname}${originalSearch}`);
});
});
22 changes: 20 additions & 2 deletions libs/acf/util/src/lib/value.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,19 +39,37 @@ export const Value = (() => {

const getSessionCount = (value: string) => value.replaceAll('<sessionCount>', String(window.__sessionCount));

const sanitizeInput = (input: string): string => {
const element = document.createElement('div');
element.innerText = input;
return element.innerHTML;
};

const validateQueryParam = (key: string, value: string): boolean => {
const pattern = /^[a-zA-Z0-9_-]+$/;
return pattern.test(key) && pattern.test(value);
};

const getQueryParam = (value: string) => {
const [, key] = value.split('::');
const searchParams = new URLSearchParams(window.location.search);
if (searchParams.has(key)) {
value = searchParams.get(key) || key;
const paramValue = searchParams.get(key) || key;
if (validateQueryParam(key, paramValue)) {
value = sanitizeInput(paramValue);
}
}
return value;
};

const getMultiQueryParam = (value: string) => {
value = value.replace(VALUE_MATCHER.QUERY, (_, key) => {
const searchParams = new URLSearchParams(window.location.search);
return searchParams.get(key) || key;
const paramValue = searchParams.get(key) || key;
if (validateQueryParam(key, paramValue)) {
return sanitizeInput(paramValue);
}
return key;
});

Check failure

Code scanning / CodeQL

Polynomial regular expression used on uncontrolled data High

This
regular expression
that depends on
library input
may run slow on strings starting with '<query::' and with many repetitions of '<query::a'.
return value;
};
Expand Down

0 comments on commit d2714e1

Please sign in to comment.