From 4c952925fa0240b26a41e3d8e19a6c46fca8f930 Mon Sep 17 00:00:00 2001 From: milanmajchrak Date: Thu, 26 Nov 2026 14:57:49 +0100 Subject: [PATCH 1/5] Return the share link when the e-mail cannot be sent The token is already saved, so a mail failure is logged and the link is still returned. The new emailSent flag tells the UI whether the mail went out. Co-Authored-By: Claude Opus 5.5 --- .../rest/model/ShareSubmissionLinkDTO.java | 10 +++++ .../rest/repository/SubmissionController.java | 38 +++++++++---------- .../app/rest/SubmissionControllerIT.java | 32 ++++++++++++++++ 3 files changed, 59 insertions(+), 21 deletions(-) diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/ShareSubmissionLinkDTO.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/ShareSubmissionLinkDTO.java index 26b9d5e0679f..09da3c723494 100644 --- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/ShareSubmissionLinkDTO.java +++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/ShareSubmissionLinkDTO.java @@ -17,6 +17,8 @@ public class ShareSubmissionLinkDTO { private String shareLink; + private boolean emailSent; + public ShareSubmissionLinkDTO() { } public String getShareLink() { @@ -26,4 +28,12 @@ public String getShareLink() { public void setShareLink(String shareLink) { this.shareLink = shareLink; } + + public boolean isEmailSent() { + return emailSent; + } + + public void setEmailSent(boolean emailSent) { + this.emailSent = emailSent; + } } diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/SubmissionController.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/SubmissionController.java index 9a4f485b89f6..13e3daf1384c 100644 --- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/SubmissionController.java +++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/SubmissionController.java @@ -15,7 +15,6 @@ import jakarta.mail.MessagingException; import jakarta.servlet.http.HttpServletRequest; -import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.Logger; import org.dspace.app.rest.converter.ConverterService; import org.dspace.app.rest.exception.DSpaceBadRequestException; @@ -119,17 +118,17 @@ public ResponseEntity generateShareLink(@RequestParam(na throw new DSpaceBadRequestException(errorMessage); } + // Compose the url with the share token. The user will be redirected to the UI. + String shareLink = configurationService.getProperty("dspace.ui.url") + + "/share-submission/change-submitter?share_token=" + wsi.getShareToken() + + "&workspaceitemid=" + wsi.getID(); // Send email to submitter with share link - String shareLink = sendShareLinkEmail(context, wsi, currentUser); - if (StringUtils.isEmpty(shareLink)) { - String errorMessage = "The share link is empty."; - log.error(errorMessage); - throw new RuntimeException(errorMessage); - } + boolean emailSent = sendShareLinkEmail(context, shareLink, currentUser); // Create a DTO with the share link for better processing in the FE ShareSubmissionLinkDTO shareSubmissionLinkDTO = new ShareSubmissionLinkDTO(); shareSubmissionLinkDTO.setShareLink(shareLink); + shareSubmissionLinkDTO.setEmailSent(emailSent); // Send share link in response return ResponseEntity.ok().body(shareSubmissionLinkDTO); @@ -225,26 +224,23 @@ private static String generateShareToken() { return UUID.randomUUID().toString().replace("-", "").substring(0, 32); } - private String sendShareLinkEmail(Context context, WorkspaceItem wsi, EPerson currentUser) { - // Get the UI URL from the configuration - String uiUrl = configurationService.getProperty("dspace.ui.url"); - // Get submitter email - String email = currentUser.getEmail(); - // Compose the url with the share token. The user will be redirected to the UI. - String shareTokenUrl = uiUrl + "/share-submission/change-submitter?share_token=" + wsi.getShareToken() + - "&workspaceitemid=" + wsi.getID(); + /** + * Send the share link to the current user. A failure is only logged: the link works without the email. + * + * @return true if the email was sent + */ + private boolean sendShareLinkEmail(Context context, String shareLink, EPerson currentUser) { try { Locale locale = context.getCurrentLocale(); Email bean = Email.getEmail(I18nUtil.getEmailFilename(locale, "share_submission")); - bean.addArgument(shareTokenUrl); - bean.addRecipient(email); + bean.addArgument(shareLink); + bean.addRecipient(currentUser.getEmail()); bean.send(); + return !configurationService.getBooleanProperty("mail.server.disabled", false); } catch (MessagingException | IOException e) { - String errorMessage = "Unable send the email because: " + e.getMessage(); - log.error(errorMessage); - throw new RuntimeException(errorMessage); + log.error("Unable to send the share link email: {}", e.getMessage(), e); + return false; } - return shareTokenUrl; } /** diff --git a/dspace-server-webapp/src/test/java/org/dspace/app/rest/SubmissionControllerIT.java b/dspace-server-webapp/src/test/java/org/dspace/app/rest/SubmissionControllerIT.java index 9eb919f2030d..a4129e310b5c 100644 --- a/dspace-server-webapp/src/test/java/org/dspace/app/rest/SubmissionControllerIT.java +++ b/dspace-server-webapp/src/test/java/org/dspace/app/rest/SubmissionControllerIT.java @@ -9,6 +9,7 @@ import static com.jayway.jsonpath.JsonPath.read; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.hasSize; @@ -52,6 +53,9 @@ import org.dspace.eperson.Group; import org.dspace.eperson.service.EPersonService; import org.dspace.eperson.service.GroupService; +import org.dspace.services.ConfigurationService; +import org.dspace.services.email.EmailServiceImpl; +import org.dspace.services.factory.DSpaceServicesFactory; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -72,6 +76,8 @@ public class SubmissionControllerIT extends AbstractControllerIntegrationTest { private GroupService groupService; @Autowired private AuthorizeService authorizeService; + @Autowired + private ConfigurationService configurationService; WorkspaceItem wsi; @@ -117,6 +123,8 @@ public void generateShareTokenAndSetOwnerTest() throws Exception { .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.shareLink", is(notNullValue()))) + // Mail is disabled in the test configuration, so nothing was sent. + .andExpect(jsonPath("$.emailSent", is(false))) .andDo(result -> shareLink.set(read(result.getResponse().getContentAsString(), "$.shareLink"))); // Check that the share token was set on the WorkspaceItem and persisted into the database @@ -141,6 +149,30 @@ public void generateShareTokenAndSetOwnerTest() throws Exception { assertThat(updatedWsi.getSubmitter().getEmail(), not(SUBMITTER_EMAIL)); } + @Test + public void generateShareLinkWhenEmailCannotBeSent() throws Exception { + // Nothing listens on port 1, so sending the email fails. + configurationService.setProperty("mail.server.disabled", false); + configurationService.setProperty("mail.server.port", "1"); + EmailServiceImpl emailService = (EmailServiceImpl) DSpaceServicesFactory.getInstance().getEmailService(); + emailService.reset(); + try { + String adminToken = getAuthToken(admin.getEmail(), password); + getClient(adminToken).perform(get("/api/submission/share") + .param("workspaceitemid", wsi.getID().toString())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.shareLink", containsString("share_token="))) + .andExpect(jsonPath("$.emailSent", is(false))); + + WorkspaceItem updatedWsi = workspaceItemService.find(context, wsi.getID()); + assertThat(updatedWsi.getShareToken(), is(notNullValue())); + } finally { + configurationService.setProperty("mail.server.disabled", true); + configurationService.setProperty("mail.server.port", null); + emailService.reset(); + } + } + @Test public void generateShareTokenAndSetOwnerTo3rdPersonTest() throws Exception { context.turnOffAuthorisationSystem(); From aa5aa1063da6a7be8af1b6c474f4653461114ef7 Mon Sep 17 00:00:00 2001 From: milanmajchrak Date: Thu, 26 Nov 2026 14:57:50 +0100 Subject: [PATCH 2/5] Say the ePIC service is not configured instead of 500 Without lr.pid.service.url, user or pass, the ePIC endpoints answer 404 with a message the admin page shows, and do not call ePIC. Co-Authored-By: Claude Opus 5.5 --- .../repository/EpicHandleRestController.java | 21 ++++++++++++ .../app/rest/EpicHandleRestControllerIT.java | 33 ++++++++++++++++++- 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/EpicHandleRestController.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/EpicHandleRestController.java index 321285d32293..f2c4c25f589a 100644 --- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/EpicHandleRestController.java +++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/repository/EpicHandleRestController.java @@ -21,6 +21,7 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.Response; +import org.apache.commons.lang3.StringUtils; import org.dspace.app.rest.converter.ConverterService; import org.dspace.app.rest.exception.DSpaceBadRequestException; import org.dspace.app.rest.exception.RepositoryMethodNotImplementedException; @@ -30,6 +31,7 @@ import org.dspace.app.rest.utils.Utils; import org.dspace.core.Context; import org.dspace.handle.service.EpicHandleService; +import org.dspace.services.ConfigurationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; @@ -61,6 +63,8 @@ public class EpicHandleRestController extends DSpaceRestRepository getDomainClass() { @RequestMapping(method = RequestMethod.POST, path = "{prefix}") public ResponseEntity createHandle(@PathVariable String prefix, HttpServletRequest request) throws IOException, URISyntaxException { + checkPidServiceConfigured(); if (prefix == null || prefix.isEmpty()) { throw new DSpaceBadRequestException("Epic handle prefix cannot be empty string"); } @@ -106,6 +111,7 @@ public ResponseEntity createHandle(@PathVariable String pref public ResponseEntity updateHandle(@PathVariable String prefix, @PathVariable String suffix, HttpServletRequest request) throws IOException, URISyntaxException { + checkPidServiceConfigured(); if (prefix == null || prefix.isEmpty()) { throw new DSpaceBadRequestException("Epic handle prefix cannot be empty string"); } @@ -133,6 +139,7 @@ public ResponseEntity updateHandle(@PathVariable String prefix, @PreAuthorize("hasAuthority('ADMIN')") @RequestMapping(method = RequestMethod.GET, path = "{prefix}/{suffix}") public EpicHandleResource getHandle(@PathVariable String prefix, @PathVariable String suffix) throws IOException { + checkPidServiceConfigured(); if (prefix == null || prefix.isEmpty()) { throw new DSpaceBadRequestException("Epic handle prefix cannot be empty string"); } @@ -154,6 +161,7 @@ public EpicHandleResource getHandle(@PathVariable String prefix, @PathVariable S @PreAuthorize("hasAuthority('ADMIN')") @RequestMapping(method = RequestMethod.GET, path = "{prefix}") public Page search(@PathVariable String prefix, HttpServletRequest request) throws IOException { + checkPidServiceConfigured(); if (prefix == null || prefix.isEmpty()) { throw new DSpaceBadRequestException("Epic handle prefix cannot be empty string"); } @@ -215,6 +223,7 @@ public Page search(@PathVariable String prefix, HttpServletR @RequestMapping(method = RequestMethod.DELETE, path = "{prefix}/{suffix}") public ResponseEntity deleteHandle(@PathVariable String prefix, @PathVariable String suffix) throws IOException { + checkPidServiceConfigured(); if (prefix == null || prefix.isEmpty()) { throw new DSpaceBadRequestException("Epic handle prefix cannot be empty string"); } @@ -229,6 +238,18 @@ public ResponseEntity deleteHandle(@PathVariable String prefix, @PathVariable } } + /** + * Without these properties every ePIC call fails, so answer with a message the admin page can show. + */ + private void checkPidServiceConfigured() { + if (StringUtils.isAnyBlank(configurationService.getProperty("lr.pid.service.url"), + configurationService.getProperty("lr.pid.service.user"), + configurationService.getProperty("lr.pid.service.pass"))) { + throw new ResourceNotFoundException("The ePIC PID service is not configured. Set " + + "lr.pid.service.url, lr.pid.service.user and lr.pid.service.pass in the DSpace configuration."); + } + } + private EpicHandleRest toRest(Handle handle, Projection projection) { return converter.toRest(handle, projection); } diff --git a/dspace-server-webapp/src/test/java/org/dspace/app/rest/EpicHandleRestControllerIT.java b/dspace-server-webapp/src/test/java/org/dspace/app/rest/EpicHandleRestControllerIT.java index 0701d5d7005e..5c327712b04e 100644 --- a/dspace-server-webapp/src/test/java/org/dspace/app/rest/EpicHandleRestControllerIT.java +++ b/dspace-server-webapp/src/test/java/org/dspace/app/rest/EpicHandleRestControllerIT.java @@ -14,6 +14,7 @@ import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; @@ -25,11 +26,14 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import java.net.Authenticator; + import jakarta.ws.rs.core.Response; import org.dspace.app.rest.test.AbstractControllerIntegrationTest; import org.dspace.handle.EpicHandleRestHelper; import org.dspace.services.ConfigurationService; import org.dspace.services.factory.DSpaceServicesFactory; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.MockedStatic; @@ -47,13 +51,23 @@ public class EpicHandleRestControllerIT extends AbstractControllerIntegrationTes private String adminToken; private String nonAdminToken; private String pidServiceUrl; + private ConfigurationService configurationService; @Before public void setup() throws Exception { adminToken = getAuthToken(admin.getEmail(), password); nonAdminToken = getAuthToken(eperson.getEmail(), password); - ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService(); + configurationService = DSpaceServicesFactory.getInstance().getConfigurationService(); pidServiceUrl = configurationService.getProperty("lr.pid.service.url"); + // The endpoints refuse to work without credentials; the ePIC calls themselves are mocked. + configurationService.setProperty("lr.pid.service.user", "test-user"); + configurationService.setProperty("lr.pid.service.pass", "test-pass"); + } + + @After + public void resetAuthenticator() { + // With credentials set, the service registers a JVM-wide Authenticator. + Authenticator.setDefault(null); } @Test @@ -180,6 +194,23 @@ public void testSearchHandles() throws Exception { } } + @Test + public void testSearchHandlesWithoutCredentials() throws Exception { + configurationService.setProperty("lr.pid.service.user", null); + configurationService.setProperty("lr.pid.service.pass", null); + try (MockedStatic mockedHelper = Mockito.mockStatic(EpicHandleRestHelper.class)) { + // Without credentials the ePIC service refuses every request. + mockedHelper.when(() -> EpicHandleRestHelper.countHandles(pidServiceUrl, PREFIX, "*")) + .thenReturn(Response.status(Response.Status.UNAUTHORIZED).build()); + mockedHelper.when(() -> EpicHandleRestHelper.searchHandles(pidServiceUrl, PREFIX, "*", 1, 10)) + .thenReturn(Response.status(Response.Status.UNAUTHORIZED).build()); + getClient(adminToken).perform(get(PREFIX_URL + "?page=0&size=10&runCountSynchronously=true")) + .andExpect(status().isNotFound()) + .andExpect(status().reason(containsString("lr.pid.service.user"))); + mockedHelper.verifyNoInteractions(); + } + } + @Test public void testCreateHandle() throws Exception { String requestJson = "[{\"type\":\"URL\",\"parsed_data\":\"" + TEST_URL + "\"}]"; From 9ac0d3f843f8476b847209677f59b62f48975098 Mon Sep 17 00:00:00 2001 From: milanmajchrak Date: Thu, 26 Nov 2026 14:57:50 +0100 Subject: [PATCH 3/5] Answer 405 instead of 500 on the featured services list findAll returned null. Featured services come from the configuration per item. Co-Authored-By: Claude Opus 5.5 --- .../app/rest/ClarinFeaturedServiceRestRepository.java | 4 +++- .../java/org/dspace/app/rest/ClarinRefBoxControllerIT.java | 7 +++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/ClarinFeaturedServiceRestRepository.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/ClarinFeaturedServiceRestRepository.java index cd43b0fdca9c..dd2cf12644dc 100644 --- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/ClarinFeaturedServiceRestRepository.java +++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/ClarinFeaturedServiceRestRepository.java @@ -7,6 +7,7 @@ */ package org.dspace.app.rest; +import org.dspace.app.rest.exception.RepositoryMethodNotImplementedException; import org.dspace.app.rest.model.ClarinFeaturedServiceRest; import org.dspace.app.rest.repository.DSpaceRestRepository; import org.dspace.core.Context; @@ -32,7 +33,8 @@ public ClarinFeaturedServiceRest findOne(Context context, Integer integer) { @Override @PreAuthorize("hasAuthority('ADMIN')") public Page findAll(Context context, Pageable pageable) { - return null; + // Featured services come from the configuration, per item, via /api/core/refbox/services. + throw new RepositoryMethodNotImplementedException(ClarinFeaturedServiceRest.NAME, "findAll"); } @Override diff --git a/dspace-server-webapp/src/test/java/org/dspace/app/rest/ClarinRefBoxControllerIT.java b/dspace-server-webapp/src/test/java/org/dspace/app/rest/ClarinRefBoxControllerIT.java index aa767b9895b0..1ed03394237a 100644 --- a/dspace-server-webapp/src/test/java/org/dspace/app/rest/ClarinRefBoxControllerIT.java +++ b/dspace-server-webapp/src/test/java/org/dspace/app/rest/ClarinRefBoxControllerIT.java @@ -146,6 +146,13 @@ public void returnFeaturedServiceWithLinks() throws Exception { .andExpect(status().isOk()); } + @Test + public void featuredServicesListIsNotImplemented() throws Exception { + String token = getAuthToken(admin.getEmail(), password); + getClient(token).perform(get("/api/core/featuredservices")) + .andExpect(status().isMethodNotAllowed()); + } + @Test public void testReturnAllRefboxInfoForItemWithFeaturedService() throws Exception { String token = getAuthToken(admin.getEmail(), password); From dd05841987594800c2065779135b2fb32a4e7fb5 Mon Sep 17 00:00:00 2001 From: milanmajchrak Date: Thu, 26 Nov 2026 14:57:51 +0100 Subject: [PATCH 4/5] Stream the by-handle download with the request context The anonymous download context failed the second READ check, so a user allowed to read a non-public file got 500. Co-Authored-By: Claude Opus 5.5 --- .../rest/BitstreamByHandleRestController.java | 26 ++++-------- .../BitstreamByHandleRestControllerIT.java | 41 +++++++++++++++++++ 2 files changed, 48 insertions(+), 19 deletions(-) diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/BitstreamByHandleRestController.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/BitstreamByHandleRestController.java index f704cb4123ab..5ad7af69e9bf 100644 --- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/BitstreamByHandleRestController.java +++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/BitstreamByHandleRestController.java @@ -223,26 +223,14 @@ public void downloadBitstreamByHandle(@PathVariable String prefix, return; } - // Stream the bitstream content. The context must remain open because - // bitstreamService.retrieve() needs an active DB connection / assetstore session. - Context downloadContext = null; - boolean downloadContextCompleted = false; - try { - downloadContext = new Context(); - try (InputStream is = bitstreamService.retrieve(downloadContext, bitstream)) { - byte[] buffer = new byte[BUFFER_SIZE]; - int bytesRead; - while ((bytesRead = is.read(buffer)) != -1) { - response.getOutputStream().write(buffer, 0, bytesRead); - } - response.getOutputStream().flush(); - } - downloadContext.complete(); - downloadContextCompleted = true; - } finally { - if (downloadContext != null && !downloadContextCompleted) { - downloadContext.abort(); + // Stream with the request context: retrieve() checks READ again, so it needs the current user. + try (InputStream is = bitstreamService.retrieve(context, bitstream)) { + byte[] buffer = new byte[BUFFER_SIZE]; + int bytesRead; + while ((bytesRead = is.read(buffer)) != -1) { + response.getOutputStream().write(buffer, 0, bytesRead); } + response.getOutputStream().flush(); } // Close DB connection after streaming is complete context.complete(); diff --git a/dspace-server-webapp/src/test/java/org/dspace/app/rest/BitstreamByHandleRestControllerIT.java b/dspace-server-webapp/src/test/java/org/dspace/app/rest/BitstreamByHandleRestControllerIT.java index 04cd43b10007..e41b9e06caeb 100644 --- a/dspace-server-webapp/src/test/java/org/dspace/app/rest/BitstreamByHandleRestControllerIT.java +++ b/dspace-server-webapp/src/test/java/org/dspace/app/rest/BitstreamByHandleRestControllerIT.java @@ -377,6 +377,47 @@ public void downloadBitstreamByHandleForbidden() throws Exception { .andExpect(status().isForbidden()); } + @Test + public void downloadNonPublicBitstreamByHandleAsAuthorizedUser() throws Exception { + context.turnOffAuthorisationSystem(); + parentCommunity = CommunityBuilder.createCommunity(context) + .withName("Parent Community") + .build(); + Collection col = CollectionBuilder.createCollection(context, parentCommunity) + .withName("Collection") + .build(); + Item item = ItemBuilder.createItem(context, col) + .withAuthor("Test Author") + .build(); + + String bitstreamContent = "NonPublicContent"; + Bitstream bitstream; + try (InputStream is = IOUtils.toInputStream(bitstreamContent, CharEncoding.UTF_8)) { + bitstream = BitstreamBuilder.createBitstream(context, item, is) + .withName("non-public.txt") + .withMimeType("text/plain") + .build(); + } + + // Only the logged-in user may read the file, anonymous users may not + authorizeService.removeAllPolicies(context, bitstream); + ResourcePolicyBuilder.createResourcePolicy(context, eperson, null) + .withDspaceObject(bitstream) + .withAction(Constants.READ) + .build(); + + context.restoreAuthSystemState(); + + String handle = item.getHandle(); + String[] handleParts = handle.split("/"); + + String token = getAuthToken(eperson.getEmail(), password); + getClient(token).perform( + get(ENDPOINT_BASE + "/" + handleParts[0] + "/" + handleParts[1] + "/non-public.txt")) + .andExpect(status().isOk()) + .andExpect(content().string(bitstreamContent)); + } + @Test public void downloadBitstreamFromNonOriginalBundle() throws Exception { context.turnOffAuthorisationSystem(); From 4210e7e71eaabca84269fe5a2f2e27ef0f13d21a Mon Sep 17 00:00:00 2001 From: milanmajchrak Date: Thu, 26 Nov 2026 14:57:52 +0100 Subject: [PATCH 5/5] Put unsafe CMDI download file names in the query A proxy that rewrites the path decodes it, and Tomcat refuses a bare quote and similar characters. Only such names use ?filename=; all other links stay the same. Co-Authored-By: Claude Opus 5.5 --- .../dspace/app/oai/CmdiDownloadLinkIT.java | 48 +++++++++++++++++++ .../oai/metadataFormats/lindat_cmdi.xsl | 12 ++++- 2 files changed, 59 insertions(+), 1 deletion(-) diff --git a/dspace-server-webapp/src/test/java/org/dspace/app/oai/CmdiDownloadLinkIT.java b/dspace-server-webapp/src/test/java/org/dspace/app/oai/CmdiDownloadLinkIT.java index d67258e88d76..f014c52c7cf2 100644 --- a/dspace-server-webapp/src/test/java/org/dspace/app/oai/CmdiDownloadLinkIT.java +++ b/dspace-server-webapp/src/test/java/org/dspace/app/oai/CmdiDownloadLinkIT.java @@ -7,6 +7,8 @@ */ package org.dspace.app.oai; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -204,6 +206,52 @@ public void cmdiResourceRefIsMachineActionableDownloadLink() throws Exception { .andExpect(content().string(BITSTREAM_CONTENT)); } + @Test + public void cmdiResourceRefPutsUnsafeFilenameInQueryParameter() throws Exception { + context.turnOffAuthorisationSystem(); + parentCommunity = CommunityBuilder.createCommunity(context) + .withName("Parent Community") + .build(); + Collection collection = CollectionBuilder.createCollection(context, parentCommunity) + .withName("Collection") + .build(); + Item item = ItemBuilder.createItem(context, collection) + .withTitle("CMDI Quote In Filename Test Item") + .withIssueDate("2023-01-01") + .build(); + for (String name : List.of("plain file.txt", "file \"quoted\".txt")) { + try (InputStream is = IOUtils.toInputStream(BITSTREAM_CONTENT, StandardCharsets.UTF_8)) { + BitstreamBuilder.createBitstream(context, item, is) + .withName(name) + .withMimeType("text/plain") + .build(); + } + } + context.restoreAuthSystemState(); + solrOAIReindexer.reindexItem(item); + + String response = getClient().perform(get("/oai/request") + .param("verb", "GetRecord") + .param("metadataPrefix", "cmdi") + .param("identifier", DSpaceItem.buildIdentifier(item.getHandle()))) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + + // A proxy that rewrites the path decodes %22 to a bare quote, which Tomcat answers with 400. + // Names without such characters keep the path form. + String serverUrl = configurationService.getProperty("dspace.server.url"); + String base = serverUrl + "/api/core/bitstreams/handle/" + item.getHandle(); + String plainRef = base + "/plain%20file.txt"; + String quotedRef = base + "?filename=file%20%22quoted%22.txt"; + assertThat(extractResourceProxyRefs(response), containsInAnyOrder(plainRef, quotedRef)); + + for (String ref : List.of(plainRef, quotedRef)) { + getClient().perform(get(URI.create(ref.substring(serverUrl.length())))) + .andExpect(status().isOk()) + .andExpect(content().string(BITSTREAM_CONTENT)); + } + } + /** * Parses the OAI-PMH GetRecord response and returns the text content of every {@code cmd:ResourceRef} * element whose parent {@code cmd:ResourceProxy} is a bitstream proxy: {@code cmd:ResourceType} of diff --git a/dspace/config/crosswalks/oai/metadataFormats/lindat_cmdi.xsl b/dspace/config/crosswalks/oai/metadataFormats/lindat_cmdi.xsl index f756afb9734f..c238c5ceb946 100644 --- a/dspace/config/crosswalks/oai/metadataFormats/lindat_cmdi.xsl +++ b/dspace/config/crosswalks/oai/metadataFormats/lindat_cmdi.xsl @@ -110,11 +110,21 @@ + + "%/;<>[\]^`{|} + + + + ?filename= + / + + _ Resource - +