Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,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:
Expand Down
4 changes: 4 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,10 @@
<version>${fineract.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-core</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.birt</groupId>
<artifactId>org.eclipse.birt.core</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -43,6 +44,15 @@ public class BirtParameterMapper {
*/
public static final Set<String> 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<DateTimeFormatter> 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.
*
Expand Down Expand Up @@ -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) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
log.trace("Date '{}' does not match {}", value, format);
Comment thread
IOhacker marked this conversation as resolved.
Resolved
}
}
throw new PlatformDataIntegrityException(
"error.msg.reporting.invalid.date", "Invalid date format. Expected: 'dd MMMM yyyy' or 'yyyy-MM-dd'");
}

@FunctionalInterface
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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);
Comment thread
IOhacker marked this conversation as resolved.
Resolved
} 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.
*
* <p>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.
*
* <p>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.
*
* <p>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<String, String> getReportParams(String reportName, MultivaluedMap<String, String> queryParams) {
if (KycReportDataService.isKycReport(reportName)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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 {
Expand Down
Loading