공지 본문 HTML 정제 유틸 추가 및 API Status 화면 적용
- HTML 인코딩 복원 및 허용 태그 외 제거 구현 (NoticeHtmlSanitizer) - 공지 본문 렌더링 시 XSS 방지 및 불필요 태그 삭제 처리 - jsoup 의 Safelist 기반 정제 로직 추가로 안전성 확보 - "지난 이슈 사항" 섹션 표시/숨김 프로퍼티 및 로직 추가
This commit is contained in:
@@ -112,6 +112,9 @@ dependencies {
|
||||
// SafeConstructor() no-arg 를 호출해 NoSuchMethodError 를 낸다. 되살릴 경우 1.6.1 이상.
|
||||
implementation 'org.apache.httpcomponents:httpclient:4.5.14'
|
||||
implementation 'com.navercorp.lucy:lucy-xss-servlet:2.0.1'
|
||||
// 관리자 작성 HTML(공지 본문 등) 화이트리스트 정제. lucy-xss 는 허용 외 태그를 escape 해 그대로 노출하므로
|
||||
// 태그를 제거해야 하는 곳(API Status 공지 본문)은 jsoup Safelist 를 쓴다. 1.17.x 는 Java 8 지원.
|
||||
implementation 'org.jsoup:jsoup:1.17.2'
|
||||
implementation 'javax.servlet:javax.servlet-api:4.0.0'
|
||||
implementation 'org.jasypt:jasypt:1.9.3'
|
||||
implementation 'xerces:xercesImpl:2.12.2'
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.eactive.apim.portal.common.util;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jsoup.Jsoup;
|
||||
import org.jsoup.nodes.Document;
|
||||
import org.jsoup.parser.Parser;
|
||||
import org.jsoup.safety.Safelist;
|
||||
|
||||
/**
|
||||
* 관리자가 작성한 공지 본문(HTML)을 화면에 그대로 넣을 수 있게 정제한다.
|
||||
*
|
||||
* <p>공지 본문은 eapim-admin(Summernote 에디터, PTL_PROPERTY 문구)에서 저장되는데, 저장 경로의
|
||||
* XSS 필터 때문에 태그가 엔티티로 escape 된 채(예: {@code <p>}) 들어오는 경우가 있다.
|
||||
* 일부만 escape 되기도 한다 - 자동 탐지 공지는 머리말만 PTL_PROPERTY 문구라 그 부분만 escape 된다.
|
||||
* 공지 상세 화면은 클라이언트에서 엔티티를 한 번 풀어 렌더하므로 여기서도 같은 기준으로 한 번 푼다.</p>
|
||||
*
|
||||
* <p>푼 결과는 허용 태그만 남기고 나머지 태그는 제거한다(텍스트는 유지, script/style 은 내용째 제거).
|
||||
* 속성은 링크·이미지·표 병합에 필요한 것만 남기며 style·class·on* 이벤트는 모두 버린다.</p>
|
||||
*/
|
||||
public final class NoticeHtmlSanitizer {
|
||||
|
||||
/** 상대 링크 판정용 기준 URI. 상대 링크는 {@link Safelist#preserveRelativeLinks} 로 그대로 남는다 */
|
||||
private static final String BASE_URI = "http://localhost/";
|
||||
|
||||
/** Summernote 출력 + editor-content.css 가 스타일을 갖는 태그 */
|
||||
private static final Safelist SAFELIST = new Safelist()
|
||||
.addTags("p", "br", "hr", "div", "span",
|
||||
"b", "strong", "i", "em", "u", "s", "strike", "del", "mark", "sub", "sup", "code", "pre",
|
||||
"blockquote", "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "li",
|
||||
"table", "caption", "colgroup", "col", "thead", "tbody", "tfoot", "tr", "th", "td",
|
||||
"a", "img")
|
||||
.addAttributes("a", "href", "title", "target")
|
||||
.addAttributes("img", "src", "alt", "title", "width", "height")
|
||||
.addAttributes("th", "colspan", "rowspan")
|
||||
.addAttributes("td", "colspan", "rowspan")
|
||||
.addAttributes("ol", "start")
|
||||
.addProtocols("a", "href", "http", "https", "mailto", "tel")
|
||||
// Summernote 는 붙여 넣은 이미지를 base64 data URI 로 본문에 넣는다
|
||||
.addProtocols("img", "src", "http", "https", "data")
|
||||
.addEnforcedAttribute("a", "rel", "noopener noreferrer")
|
||||
.preserveRelativeLinks(true);
|
||||
|
||||
private static final Document.OutputSettings OUTPUT_SETTINGS = new Document.OutputSettings().prettyPrint(false);
|
||||
|
||||
private NoticeHtmlSanitizer() {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return 정제된 HTML. 입력이 비었거나 정제 후 남는 내용이 없으면 {@code null}
|
||||
*/
|
||||
public static String sanitize(String html) {
|
||||
if (StringUtils.isBlank(html)) {
|
||||
return null;
|
||||
}
|
||||
String decoded = Parser.unescapeEntities(html, false);
|
||||
String cleaned = Jsoup.clean(decoded, BASE_URI, SAFELIST, OUTPUT_SETTINGS);
|
||||
return StringUtils.isBlank(cleaned) ? null : cleaned;
|
||||
}
|
||||
}
|
||||
+1
@@ -73,6 +73,7 @@ public class ApiStatusController {
|
||||
mav.addObject("lastFireRelative",
|
||||
ApiStatusSupport.relativeTime(lastFireAt, ApiStatusSupport.now()));
|
||||
mav.addObject("lastStatusChangedAt", catalogService.getLastStatusChangedAt());
|
||||
mav.addObject("recentIssuesVisible", catalogService.isRecentIssuesVisible());
|
||||
return mav;
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import com.eactive.apim.portal.djb.apistatus.incident.entity.IncidentKind;
|
||||
import com.eactive.apim.portal.djb.apistatus.incident.repository.DjbApistatusIncidentApiRepository;
|
||||
import com.eactive.apim.portal.djb.apistatus.incident.repository.DjbApistatusIncidentTimelineRepository;
|
||||
import com.eactive.apim.portal.apps.community.notice.repository.PortalNoticeRepository;
|
||||
import com.eactive.apim.portal.common.util.NoticeHtmlSanitizer;
|
||||
import com.eactive.apim.portal.portalNotice.entity.PortalNotice;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -164,7 +165,7 @@ public class ApiStatusAssembler {
|
||||
PortalNotice notice = incident.getNoticeId() == null ? null : notices.get(incident.getNoticeId());
|
||||
if (notice != null) {
|
||||
dto.setNoticeSubject(notice.getNoticeSubject());
|
||||
dto.setNoticeDetail(notice.getNoticeDetail());
|
||||
dto.setNoticeDetail(NoticeHtmlSanitizer.sanitize(notice.getNoticeDetail()));
|
||||
}
|
||||
|
||||
List<TimelineEntryDTO> all = timelines.getOrDefault(incident.getIncidentId(), Collections.emptyList());
|
||||
@@ -194,7 +195,7 @@ public class ApiStatusAssembler {
|
||||
PortalNotice notice = incident.getNoticeId() == null ? null : notices.get(incident.getNoticeId());
|
||||
if (notice != null) {
|
||||
dto.setNoticeSubject(notice.getNoticeSubject());
|
||||
dto.setNoticeDetail(notice.getNoticeDetail());
|
||||
dto.setNoticeDetail(NoticeHtmlSanitizer.sanitize(notice.getNoticeDetail()));
|
||||
}
|
||||
|
||||
dto.setTitle(incident.getTitle());
|
||||
@@ -243,7 +244,7 @@ public class ApiStatusAssembler {
|
||||
PortalNotice notice = incident.getNoticeId() == null ? null : notices.get(incident.getNoticeId());
|
||||
if (notice != null) {
|
||||
dto.setNoticeSubject(notice.getNoticeSubject());
|
||||
dto.setNoticeDetail(notice.getNoticeDetail());
|
||||
dto.setNoticeDetail(NoticeHtmlSanitizer.sanitize(notice.getNoticeDetail()));
|
||||
}
|
||||
|
||||
dto.setKind(incident.getKind() == null ? null : incident.getKind().name());
|
||||
|
||||
+31
-6
@@ -49,6 +49,11 @@ public class ApiStatusCatalogService {
|
||||
|
||||
private static final boolean DEFAULT_API_LIST_STATUS_BADGE = true;
|
||||
|
||||
/** API Status 메인(/apistatus)의 "지난 이슈 사항" 섹션 노출 여부 (true/false) */
|
||||
public static final String KEY_RECENT_ISSUES_VISIBLE = "djb.apistatus.recent-issues-visible";
|
||||
|
||||
private static final boolean DEFAULT_RECENT_ISSUES_VISIBLE = true;
|
||||
|
||||
private static final int MIN_WINDOW_DAYS = 1;
|
||||
private static final int MAX_WINDOW_DAYS = 365;
|
||||
|
||||
@@ -178,11 +183,31 @@ public class ApiStatusCatalogService {
|
||||
*/
|
||||
@Transactional
|
||||
public boolean isApiListStatusBadgeEnabled() {
|
||||
return getBooleanProperty(KEY_API_LIST_STATUS_BADGE, DEFAULT_API_LIST_STATUS_BADGE,
|
||||
"OPEN API 목록 카드에 현재 상태(정상/점검/지연/장애) 태그 노출 여부 (true/false)");
|
||||
}
|
||||
|
||||
/**
|
||||
* API Status 메인의 "지난 이슈 사항"(종결 이슈 최근 5건) 섹션 노출 여부.
|
||||
* PTL_PROPERTY({@code Portal} / {@code djb.apistatus.recent-issues-visible}) 로 켜고 끈다.
|
||||
* 숨겨도 전체 이슈 이력(/apistatus/issues)으로 가는 링크는 남는다.
|
||||
*
|
||||
* <p>{@code true/Y/1} 이면 노출, {@code false/N/0} 이면 숨김. 값이 비었거나 이상하면 기본 노출.</p>
|
||||
*/
|
||||
@Transactional
|
||||
public boolean isRecentIssuesVisible() {
|
||||
return getBooleanProperty(KEY_RECENT_ISSUES_VISIBLE, DEFAULT_RECENT_ISSUES_VISIBLE,
|
||||
"API Status 메인의 '지난 이슈 사항' 섹션 노출 여부 (true/false). 숨겨도 전체 이력 보기 링크는 남는다");
|
||||
}
|
||||
|
||||
/**
|
||||
* true/false 프로퍼티 조회. {@code true/Y/1}, {@code false/N/0} 만 인정하고
|
||||
* 값이 비었거나 이상하거나 조회에 실패하면 기본값을 쓴다. 최초 접근 시 기본값으로 row 를 만든다.
|
||||
*/
|
||||
private boolean getBooleanProperty(String key, boolean defaultValue, String description) {
|
||||
try {
|
||||
String value = portalPropertyService.getOrCreateProperty(
|
||||
PROPERTY_GROUP, KEY_API_LIST_STATUS_BADGE,
|
||||
String.valueOf(DEFAULT_API_LIST_STATUS_BADGE),
|
||||
"OPEN API 목록 카드에 현재 상태(정상/점검/지연/장애) 태그 노출 여부 (true/false)");
|
||||
PROPERTY_GROUP, key, String.valueOf(defaultValue), description);
|
||||
String normalized = StringUtils.trimToEmpty(value);
|
||||
if (StringUtils.equalsAnyIgnoreCase(normalized, "false", "n", "0")) {
|
||||
return false;
|
||||
@@ -190,10 +215,10 @@ public class ApiStatusCatalogService {
|
||||
if (StringUtils.equalsAnyIgnoreCase(normalized, "true", "y", "1")) {
|
||||
return true;
|
||||
}
|
||||
return DEFAULT_API_LIST_STATUS_BADGE;
|
||||
return defaultValue;
|
||||
} catch (Exception e) {
|
||||
log.warn("API 목록 상태 태그 노출 프로퍼티 조회 실패 - 기본값 {} 사용", DEFAULT_API_LIST_STATUS_BADGE, e);
|
||||
return DEFAULT_API_LIST_STATUS_BADGE;
|
||||
log.warn("프로퍼티 {} 조회 실패 - 기본값 {} 사용", key, defaultValue, e);
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -198,7 +198,7 @@
|
||||
|
||||
/**
|
||||
* 이슈에 연결된 공지 본문. 서버가 게시 중(USE_YN='Y')인 공지만 내려주므로 여기서는 존재 여부만 본다.
|
||||
* 본문은 관리자가 에디터로 작성한 HTML 이라 공지 상세(th:utext)와 같이 그대로 렌더한다.
|
||||
* 본문은 서버(NoticeHtmlSanitizer)가 escape 된 태그를 복원하고 허용 태그만 남긴 HTML 이라 그대로 렌더한다.
|
||||
*/
|
||||
function noticeHtml(issue) {
|
||||
if (!issue.noticeDetail) return '';
|
||||
|
||||
@@ -110,7 +110,7 @@
|
||||
|
||||
/**
|
||||
* 이슈에 연결된 공지 본문. 서버가 게시 중(USE_YN='Y')인 공지만 내려주므로 여기서는 존재 여부만 본다.
|
||||
* 본문은 관리자가 에디터로 작성한 HTML 이라 공지 상세(th:utext)와 같이 그대로 렌더한다.
|
||||
* 본문은 서버(NoticeHtmlSanitizer)가 escape 된 태그를 복원하고 허용 태그만 남긴 HTML 이라 그대로 렌더한다.
|
||||
*/
|
||||
function noticeHtml(incident) {
|
||||
if (!incident.noticeDetail) return '';
|
||||
@@ -378,9 +378,12 @@
|
||||
.then(renderMaintenance)
|
||||
.catch(function () { handleError('maintenanceList', '점검 정보를 불러올 수 없습니다.'); });
|
||||
|
||||
fetchJson(base + '/recent-issues.json?size=5')
|
||||
.then(renderRecentIssues)
|
||||
.catch(function () { handleError('recentIssueList', '지난 이슈를 불러올 수 없습니다.'); });
|
||||
// 지난 이슈 섹션은 프로퍼티로 숨길 수 있다 (숨기면 마크업이 없으므로 조회도 하지 않는다)
|
||||
if (document.getElementById('recentIssueList')) {
|
||||
fetchJson(base + '/recent-issues.json?size=5')
|
||||
.then(renderRecentIssues)
|
||||
.catch(function () { handleError('recentIssueList', '지난 이슈를 불러올 수 없습니다.'); });
|
||||
}
|
||||
|
||||
if (authenticated) {
|
||||
fetchJson(base + '/my-apis.json')
|
||||
|
||||
@@ -100,8 +100,8 @@
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<!-- ❺ 지난 이슈 사항 -->
|
||||
<section>
|
||||
<!-- ❺ 지난 이슈 사항 (PTL_PROPERTY djb.apistatus.recent-issues-visible 로 노출 여부 조절) -->
|
||||
<section th:if="${recentIssuesVisible}">
|
||||
<div class="as-section-title">
|
||||
<h2>지난 이슈 사항</h2>
|
||||
<span class="as-desc">종결된 장애·점검 내역</span>
|
||||
@@ -116,6 +116,8 @@
|
||||
</div>
|
||||
<a class="as-more-link" th:href="@{/apistatus/issues}">전체 이력 보기 →</a>
|
||||
</section>
|
||||
<!-- 섹션을 숨겨도 전체 이슈 이력으로 가는 길은 남긴다 -->
|
||||
<a class="as-more-link" th:href="@{/apistatus/issues}" th:unless="${recentIssuesVisible}">전체 이력 보기 →</a>
|
||||
</div>
|
||||
</th:block>
|
||||
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.eactive.apim.portal.common.util;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class NoticeHtmlSanitizerTest {
|
||||
|
||||
/** 자동 탐지 공지: 머리말(PTL_PROPERTY 문구)만 escape 되어 저장된 경우 - API Status 화면에 "<p>" 가 글자로 보이던 사례 */
|
||||
@Test
|
||||
void sanitize_partiallyEscapedLead_restoresTags() {
|
||||
String stored = "<p>에러율 임계 초과 로 자동 감지된 장애입니다.</p>"
|
||||
+ "<p><b>영향 API</b></p><ul><li>빅테크 건축물대장 열람요청수신</li></ul>";
|
||||
|
||||
assertEquals("<p>에러율 임계 초과 로 자동 감지된 장애입니다.</p>"
|
||||
+ "<p><b>영향 API</b></p><ul><li>빅테크 건축물대장 열람요청수신</li></ul>",
|
||||
NoticeHtmlSanitizer.sanitize(stored));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sanitize_fullyEscapedBody_restoresTags() {
|
||||
String stored = "<p>테스트</p><h1 class=\"\">제목</h1><p>본문<br></p>";
|
||||
|
||||
assertEquals("<p>테스트</p><h1>제목</h1><p>본문<br></p>", NoticeHtmlSanitizer.sanitize(stored));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sanitize_unsupportedTags_removedButTextKept() {
|
||||
String html = "<p><font color=\"red\">빨강</font> <marquee>흐름</marquee></p><iframe src=\"https://x\"></iframe>";
|
||||
|
||||
assertEquals("<p>빨강 흐름</p>", NoticeHtmlSanitizer.sanitize(html));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sanitize_scriptAndStyle_removedWithContent() {
|
||||
String html = "<p>안내</p><script>alert(1)</script><style>p{display:none}</style>";
|
||||
|
||||
assertEquals("<p>안내</p>", NoticeHtmlSanitizer.sanitize(html));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sanitize_dangerousAttributes_removed() {
|
||||
String html = "<p style=\"color:red\" class=\"x\" onclick=\"alert(1)\">글</p>"
|
||||
+ "<a href=\"javascript:alert(1)\">링크</a><img src=\"x\" onerror=\"alert(1)\">";
|
||||
|
||||
String cleaned = NoticeHtmlSanitizer.sanitize(html);
|
||||
|
||||
assertFalse(cleaned.contains("style"));
|
||||
assertFalse(cleaned.contains("class"));
|
||||
assertFalse(cleaned.contains("onclick"));
|
||||
assertFalse(cleaned.contains("onerror"));
|
||||
assertFalse(cleaned.contains("javascript"));
|
||||
assertTrue(cleaned.startsWith("<p>글</p>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sanitize_links_keepRelativeAndAddRel() {
|
||||
String html = "<a href=\"/apis/detail?id=A1\" target=\"_blank\">상세</a>";
|
||||
|
||||
assertEquals("<a href=\"/apis/detail?id=A1\" target=\"_blank\" rel=\"noopener noreferrer\">상세</a>",
|
||||
NoticeHtmlSanitizer.sanitize(html));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sanitize_tableAndDataUriImage_kept() {
|
||||
String html = "<table><tbody><tr><td colspan=\"2\">셀</td></tr></tbody></table>"
|
||||
+ "<img src=\"data:image/png;base64,iVBORw0KGgo=\" alt=\"그림\">";
|
||||
|
||||
assertEquals(html, NoticeHtmlSanitizer.sanitize(html));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sanitize_textComparisonEntity_staysText() {
|
||||
assertEquals("<p>응답 < 3초</p>", NoticeHtmlSanitizer.sanitize("<p>응답 < 3초</p>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sanitize_blankOrEmptyAfterClean_returnsNull() {
|
||||
assertNull(NoticeHtmlSanitizer.sanitize(null));
|
||||
assertNull(NoticeHtmlSanitizer.sanitize(" "));
|
||||
assertNull(NoticeHtmlSanitizer.sanitize("<script>alert(1)</script>"));
|
||||
}
|
||||
}
|
||||
+31
@@ -4,6 +4,8 @@ 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.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.eactive.apim.gateway.data.statistics.repository.GwApiStatusRepository;
|
||||
@@ -63,6 +65,35 @@ class ApiStatusCatalogServiceTest {
|
||||
assertFalse(visibleApiIds.isEmpty());
|
||||
}
|
||||
|
||||
/** "지난 이슈 사항" 노출 프로퍼티: true/Y/1 노출, false/N/0 숨김, 그 외·조회 실패는 기본 노출 */
|
||||
@Test
|
||||
void isRecentIssuesVisible_parsesPropertyValue() {
|
||||
assertTrue(recentIssuesVisibleWhen("true"));
|
||||
assertTrue(recentIssuesVisibleWhen(" Y "));
|
||||
assertTrue(recentIssuesVisibleWhen("1"));
|
||||
assertFalse(recentIssuesVisibleWhen("false"));
|
||||
assertFalse(recentIssuesVisibleWhen("N"));
|
||||
assertFalse(recentIssuesVisibleWhen("0"));
|
||||
assertTrue(recentIssuesVisibleWhen(""));
|
||||
assertTrue(recentIssuesVisibleWhen("hide"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void isRecentIssuesVisible_whenPropertyLookupFails_defaultsToVisible() {
|
||||
when(portalPropertyService.getOrCreateProperty(eq(ApiStatusCatalogService.PROPERTY_GROUP),
|
||||
eq(ApiStatusCatalogService.KEY_RECENT_ISSUES_VISIBLE), eq("true"), anyString()))
|
||||
.thenThrow(new IllegalStateException("DB down"));
|
||||
|
||||
assertTrue(service.isRecentIssuesVisible());
|
||||
}
|
||||
|
||||
private boolean recentIssuesVisibleWhen(String value) {
|
||||
when(portalPropertyService.getOrCreateProperty(eq(ApiStatusCatalogService.PROPERTY_GROUP),
|
||||
eq(ApiStatusCatalogService.KEY_RECENT_ISSUES_VISIBLE), eq("true"), anyString()))
|
||||
.thenReturn(value);
|
||||
return service.isRecentIssuesVisible();
|
||||
}
|
||||
|
||||
private void stubSearchApis(ApiSpecInfoDto... apis) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("apis", Arrays.asList(apis));
|
||||
|
||||
Reference in New Issue
Block a user