Compare commits

..

2 Commits

Author SHA1 Message Date
e6c73a4f88 Merge: 报表保真层安全/OOM收口(SQLi门/IDOR授权/XXE/并发字节超时,69单测+live e2e全绿)
Some checks failed
ci / build-test-parity (push) Has been cancelled
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 07:52:03 +08:00
ffb2f042d0 报表保真层安全/OOM收口(platform-report):SQLi门/IDOR授权/XXE/并发字节超时
审计揪出真问题(jatools引擎预编译不可改,全在包装层收口):
- SQL注入(Critical):${PARAM}经evalTemplate字符串拼接进SQL后prepareStatement执行(无占位符绑定)
- IDOR:render/frame对templateId无对象级授权,任意已认证用户可渲染任意报表
- XXE:报表XML经裸DocumentBuilderFactory解析(外部实体/SSRF/OOB)
- ?tpl任意本地文件读+路径穿越;RBAC旁路(固定DB账号);OOM链(结果集全量物化+无并发闸+无超时+产物多副本)

实现:
- ReportParamGuard:模板${name}引用白名单 + isSafeValue字符白名单(拒空格挡无引号注入/拒--/::) +
  身份数据域保留集{CURRENTUSER,CURRENTDEPART,CURRENTORG,USERID,DEPARTID,ORGID}剥客户端+服务端注入可信值
- ReportXmlGuard.hasDoctypeInBytes:字节级拒DOCTYPE(防BOM/UTF-16编码绕过)
- ReportTplGuard + profile守卫:?tpl限定templates-dir内、仅.xml、仅旁路profile
- ReportController.enforceReportAccess:菜单授权对象级鉴权(超管bypass/匿名跳过/认证态无身份fail-closed)
- RenderConcurrencyLimiter(429)/LimitedByteArrayOutputStream(413)/JatoolsConfig注入statement_timeout+socketTimeout
- 错误响应改通用文案(细节仅落日志)

验证:69单测全绿(TDD);真库live e2e全绿(数值注入=400/IDOR=403/合法render+PDF=200/forged USERID剥离);
对象授权SQL逐对实证;独立security-reviewer对抗复审揪修2真漏(无引号数值注入绕黑名单、身份注入护错变量名)。

残留(非本层可修):凭据外泄(模板${property("DBPassword")}同解析路径,需模板创作授权+DB只读账号);
结果集全量物化OOM根因在引擎;预编译jar高危CVE(log4j1.2.8/commons-collections3.0/bsh)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 07:51:54 +08:00
18 changed files with 1195 additions and 81 deletions

View File

@@ -82,6 +82,11 @@
<artifactId>postgresql</artifactId>
</dependency>
<!-- 安全收口:可信当前用户身份(UserSession/LoggedInUser)、profile 守卫(SecurityProfiles)、
报表对象级授权所需。platform-auth 传递依赖 platform-legacy-core,显式声明对齐其它模块惯例。 -->
<dependency><groupId>com.eip4</groupId><artifactId>platform-legacy-core</artifactId></dependency>
<dependency><groupId>com.eip4</groupId><artifactId>platform-auth</artifactId></dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>

View File

@@ -53,6 +53,14 @@ public class JatoolsConfig {
@Value("${eip4.report.company:EIP4}")
private String company;
/** 报表查询的 PG 服务端 statement_timeout(毫秒,0=不设)。慢/重 SQL 超时即被 DB 中止,防长时间占连接/堆。 */
@Value("${eip4.report.db.statement-timeout-ms:30000}")
private long statementTimeoutMs;
/** 报表连接的 pgjdbc socketTimeout(秒,0=不设)。网络层兜底,泄露/挂死的裸连接最终被 OS 断开。 */
@Value("${eip4.report.db.socket-timeout-sec:35}")
private int socketTimeoutSec;
/**
* PDF 导出兜底字体(CJK 保真)候选路径,按序探测,取首个可加载者注册为
* iText {@code DefaultFontMapper.defaultFont}。覆盖 macOS(本地验证)与常见 Linux 路径。
@@ -88,8 +96,9 @@ public class JatoolsConfig {
p.setProperty("font.dirs",
"/System/Library/Fonts;/Library/Fonts;"
+ "/usr/share/fonts;/usr/share/fonts/truetype;/usr/local/share/fonts");
// 报表模板 <Connection> 解析到 EIP4 数据源
p.setProperty("DBJdbcUrl", jdbcUrl == null ? "" : jdbcUrl);
// 报表模板 <Connection> 解析到 EIP4 数据源(URL 追加 statement_timeout/socketTimeout 超时加固)
String hardenedUrl = appendPgTimeouts(jdbcUrl == null ? "" : jdbcUrl, statementTimeoutMs, socketTimeoutSec);
p.setProperty("DBJdbcUrl", hardenedUrl);
p.setProperty("DBUser", dbUser == null ? "" : dbUser);
p.setProperty("DBPassword", dbPassword == null ? "" : dbPassword);
@@ -99,7 +108,8 @@ public class JatoolsConfig {
p.store(baos, "EIP4 injected jatools config");
System2.properties = new java.util.PropertyResourceBundle(
new ByteArrayInputStream(baos.toByteArray()));
log.info("jatools 配置已注入 System2.properties: DBJdbcUrl={}, DBUser={}", jdbcUrl, dbUser);
log.info("jatools 配置已注入 System2.properties: DBJdbcUrl={}, DBUser={} (statementTimeoutMs={}, socketTimeoutSec={})",
hardenedUrl, dbUser, statementTimeoutMs, socketTimeoutSec);
} catch (Exception e) {
throw new IllegalStateException("注入 jatools System2 配置失败: " + e.getMessage(), e);
}
@@ -140,4 +150,30 @@ public class JatoolsConfig {
init();
}
}
/**
* 给 PostgreSQL JDBC URL 追加超时加固参数(P1):pgjdbc {@code socketTimeout}(秒,网络层兜底,
* 泄露/挂死连接最终被 OS 断开)与服务端 {@code statement_timeout}(毫秒,经 {@code options=-c ...},
* pgjdbc 会对参数值做 URL 解码故用 {@code %20}/{@code %3D} 编码空格与等号)。
* 仅作用于 {@code jdbc:postgresql} URL;已含同名参数则不重复(幂等);非正值则跳过对应项;
* null/空/非 PG URL 原样返回。
*/
static String appendPgTimeouts(String url, long statementTimeoutMs, int socketTimeoutSec) {
if (url == null || url.isBlank() || !url.startsWith("jdbc:postgresql")) {
return url;
}
StringBuilder sb = new StringBuilder(url);
boolean hasQuery = url.indexOf('?') >= 0;
if (socketTimeoutSec > 0 && !url.contains("socketTimeout=")) {
sb.append(hasQuery ? '&' : '?').append("socketTimeout=").append(socketTimeoutSec);
hasQuery = true;
}
// 经 options= 设 statement_timeout;若 URL 已有 options=(如 search_path),不重复追加
// (pgjdbc 同名后者覆盖前者会丢原配置),由部署方在既有 options 内自行加 statement_timeout。
if (statementTimeoutMs > 0 && !url.contains("statement_timeout") && !url.contains("options=")) {
sb.append(hasQuery ? '&' : '?')
.append("options=-c%20statement_timeout%3D").append(statementTimeoutMs);
}
return sb.toString();
}
}

View File

@@ -0,0 +1,35 @@
package com.eip4.platform.report;
import java.io.ByteArrayOutputStream;
/**
* 带字节上限的 {@link ByteArrayOutputStream}:写入累计超过 {@code limitBytes} 时抛
* {@link ReportSizeExceededException}。用于给报表渲染产物在堆里设硬上限(P1 OOM 收口) ——
* 原实现把整篇产物无上限缓冲,单请求即可 OOM。{@code limitBytes <= 0} 表示不限。
*/
public class LimitedByteArrayOutputStream extends ByteArrayOutputStream {
private final long limitBytes;
public LimitedByteArrayOutputStream(long limitBytes) {
this.limitBytes = limitBytes;
}
@Override
public synchronized void write(int b) {
ensureCapacity(1);
super.write(b);
}
@Override
public synchronized void write(byte[] b, int off, int len) {
ensureCapacity(len);
super.write(b, off, len);
}
private void ensureCapacity(long additional) {
if (limitBytes > 0 && (long) size() + additional > limitBytes) {
throw new ReportSizeExceededException(limitBytes);
}
}
}

View File

@@ -0,0 +1,42 @@
package com.eip4.platform.report;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
/**
* 渲染并发闸(P1):用有界信号量限制同时渲染数,在 {@code acquireTimeoutMs} 内取不到许可即抛
* {@link ReportBusyException}(控制器映射 429)。把峰值堆收敛到「并发上限 × 单请求」,防止 N 个
* 并发大报表线性叠加(全量结果集 + 全量文档 + 全量产物)撑爆 JVM。
*/
public class RenderConcurrencyLimiter {
private final Semaphore semaphore;
private final int maxConcurrent;
private final long acquireTimeoutMs;
public RenderConcurrencyLimiter(int maxConcurrent, long acquireTimeoutMs) {
this.maxConcurrent = maxConcurrent;
this.acquireTimeoutMs = acquireTimeoutMs;
this.semaphore = new Semaphore(maxConcurrent, true); // 公平,防饥饿
}
/** 取得许可后执行 {@code task};取不到则抛 {@link ReportBusyException}。许可在 finally 中必释放。 */
public <T> T call(Supplier<T> task) {
boolean acquired;
try {
acquired = semaphore.tryAcquire(acquireTimeoutMs, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ReportBusyException(maxConcurrent);
}
if (!acquired) {
throw new ReportBusyException(maxConcurrent);
}
try {
return task.get();
} finally {
semaphore.release();
}
}
}

View File

@@ -0,0 +1,19 @@
package com.eip4.platform.report;
/**
* 渲染并发已达上限({@code eip4.report.max-concurrent-renders}),在等待超时内未取得许可。
* 控制器据此返回 429 Too Many Requests,避免 N 个并发大报表线性叠加堆占用导致 OOM。
*/
public class ReportBusyException extends RuntimeException {
private final int maxConcurrent;
public ReportBusyException(int maxConcurrent) {
super("报表渲染并发已达上限 " + maxConcurrent + ",请稍后重试");
this.maxConcurrent = maxConcurrent;
}
public int getMaxConcurrent() {
return maxConcurrent;
}
}

View File

@@ -1,6 +1,7 @@
package com.eip4.platform.report;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
@@ -8,11 +9,13 @@ import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@@ -23,26 +26,27 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import com.dsasp.server.common.user.service.LoggedInUser;
import com.dsasp.server.common.util.UserSession;
import com.eip4.platform.auth.security.SecurityProfiles;
import jakarta.servlet.http.HttpServletRequest;
/**
* 报表渲染端点。
* 报表渲染端点(含安全收口)。
*
* <p>{@code GET /api/report/render/{templateId}?format=html|pdf|xls&<查询参数...>}
* → 把 {@code templateId} 解析为 JOR 模板 .xml → {@link ReportService#render} → 返回
* 渲染产物(HTML/PDF/XLS)。除 {@code format}/{@code tpl} 外的全部查询参数原样作为报表参数
* 透传(报表 SQL 里的 {@code ${PARAM}} 据此绑定)。
* → 把 {@code templateId} 解析为 JOR 模板 → {@link ReportService#render} → 返回渲染产物。
*
* <p>模板解析(v1):
* <p>安全门(P0/P1,见各 {@code ReportXxxGuard}):
* <ul>
* <li>{@code ?tpl=<绝对路径>} —— 验证/演示用,直接指定 .xml 绝对路径(仅 dev/local 便利)。</li>
* <li>否则把 {@code templateId} 当作相对 {@code eip4.report.templates-dir} 的路径解析,
* 默认基目录指向 EIP3 report 根。Phase 3 改为查 {@code sys_report_template} 表。</li>
* <li><b>对象级授权</b> {@link #enforceReportAccess}:已认证非超管用户只能渲染其可见菜单暴露的报表(防 IDOR);</li>
* <li><b>SQL 注入门</b> {@link ReportParamGuard}:只放行模板引用过的参数名 + 值校验 + 剥离身份保留位;</li>
* <li><b>可信身份注入</b>:{@code ${CURRENTUSER}} 等由服务端从 JWT 上下文注入,杜绝客户端伪造越权;</li>
* <li><b>{@code ?tpl} 守卫</b> {@link ReportTplGuard}:仅旁路 profile 允许,且限定在 templates-dir 内、仅 .xml;</li>
* <li>XXE/并发/字节上限/超时在 {@link ReportService}/{@link JatoolsConfig} 侧。</li>
* </ul>
*
* <p>注:不与既有 {@code /api/report/menu-tree}(platform-metadata)冲突 —— 该控制器只占
* {@code /api/report/render/**}。安全:这是 {@code /api/**} 端点,在 dev/local/ci 宽松链下放行,
* 严格 profile 下走 {@code authenticated()},沿用既有安全模型,无需改 SecurityConfig。
* 错误响应只回通用文案(底层 SQL/路径/异常细节仅写服务端日志,杜绝信息泄露)。
*/
@RestController
public class ReportController {
@@ -51,14 +55,21 @@ public class ReportController {
private final ReportService reportService;
private final ReportTemplateRepository templateRepository;
private final Environment environment;
@Value("${eip4.report.templates-dir:/Users/zhengwr/workspace/EIP-3.0}")
private String templatesDir;
/** 是否要求报表对象级菜单授权(默认开)。关闭后已认证非超管用户可渲染任意报表(仅排障用)。 */
@Value("${eip4.report.require-menu-grant:true}")
private boolean requireMenuGrant;
public ReportController(ReportService reportService,
ReportTemplateRepository templateRepository) {
ReportTemplateRepository templateRepository,
Environment environment) {
this.reportService = reportService;
this.templateRepository = templateRepository;
this.environment = environment;
}
@GetMapping("/api/report/render/{templateId}")
@@ -66,33 +77,42 @@ public class ReportController {
@RequestParam(value = "format", required = false, defaultValue = "html") String format,
@RequestParam(value = "tpl", required = false) String tplPath,
HttpServletRequest request) {
Map<String, String> params = collectReportParams(request);
ReportService.Format fmt = ReportService.Format.parse(format);
ReportService.Format fmt;
try {
fmt = ReportService.Format.parse(format);
} catch (IllegalArgumentException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "不支持的报表格式");
}
enforceReportAccess(templateId);
byte[] body;
try {
if (tplPath != null && !tplPath.isBlank()) {
// dev/演示覆盖:直接渲染指定 .xml 文件(可为 JOR 文档或 view_template 外壳)。
Path xml = resolveTemplate(templateId, tplPath);
try (InputStream is = Files.newInputStream(xml)) {
body = reportService.render(is, params, format);
}
} else {
// 标准路径:按 templateId 从 view_template(type=200) 取 JOR 文档并渲染。
String jorXml = templateRepository.loadJorXml(templateId);
body = reportService.render(jorXml, params, format);
}
byte[] xmlBytes = loadTemplateBytes(templateId, tplPath);
Map<String, String> params = buildReportParams(request, xmlBytes);
body = reportService.render(new ByteArrayInputStream(xmlBytes), params, format);
} catch (ReportTemplateRepository.ReportTemplateNotFoundException e) {
log.warn("报表模板未找到 templateId={} : {}", templateId, e.getMessage());
throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage(), e);
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "报表模板未找到");
} catch (ReportBusyException e) {
log.warn("报表渲染并发已满 templateId={} : {}", templateId, e.getMessage());
throw new ResponseStatusException(HttpStatus.TOO_MANY_REQUESTS, "报表渲染繁忙,请稍后重试");
} catch (ReportSizeExceededException e) {
log.warn("报表产物超限 templateId={} : {}", templateId, e.getMessage());
throw new ResponseStatusException(HttpStatus.PAYLOAD_TOO_LARGE, "报表数据过大,请缩小查询范围");
} catch (SecurityException e) {
log.warn("报表请求被安全门拒绝 templateId={} tpl={} : {}", templateId, tplPath, e.getMessage());
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "请求被拒绝");
} catch (IllegalArgumentException e) {
log.warn("报表请求参数非法 templateId={} tpl={} : {}", templateId, tplPath, e.getMessage());
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "请求参数非法");
} catch (ReportService.ReportRenderException e) {
log.warn("报表渲染失败 templateId={} tpl={} : {}", templateId, tplPath, e.getMessage());
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage(), e);
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "报表渲染失败");
} catch (ResponseStatusException e) {
throw e;
} catch (Exception e) {
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR,
"读取/渲染报表模板失败: " + e.getMessage(), e);
log.warn("报表处理失败 templateId={} : {}", templateId, e.toString());
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "报表处理失败");
}
ResponseEntity.BodyBuilder rb = ResponseEntity.ok()
@@ -113,28 +133,124 @@ public class ReportController {
* → 返回 amis CRUD 单行信封 {@code {status:0,msg:"",data:{items:[{__url}],total:1}}},
* {@code __url} = {@code /api/report/render/{id}?format=html&<回显的查询参数>}。
*
* <p>报表页是 amis {@code crud}:查询条件放在 {@code crud.filter}(实测唯一能让 picker
* 正常加载选项的上下文;放在独立 form 里 picker 弹窗「暂无数据」)。crud 的单个 html 列把
* {@code __url} 渲成 {@code <iframe>}。用户「选工程→查询」时 crud 携 filter 参数请求本端点,
* 拿到带新参数的 {@code __url} → iframe 重新加载 → 报表按工程过滤刷新。本端点只回显 URL(不渲染),
* 真正的 JOR 渲染由 iframe 加载 {@code /api/report/render} 完成(HTML 文档独立,CSS 隔离保真)。
* <p>身份保留位(CURRENTUSER 等)不进 iframe URL —— 由 {@code /render} 服务端从认证上下文注入,
* 防止客户端经 URL 伪造身份;对象级授权同样在此前置(无权直接 403)。
*/
@GetMapping("/api/report/frame/{templateId}")
public Map<String, Object> frame(@PathVariable("templateId") String templateId,
HttpServletRequest request) {
enforceReportAccess(templateId);
Map<String, String> params = reportParamsFrom(request.getParameterMap());
params.keySet().removeIf(ReportParamGuard::isReservedIdentityParam);
return frameResult(buildFrameUrl(templateId, params));
}
// ===================== 安全门:授权 / 身份 / 参数 / 模板加载 =====================
/**
* frame 端点的非报表参数:渲染控制位(format/tpl)+ amis crud 自动追加的分页位(page/perPage)。
* 注:{@code /render} 端点不剥分页位(见 {@link #collectReportParams}),保持其原有行为不变。
* 对象级授权(防 IDOR):已认证非超管用户只能渲染其可见菜单暴露的报表。
* 无认证身份(旁路 profile 匿名)沿用宽松链不强制;超管放行;配置 {@code require-menu-grant=false} 时跳过。
*/
private void enforceReportAccess(String templateId) {
Properties ctx = UserSession.get();
if (ctx == null) {
return; // 匿名(旁路 profile 无令牌)→ 沿用宽松链不强制
}
if (!requireMenuGrant) {
return; // 配置显式关闭对象级授权(仅排障用)
}
String userId = ctx.getProperty(LoggedInUser.CURRENTUSER);
if (isAdmin(userId)) {
return; // 超管放行
}
if (userId == null || userId.isBlank()) {
// 已绑定认证上下文却取不到用户身份 → fail-closed,绝不放行(防畸形令牌绕过)
log.warn("报表访问:认证态但无用户身份,拒绝 templateId={}", templateId);
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "无权访问该报表");
}
if (!templateRepository.isReportVisibleTo(userId, templateId)) {
log.warn("报表越权访问被拒 userId={} templateId={}", userId, templateId);
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "无权访问该报表");
}
}
/** userId trim 后等于 {@code LoggedInUser.ADMIN}("ADMIN" + 补白)。大小写敏感,与 EngineContextBinder 对齐。 */
static boolean isAdmin(String userId) {
return userId != null && LoggedInUser.ADMIN.trim().equals(userId.trim());
}
/**
* 从可信上下文(UserSession)取身份/数据域保留参数值,供注入报表 SQL。真实模板用
* {@code ${USERID}}/{@code ${ORGID}}/{@code ${DEPARTID}} 做行级数据域过滤,与 {@code CURRENTUSER} 同源映射当前用户,
* 把数据域钉死为「本人/本部门/本机构」,客户端无法经 {@code ?USERID=他人} 越权读。
*/
private static Map<String, String> trustedIdentity() {
Properties ctx = UserSession.get();
Map<String, String> id = new LinkedHashMap<>();
if (ctx != null) {
String user = ctx.getProperty(LoggedInUser.CURRENTUSER);
String dept = ctx.getProperty(LoggedInUser.CURRENTDEPART);
String org = ctx.getProperty(LoggedInUser.CURRENTORG);
putIfPresent(id, "CURRENTUSER", user);
putIfPresent(id, "CURRENTDEPART", dept);
putIfPresent(id, "CURRENTORG", org);
putIfPresent(id, "USERID", user);
putIfPresent(id, "DEPARTID", dept);
putIfPresent(id, "ORGID", org);
}
return id;
}
private static void putIfPresent(Map<String, String> m, String key, String value) {
if (value != null && !value.isBlank()) {
m.put(key, value);
}
}
/**
* 报表参数(SQL 注入门):只保留模板 {@code ${name}} 引用过且非身份保留位的参数(值经安全校验),
* 再为模板引用过的身份保留位注入服务端可信值。
*/
private Map<String, String> buildReportParams(HttpServletRequest request, byte[] xmlBytes) {
// 用 ISO-8859-1 无损解码字节扫描 ${...}(标识符为 ASCII,不受真实编码影响)。
Set<String> referenced = ReportParamGuard.extractReferencedParamNames(
new String(xmlBytes, StandardCharsets.ISO_8859_1));
Map<String, String> client = collectReportParams(request);
Map<String, String> safe = ReportParamGuard.sanitizeClientParams(client, referenced);
return ReportParamGuard.applyTrustedIdentity(safe, referenced, trustedIdentity());
}
/**
* 加载模板原始字节。标准路径走 DB({@code view_template} type=200);{@code ?tpl} 文件直读仅旁路 profile
* (dev/local/ci/parity)允许,且经 {@link ReportTplGuard} 限定在 templates-dir 内、仅 .xml。
*/
private byte[] loadTemplateBytes(String templateId, String tplPath) {
if (tplPath != null && !tplPath.isBlank()) {
if (!SecurityProfiles.isBypassActive(environment)) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "tpl 文件直读仅开发环境可用");
}
Path xml = ReportTplGuard.resolveConfinedTplPath(templatesDir, tplPath);
if (!Files.isRegularFile(xml)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "报表模板未找到");
}
try {
return Files.readAllBytes(xml);
} catch (IOException e) {
throw new ReportService.ReportRenderException("读取报表模板文件失败", e);
}
}
return templateRepository.loadJorXml(templateId).getBytes(StandardCharsets.UTF_8);
}
// ===================== frame 端点纯逻辑(原有,保持不变) =====================
/**
* frame 端点的非报表参数:渲染控制位(format/tpl)+ amis crud 自动追加的分页位(page/perPage)。
*/
private static final Set<String> FRAME_NON_REPORT_PARAMS = Set.of("format", "tpl", "page", "perPage");
/**
* 从原始请求参数表抽出报表参数(剔除 {@link #FRAME_NON_REPORT_PARAMS},多值取第一个,跳过空/null)。
* frame 端点专用——crud 会带 page/perPage,需剥掉。报表 SQL 里的 {@code ${PARAM}} 据此绑定。纯函数,便于单测。
* 从原始请求参数表抽出报表参数(剔除 {@link #FRAME_NON_REPORT_PARAMS},多值取第一个,跳过空/null)。纯函数,便于单测。
*/
static Map<String, String> reportParamsFrom(Map<String, String[]> raw) {
Map<String, String> params = new LinkedHashMap<>();
@@ -154,9 +270,7 @@ public class ReportController {
/**
* 构造 iframe 用的 HTML 渲染 URL:{@code /api/report/render/{id}?format=html&k=v&...}。
* {@code templateId} 路径段与各参数键值均经 UTF-8 URL 编码 —— 该 URL 最终被注入 amis html 列的
* {@code <iframe src="${__url}">},编码确保任何特殊字符({@code " & # / < >})都不会破坏 query 结构
* 或逃逸出 src 属性(防注入,安全评审防御纵深)。templateId 实为 view_template_id(UUID),编码对其无副作用。
* templateId 路径段与各参数键值均经 UTF-8 URL 编码,确保特殊字符不会破坏 query 结构或逃逸出 src 属性。纯函数。
*/
static String buildFrameUrl(String templateId, Map<String, String> params) {
StringBuilder sb = new StringBuilder("/api/report/render/")
@@ -171,7 +285,7 @@ public class ReportController {
return sb.toString();
}
/** 把单条 URL 包成 amis CRUD 单行信封:{@code {status:0,msg:"",data:{items:[{__url}],total:1}}}。 */
/** 把单条 URL 包成 amis CRUD 单行信封:{@code {status:0,msg:"",data:{items:[{__url}],total:1}}}。 */
static Map<String, Object> frameResult(String url) {
Map<String, Object> item = new LinkedHashMap<>();
item.put("__url", url);
@@ -186,13 +300,9 @@ public class ReportController {
}
/**
* 构造导出下载的 {@code Content-Disposition} 头值。
* <ul>
* <li>{@code html} → {@code null}(查看器 iframe 内嵌,inline);</li>
* <li>{@code pdf}/{@code xls} → {@code attachment},中文报表名经 RFC5987 {@code filename*=UTF-8''} 编码,
* ASCII 回退 {@code filename="<templateId>.<ext>"}(UUID 安全,老客户端兜底)。</li>
* </ul>
* 文件名经 {@link #sanitizeFilename} 净化(剔除 CRLF/引号/斜杠/控制符),杜绝响应头注入与属性逃逸。纯函数,便于单测。
* 构造导出下载的 {@code Content-Disposition} 头值。html→null(inline);pdf/xls→attachment,中文名经 RFC5987
* {@code filename*=UTF-8''} 编码,ASCII 回退 {@code filename="<templateId>.<ext>"}。文件名经 {@link #sanitizeFilename}
* 净化,杜绝响应头注入与属性逃逸。纯函数。
*/
static String contentDisposition(ReportService.Format fmt, String reportName, String templateId) {
if (fmt == ReportService.Format.HTML) {
@@ -206,8 +316,6 @@ public class ReportController {
if (base.isEmpty()) {
base = "report";
}
// RFC5987 ext-value:URLEncoder 是 x-www-form-urlencoded(空格→+,且保留 * 不编码),
// 修正成 RFC5987 attr-char 口径——空格→%20、* →%2A(. - _ 本就是合法 attr-char)。
String encoded = URLEncoder.encode(base + "." + ext, StandardCharsets.UTF_8)
.replace("+", "%20").replace("*", "%2A");
String ascii = sanitizeFilename(templateId == null ? "" : templateId.replaceAll("[^\\x20-\\x7E]", "_"));
@@ -225,29 +333,9 @@ public class ReportController {
return s.replaceAll("[\\r\\n\"\\\\/\\x00-\\x1F\\x7F]", "").trim();
}
/** templateId / ?tpl 解析为模板文件路径。 */
private Path resolveTemplate(String templateId, String tplPath) {
Path xml;
if (tplPath != null && !tplPath.isBlank()) {
xml = Path.of(tplPath);
} else {
String rel = templateId;
if (!rel.toLowerCase().endsWith(".xml")) {
rel = rel + ".xml";
}
xml = Path.of(templatesDir).resolve(rel);
}
if (!Files.isRegularFile(xml)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND,
"报表模板未找到: " + xml);
}
return xml;
}
/**
* {@code /render} 端点的报表参数 = 请求参数剔除渲染控制位 {@code format}/{@code tpl}(仅此两位)。
* 不剥 {@code page}/{@code perPage} —— 保持本端点<strong>原有行为不变</strong>(与 frame 端点的
* {@link #reportParamsFrom} 有意分流:仅 crud 驱动的 frame 才会带分页位需要剥离)。
* {@code /render} 端点的客户端报表参数 = 请求参数剔除渲染控制位 {@code format}/{@code tpl}。
* 后续由 {@link #buildReportParams} 经 {@link ReportParamGuard} 收口(名单/值校验/身份注入)。
*/
private Map<String, String> collectReportParams(HttpServletRequest request) {
Map<String, String> params = new LinkedHashMap<>();

View File

@@ -0,0 +1,142 @@
package com.eip4.platform.report;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 报表查询参数的 SQL 注入门(P0,包装层唯一可改面)。
*
* <p>jatools 引擎对报表 SQL 里的 {@code ${PARAM}} 做<strong>字符串模板替换</strong>后再
* {@code prepareStatement(sqlcopy)} 执行(见 {@code SqlReader.readStart}/{@code ReportContext.evalTemplate}),
* 即参数值被字面拼进 SQL、无占位符绑定。引擎为预编译 jar 不可改,故在 HTTP 入口处对透传参数收口:
* <ul>
* <li><b>名单</b> {@link #extractReferencedParamNames}:只放行模板 SQL 里真正以 {@code ${name}}
* 引用过的参数名(自校准白名单),未引用的参数本就到不了 SQL,直接丢弃缩小面;</li>
* <li><b>值校验</b> {@link #isSafeValue}:拒绝引号/分号/注释符/反斜杠/控制符与超长值,
* 挡掉 {@code ' OR '1'='1} / {@code ;DROP ...} / {@code -- 注释} 这类注入载荷;</li>
* <li><b>保留位</b> {@link #isReservedIdentityParam} + {@link #applyTrustedIdentity}:身份保留参数
* (CURRENTUSER 等)一律剥掉客户端值,改由服务端可信上下文注入,杜绝越权伪造。</li>
* </ul>
* 全为纯函数,便于单测。
*/
public final class ReportParamGuard {
private ReportParamGuard() {
}
/**
* 身份/数据域保留参数:客户端不得设置,由服务端从认证上下文注入(大小写不敏感匹配)。
* <p><strong>保留集 == 服务端可信注入集</strong>(见 {@code ReportController.trustedIdentity}),
* 避免「剥离客户端值却不注入可信值」造成变量为空 → fail-open。真实模板按 {@code ${USERID}}/{@code ${ORGID}}/
* {@code ${DEPARTID}} 做行级数据域过滤,故必须纳入(否则客户端可经 {@code ?USERID=他人} 越权读)。
* {@code PROJECTID} 是报表查看器 picker 的用户可选过滤(非身份),不在此集,但其值仍经 {@link #isSafeValue} 校验。
*/
static final Set<String> RESERVED_IDENTITY_PARAMS = Set.of(
"CURRENTUSER", "CURRENTDEPART", "CURRENTORG", "USERID", "DEPARTID", "ORGID");
/** 单个参数值长度上限(报表过滤值为编码/ID/日期,1024 足够,超长视为攻击/异常)。 */
static final int MAX_VALUE_LEN = 1024;
/** {@code ${ ... }} 宏跨度。 */
private static final Pattern MACRO = Pattern.compile("\\$\\{([^}]*)\\}");
/** 宏内的标识符 token。 */
private static final Pattern IDENT = Pattern.compile("[A-Za-z_][A-Za-z0-9_]*");
/** 多字符危险子串:行注释 {@code --}、类型转换 {@code ::}(白名单已排除其它注释/星号字符)。 */
private static final Pattern UNSAFE_SUBSTR = Pattern.compile("--|::");
/** 除字母/数字(含 CJK)外允许的安全标点:ID/编码/日期所需。<strong>不含空格</strong>是挡住无引号注入的关键。 */
private static final String EXTRA_SAFE_CHARS = "-_./:";
/**
* 从模板文本里抽出所有在 {@code ${...}} 宏内出现过的标识符 token(自校准白名单)。
* 过包含函数名(iif 等)无害:它们不是客户端可控的绑定目标,且值仍走 {@link #isSafeValue} 校验。
*/
static Set<String> extractReferencedParamNames(String jorXml) {
Set<String> names = new LinkedHashSet<>();
if (jorXml == null || jorXml.isEmpty()) {
return names;
}
Matcher macro = MACRO.matcher(jorXml);
while (macro.find()) {
Matcher id = IDENT.matcher(macro.group(1));
while (id.find()) {
names.add(id.group());
}
}
return names;
}
/**
* 参数值是否安全。<strong>白名单</strong>:只允许字母/数字(含 CJK)与 {@code -_./:},外加拒绝
* {@code --}/{@code ::} 子串与超长。报表过滤值本就是编码/ID/日期/年月/时间戳,不含空格。
* <p>关键:真实模板存在<em>无引号</em>数值上下文({@code =${YEAR}}),黑名单挡不住
* {@code 0 union select ...}/{@code 1=(select ...)} 这类无引号注入;拒绝空格与 {@code = ( ) , * '} 等
* 结构字符即从根上切断(SQL 关键字间必须有空白/注释分隔,而空白与注释均被拒)。null/空串视为无值(安全)。
*/
static boolean isSafeValue(String value) {
if (value == null || value.isEmpty()) {
return true;
}
if (value.length() > MAX_VALUE_LEN) {
return false;
}
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (!Character.isLetterOrDigit(c) && EXTRA_SAFE_CHARS.indexOf(c) < 0) {
return false; // 白名单外一律拒(含空格/引号/分号/= ( ) , * 反斜杠/控制符等)
}
}
return !UNSAFE_SUBSTR.matcher(value).find();
}
/** 是否身份保留参数(大小写不敏感)。 */
static boolean isReservedIdentityParam(String name) {
return name != null && RESERVED_IDENTITY_PARAMS.contains(name.toUpperCase(Locale.ROOT));
}
/**
* 净化客户端参数:只保留<em>被模板引用过</em>且<em>非身份保留位</em>的参数;对保留的参数值做
* 安全校验,任一不安全则抛 {@link IllegalArgumentException}(由控制器映射 400)。
*/
static Map<String, String> sanitizeClientParams(Map<String, String> client, Set<String> referenced) {
Map<String, String> out = new LinkedHashMap<>();
if (client == null || referenced == null) {
return out;
}
for (Map.Entry<String, String> e : client.entrySet()) {
String name = e.getKey();
if (name == null || !referenced.contains(name) || isReservedIdentityParam(name)) {
continue; // 未引用 → 丢;身份保留位 → 服务端注入
}
String value = e.getValue();
if (!isSafeValue(value)) {
throw new IllegalArgumentException("报表参数值含非法字符: " + name);
}
out.put(name, value);
}
return out;
}
/**
* 为模板<em>引用过</em>的身份保留位注入服务端可信值(覆盖任何同名,防伪造);
* 模板未引用的保留位不注入。{@code identity} 为空时原样返回。
*/
static Map<String, String> applyTrustedIdentity(Map<String, String> safe, Set<String> referenced,
Map<String, String> identity) {
Map<String, String> out = new LinkedHashMap<>(safe == null ? Map.of() : safe);
if (identity == null || identity.isEmpty() || referenced == null) {
return out;
}
for (Map.Entry<String, String> e : identity.entrySet()) {
String name = e.getKey();
if (name != null && referenced.contains(name)) {
out.put(name, e.getValue());
}
}
return out;
}
}

View File

@@ -12,6 +12,7 @@ import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import jatools.ReportDocument;
@@ -45,9 +46,19 @@ public class ReportService {
System.setProperty("java.awt.headless", "true");
}
public ReportService(JatoolsConfig jatoolsConfig) {
/** 并发闸:限制同时渲染数,防 N 个并发大报表线性叠加堆 → OOM。 */
private final RenderConcurrencyLimiter limiter;
/** 单次渲染产物字节上限,超出抛 {@link ReportSizeExceededException}(控制器 413)。 */
private final long maxOutputBytes;
public ReportService(JatoolsConfig jatoolsConfig,
@Value("${eip4.report.max-concurrent-renders:4}") int maxConcurrentRenders,
@Value("${eip4.report.render-acquire-timeout-ms:3000}") long acquireTimeoutMs,
@Value("${eip4.report.max-output-bytes:67108864}") long maxOutputBytes) {
// 触发 JatoolsConfig 构造(@PostConstruct 注入 System2 配置)先于任何渲染。
jatoolsConfig.ensureInitialized();
this.limiter = new RenderConcurrencyLimiter(Math.max(1, maxConcurrentRenders), acquireTimeoutMs);
this.maxOutputBytes = maxOutputBytes;
}
/** 支持的导出格式。 */
@@ -94,10 +105,21 @@ public class ReportService {
}
public byte[] render(InputStream templateXml, Map<String, String> params, String format) {
// 并发闸:超过同时渲染上限即抛 ReportBusyException(控制器 429),把峰值堆收敛到「并发上限 × 单请求」。
return limiter.call(() -> doRender(templateXml, params, format));
}
private byte[] doRender(InputStream templateXml, Map<String, String> params, String format) {
Format fmt = Format.parse(format);
File tmpDir = null;
try {
ReportDocument doc = ReportDocument.load(templateXml);
byte[] xmlBytes = templateXml.readAllBytes();
// XXE 防护:JOR 报表文档无需 DOCTYPE,带 DOCTYPE 声明的一律拒绝
// (阻断外部实体/SSRF/OOB 文件外带/billion-laughs)。字节级检测,防 BOM/UTF-16 编码绕过。
if (ReportXmlGuard.hasDoctypeInBytes(xmlBytes)) {
throw new ReportRenderException("报表模板含 DOCTYPE 声明,已拒绝渲染(XXE 防护)", null);
}
ReportDocument doc = ReportDocument.load(new ByteArrayInputStream(xmlBytes));
ReportJob job = new ReportJob(doc);
if (params != null) {
@@ -108,7 +130,8 @@ public class ReportService {
}
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
// 带字节上限的产物缓冲:超过 maxOutputBytes 抛 ReportSizeExceededException(控制器 413),单请求堆封顶。
ByteArrayOutputStream out = new LimitedByteArrayOutputStream(maxOutputBytes);
switch (fmt) {
case HTML -> {
// HTML 内嵌图片等资源经 ResourceOutputFactory 落到临时目录(替代 servlet 会话沉淀)。

View File

@@ -0,0 +1,19 @@
package com.eip4.platform.report;
/**
* 渲染产物超过配置的字节上限({@code eip4.report.max-output-bytes})。
* 控制器据此返回 413 Payload Too Large,把单请求堆占用封顶,防止超大报表撑爆 JVM。
*/
public class ReportSizeExceededException extends RuntimeException {
private final long limitBytes;
public ReportSizeExceededException(long limitBytes) {
super("报表渲染产物超过上限 " + limitBytes + " 字节");
this.limitBytes = limitBytes;
}
public long getLimitBytes() {
return limitBytes;
}
}

View File

@@ -34,6 +34,16 @@ public class ReportTemplateRepository {
private static final String NAME_SQL =
"SELECT name FROM eip3.view_template WHERE trim(view_template_id) = ? AND type = 200";
/**
* 对象级授权(防 IDOR):该 templateId 报表是否经某个<em>用户可见菜单</em>暴露给该用户。
* 关联 {@code view_sys_menu.view_templateid} ←→ {@code view_sys_usermenuid}(用户→可见菜单);
* CHAR 列两端补白故 join/比较均 trim。已对真实库(granted 返 1 / not-granted 空)实证。
*/
private static final String AUTHZ_SQL =
"SELECT 1 FROM eip3.view_sys_menu m "
+ "JOIN eip3.view_sys_usermenuid um ON trim(um.menuid) = trim(m.view_sys_menu_id) "
+ "WHERE trim(m.view_templateid) = ? AND trim(um.userid) = ? LIMIT 1";
private final JdbcTemplate jdbcTemplate;
public ReportTemplateRepository(JdbcTemplate jdbcTemplate) {
@@ -84,6 +94,20 @@ public class ReportTemplateRepository {
}
}
/**
* 当前用户能否访问该报表(经其可见菜单暴露)。userId/templateId 为空返回 {@code false}。
* 仅做存在性判定,超管放行由调用方(控制器)按身份决定,本方法不含超管旁路。
*/
public boolean isReportVisibleTo(String userId, String templateId) {
String u = userId == null ? "" : userId.trim();
String t = templateId == null ? "" : templateId.trim();
if (u.isEmpty() || t.isEmpty()) {
return false;
}
List<Integer> rows = jdbcTemplate.queryForList(AUTHZ_SQL, Integer.class, t, u);
return !rows.isEmpty();
}
/**
* 从 {@code <report>} 外壳里抽出 {@code <reportfile>} 内层 JOR 文档。
*

View File

@@ -0,0 +1,41 @@
package com.eip4.platform.report;
import java.nio.file.Path;
import java.util.Locale;
/**
* {@code ?tpl=<路径>} 文件直读的基目录限定门(P0)。
*
* <p>原 {@code ReportController.resolveTemplate} 在 tpl 非空时直接 {@code Path.of(tplPath)},无基目录限定、
* 无 {@code ..} 穿越拦截、无扩展名约束、无 profile 守卫 → 任意已登录用户可读服务器任意文件,并作为 XXE 的
* 投递面。本门把 tpl 强制限定在 {@code templates-dir} 内、仅允许 {@code .xml};是否启用 tpl 通道本身由控制器
* 按 profile 守卫(仅 dev/local/ci/parity 旁路 profile 才接受 tpl)。
*
* <p>限定算法:{@code base.resolve(tpl).normalize()} 后校验 {@code startsWith(base)} ——
* 绝对路径会被 {@code resolve} 直接采用(故 {@code /etc/passwd} 不在 base 下 → 拒绝),
* {@code ../} 经 {@code normalize} 抵消后若越出 base 亦拒绝;base 内的良性 {@code ..} 归一后仍在 base 内则放行。
*/
public final class ReportTplGuard {
private ReportTplGuard() {
}
static Path resolveConfinedTplPath(String templatesDir, String tplPath) {
if (templatesDir == null || templatesDir.isBlank()) {
throw new IllegalArgumentException("报表模板根目录(templates-dir)未配置");
}
if (tplPath == null || tplPath.isBlank()) {
throw new IllegalArgumentException("tpl 路径为空");
}
Path base = Path.of(templatesDir).toAbsolutePath().normalize();
Path target = base.resolve(tplPath).normalize();
if (!target.startsWith(base)) {
throw new SecurityException("tpl 越出模板根目录: " + tplPath);
}
Path fileName = target.getFileName();
if (fileName == null || !fileName.toString().toLowerCase(Locale.ROOT).endsWith(".xml")) {
throw new IllegalArgumentException("tpl 只允许 .xml 文件: " + tplPath);
}
return target;
}
}

View File

@@ -0,0 +1,99 @@
package com.eip4.platform.report;
import java.nio.charset.StandardCharsets;
/**
* 报表 XML 的 XXE 防御门(P0)。
*
* <p>jatools {@code XmlReader.read} 用裸 {@code DocumentBuilderFactory.newInstance()} 解析报表 XML,
* 未禁 DOCTYPE/外部实体 → 经典 XXE(SSRF / OOB 文件外带 / billion-laughs DoS)。引擎为预编译 jar
* 不便改,故在把模板交给引擎前先用本门拒绝任何带 DOCTYPE 声明的文档 —— JOR 报表文档本就无需 DOCTYPE,
* 整体禁用即可阻断全部基于实体的 XXE。
*
* <p>{@link #hasDoctype} 只扫描 prolog(根元素之前),正确跳过 XML 声明 {@code <?xml?>} 与注释
* {@code <!-- -->}(注释里出现的 {@code <!DOCTYPE} 文本不算),命中根元素即停(元素内容里的字面
* {@code <!DOCTYPE} 文本不算)。纯函数,便于单测。
*/
public final class ReportXmlGuard {
private ReportXmlGuard() {
}
/** prolog 扫描只需看前若干字节(BOM/XML 声明/注释/DOCTYPE 都在最前)。 */
private static final int PROLOG_SCAN_BYTES = 8192;
/**
* 字节级 DOCTYPE 检测,消除「扫描端与引擎解析端编码视角不一致」的绕过:按 BOM / 无 BOM 的 UTF-16
* 空字节特征识别编码后再解码 prolog,然后走 {@link #hasDoctype}。否则 UTF-8 BOM(EF BB BF)或 UTF-16
* 会让纯 ISO-8859-1 扫描漏判 {@code <!DOCTYPE},而 xerces 仍按 BOM 正确解析触发 XXE。
*/
static boolean hasDoctypeInBytes(byte[] raw) {
if (raw == null || raw.length == 0) {
return false;
}
java.nio.charset.Charset cs;
int off = 0;
int u0 = raw[0] & 0xFF;
int u1 = raw.length > 1 ? raw[1] & 0xFF : -1;
int u2 = raw.length > 2 ? raw[2] & 0xFF : -1;
if (u0 == 0xEF && u1 == 0xBB && u2 == 0xBF) {
cs = StandardCharsets.UTF_8;
off = 3; // UTF-8 BOM
} else if (u0 == 0xFF && u1 == 0xFE) {
cs = StandardCharsets.UTF_16LE;
off = 2; // UTF-16LE BOM
} else if (u0 == 0xFE && u1 == 0xFF) {
cs = StandardCharsets.UTF_16BE;
off = 2; // UTF-16BE BOM
} else if (u0 == '<' && u1 == 0x00) {
cs = StandardCharsets.UTF_16LE; // 无 BOM UTF-16LE(ASCII 起始字符夹空字节)
} else if (u0 == 0x00 && u1 == '<') {
cs = StandardCharsets.UTF_16BE; // 无 BOM UTF-16BE
} else {
cs = StandardCharsets.ISO_8859_1; // UTF-8 / Latin1:prolog 为 ASCII,字节级保真扫描
}
int scanLen = Math.min(raw.length - off, PROLOG_SCAN_BYTES);
return hasDoctype(new String(raw, off, scanLen, cs));
}
/** 文档 prolog 是否含 DOCTYPE 声明(大小写不敏感)。 */
static boolean hasDoctype(String xml) {
if (xml == null) {
return false;
}
int i = 0;
int n = xml.length();
while (i < n) {
char c = xml.charAt(i);
// 跳过空白与 BOM
if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '') {
i++;
continue;
}
if (c != '<') {
return false; // prolog 里非标记的文本(异常)→ 视为无 DOCTYPE
}
if (xml.regionMatches(true, i, "<!DOCTYPE", 0, 9)) {
return true;
}
if (xml.startsWith("<!--", i)) { // 注释:整段跳过
int end = xml.indexOf("-->", i + 4);
if (end < 0) {
return false; // 注释未闭合(畸形)→ 不再继续
}
i = end + 3;
continue;
}
if (xml.startsWith("<?", i)) { // XML 声明 / 处理指令:整段跳过
int end = xml.indexOf("?>", i + 2);
if (end < 0) {
return false;
}
i = end + 2;
continue;
}
return false; // 到达根元素起始标签,prolog 结束,无 DOCTYPE
}
return false;
}
}

View File

@@ -0,0 +1,74 @@
package com.eip4.platform.report;
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 org.junit.jupiter.api.Test;
/**
* 报表数据源 URL 的超时加固(P1):jatools 用裸 {@code DriverManager} 直连且全程无 {@code setQueryTimeout},
* 慢/重 SQL 可无限期占用连接与堆,泄露的连接也永不释放。无法改预编译引擎,故在 {@link JatoolsConfig} 注入
* 的 DBJdbcUrl 上追加 PG 服务端 {@code statement_timeout} 与 pgjdbc {@code socketTimeout}。
*/
class JatoolsConfigUrlTest {
@Test
void appends_statement_timeout_and_socket_timeout_with_existing_query() {
String url = JatoolsConfig.appendPgTimeouts(
"jdbc:postgresql://localhost:5433/eip4dev?currentSchema=eip3", 30000, 35);
assertTrue(url.startsWith("jdbc:postgresql://localhost:5433/eip4dev?currentSchema=eip3"), url);
assertTrue(url.contains("currentSchema=eip3"), "原参数必须保留: " + url);
assertTrue(url.contains("socketTimeout=35"), url);
// pgjdbc 对参数值做 URL 解码,故 options 用 %20/%3D 编码 -> "-c statement_timeout=30000"
assertTrue(url.contains("options=-c%20statement_timeout%3D30000"), url);
// 追加用 & 衔接已有 query
assertFalse(url.contains("??"), url);
}
@Test
void uses_question_mark_when_no_existing_query() {
String url = JatoolsConfig.appendPgTimeouts("jdbc:postgresql://h:5432/db", 10000, 20);
assertTrue(url.startsWith("jdbc:postgresql://h:5432/db?"), url);
assertTrue(url.contains("socketTimeout=20"), url);
assertTrue(url.contains("options=-c%20statement_timeout%3D10000"), url);
}
@Test
void skips_statement_timeout_when_non_positive() {
String url = JatoolsConfig.appendPgTimeouts("jdbc:postgresql://h/db", 0, 20);
assertFalse(url.contains("statement_timeout"), url);
assertTrue(url.contains("socketTimeout=20"), url);
}
@Test
void skips_socket_timeout_when_non_positive() {
String url = JatoolsConfig.appendPgTimeouts("jdbc:postgresql://h/db", 5000, 0);
assertFalse(url.contains("socketTimeout"), url);
assertTrue(url.contains("statement_timeout"), url);
}
@Test
void idempotent_when_timeout_already_present() {
String once = JatoolsConfig.appendPgTimeouts("jdbc:postgresql://h/db?currentSchema=eip3", 5000, 30);
String twice = JatoolsConfig.appendPgTimeouts(once, 5000, 30);
assertEquals(once, twice, "重复加固应幂等");
}
@Test
void does_not_duplicate_options_when_url_already_has_options() {
// 已有 options=(如 search_path 设置)时,不再追加第二个 options= 以免 pgjdbc 后者覆盖前者丢配置。
String url = JatoolsConfig.appendPgTimeouts(
"jdbc:postgresql://h/db?options=-c%20search_path%3Deip3", 5000, 30);
assertEquals(1, url.split("options=", -1).length - 1, "options= 不应重复: " + url);
assertTrue(url.contains("socketTimeout=30"), url); // socketTimeout 仍可加(独立参数)
}
@Test
void leaves_non_postgres_url_and_blank_unchanged() {
assertEquals("jdbc:oracle:thin:@h:1521:db",
JatoolsConfig.appendPgTimeouts("jdbc:oracle:thin:@h:1521:db", 5000, 30));
assertEquals("", JatoolsConfig.appendPgTimeouts("", 5000, 30));
assertEquals(null, JatoolsConfig.appendPgTimeouts(null, 5000, 30));
}
}

View File

@@ -0,0 +1,52 @@
package com.eip4.platform.report;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
/**
* 渲染产物字节上限(P1 OOM 收口)。报表产物原整篇缓冲进无上限 ByteArrayOutputStream → 单请求即可撑爆堆。
* 本流在超过上限时抛 {@link ReportSizeExceededException}(控制器映射 413),把单请求堆占用封顶。
*/
class LimitedByteArrayOutputStreamTest {
@Test
void writes_within_limit_are_buffered() {
LimitedByteArrayOutputStream out = new LimitedByteArrayOutputStream(10);
out.write(new byte[]{1, 2, 3, 4, 5}, 0, 5);
assertEquals(5, out.toByteArray().length);
}
@Test
void single_byte_writes_up_to_limit_ok_then_throw() {
LimitedByteArrayOutputStream out = new LimitedByteArrayOutputStream(3);
out.write(1);
out.write(2);
out.write(3);
assertThrows(ReportSizeExceededException.class, () -> out.write(4));
}
@Test
void bulk_write_exceeding_limit_throws() {
LimitedByteArrayOutputStream out = new LimitedByteArrayOutputStream(4);
assertThrows(ReportSizeExceededException.class,
() -> out.write(new byte[]{1, 2, 3, 4, 5}, 0, 5));
}
@Test
void accumulated_writes_crossing_limit_throw() {
LimitedByteArrayOutputStream out = new LimitedByteArrayOutputStream(4);
out.write(new byte[]{1, 2, 3}, 0, 3);
assertThrows(ReportSizeExceededException.class,
() -> out.write(new byte[]{4, 5}, 0, 2));
}
@Test
void exception_carries_the_limit() {
LimitedByteArrayOutputStream out = new LimitedByteArrayOutputStream(2);
ReportSizeExceededException ex = assertThrows(ReportSizeExceededException.class,
() -> out.write(new byte[]{1, 2, 3}, 0, 3));
assertEquals(2, ex.getLimitBytes());
}
}

View File

@@ -0,0 +1,42 @@
package com.eip4.platform.report;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
/**
* 渲染并发闸(P1 OOM 收口)。渲染原直接跑在 Tomcat 工作线程、无任何并发上限,N 个并发大报表线性叠加
* (全量结果集+全量文档+全量产物)→ OOM。本闸用有界信号量限制同时渲染数,超出即抛
* {@link ReportBusyException}(控制器映射 429),把峰值堆收敛到「并发上限 × 单请求」。
*/
class RenderConcurrencyLimiterTest {
@Test
void runs_task_when_permit_available() {
RenderConcurrencyLimiter limiter = new RenderConcurrencyLimiter(1, 50);
assertEquals("ok", limiter.call(() -> "ok"));
}
@Test
void releases_permit_after_task_so_next_call_succeeds() {
RenderConcurrencyLimiter limiter = new RenderConcurrencyLimiter(1, 50);
assertEquals("a", limiter.call(() -> "a"));
assertEquals("b", limiter.call(() -> "b")); // 许可已释放,可再次获取
}
@Test
void releases_permit_even_when_task_throws() {
RenderConcurrencyLimiter limiter = new RenderConcurrencyLimiter(1, 50);
assertThrows(IllegalStateException.class, () -> limiter.call(() -> {
throw new IllegalStateException("boom");
}));
assertEquals("recovered", limiter.call(() -> "recovered")); // 许可未泄露
}
@Test
void throws_busy_when_no_permit_within_timeout() {
RenderConcurrencyLimiter limiter = new RenderConcurrencyLimiter(0, 10);
assertThrows(ReportBusyException.class, () -> limiter.call(() -> "never"));
}
}

View File

@@ -0,0 +1,195 @@
package com.eip4.platform.report;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
/**
* SQL 注入参数门(P0)的纯逻辑单测。
*
* <p>报表 SQL 里 {@code ${PARAM}} 由 jatools 引擎做<strong>字符串模板替换</strong>后直接执行
* (非占位符绑定),故 HTTP 透传的参数构成 SQL 注入面。本门(包装层唯一可改面)做三件事:
* <ol>
* <li>名单:只放行模板 SQL 里真正以 {@code ${name}} 引用过的参数名(自校准白名单);</li>
* <li>值校验:拒绝引号/分号/注释符/反斜杠/控制符等危险字符;</li>
* <li>保留位:剥掉客户端传入的身份保留参数(CURRENTUSER 等),由服务端可信上下文注入。</li>
* </ol>
*/
class ReportParamGuardTest {
// ---- extractReferencedParamNames:从模板抽出 ${...} 引用过的标识符 ----
@Test
void extractReferenced_picks_identifier_inside_macro() {
Set<String> names = ReportParamGuard.extractReferencedParamNames(
"select * from t where pid = '${PROJECTID}'");
assertTrue(names.contains("PROJECTID"), names.toString());
}
@Test
void extractReferenced_ignores_tokens_outside_macros() {
Set<String> names = ReportParamGuard.extractReferencedParamNames(
"SELECT FOO FROM tbl WHERE x = ${BAR} AND y = 1");
assertTrue(names.contains("BAR"), names.toString());
assertFalse(names.contains("FOO"), "宏外的 token 不应入名单");
assertFalse(names.contains("SELECT"), names.toString());
}
@Test
void extractReferenced_handles_multiple_and_function_macros() {
Set<String> names = ReportParamGuard.extractReferencedParamNames(
"${owner}=${CURRENTUSER} and ${iif(STATUS,'a','b')} and ${B_1}");
assertTrue(names.containsAll(Set.of("owner", "CURRENTUSER", "STATUS", "B_1")), names.toString());
}
@Test
void extractReferenced_empty_when_no_macros_or_null() {
assertTrue(ReportParamGuard.extractReferencedParamNames("plain sql no macros").isEmpty());
assertTrue(ReportParamGuard.extractReferencedParamNames(null).isEmpty());
}
// ---- isSafeValue:危险字符黑名单 + 长度上限 ----
@Test
void isSafeValue_allows_typical_report_filter_values() {
assertTrue(ReportParamGuard.isSafeValue("P-001"));
assertTrue(ReportParamGuard.isSafeValue("2026-06-25")); // 单连字符(日期)允许
assertTrue(ReportParamGuard.isSafeValue("2026/06/25")); // 斜杠日期允许
assertTrue(ReportParamGuard.isSafeValue("201501")); // yyyymm 整数
assertTrue(ReportParamGuard.isSafeValue("1498838400000")); // epoch 毫秒
assertTrue(ReportParamGuard.isSafeValue("ba842507-cd30-4a86-8605-88068d913bba")); // UUID
assertTrue(ReportParamGuard.isSafeValue("研发部")); // 中文允许
assertTrue(ReportParamGuard.isSafeValue("")); // 空串允许
assertTrue(ReportParamGuard.isSafeValue(null)); // null 视为无值,安全
}
@Test
void isSafeValue_rejects_numeric_context_injection_without_quotes() {
// 真实模板大量是无引号数值上下文(=${YEAR}/=${PROJECTID}),注入无需引号/分号 —— 黑名单挡不住,
// 必须靠「拒空格 + 字符白名单」。这些 PoC 不含引号/分号但仍须拒绝。
assertFalse(ReportParamGuard.isSafeValue("0 union select password from sys_user"));
assertFalse(ReportParamGuard.isSafeValue("2024 and 1=(select 1 from pg_sleep(5))"));
assertFalse(ReportParamGuard.isSafeValue("1=1")); // 等号
assertFalse(ReportParamGuard.isSafeValue("a b")); // 空格
assertFalse(ReportParamGuard.isSafeValue("f(x)")); // 括号
assertFalse(ReportParamGuard.isSafeValue("a,b")); // 逗号
}
@Test
void isSafeValue_rejects_sql_metacharacters_and_comments() {
assertFalse(ReportParamGuard.isSafeValue("' OR '1'='1")); // 单引号
assertFalse(ReportParamGuard.isSafeValue("x\"y")); // 双引号
assertFalse(ReportParamGuard.isSafeValue("a;b")); // 分号
assertFalse(ReportParamGuard.isSafeValue("a--b")); // 行注释(双连字符)
assertFalse(ReportParamGuard.isSafeValue("a::text")); // 类型转换(双冒号)
assertFalse(ReportParamGuard.isSafeValue("a\\b")); // 反斜杠
assertFalse(ReportParamGuard.isSafeValue("a*b")); // 星号
}
@Test
void isSafeValue_rejects_control_chars_and_overlong() {
assertFalse(ReportParamGuard.isSafeValue("line1\nline2")); // 换行(控制符)
assertFalse(ReportParamGuard.isSafeValue("a\tb")); // 制表符
assertFalse(ReportParamGuard.isSafeValue("a".repeat(1025))); // 超长
assertTrue(ReportParamGuard.isSafeValue("a".repeat(1024))); // 边界内
}
// ---- isReservedIdentityParam:身份保留参数(大小写不敏感) ----
@Test
void reserved_identity_params_recognized_case_insensitively() {
// 保留集 = 服务端可信注入集(身份/数据域),避免「剥离却不注入」造成 fail-open。
for (String n : new String[]{"CURRENTUSER", "CURRENTDEPART", "CURRENTORG",
"USERID", "DEPARTID", "ORGID"}) {
assertTrue(ReportParamGuard.isReservedIdentityParam(n), n);
assertTrue(ReportParamGuard.isReservedIdentityParam(n.toLowerCase()), n.toLowerCase());
}
// PROJECTID 是报表查看器 picker 的用户可选过滤(非身份)→ 不保留,但值仍经安全校验。
assertFalse(ReportParamGuard.isReservedIdentityParam("PROJECTID"));
// 无可信来源、强行剥离会 fail-open 的不纳入保留集。
assertFalse(ReportParamGuard.isReservedIdentityParam("CURRENTPROJECT"));
assertFalse(ReportParamGuard.isReservedIdentityParam("CURRENTTIME"));
}
// ---- sanitizeClientParams:丢未引用 + 丢保留 + 校验值 ----
@Test
void sanitize_keeps_only_referenced_nonreserved_safe_params() {
Set<String> referenced = Set.of("PROJECTID", "CURRENTUSER");
Map<String, String> client = new LinkedHashMap<>();
client.put("PROJECTID", "P-001"); // 引用过 + 非保留 + 安全 → 保留
client.put("FOO", "x"); // 未引用 → 丢
client.put("CURRENTUSER", "hacker"); // 保留位 → 丢(服务端注入)
Map<String, String> out = ReportParamGuard.sanitizeClientParams(client, referenced);
assertEquals(Set.of("PROJECTID"), out.keySet());
assertEquals("P-001", out.get("PROJECTID"));
}
@Test
void sanitize_throws_on_unsafe_value_for_referenced_param() {
Set<String> referenced = Set.of("PROJECTID");
Map<String, String> client = new LinkedHashMap<>();
client.put("PROJECTID", "' OR 1=1 --");
assertThrows(IllegalArgumentException.class,
() -> ReportParamGuard.sanitizeClientParams(client, referenced));
}
@Test
void sanitize_empty_inputs_yield_empty() {
assertTrue(ReportParamGuard.sanitizeClientParams(
new LinkedHashMap<>(), Set.of("A")).isEmpty());
assertTrue(ReportParamGuard.sanitizeClientParams(
Map.of("A", "1"), Set.of()).isEmpty());
}
// ---- applyTrustedIdentity:只为模板引用过的保留位注入可信值 ----
@Test
void applyTrustedIdentity_injects_only_referenced_reserved_names() {
Set<String> referenced = Set.of("PROJECTID", "CURRENTUSER", "CURRENTDEPART");
Map<String, String> safe = new LinkedHashMap<>();
safe.put("PROJECTID", "P-001");
Map<String, String> identity = new LinkedHashMap<>();
identity.put("CURRENTUSER", "u123");
identity.put("CURRENTDEPART", "d9");
identity.put("CURRENTORG", "o1"); // 模板未引用 → 不注入
Map<String, String> out = ReportParamGuard.applyTrustedIdentity(safe, referenced, identity);
assertEquals("P-001", out.get("PROJECTID"));
assertEquals("u123", out.get("CURRENTUSER")); // 可信值注入
assertEquals("d9", out.get("CURRENTDEPART"));
assertFalse(out.containsKey("CURRENTORG"), "模板未引用的保留位不注入");
}
@Test
void applyTrustedIdentity_overrides_forged_client_value() {
// 即便 safe 里混进了同名(防御纵深),可信值也应覆盖
Set<String> referenced = Set.of("CURRENTUSER");
Map<String, String> safe = new LinkedHashMap<>();
safe.put("CURRENTUSER", "forged");
Map<String, String> identity = Map.of("CURRENTUSER", "real-user");
Map<String, String> out = ReportParamGuard.applyTrustedIdentity(safe, referenced, identity);
assertEquals("real-user", out.get("CURRENTUSER"));
}
@Test
void applyTrustedIdentity_null_or_empty_identity_is_noop() {
Set<String> referenced = Set.of("CURRENTUSER");
Map<String, String> safe = Map.of("PROJECTID", "P-001");
assertEquals(safe, ReportParamGuard.applyTrustedIdentity(safe, referenced, null));
assertEquals(safe, ReportParamGuard.applyTrustedIdentity(safe, referenced, Map.of()));
}
}

View File

@@ -0,0 +1,70 @@
package com.eip4.platform.report;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
/**
* {@code ?tpl=<路径>} 文件直读的基目录限定(P0)。原实现 {@code Path.of(tplPath)} 直接用客户端串构造
* Path,无基目录/穿越/扩展名约束 → 任意本地文件读取 + XXE 投递面。本门把 tpl 限定在 templates-dir 内、
* 仅 .xml(profile 守卫由控制器负责,仅 dev/local/ci/parity 才允许 tpl)。
*/
class ReportTplGuardTest {
private static final String BASE = "/tmp/eip4-tpl-root";
@Test
void plain_filename_resolves_under_base() {
Path p = ReportTplGuard.resolveConfinedTplPath(BASE, "report.xml");
assertEquals(Path.of(BASE, "report.xml").toAbsolutePath().normalize(), p);
}
@Test
void nested_relative_path_under_base_is_allowed() {
Path p = ReportTplGuard.resolveConfinedTplPath(BASE, "sub/dir/r.xml");
assertTrue(p.startsWith(Path.of(BASE).toAbsolutePath().normalize()), p.toString());
assertTrue(p.toString().endsWith("r.xml"));
}
@Test
void benign_dotdot_that_stays_in_base_is_allowed() {
Path p = ReportTplGuard.resolveConfinedTplPath(BASE, "a/../b.xml");
assertEquals(Path.of(BASE, "b.xml").toAbsolutePath().normalize(), p);
}
@Test
void absolute_path_outside_base_is_rejected() {
assertThrows(SecurityException.class,
() -> ReportTplGuard.resolveConfinedTplPath(BASE, "/etc/passwd"));
}
@Test
void path_traversal_escaping_base_is_rejected() {
assertThrows(SecurityException.class,
() -> ReportTplGuard.resolveConfinedTplPath(BASE, "../../etc/hosts"));
}
@Test
void non_xml_extension_is_rejected() {
assertThrows(IllegalArgumentException.class,
() -> ReportTplGuard.resolveConfinedTplPath(BASE, "report.txt"));
}
@Test
void xml_extension_is_case_insensitive() {
Path p = ReportTplGuard.resolveConfinedTplPath(BASE, "Report.XML");
assertTrue(p.toString().endsWith("Report.XML"));
}
@Test
void blank_inputs_rejected() {
assertThrows(IllegalArgumentException.class,
() -> ReportTplGuard.resolveConfinedTplPath(BASE, " "));
assertThrows(IllegalArgumentException.class,
() -> ReportTplGuard.resolveConfinedTplPath(null, "r.xml"));
}
}

View File

@@ -0,0 +1,108 @@
package com.eip4.platform.report;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.Test;
/**
* XXE 防御(P0):报表 XML 经 jatools 未加固的 {@code DocumentBuilderFactory} 解析,默认处理 DOCTYPE
* 与外部实体 → XXE/SSRF/OOB/billion-laughs。引擎为预编译 jar 不便改,故在喂入引擎前先拒绝任何带
* DOCTYPE 的模板(JOR 文档本就无需 DOCTYPE)。本测覆盖 prolog 检测的纯逻辑。
*/
class ReportXmlGuardTest {
@Test
void normal_jor_document_has_no_doctype() {
assertFalse(ReportXmlGuard.hasDoctype(
"<?xml version='1.0' encoding='UTF-8'?><jatools class='jatools.ReportDocument'>x</jatools>"));
}
@Test
void doctype_in_prolog_is_detected() {
assertTrue(ReportXmlGuard.hasDoctype(
"<?xml version='1.0'?><!DOCTYPE r [<!ENTITY x SYSTEM 'file:///etc/passwd'>]><jatools/>"));
}
@Test
void doctype_is_case_insensitive() {
assertTrue(ReportXmlGuard.hasDoctype("<!doctype foo><root/>"));
}
@Test
void doctype_after_comment_is_detected() {
assertTrue(ReportXmlGuard.hasDoctype("<!-- header --><!DOCTYPE foo><root/>"));
}
@Test
void doctype_text_inside_comment_is_not_a_real_doctype() {
assertFalse(ReportXmlGuard.hasDoctype("<!-- <!DOCTYPE fake> --><jatools/>"));
}
@Test
void doctype_text_inside_element_content_after_root_is_ignored() {
assertFalse(ReportXmlGuard.hasDoctype("<jatools>literal <!DOCTYPE not-really > text</jatools>"));
}
@Test
void leading_whitespace_and_bom_before_doctype_still_detected() {
assertTrue(ReportXmlGuard.hasDoctype("\n <?xml version='1.0'?>\n<!DOCTYPE x><r/>"));
}
@Test
void null_or_empty_has_no_doctype() {
assertFalse(ReportXmlGuard.hasDoctype(null));
assertFalse(ReportXmlGuard.hasDoctype(""));
assertFalse(ReportXmlGuard.hasDoctype(" "));
}
// ---- hasDoctypeInBytes:防 BOM/UTF-16 编码绕过(引擎按 BOM 自动探测编码解析) ----
private static final String DOC = "<?xml version='1.0'?><!DOCTYPE r [<!ENTITY x SYSTEM 'file:///etc/passwd'>]><jatools/>";
private static final String CLEAN = "<?xml version='1.0' encoding='UTF-8'?><jatools class='jatools.ReportDocument'>x</jatools>";
private static byte[] concat(byte[] a, byte[] b) {
ByteArrayOutputStream o = new ByteArrayOutputStream();
o.writeBytes(a);
o.writeBytes(b);
return o.toByteArray();
}
@Test
void bytes_plain_utf8_detects_doctype_and_clean() {
assertTrue(ReportXmlGuard.hasDoctypeInBytes(DOC.getBytes(StandardCharsets.UTF_8)));
assertFalse(ReportXmlGuard.hasDoctypeInBytes(CLEAN.getBytes(StandardCharsets.UTF_8)));
}
@Test
void bytes_utf8_bom_does_not_hide_doctype() {
byte[] bom = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};
assertTrue(ReportXmlGuard.hasDoctypeInBytes(concat(bom, DOC.getBytes(StandardCharsets.UTF_8))));
assertFalse(ReportXmlGuard.hasDoctypeInBytes(concat(bom, CLEAN.getBytes(StandardCharsets.UTF_8))));
}
@Test
void bytes_utf16le_with_bom_detects_doctype() {
byte[] bom = {(byte) 0xFF, (byte) 0xFE};
assertTrue(ReportXmlGuard.hasDoctypeInBytes(concat(bom, DOC.getBytes(StandardCharsets.UTF_16LE))));
}
@Test
void bytes_utf16le_without_bom_detects_doctype() {
assertTrue(ReportXmlGuard.hasDoctypeInBytes(DOC.getBytes(StandardCharsets.UTF_16LE)));
}
@Test
void bytes_utf16be_without_bom_detects_doctype() {
assertTrue(ReportXmlGuard.hasDoctypeInBytes(DOC.getBytes(StandardCharsets.UTF_16BE)));
}
@Test
void bytes_null_or_empty_has_no_doctype() {
assertFalse(ReportXmlGuard.hasDoctypeInBytes(null));
assertFalse(ReportXmlGuard.hasDoctypeInBytes(new byte[0]));
}
}