-
Notifications
You must be signed in to change notification settings - Fork 732
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
fix: externalize links fails with ac scriptlets #2388
Draft
Buuhuu
wants to merge
2
commits into
adobe:main
Choose a base branch
from
Buuhuu:issue/2387-externalizer-with-ac-scriptlets
base: main
Could not load branches
Branch not found: {{ refName }}
Could not load tags
Nothing to show
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
131 changes: 131 additions & 0 deletions
131
...es/core/src/main/java/com/adobe/cq/wcm/core/components/internal/link/LinkMaskingUtil.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | ||
~ Copyright 2022 Adobe | ||
~ | ||
~ Licensed under the Apache License, Version 2.0 (the "License"); | ||
~ you may not use this file except in compliance with the License. | ||
~ You may obtain a copy of the License at | ||
~ | ||
~ http://www.apache.org/licenses/LICENSE-2.0 | ||
~ | ||
~ Unless required by applicable law or agreed to in writing, software | ||
~ distributed under the License is distributed on an "AS IS" BASIS, | ||
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
~ See the License for the specific language governing permissions and | ||
~ limitations under the License. | ||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ | ||
package com.adobe.cq.wcm.core.components.internal.link; | ||
|
||
import java.math.BigInteger; | ||
import java.security.SecureRandom; | ||
import java.util.Collections; | ||
import java.util.LinkedHashMap; | ||
import java.util.List; | ||
import java.util.Map; | ||
import java.util.regex.Matcher; | ||
import java.util.regex.Pattern; | ||
|
||
class LinkMaskingUtil { | ||
|
||
private final static List<Pattern> PATTERNS = Collections.singletonList(Pattern.compile("(<%[=@].*?%>)")); | ||
|
||
private LinkMaskingUtil() { | ||
super(); | ||
} | ||
|
||
/** | ||
* This functional interface is used to pass a callable to {@link LinkMaskingUtil#maskAndDo(String, Fn)} which has the semantics of a | ||
* {@link java.util.function.Function} but allows to throw a checked exception. | ||
* | ||
* @param <T> | ||
* @param <R> | ||
*/ | ||
@FunctionalInterface | ||
interface Fn<T, R> { | ||
R apply(T t) throws Exception; | ||
} | ||
|
||
/** | ||
* Masks the given {@link String}, calls the given {@link Fn} with it and unmasks the returned {@link String}. | ||
* | ||
* @param original a {@link String} to be masked and passed to the callable | ||
* @param callable the {@link Fn} to process the masked original | ||
* @return the unmasked return value of the given callable | ||
* @throws Exception when the given callable throws ans exception | ||
*/ | ||
static String maskAndDo(String original, Fn<String, String> callable) throws Exception { | ||
// The link contain character sequences that are not well formatted and cannot be decoded, for example | ||
// Adobe Campaign expressions like: /content/path/to/page.html?recipient=<%= recipient.id %> | ||
Map<String, String> placeholders = new LinkedHashMap<>(); | ||
String masked = mask(original, placeholders); | ||
masked = callable.apply(masked); | ||
return unmask(masked, placeholders); | ||
} | ||
|
||
/** | ||
* Masks a given {@link String} by replacing all occurrences of {@link LinkMaskingUtil#PATTERNS} with a placeholder. | ||
* The generated placeholders are put into the given {@link Map} and can be used to unmask a {@link String} later on. | ||
* <p> | ||
* For example the given original {@link String} {@code /path/to/page.html?r=<%= recipient.id %>} will be transformed to | ||
* {@code /path/to/page.html?r=_abcd_} and the placeholder with the expression will be put into the given {@link Map}. | ||
* | ||
* @param original the original {@link String} | ||
* @param placeholders a {@link Map} the generated placeholders will be put in | ||
* @return the masked {@link String} | ||
* @see LinkMaskingUtil#unmask(String, Map) | ||
*/ | ||
private static String mask(String original, Map<String, String> placeholders) { | ||
String masked = original; | ||
for (Pattern pattern : PATTERNS) { | ||
Matcher matcher = pattern.matcher(masked); | ||
while (matcher.find()) { | ||
String expression = matcher.group(1); | ||
String placeholder = newPlaceholder(masked); | ||
masked = masked.replaceFirst(Pattern.quote(expression), placeholder); | ||
placeholders.put(placeholder, expression); | ||
} | ||
} | ||
return masked; | ||
} | ||
|
||
/** | ||
* Unmasks the given {@link String} by replacing the given placeholders with their original value. | ||
* <p> | ||
* For example the given masked {@link String} {@code /path/to/page.html?r=_abcd_} will be transformed to | ||
* {@code /path/to/page.html?r=<%= recipient.id %>} by replacing each of the given {@link Map}s keys with the corresponding value. | ||
* | ||
* @param masked the masked {@link String} | ||
* @param placeholders the {@link Map} of placeholders to replace | ||
* @return the unmasked {@link String} | ||
*/ | ||
private static String unmask(String masked, Map<String, String> placeholders) { | ||
String unmasked = masked; | ||
for (Map.Entry<String, String> placeholder : placeholders.entrySet()) { | ||
unmasked = unmasked.replaceFirst(placeholder.getKey(), placeholder.getValue()); | ||
} | ||
return unmasked; | ||
} | ||
|
||
/** | ||
* Generate a new random placeholder that is not conflicting with any character sequence in the given {@link String}. | ||
* <p> | ||
* For example the given {@link String} {@code "foo"} a new random {@link String} will be returned that is not contained in the | ||
* given {@link String}. In this example the following {@link String}s will never be returned "f", "fo", "foo", "o", "oo". | ||
* | ||
* @param str the given {@link String} | ||
* @return the placeholder name | ||
*/ | ||
private static String newPlaceholder(String str) { | ||
SecureRandom random = new SecureRandom(); | ||
StringBuilder placeholderBuilder = new StringBuilder(5); | ||
|
||
do { | ||
placeholderBuilder.setLength(0); | ||
placeholderBuilder | ||
.append("_") | ||
.append(new BigInteger(16, random).toString(16)) | ||
.append("_"); | ||
} while (str.contains(placeholderBuilder)); | ||
|
||
return placeholderBuilder.toString(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -20,6 +20,9 @@ | |
import org.apache.sling.servlethelpers.MockSlingHttpServletRequest; | ||
import org.junit.jupiter.api.Test; | ||
import org.junit.jupiter.api.extension.ExtendWith; | ||
import org.mockito.AdditionalAnswers; | ||
import org.mockito.ArgumentCaptor; | ||
import org.mockito.internal.stubbing.answers.ReturnsArgumentAt; | ||
|
||
import com.adobe.cq.wcm.core.components.context.CoreComponentTestContext; | ||
import com.day.cq.commons.Externalizer; | ||
|
@@ -30,10 +33,13 @@ | |
|
||
import static com.adobe.cq.wcm.core.components.internal.link.LinkBuilderImpl.HTML_EXTENSION; | ||
import static org.junit.jupiter.api.Assertions.assertEquals; | ||
import static org.junit.jupiter.api.Assertions.assertFalse; | ||
import static org.junit.jupiter.api.Assertions.assertTrue; | ||
import static org.mockito.ArgumentMatchers.any; | ||
import static org.mockito.ArgumentMatchers.anyString; | ||
import static org.mockito.Mockito.RETURNS_DEFAULTS; | ||
import static org.mockito.Mockito.mock; | ||
import static org.mockito.Mockito.verify; | ||
import static org.mockito.Mockito.when; | ||
|
||
@ExtendWith({AemContextExtension.class}) | ||
|
@@ -47,12 +53,28 @@ class DefaultPathProcessorTest { | |
void testExternalizeWithException() { | ||
Externalizer externalizer = mock(Externalizer.class); | ||
when(externalizer.publishLink(any(ResourceResolver.class), anyString())).thenThrow(IllegalArgumentException.class); | ||
localContext.registerService(externalizer); | ||
DefaultPathProcessor underTest = localContext.registerService(new DefaultPathProcessor()); | ||
localContext.registerService(Externalizer.class, externalizer); | ||
DefaultPathProcessor underTest = localContext.registerInjectActivateService(new DefaultPathProcessor()); | ||
String path = PATH; | ||
assertEquals(path, underTest.externalize(path, localContext.request())); | ||
} | ||
|
||
@Test | ||
void testExternalizerIsCalledWithMaskedUrl() { | ||
ArgumentCaptor<String> url = ArgumentCaptor.forClass(String.class); | ||
Externalizer externalizer = mock(Externalizer.class); | ||
when(externalizer.publishLink(any(ResourceResolver.class), anyString())).then(AdditionalAnswers.returnsSecondArg()); | ||
localContext.registerService(Externalizer.class, externalizer); | ||
DefaultPathProcessor underTest = localContext.registerInjectActivateService(new DefaultPathProcessor()); | ||
String path = PATH + ".html?recipient=<%= recipient.id %>"; | ||
|
||
assertEquals(path, underTest.externalize(path, localContext.request())); | ||
|
||
verify(externalizer).publishLink(any(ResourceResolver.class), url.capture()); | ||
assertFalse(url.getValue().contains("<%=")); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I would feel more confident if we asserted on the expected output and not on simply not having the original fragments. This would also catch situation where we might end up up with multiple masking/encoding. |
||
assertFalse(url.getValue().contains("%>")); | ||
} | ||
|
||
@Test | ||
void testMappingWithException() { | ||
ResourceResolver resourceResolver = mock(ResourceResolver.class); | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Check failure
Code scanning / CodeQL
Insertion of sensitive information into log files