From 2772cf7b7cb6f77f97242b21e6504dea91da3210 Mon Sep 17 00:00:00 2001 From: Pranav-IIITM Date: Wed, 11 Nov 2026 15:25:35 +0530 Subject: [PATCH] Fix Report Mailing Jobs for BIRT reports Report Mailing Jobs never emailed a BIRT report. The job only accepts a rendered ByteArrayOutputStream, but the plugin returned a stream that nothing runs outside an HTTP request, which also left the temporary document and its open resources behind on every attempt. Render the report immediately when running in a batch step, and accept the yyyy-MM-dd dates the job sends. API requests keep streaming. Reports for mailing jobs are held in memory, so limit them with mifos.birt.buffered-report-max-size-bytes (default 25 MiB). The HTML, PDF and CSV emitters ignore write errors, so the limit is checked once rendering ends and a report over it fails rather than being cut short. Parse yyyy-MM-dd strictly so a date such as 2026-02-30 is rejected instead of being moved to the end of the month. Closes #561 Signed-off-by: Pranav-IIITM --- README.md | 6 ++ pom.xml | 4 + .../report/config/BirtPluginProperties.java | 6 ++ .../report/service/BirtParameterMapper.java | 26 ++++-- .../BirtReportingProcessServiceImpl.java | 72 ++++++++++++++- .../config/BirtPluginPropertiesTest.java | 11 +++ .../service/BirtParameterMapperTest.java | 49 +++++++++++ .../BirtReportingProcessServiceImplTest.java | 88 +++++++++++++++++++ 8 files changed, 254 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index fd94ba78..235d2203 100644 --- a/README.md +++ b/README.md @@ -129,6 +129,12 @@ export MIFOS_BIRT_REPORTS_FONTS_PATH=/app/birt/fonts export MIFOS_BIRT_REPORTS_FONTS_CONFIG_PATH=/app/birt/config ``` +Reports sent by Report Mailing Jobs are held in memory before they are attached, so their size is capped. A larger report fails that run with `error.msg.reporting.output.too.large`, shown in the job's run history, and no email is sent. + +| Property | Default | Purpose | +| --- | --- | --- | +| `mifos.birt.buffered-report-max-size-bytes` | `26214400` (25 MiB) | Largest report a Report Mailing Job may send | + ### 6. Security & User Permissions To execute a report, the authenticated user's role must hold one of the following permissions: diff --git a/pom.xml b/pom.xml index 27ed187d..adf6d3b0 100644 --- a/pom.xml +++ b/pom.xml @@ -123,6 +123,10 @@ ${fineract.version} compile + + org.springframework.batch + spring-batch-core + org.eclipse.birt org.eclipse.birt.core diff --git a/src/main/java/org/apache/fineract/infrastructure/report/config/BirtPluginProperties.java b/src/main/java/org/apache/fineract/infrastructure/report/config/BirtPluginProperties.java index 2bdc62e4..8c86ac7d 100644 --- a/src/main/java/org/apache/fineract/infrastructure/report/config/BirtPluginProperties.java +++ b/src/main/java/org/apache/fineract/infrastructure/report/config/BirtPluginProperties.java @@ -37,6 +37,8 @@ public class BirtPluginProperties { private int readOnlyPoolMaxSize = 5; // How long a report waits for one of them before failing private long readOnlyConnectionTimeoutMillis = 10_000L; + // Largest report held in memory for a report mailing job, in line with common attachment limits + private long bufferedReportMaxSizeBytes = 25L * 1024 * 1024; /** * Both values are handed to HikariCP, which refuses a maximum pool size below 1 and any of its @@ -57,5 +59,9 @@ void validate() { throw new IllegalStateException("mifos.birt.read-only-connection-timeout-millis must be at least " + MINIMUM_TIMEOUT_MILLIS + "ms, but is " + readOnlyConnectionTimeoutMillis); } + if (bufferedReportMaxSizeBytes < 1) { + throw new IllegalStateException("mifos.birt.buffered-report-max-size-bytes must be at least 1, but is " + + bufferedReportMaxSizeBytes); + } } } diff --git a/src/main/java/org/apache/fineract/infrastructure/report/service/BirtParameterMapper.java b/src/main/java/org/apache/fineract/infrastructure/report/service/BirtParameterMapper.java index ce31311b..4ab8fa9a 100644 --- a/src/main/java/org/apache/fineract/infrastructure/report/service/BirtParameterMapper.java +++ b/src/main/java/org/apache/fineract/infrastructure/report/service/BirtParameterMapper.java @@ -9,6 +9,7 @@ import java.sql.Date; import java.time.LocalDate; import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.List; import java.util.Locale; @@ -43,6 +44,15 @@ public class BirtParameterMapper { */ public static final Set SERVER_MANAGED_PARAMETERS = Set.of("userhierarchy", "userid"); + /** + * Date formats a report parameter may arrive in: the one API callers send, and the {@code + * yyyy-MM-dd} Apache Fineract® report mailing jobs use when they resolve {@code today}, {@code + * yesterday} and {@code tomorrow}. The ISO formatter is strict, so an impossible date such as + * {@code 2026-02-30} is refused rather than moved to the end of the month. + */ + private static final List DATE_FORMATS = + List.of(DateTimeFormatter.ofPattern("dd MMMM yyyy", Locale.ENGLISH), DateTimeFormatter.ISO_LOCAL_DATE); + /** * Validates and applies report parameters to the BIRT run task. * @@ -128,15 +138,17 @@ private void setTypedParameter(IRunTask task, IParameterDefn paramDef, String na } } + /** Parses a date parameter using the first of {@link #DATE_FORMATS} that accepts it. */ private Date parseDate(String value) { - try { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMMM yyyy", Locale.ENGLISH); - LocalDate localDate = LocalDate.parse(value, formatter); - return Date.valueOf(localDate); - } catch (Exception e) { - throw new PlatformDataIntegrityException( - "error.msg.reporting.invalid.date", "Invalid date format. Expected: 'dd MMMM yyyy'", e); + for (DateTimeFormatter format : DATE_FORMATS) { + try { + return Date.valueOf(LocalDate.parse(value, format)); + } catch (DateTimeParseException e) { + log.trace("Date '{}' does not match {}", value, format); + } } + throw new PlatformDataIntegrityException( + "error.msg.reporting.invalid.date", "Invalid date format. Expected: 'dd MMMM yyyy' or 'yyyy-MM-dd'"); } @FunctionalInterface diff --git a/src/main/java/org/apache/fineract/infrastructure/report/service/BirtReportingProcessServiceImpl.java b/src/main/java/org/apache/fineract/infrastructure/report/service/BirtReportingProcessServiceImpl.java index d6f79807..f26aa4ef 100644 --- a/src/main/java/org/apache/fineract/infrastructure/report/service/BirtReportingProcessServiceImpl.java +++ b/src/main/java/org/apache/fineract/infrastructure/report/service/BirtReportingProcessServiceImpl.java @@ -8,6 +8,10 @@ import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.StreamingOutput; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.sql.Connection; @@ -33,6 +37,7 @@ import org.eclipse.birt.report.engine.api.IReportRunnable; import org.eclipse.birt.report.engine.api.IRunTask; import org.eclipse.birt.report.model.api.ReportDesignHandle; +import org.springframework.batch.core.scope.context.StepSynchronizationManager; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; @@ -327,16 +332,81 @@ private void setConnectionDetail(IRunTask runTask, Connection birtConnection) th runTask.getAppContext().put("OdaJDBCDriverPassInConnectionCloseAfterUse", false); } + /** Streams the report to an HTTP caller, or renders it immediately inside a batch step. */ private Response renderReport(String reportName, String outputType, String documentPath) { try { final BirtRenderer renderer = getRenderer(outputType); - return renderer.render(reportEngine, documentPath, reportName); + final Response response = renderer.render(reportEngine, documentPath, reportName); + return StepSynchronizationManager.getContext() == null ? response : buffered(response); + } catch (PlatformDataIntegrityException e) { + throw e; } catch (Exception e) { throw new PlatformDataIntegrityException( "error.msg.reporting.error", "Failed to initialize report stream.", e); } } + /** + * Renders the report now instead of leaving it for the HTTP layer to stream. + * + *

A report mailing job runs in a Spring Batch step, where nothing writes the response, so a + * stream would never run and never release what it holds. Apache Fineract® only attaches the + * report when the entity is exactly a {@link ByteArrayOutputStream}. The renderer's stream still + * does the work, so it also still closes the document and deletes the temporary file. + * + *

The whole report has to fit in memory, so its size is capped by {@code + * mifos.birt.buffered-report-max-size-bytes}. A report over the cap fails, and is never handed + * over cut short. + */ + private Response buffered(Response response) throws IOException { + final long maxSizeBytes = birtProperties.getBufferedReportMaxSizeBytes(); + final BoundedBuffer buffer = new BoundedBuffer(maxSizeBytes); + ((StreamingOutput) response.getEntity()).write(buffer); + if (buffer.exceeded) { + throw new PlatformDataIntegrityException( + "error.msg.reporting.output.too.large", + "The rendered report exceeds the limit of " + maxSizeBytes + " bytes."); + } + return Response.fromResponse(response).entity(buffer.content).build(); + } + + /** + * Keeps a report up to a size limit and records when more arrives. + * + *

It discards the excess instead of throwing, because the HTML, PDF and CSV emitters swallow + * an {@link IOException} from their output and finish normally. A throw here would leave a + * truncated report that looks complete, so {@link #buffered} checks the flag once rendering ends. + */ + private static final class BoundedBuffer extends OutputStream { + + private final ByteArrayOutputStream content = new ByteArrayOutputStream(); + private final long maxSizeBytes; + private boolean exceeded; + + private BoundedBuffer(long maxSizeBytes) { + this.maxSizeBytes = maxSizeBytes; + } + + @Override + public void write(int b) { + if (fits(1)) { + content.write(b); + } + } + + @Override + public void write(byte[] bytes, int offset, int length) { + if (fits(length)) { + content.write(bytes, offset, length); + } + } + + private boolean fits(int length) { + exceeded = exceeded || content.size() + (long) length > maxSizeBytes; + return !exceeded; + } + } + @Override public Map getReportParams(String reportName, MultivaluedMap queryParams) { if (KycReportDataService.isKycReport(reportName)) { diff --git a/src/test/java/org/apache/fineract/infrastructure/report/config/BirtPluginPropertiesTest.java b/src/test/java/org/apache/fineract/infrastructure/report/config/BirtPluginPropertiesTest.java index 98bc8ba6..c264b509 100644 --- a/src/test/java/org/apache/fineract/infrastructure/report/config/BirtPluginPropertiesTest.java +++ b/src/test/java/org/apache/fineract/infrastructure/report/config/BirtPluginPropertiesTest.java @@ -37,6 +37,17 @@ void shouldRefuseAPoolSizeBelowOne() { assertTrue(ex.getMessage().contains("mifos.birt.read-only-pool-max-size"), ex.getMessage()); } + @Test + @DisplayName("Should refuse a buffered report limit that no report can fit in") + void shouldRefuseABufferedReportLimitBelowOne() { + final BirtPluginProperties properties = new BirtPluginProperties(); + properties.setBufferedReportMaxSizeBytes(0L); + + final IllegalStateException ex = assertThrows(IllegalStateException.class, properties::validate); + + assertTrue(ex.getMessage().contains("mifos.birt.buffered-report-max-size-bytes"), ex.getMessage()); + } + /** Hikari reads 0 as "wait forever" for a connection timeout, but refuses it as a validation one. */ @Test @DisplayName("Should refuse a timeout below Hikari's floor, zero included") diff --git a/src/test/java/org/apache/fineract/infrastructure/report/service/BirtParameterMapperTest.java b/src/test/java/org/apache/fineract/infrastructure/report/service/BirtParameterMapperTest.java index fba59f1e..dbe7ba61 100644 --- a/src/test/java/org/apache/fineract/infrastructure/report/service/BirtParameterMapperTest.java +++ b/src/test/java/org/apache/fineract/infrastructure/report/service/BirtParameterMapperTest.java @@ -131,6 +131,55 @@ void shouldAllowMissingOptionalParameters() throws Exception { verify(paramTask).close(); } + @Test + @DisplayName("Should accept the yyyy-MM-dd dates report mailing jobs send") + void shouldAcceptReportMailingJobDateFormat() throws Exception { + stubDateParameter("startDate"); + + mapper.applyParameters(runTask, Map.of("startDate", "2026-11-04")); + + verify(runTask).setParameterValue("startDate", java.sql.Date.valueOf("2026-11-04")); + } + + @Test + @DisplayName("Should reject a date in neither supported format") + void shouldRejectUnsupportedDateFormat() throws Exception { + stubDateParameter("startDate"); + when(reportErrorHandler.reportError(eq("error.msg.reporting.invalid.parameter"), anyString(), any())) + .thenAnswer(inv -> new PlatformDataIntegrityException(inv.getArgument(0), inv.getArgument(1))); + + assertThrows( + PlatformDataIntegrityException.class, + () -> mapper.applyParameters(runTask, Map.of("startDate", "04/11/2026"))); + + verify(runTask, never()).setParameterValue(eq("startDate"), any()); + } + + @Test + @DisplayName("Should reject an impossible yyyy-MM-dd date instead of adjusting it") + void shouldRejectImpossibleIsoDate() throws Exception { + stubDateParameter("startDate"); + when(reportErrorHandler.reportError(eq("error.msg.reporting.invalid.parameter"), anyString(), any())) + .thenAnswer(inv -> new PlatformDataIntegrityException(inv.getArgument(0), inv.getArgument(1))); + + assertThrows( + PlatformDataIntegrityException.class, + () -> mapper.applyParameters(runTask, Map.of("startDate", "2026-02-30"))); + + verify(runTask, never()).setParameterValue(eq("startDate"), any()); + } + + private void stubDateParameter(String name) throws Exception { + when(runTask.getReportRunnable()).thenReturn(reportRunnable); + when(reportEngine.createGetParameterDefinitionTask(reportRunnable)).thenReturn(paramTask); + + IParameterDefn dateParam = mock(IParameterDefn.class); + when(dateParam.getName()).thenReturn(name); + when(dateParam.getDataType()).thenReturn(IParameterDefn.TYPE_DATE); + + when(paramTask.getParameterDefns(anyBoolean())).thenReturn(List.of(dateParam)); + } + @Test @DisplayName("Should throw when a single required parameter is missing") void shouldThrowExceptionWhenSingleRequiredParameterMissing() throws Exception { diff --git a/src/test/java/org/apache/fineract/infrastructure/report/service/BirtReportingProcessServiceImplTest.java b/src/test/java/org/apache/fineract/infrastructure/report/service/BirtReportingProcessServiceImplTest.java index e56b0f0a..c5bf6786 100644 --- a/src/test/java/org/apache/fineract/infrastructure/report/service/BirtReportingProcessServiceImplTest.java +++ b/src/test/java/org/apache/fineract/infrastructure/report/service/BirtReportingProcessServiceImplTest.java @@ -28,6 +28,10 @@ import jakarta.ws.rs.core.MultivaluedHashMap; import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.StreamingOutput; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.Statement; @@ -55,6 +59,8 @@ import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.batch.core.scope.context.StepSynchronizationManager; +import org.springframework.batch.core.step.StepExecution; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.support.SimpleTransactionStatus; @@ -502,6 +508,88 @@ void shouldInjectServerContextAfterClientParameters() throws Exception { inOrder.verify(task).run(anyString()); } + @Test + @DisplayName("Should hand a report mailing job the rendered report as a ByteArrayOutputStream") + void shouldBufferReportInsideBatchStep() throws Exception { + StreamingOutput stream = output -> output.write("report".getBytes(StandardCharsets.UTF_8)); + stubReportRun(stream); + when(birtProperties.getBufferedReportMaxSizeBytes()).thenReturn(6L); + + StepSynchronizationManager.register(mock(StepExecution.class)); + try { + Response response = service.processRequest("sample", queryParams("PDF")); + + assertEquals(ByteArrayOutputStream.class, response.getEntity().getClass()); + assertEquals("report", response.getEntity().toString()); + assertEquals("application/pdf", response.getMediaType().toString()); + } finally { + StepSynchronizationManager.release(); + } + } + + @Test + @DisplayName("Should keep streaming the report outside a batch step") + void shouldStreamReportOutsideBatchStep() throws Exception { + StreamingOutput stream = mock(StreamingOutput.class); + stubReportRun(stream); + + Response response = service.processRequest("sample", queryParams("PDF")); + + assertSame(stream, response.getEntity()); + verify(stream, never()).write(any()); + } + + @Test + @DisplayName("Should fail the report mailing job when rendering the report fails") + void shouldFailWhenBufferingFailsInsideBatchStep() throws Exception { + StreamingOutput stream = output -> { + throw new IOException("render failed"); + }; + stubReportRun(stream); + when(birtProperties.getBufferedReportMaxSizeBytes()).thenReturn(1024L); + + StepSynchronizationManager.register(mock(StepExecution.class)); + try { + assertThrows( + PlatformDataIntegrityException.class, () -> service.processRequest("sample", queryParams("PDF"))); + } finally { + StepSynchronizationManager.release(); + } + } + + @Test + @DisplayName("Should fail instead of handing over a report cut short at the size limit") + void shouldFailWhenReportExceedsBufferLimit() throws Exception { + StreamingOutput stream = output -> { + output.write("report".getBytes(StandardCharsets.UTF_8)); + output.write('!'); + }; + stubReportRun(stream); + when(birtProperties.getBufferedReportMaxSizeBytes()).thenReturn(6L); + + StepSynchronizationManager.register(mock(StepExecution.class)); + try { + PlatformDataIntegrityException ex = assertThrows( + PlatformDataIntegrityException.class, () -> service.processRequest("sample", queryParams("PDF"))); + + assertEquals("error.msg.reporting.output.too.large", ex.getGlobalisationMessageCode()); + } finally { + StepSynchronizationManager.release(); + } + } + + private void stubReportRun(StreamingOutput stream) throws Exception { + IReportRunnable design = mock(IReportRunnable.class); + IRunTask task = mock(IRunTask.class); + + when(task.getAppContext()).thenReturn(new HashMap<>()); + when(reportExecutionFactory.createExecutionRunnable(anyString(), any())).thenReturn(design); + when(design.getDesignHandle()).thenReturn(mock(ReportDesignHandle.class)); + when(reportEngine.createRunTask(design)).thenReturn(task); + when(pdfRenderer.render(eq(reportEngine), anyString(), anyString())) + .thenReturn(Response.ok(stream).type("application/pdf").build()); + } + @ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(strings = {"KYCNaturalPerson", "KYCLegalPerson"}) void kycUsesExistingBirtPipelineWithPrivateExecutionDataAndSecureHeaders(String report) throws Exception {