|
| 1 | +package gov.cms.madie.models.validators; |
| 2 | + |
| 3 | +import jakarta.validation.ConstraintValidatorContext; |
| 4 | +import org.junit.jupiter.api.BeforeEach; |
| 5 | +import org.junit.jupiter.api.Test; |
| 6 | +import org.junit.jupiter.api.extension.ExtendWith; |
| 7 | +import org.junit.jupiter.params.ParameterizedTest; |
| 8 | +import org.junit.jupiter.params.provider.ValueSource; |
| 9 | +import org.mockito.Mock; |
| 10 | +import org.mockito.junit.jupiter.MockitoExtension; |
| 11 | + |
| 12 | +import static org.junit.jupiter.api.Assertions.assertFalse; |
| 13 | +import static org.junit.jupiter.api.Assertions.assertTrue; |
| 14 | + |
| 15 | +@ExtendWith(MockitoExtension.class) |
| 16 | +class XssValidatorTest { |
| 17 | + |
| 18 | + private XssValidator xssValidator; |
| 19 | + |
| 20 | + @Mock |
| 21 | + private ConstraintValidatorContext context; |
| 22 | + |
| 23 | + @BeforeEach |
| 24 | + void setUp() { |
| 25 | + xssValidator = new XssValidator(); |
| 26 | + } |
| 27 | + |
| 28 | + @Test |
| 29 | + void testIsValidReturnsTrueForNullInput() { |
| 30 | + assertTrue(xssValidator.isValid(null, context)); |
| 31 | + } |
| 32 | + |
| 33 | + @ParameterizedTest |
| 34 | + @ValueSource(strings = { |
| 35 | + "", |
| 36 | + " ", |
| 37 | + "Just a regular string with no tags", |
| 38 | + "Medicare Advantage Plan 2026", |
| 39 | + "This is safe alphanumeric input 123" |
| 40 | + }) |
| 41 | + void testIsValidReturnsTrueForSafeStrings(String safeInput) { |
| 42 | + assertTrue(xssValidator.isValid(safeInput, context)); |
| 43 | + } |
| 44 | + |
| 45 | + @ParameterizedTest |
| 46 | + @ValueSource(strings = { |
| 47 | + "{base}*1 ", |
| 48 | + "${spring.expression}", |
| 49 | + "#{systemProperties}", |
| 50 | + "some[array]element", |
| 51 | + "multiplication*sign" |
| 52 | + }) |
| 53 | + void testIsValidReturnsFalseForBackendExpressions(String expressionInput) { |
| 54 | + assertFalse(xssValidator.isValid(expressionInput, context)); |
| 55 | + } |
| 56 | + |
| 57 | + @ParameterizedTest |
| 58 | + @ValueSource(strings = { |
| 59 | + "<script>alert(1)</script>", |
| 60 | + "<html><body>malicious</body></html>", |
| 61 | + "<div>plain div tag</div>", |
| 62 | + "<b>bold text</b>", |
| 63 | + "<img src=x onerror=alert(1)>" |
| 64 | + }) |
| 65 | + void testIsValidReturnsFalseForFrontendXssAndHtmlTags(String htmlInput) { |
| 66 | + assertFalse(xssValidator.isValid(htmlInput, context)); |
| 67 | + } |
| 68 | + |
| 69 | + @ParameterizedTest |
| 70 | + @ValueSource(strings = { |
| 71 | + "%3cbody%20onresize%3d%22print()%22%3e", // URL encoded <body onresize="print()"> |
| 72 | + "%3cscript%3ealert(1)%3c/script%3e", // URL encoded <script>alert(1)</script> |
| 73 | + "hello%20world%2a" // URL encoded '*' character at the end |
| 74 | + }) |
| 75 | + void testIsValidReturnsFalseForUrlEncodedPayloads(String encodedInput) { |
| 76 | + assertFalse(xssValidator.isValid(encodedInput, context)); |
| 77 | + } |
| 78 | +} |
0 commit comments