-
Notifications
You must be signed in to change notification settings - Fork 0
링크 저장 URL 정규화 및 검증 적용 #300
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
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 hidden or 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
84 changes: 84 additions & 0 deletions
84
src/main/java/com/sofa/linkiving/domain/link/util/UrlNormalizer.java
This file contains hidden or 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,84 @@ | ||
| package com.sofa.linkiving.domain.link.util; | ||
|
|
||
| import java.net.URI; | ||
| import java.net.URISyntaxException; | ||
| import java.util.Locale; | ||
| import java.util.regex.Matcher; | ||
| import java.util.regex.Pattern; | ||
|
|
||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import com.sofa.linkiving.domain.link.error.LinkErrorCode; | ||
| import com.sofa.linkiving.global.error.exception.BusinessException; | ||
|
|
||
| @Component | ||
| public class UrlNormalizer { | ||
|
|
||
| private static final Pattern SCHEME_PATTERN = Pattern.compile("^[a-zA-Z][a-zA-Z0-9+.-]*://"); | ||
| private static final Pattern DUPLICATED_HTTP_SCHEME_PATTERN = Pattern.compile( | ||
| "^(https?://)(?:https?://)+", | ||
| Pattern.CASE_INSENSITIVE | ||
| ); | ||
|
|
||
| public String normalize(String rawUrl) { | ||
| if (rawUrl == null || rawUrl.isBlank()) { | ||
| throw new BusinessException(LinkErrorCode.INVALID_URL); | ||
| } | ||
|
|
||
| String normalizedUrl = removeDuplicatedHttpScheme(rawUrl.strip()); | ||
| if (!SCHEME_PATTERN.matcher(normalizedUrl).find()) { | ||
| normalizedUrl = "https://" + normalizedUrl; | ||
| } | ||
|
|
||
| return normalizeSchemeAndHost(normalizedUrl); | ||
| } | ||
|
|
||
| private String removeDuplicatedHttpScheme(String url) { | ||
| Matcher matcher = DUPLICATED_HTTP_SCHEME_PATTERN.matcher(url); | ||
| return matcher.find() ? matcher.replaceFirst(matcher.group(1)) : url; | ||
| } | ||
|
|
||
| private String normalizeSchemeAndHost(String url) { | ||
| try { | ||
| URI uri = new URI(url); | ||
| String scheme = uri.getScheme(); | ||
| if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) { | ||
| throw new BusinessException(LinkErrorCode.INVALID_URL_PROTOCOL); | ||
| } | ||
|
|
||
| String host = uri.getHost(); | ||
| if (host == null || host.isBlank() || !host.contains(".")) { | ||
| throw new BusinessException(LinkErrorCode.INVALID_URL); | ||
| } | ||
|
|
||
| return rebuildUrl(uri, scheme.toLowerCase(Locale.ROOT), host.toLowerCase(Locale.ROOT)); | ||
| } catch (URISyntaxException exception) { | ||
| throw new BusinessException(LinkErrorCode.INVALID_URL); | ||
| } | ||
| } | ||
|
|
||
| private String rebuildUrl(URI uri, String scheme, String host) { | ||
| String authority = uri.getRawAuthority(); | ||
| int hostStart = authority.lastIndexOf('@') + 1; | ||
| int hostEnd = authority.indexOf(':', hostStart); | ||
| if (hostEnd == -1) { | ||
| hostEnd = authority.length(); | ||
| } | ||
|
|
||
| String normalizedAuthority = authority.substring(0, hostStart) | ||
| + host | ||
| + authority.substring(hostEnd); | ||
| StringBuilder normalizedUrl = new StringBuilder(scheme) | ||
| .append("://") | ||
| .append(normalizedAuthority) | ||
| .append(uri.getRawPath()); | ||
|
|
||
| if (uri.getRawQuery() != null) { | ||
| normalizedUrl.append('?').append(uri.getRawQuery()); | ||
| } | ||
| if (uri.getRawFragment() != null) { | ||
| normalizedUrl.append('#').append(uri.getRawFragment()); | ||
| } | ||
| return normalizedUrl.toString(); | ||
| } | ||
| } |
This file contains hidden or 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
67 changes: 67 additions & 0 deletions
67
src/test/java/com/sofa/linkiving/domain/link/util/OgTagCrawlerTest.java
This file contains hidden or 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,67 @@ | ||
| package com.sofa.linkiving.domain.link.util; | ||
|
|
||
| import static org.assertj.core.api.Assertions.*; | ||
| import static org.mockito.BDDMockito.*; | ||
|
|
||
| import java.io.IOException; | ||
| import java.util.concurrent.TimeUnit; | ||
|
|
||
| import org.junit.jupiter.api.DisplayName; | ||
| import org.junit.jupiter.api.Test; | ||
|
|
||
| import com.sofa.linkiving.domain.link.error.LinkErrorCode; | ||
| import com.sofa.linkiving.global.error.exception.BusinessException; | ||
|
|
||
| import okhttp3.mockwebserver.MockResponse; | ||
| import okhttp3.mockwebserver.MockWebServer; | ||
| import okhttp3.mockwebserver.RecordedRequest; | ||
|
|
||
| class OgTagCrawlerTest { | ||
|
|
||
| @Test | ||
| @DisplayName("메타데이터 수집 전 정규화된 URL을 SSRF 검증한다") | ||
| void validateNormalizedUrlBeforeCrawling() { | ||
| UrlValidator urlValidator = mock(UrlValidator.class); | ||
| UrlNormalizer urlNormalizer = mock(UrlNormalizer.class); | ||
| OgTagCrawler ogTagCrawler = new OgTagCrawler(urlValidator, urlNormalizer); | ||
| String rawUrl = " 192.168.0.1 "; | ||
| String normalizedUrl = "https://192.168.0.1"; | ||
|
|
||
| given(urlNormalizer.normalize(rawUrl)).willReturn(normalizedUrl); | ||
| willThrow(new BusinessException(LinkErrorCode.INVALID_URL_PRIVATE_IP)) | ||
| .given(urlValidator).validateSafeUrl(normalizedUrl); | ||
|
|
||
| assertThatThrownBy(() -> ogTagCrawler.crawl(rawUrl)) | ||
| .isInstanceOf(BusinessException.class) | ||
| .hasFieldOrPropertyWithValue("errorCode", LinkErrorCode.INVALID_URL_PRIVATE_IP); | ||
|
|
||
| then(urlNormalizer).should().normalize(rawUrl); | ||
| then(urlValidator).should().validateSafeUrl(normalizedUrl); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("정규화된 URL로 메타데이터를 요청한다") | ||
| void crawlNormalizedUrl() throws IOException, InterruptedException { | ||
| try (MockWebServer mockWebServer = new MockWebServer()) { | ||
| mockWebServer.enqueue(new MockResponse().setBody(""" | ||
| <html> | ||
| <head><meta property="og:title" content="normalized target"></head> | ||
| </html> | ||
| """)); | ||
| mockWebServer.start(); | ||
|
|
||
| UrlValidator urlValidator = mock(UrlValidator.class); | ||
| UrlNormalizer urlNormalizer = mock(UrlNormalizer.class); | ||
| OgTagCrawler ogTagCrawler = new OgTagCrawler(urlValidator, urlNormalizer); | ||
| String rawUrl = "naver.com"; | ||
| String normalizedUrl = mockWebServer.url("/article?Q=Abc").toString(); | ||
| given(urlNormalizer.normalize(rawUrl)).willReturn(normalizedUrl); | ||
|
|
||
| assertThat(ogTagCrawler.crawl(rawUrl).title()).isEqualTo("normalized target"); | ||
| RecordedRequest request = mockWebServer.takeRequest(1, TimeUnit.SECONDS); | ||
| assertThat(request).isNotNull(); | ||
| assertThat(request.getPath()).isEqualTo("/article?Q=Abc"); | ||
| then(urlValidator).should().validateSafeUrl(normalizedUrl); | ||
| } | ||
| } | ||
| } | ||
67 changes: 67 additions & 0 deletions
67
src/test/java/com/sofa/linkiving/domain/link/util/UrlNormalizerTest.java
This file contains hidden or 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,67 @@ | ||
| package com.sofa.linkiving.domain.link.util; | ||
|
|
||
| import static org.assertj.core.api.Assertions.*; | ||
|
|
||
| import org.junit.jupiter.api.DisplayName; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.junit.jupiter.params.ParameterizedTest; | ||
| import org.junit.jupiter.params.provider.CsvSource; | ||
| import org.junit.jupiter.params.provider.ValueSource; | ||
|
|
||
| import com.sofa.linkiving.domain.link.error.LinkErrorCode; | ||
| import com.sofa.linkiving.global.error.exception.BusinessException; | ||
|
|
||
| class UrlNormalizerTest { | ||
|
|
||
| private final UrlNormalizer urlNormalizer = new UrlNormalizer(); | ||
|
|
||
| @ParameterizedTest | ||
| @CsvSource({ | ||
| "naver.com, https://naver.com", | ||
| "www.naver.com, https://www.naver.com", | ||
| "https://www.naver.com, https://www.naver.com", | ||
| "http://old-site.com, http://old-site.com", | ||
| "https://https://naver.com, https://naver.com", | ||
| "' https://naver.com ', https://naver.com", | ||
| "'https://naver.com/path?q=abc#section', 'https://naver.com/path?q=abc#section'", | ||
| "Naver.com, https://naver.com", | ||
| "HTTPS://NAVER.COM, https://naver.com", | ||
| "'https://Naver.com/Path?Q=Abc#Frag', 'https://naver.com/Path?Q=Abc#Frag'" | ||
| }) | ||
| @DisplayName("URL을 규칙에 맞게 정규화한다") | ||
| void normalizeUrl(String input, String expected) { | ||
| assertThat(urlNormalizer.normalize(input)).isEqualTo(expected); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("앞뒤 줄바꿈을 제거한다") | ||
| void removeLeadingAndTrailingLineBreaks() { | ||
| assertThat(urlNormalizer.normalize("\nhttps://naver.com\r\n")) | ||
| .isEqualTo("https://naver.com"); | ||
| } | ||
|
|
||
| @ParameterizedTest | ||
| @ValueSource(strings = {"", " ", "안녕하세요", "https://localhost", "https://naver"}) | ||
| @DisplayName("빈 값이거나 점이 없는 도메인은 거부한다") | ||
| void rejectInvalidUrl(String input) { | ||
| assertThatThrownBy(() -> urlNormalizer.normalize(input)) | ||
| .isInstanceOf(BusinessException.class) | ||
| .hasFieldOrPropertyWithValue("errorCode", LinkErrorCode.INVALID_URL); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("null URL은 거부한다") | ||
| void rejectNullUrl() { | ||
| assertThatThrownBy(() -> urlNormalizer.normalize(null)) | ||
| .isInstanceOf(BusinessException.class) | ||
| .hasFieldOrPropertyWithValue("errorCode", LinkErrorCode.INVALID_URL); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("HTTP와 HTTPS 외의 프로토콜은 거부한다") | ||
| void rejectUnsupportedProtocol() { | ||
| assertThatThrownBy(() -> urlNormalizer.normalize("ftp://example.com")) | ||
| .isInstanceOf(BusinessException.class) | ||
| .hasFieldOrPropertyWithValue("errorCode", LinkErrorCode.INVALID_URL_PROTOCOL); | ||
| } | ||
| } |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.