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 @@ -39,6 +39,7 @@
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.content.service.BitstreamService;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.handle.service.HandleService;
import org.dspace.services.ConfigurationService;
Expand Down Expand Up @@ -116,10 +117,17 @@ public void downloadFileZip(@PathVariable UUID uuid, @RequestParam("handleId") S
}

Item item = (Item) dso;
List<Bundle> bundles = item.getBundles("ORIGINAL");
// Refuse before the headers go out: once the zip stream is open, an AuthorizeException
// can no longer become a 401/403 response.
for (Bundle original : bundles) {
for (Bitstream bitstream : original.getBitstreams()) {
authorizeService.authorizeAction(context, bitstream, Constants.READ);
}
}
name = item.getName() + ".zip";
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, buildContentDisposition(name));
response.setContentType("application/zip");
List<Bundle> bundles = item.getBundles("ORIGINAL");

ZipArchiveOutputStream zip = new ZipArchiveOutputStream(response.getOutputStream());
zip.setCreateUnicodeExtraFields(ZipArchiveOutputStream.UnicodeExtraFieldPolicy.ALWAYS);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,33 +8,56 @@
package org.dspace.app.rest;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletResponseWrapper;
import org.apache.commons.codec.CharEncoding;
import org.apache.commons.io.IOUtils;
import org.dspace.app.rest.model.ItemRest;
import org.dspace.app.rest.test.AbstractControllerIntegrationTest;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.builder.BitstreamBuilder;
import org.dspace.builder.ClarinLicenseBuilder;
import org.dspace.builder.CollectionBuilder;
import org.dspace.builder.CommunityBuilder;
import org.dspace.builder.EPersonBuilder;
import org.dspace.builder.ItemBuilder;
import org.dspace.content.Bitstream;
import org.dspace.content.Collection;
import org.dspace.content.Item;
import org.dspace.content.clarin.ClarinLicense;
import org.dspace.content.service.clarin.ClarinLicenseResourceMappingService;
import org.dspace.content.service.clarin.ClarinLicenseService;
import org.dspace.eperson.EPerson;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.support.ErrorPageFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;

public class MetadataBitstreamControllerIT extends AbstractControllerIntegrationTest {
private static final String METADATABITSTREAM_ENDPOINT = "/api/" + ItemRest.CATEGORY + "/" + ItemRest.PLURAL_NAME;
Expand All @@ -49,6 +72,14 @@ public class MetadataBitstreamControllerIT extends AbstractControllerIntegration

@Autowired
AuthorizeService authorizeService;
@Autowired
private ClarinLicenseService clarinLicenseService;
@Autowired
private ClarinLicenseResourceMappingService clarinLicenseResourceMappingService;
@Autowired
private WebApplicationContext webApplicationContext;
@Autowired
private List<Filter> requestFilters;


@Override
Expand Down Expand Up @@ -163,4 +194,117 @@ public void downloadAllZipWithNonAsciiItemName() throws Exception {
+ " filename*=UTF-8''P%C5%99%C3%ADli%C5%A1%20%C5%BElu%C5%A5ou%C4%8Dk%C3%BD"
+ "%20k%C5%AF%C5%88.zip"));
}

/**
* A file under a CLARIN licence that has to be agreed to is refused before the zip headers or stream are
* started: 401 for an anonymous caller, 403 for a logged-in user who has not agreed to the licence.
*/
@Test
public void downloadAllZipOfLicensedItemIsRefusedBeforeAnyByte() throws Exception {
context.turnOffAuthorisationSystem();
Item licensedItem = ItemBuilder.createItem(context, col)
.withTitle("Licensed item")
.withAuthor(AUTHOR)
.build();
// an open file first, so the check has to cover every file, not only the first one
try (InputStream is = IOUtils.toInputStream("OpenContent", CharEncoding.UTF_8)) {
BitstreamBuilder.createBitstream(context, licensedItem, is)
.withName("open.txt")
.withMimeType("text/plain")
.build();
}
Bitstream licensedBitstream;
try (InputStream is = IOUtils.toInputStream("LicensedContent", CharEncoding.UTF_8)) {
licensedBitstream = BitstreamBuilder.createBitstream(context, licensedItem, is)
.withName("licensed.txt")
.withMimeType("text/plain")
.build();
}
// Not the submitter: the submitter always passes the CLARIN licence gate.
EPerson reader = EPersonBuilder.createEPerson(context)
.withEmail("[email protected]")
.withPassword(password)
.withCanLogin(true)
.build();
ClarinLicense clarinLicense = ClarinLicenseBuilder.createClarinLicense(context).build();
clarinLicense.setName("Ask once licence");
clarinLicense.setDefinition("http://example.com/licence");
clarinLicense.setConfirmation(ClarinLicense.Confirmation.ASK_ONLY_ONCE);
clarinLicenseService.update(context, clarinLicense);
clarinLicenseResourceMappingService.attachLicense(context, clarinLicense, licensedBitstream);
context.restoreAuthSystemState();
context.commit();

String url = METADATABITSTREAM_ENDPOINT + "/" + licensedItem.getID() + "/" + ALL_ZIP_PATH;
ZipResponseRecorder anonymous = new ZipResponseRecorder();
clientRecording(anonymous).perform(get(url).param(HANDLE_PARAM, licensedItem.getHandle()))
.andExpect(status().isUnauthorized());
assertFalse("zip headers or stream started before the licence refusal", anonymous.zipStarted);

ZipResponseRecorder loggedIn = new ZipResponseRecorder();
String token = getAuthToken(reader.getEmail(), password);
clientRecording(loggedIn).perform(get(url).param(HANDLE_PARAM, licensedItem.getHandle())
.header(AUTHORIZATION_HEADER, AUTHORIZATION_TYPE + token))
.andExpect(status().isForbidden());
assertFalse("zip headers or stream started before the licence refusal", loggedIn.zipStarted);
}

/**
* The client of {@link #getClient()} plus a filter next to the controller. DispatcherServlet resets the
* body and drops Content-Disposition before the exception handler answers, so even the old controller
* ends as a bare 401 here and the response alone cannot show whether the zip had started.
*/
private MockMvc clientRecording(ZipResponseRecorder recorder) {
return webAppContextSetup(webApplicationContext)
.addFilters(new ErrorPageFilter())
.addFilters(requestFilters.toArray(new Filter[0]))
.addFilters(recorder)
.apply(springSecurity())
.build();
}

/**
* Remembers whether the response got a Content-Disposition, a content type or an output stream, as the zip
* download does first.
*/
private static final class ZipResponseRecorder implements Filter {
private boolean zipStarted;

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse) response) {
@Override
public void setHeader(String name, String value) {
recordContentDisposition(name, value);
super.setHeader(name, value);
}

@Override
public void addHeader(String name, String value) {
recordContentDisposition(name, value);
super.addHeader(name, value);
}

// A null value only clears the header, as DispatcherServlet does before it handles an error.
private void recordContentDisposition(String name, String value) {
if (HttpHeaders.CONTENT_DISPOSITION.equalsIgnoreCase(name) && value != null) {
zipStarted = true;
}
}

@Override
public void setContentType(String type) {
zipStarted = true;
super.setContentType(type);
}

@Override
public ServletOutputStream getOutputStream() throws IOException {
zipStarted = true;
return super.getOutputStream();
}
});
}
}
}
Loading