Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -32,7 +33,8 @@ public ClarinFeaturedServiceRest findOne(Context context, Integer integer) {
@Override
@PreAuthorize("hasAuthority('ADMIN')")
public Page<ClarinFeaturedServiceRest> 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ public class ShareSubmissionLinkDTO {

private String shareLink;

private boolean emailSent;

public ShareSubmissionLinkDTO() { }

public String getShareLink() {
Expand All @@ -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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -61,6 +63,8 @@ public class EpicHandleRestController extends DSpaceRestRepository<EpicHandleRes
private EpicHandleService epicHandleService;
@Autowired
private Utils utils;
@Autowired
private ConfigurationService configurationService;

// v9: DSpaceRestRepository.findOne no longer carries a base-class @PreAuthorize; without one here
// the converter's security evaluation gets a null expression and every conversion 400s.
Expand All @@ -84,6 +88,7 @@ public Class<EpicHandleRest> getDomainClass() {
@RequestMapping(method = RequestMethod.POST, path = "{prefix}")
public ResponseEntity<EpicHandleResource> 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");
}
Expand All @@ -106,6 +111,7 @@ public ResponseEntity<EpicHandleResource> 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");
}
Expand Down Expand Up @@ -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");
}
Expand All @@ -154,6 +161,7 @@ public EpicHandleResource getHandle(@PathVariable String prefix, @PathVariable S
@PreAuthorize("hasAuthority('ADMIN')")
@RequestMapping(method = RequestMethod.GET, path = "{prefix}")
public Page<EpicHandleResource> search(@PathVariable String prefix, HttpServletRequest request) throws IOException {
checkPidServiceConfigured();
if (prefix == null || prefix.isEmpty()) {
throw new DSpaceBadRequestException("Epic handle prefix cannot be empty string");
}
Expand Down Expand Up @@ -215,6 +223,7 @@ public Page<EpicHandleResource> 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");
}
Expand All @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -119,17 +118,17 @@ public ResponseEntity<ShareSubmissionLinkDTO> 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);
Expand Down Expand Up @@ -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;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading
Loading