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
8 changes: 4 additions & 4 deletions doc/sphinx-guides/source/api/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,6 @@ This API changelog is experimental and we would love feedback on its usefulness.
v6.13
-----

- The ``POST /api/admin/datasetfield/loadpropertyfiles`` endpoint, which returned ``400 Bad Request`` for invalid or unsafe paths in ZIP entries, will now also return 400 if there are any file or directory entries other than ``*.properties`` files.

- The redundant /api/access/fileCardImage/{id} has been deleted - use /api/access/datafile/{fileId}?imageThumb=true instead

- The introduction of the new ActAsSuperuser permission, and the change to allow endpoints that were previously restricted to superuser only to also allow users who have the ActAsSuperuser permission on the relevant collection, dataset, or data file, results in changes to error codes and messages on the affected endpoints.

- The /api/dataverses/{identifier}/userPermissions, /api/datasets/{id}/userpermissions, and /api/access/datafile/{id}/userPermissions endpoints now include a "canActAsSuperuser": boolean key:value indicating whether the user has this permission on the relevant object.
Expand Down Expand Up @@ -90,6 +86,10 @@ v6.13

- The /api/datasets/export?exporter=oai_datacite&persistentId={id} endpoint uses "IsSupplementTo" when user doesn't choose a relationType

- The ``POST /api/admin/datasetfield/loadpropertyfiles`` endpoint, which returned ``400 Bad Request`` for invalid or unsafe paths in ZIP entries, will now also return 400 if there are any file or directory entries other than ``*.properties`` files.

- The redundant /api/access/fileCardImage/{id} has been deleted - use /api/access/datafile/{fileId}?imageThumb=true instead

v6.12
-----

Expand Down
151 changes: 132 additions & 19 deletions src/main/java/edu/harvard/iq/dataverse/EditDatafilesPage.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,20 @@

import static edu.harvard.iq.dataverse.util.JsfHelper.JH;
import java.io.File;
import java.io.FilterInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;

import edu.harvard.iq.dataverse.util.json.JsonUtil;
Expand Down Expand Up @@ -82,10 +87,15 @@
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.mutable.MutableBoolean;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.ConnectionConfig;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.util.Timeout;
import org.primefaces.PrimeFaces;

/**
Expand Down Expand Up @@ -1403,34 +1413,128 @@ public boolean showFileUploadComponent() {
* @param fileLink
* @return
*/
private InputStream getDropBoxInputStream(String fileLink) {
if (fileLink == null) {
static URI validateDropBoxUri(String fileLink) {
if (fileLink == null || fileLink.isBlank()) {
throw new IllegalArgumentException("Dropbox link must not be empty");
}

final URI uri;
try {
uri = new URI(fileLink.trim());
} catch (URISyntaxException ex) {
throw new IllegalArgumentException("Invalid Dropbox URI", ex);
}

if (!"https".equalsIgnoreCase(uri.getScheme())) {
throw new IllegalArgumentException("Dropbox link must use HTTPS");
}
if (uri.getRawUserInfo() != null) {
throw new IllegalArgumentException("Dropbox link must not contain userinfo");
}
if (uri.getPort() != -1 && uri.getPort() != 443) {
throw new IllegalArgumentException("Dropbox link must use port 443");
}

String host = uri.getHost();
if (host == null || host.isEmpty()) {
throw new IllegalArgumentException("Dropbox link must specify a valid host");
}
String normalizedHost = host.toLowerCase(Locale.ROOT);
boolean allowedHost = isHostOrSubdomainOf(normalizedHost, "dropbox.com")
|| isHostOrSubdomainOf(normalizedHost, "dropboxusercontent.com");
if (!allowedHost) {
throw new IllegalArgumentException("Host is not an allowed Dropbox download domain");
}
return uri;
}

private static boolean isHostOrSubdomainOf(String host, String domain) {
String subdomainSuffix = "." + domain;
return domain.equals(host) || (host.endsWith(subdomainSuffix)
&& host.length() > subdomainSuffix.length() && !host.contains(".."));
}

InputStream getDropBoxInputStream(String fileLink) {
final URI validatedUri;
try {
validatedUri = validateDropBoxUri(fileLink);
} catch (IllegalArgumentException ex) {
logger.log(Level.WARNING, "Rejected invalid Dropbox URL: {0}", ex.getMessage());
return null;
}

ConnectionConfig connectionConfig = ConnectionConfig.custom()
.setConnectTimeout(Timeout.ofSeconds(30))
.build();
PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create()
.setDefaultConnectionConfig(connectionConfig)
.build();
RequestConfig requestConfig = RequestConfig.custom()
.setRedirectsEnabled(false)
.setConnectionRequestTimeout(Timeout.ofSeconds(30))
.setResponseTimeout(Timeout.ofSeconds(60))
.build();

CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig)
.disableRedirectHandling()
.build();
ClassicHttpResponse response = null;
boolean streamReturned = false;
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(fileLink);

// Use the non-deprecated execute method with ClassicHttpResponse
ClassicHttpResponse response = httpClient.executeOpen(null, httpGet, null);

HttpGet httpGet = new HttpGet(validatedUri);
response = httpClient.executeOpen(null, httpGet, null);
int status = response.getCode();

if (status == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
// Return the content as a stream directly
return entity.getContent();
InputStream content = entity.getContent();
if (content != null) {
ClassicHttpResponse responseToClose = response;
streamReturned = true;
return new FilterInputStream(content) {
private final AtomicBoolean closed = new AtomicBoolean();

@Override
public void close() throws IOException {
if (closed.compareAndSet(false, true)) {
try {
super.close();
} finally {
try {
responseToClose.close();
} finally {
httpClient.close();
}
}
}
}
};
}
}
}
logger.log(Level.WARNING, "Failed to get DropBox InputStream for file: {0}. Status code: {1}", new Object[]{fileLink, status});
response.close();

logger.log(Level.WARNING, "Failed to get Dropbox InputStream for host {0}. Status code: {1}",
new Object[]{validatedUri.getHost(), status});
return null;
} catch (IOException ex) {
logger.log(Level.WARNING, "Failed to access DropBox url: {0}!", fileLink);
} catch (IOException | RuntimeException ex) {
logger.log(Level.WARNING, "Failed to access Dropbox host {0}: {1}",
new Object[]{validatedUri.getHost(), ex.getMessage()});
return null;
} finally {
if (!streamReturned) {
if (response != null) {
try {
response.close();
} catch (IOException ignored) {
}
}
try {
httpClient.close();
} catch (IOException ignored) {
}
}
}
} // end: getDropBoxInputStream

Expand Down Expand Up @@ -1502,8 +1606,16 @@ public void handleDropBoxUpload(ActionEvent event) {
// Is this a FileReplaceOperation? If so, then diverge!
// -----------------------------------------------------------
if (this.isFileReplaceOperation()) {
this.handleReplaceFileUpload(event, dropBoxStream, fileName, FileUtil.MIME_TYPE_UNDETERMINED_DEFAULT, null, event);
this.setFileMetadataSelectedForTagsPopup(fileReplacePageHelper.getNewFileMetadatasBeforeSave().get(0));
try {
this.handleReplaceFileUpload(event, dropBoxStream, fileName, FileUtil.MIME_TYPE_UNDETERMINED_DEFAULT, null, event);
this.setFileMetadataSelectedForTagsPopup(fileReplacePageHelper.getNewFileMetadatasBeforeSave().get(0));
} finally {
try {
dropBoxStream.close();
} catch (IOException ex) {
logger.log(Level.WARNING, "Failed to close the Dropbox stream for file: {0}", fileName);
}
}
return;
}
// -----------------------------------------------------------
Expand All @@ -1520,7 +1632,8 @@ public void handleDropBoxUpload(ActionEvent event) {
// zip file.
//datafiles = ingestService.createDataFiles(workingVersion, dropBoxStream, fileName, "application/octet-stream");
//CreateDataFileResult createDataFilesResult = FileUtil.createDataFiles(workingVersion, dropBoxStream, fileName, "application/octet-stream", null, null, systemConfig);
Command<CreateDataFileResult> cmd = new CreateNewDataFilesCommand(dvRequestService.getDataverseRequest(), workingVersion, dropBoxStream, fileName, "application/octet-stream", null, uploadSessionQuota, null);
Dataverse parentDataverse = mode == FileEditMode.CREATE ? workingVersion.getDataset().getOwner() : null;
Command<CreateDataFileResult> cmd = new CreateNewDataFilesCommand(dvRequestService.getDataverseRequest(), workingVersion, dropBoxStream, fileName, "application/octet-stream", null, uploadSessionQuota, null, null, null, parentDataverse);
CreateDataFileResult createDataFilesResult = commandEngine.submit(cmd);
datafiles = createDataFilesResult.getDataFiles();
Optional.ofNullable(editDataFilesPageHelper.getHtmlErrorMessage(createDataFilesResult)).ifPresent(errorMessage -> errorMessages.add(errorMessage));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ public CreateNewDataFilesCommand(DataverseRequest aRequest, DatasetVersion versi
// context of creating a brand new dataset (from the Add Dataset page):

public CreateNewDataFilesCommand(DataverseRequest aRequest, DatasetVersion version, InputStream inputStream, String fileName, String suppliedContentType, String newStorageIdentifier, UploadSessionQuotaLimit quota, String newCheckSum, DataFile.ChecksumType newCheckSumType, Long newFileSize, Dataverse dataverse, boolean replace) {
super(aRequest, dataverse);
super(aRequest, dataverse != null ? dataverse : (version != null ? version.getDataset() : null));

this.version = version;
this.inputStream = inputStream;
Expand Down Expand Up @@ -182,16 +182,29 @@ public CreateDataFileResult execute(CommandContext ctxt) throws CommandException
// temp files will always be stored on the local filesystem.
// -- L.A. Jul. 2014
logger.fine("Will attempt to save the file as: " + tempFile.toString());
Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING);
try (var outputStream = Files.newOutputStream(tempFile)) {
fileSize = FileUtil.copyWithSizeLimit(inputStream, outputStream, fileSizeLimit);
}
} catch (IOException ioex) {
try {
if (tempFile != null) {
Files.deleteIfExists(tempFile);
}
} catch (IOException ignored) {
}
if (ioex instanceof FileUtil.FileSizeLimitExceededException sizeLimitExceeded) {
throw new CommandExecutionException(MessageFormat.format(
BundleUtil.getStringFromBundle("file.addreplace.error.file_exceeds_limit"),
bytesToHumanReadable(sizeLimitExceeded.getObservedSize()),
bytesToHumanReadable(sizeLimitExceeded.getMaxSize())), ioex, this);
}
throw new CommandExecutionException("Failed to save the upload as a temp file (temp disk space?)", ioex, this);
}

// A file size check, before we do anything else:
// (note that "no size limit set" = "unlimited")
// (also note, that if this is a zip file, we'll be checking
// the size limit for each of the individual unpacked files)
fileSize = tempFile.toFile().length();
if (fileSizeLimit != null && fileSize > fileSizeLimit) {
try {
tempFile.toFile().delete();
Expand Down
43 changes: 37 additions & 6 deletions src/main/java/edu/harvard/iq/dataverse/util/FileUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,25 @@ public class FileUtil implements java.io.Serializable {
private static final Set<String> ALLOWED_IMAGE_FORMATS = Set.of("png", "jpeg", "jpg");

public static class FileSizeLimitExceededException extends IOException {
private final long maxSize;
private final long observedSize;

public FileSizeLimitExceededException(long maxSize) {
this(maxSize, maxSize);
}

public FileSizeLimitExceededException(long maxSize, long observedSize) {
super("File exceeds the maximum allowed size of " + maxSize + " bytes");
this.maxSize = maxSize;
this.observedSize = observedSize;
}

public long getMaxSize() {
return maxSize;
}

public long getObservedSize() {
return observedSize;
}
}

Expand Down Expand Up @@ -876,7 +893,7 @@ public static File saveInputStreamInTempFile(InputStream inputStream, Long fileS
throws IOException, FileExceedsMaxSizeException, FileExceedsStorageQuotaException {
return saveInputStreamInTempFile(inputStream, fileSizeLimit, null);
}

public static File saveInputStreamInTempFile(InputStream inputStream, Long fileSizeLimit, Long storageQuotaLimit)
throws IOException, FileExceedsMaxSizeException, FileExceedsStorageQuotaException {
Path tempFile = Files.createTempFile(Paths.get(getFilesTempDirectory()), "tmp", "upload");
Expand Down Expand Up @@ -2033,7 +2050,7 @@ public static BufferedImage readImageWithLimits(File imageFile) throws IOExcepti
return null;
}
if (imageFile.length() > MAX_IMAGE_UPLOAD_SIZE_BYTES) {
throw new FileSizeLimitExceededException(MAX_IMAGE_UPLOAD_SIZE_BYTES);
throw new FileSizeLimitExceededException(MAX_IMAGE_UPLOAD_SIZE_BYTES, imageFile.length());
}
try (ImageInputStream imageInputStream = ImageIO.createImageInputStream(imageFile)) {
if (imageInputStream == null) {
Expand Down Expand Up @@ -2071,18 +2088,32 @@ private static void validateImageDimensions(int width, int height) throws IOExce
}
}

private static void copyWithSizeLimit(InputStream inputStream, OutputStream outputStream, long maxSize)
/**
* Copies an input stream to an output stream, throwing if the optional size limit is exceeded.
* The streams remain open for the caller to manage.
*
* @return the number of bytes copied
*/
public static long copyWithSizeLimit(InputStream inputStream, OutputStream outputStream, Long maxSize)
throws IOException {
if (maxSize != null && maxSize < 0) {
throw new IllegalArgumentException("Maximum file size cannot be negative");
}
byte[] bytes = new byte[8192];
long totalBytes = 0;
int read;
while ((read = inputStream.read(bytes)) != -1) {
if (read > maxSize - totalBytes) {
throw new FileSizeLimitExceededException(maxSize);
if (totalBytes > Long.MAX_VALUE - read) {
throw new IOException("Upload exceeds the supported file size");
}
long observedSize = totalBytes + read;
if (maxSize != null && observedSize > maxSize) {
throw new FileSizeLimitExceededException(maxSize, observedSize);
}
outputStream.write(bytes, 0, read);
totalBytes += read;
totalBytes = observedSize;
}
return totalBytes;
}

public static boolean hasAllowedImageFileExtension(String fileName) {
Expand Down
2 changes: 1 addition & 1 deletion src/main/webapp/editFilesFragment.xhtml
Original file line number Diff line number Diff line change
Expand Up @@ -963,7 +963,7 @@
</button>
</div>
</p:dialog>
<script src="/resources/js/dropins.js" id="dropboxjs" data-app-key="#{EditDatafilesPage.dropBoxKey}"/>
<script type="text/javascript" src="https://www.dropbox.com/static/api/2/dropins.js" id="dropboxjs" data-app-key="#{EditDatafilesPage.dropBoxKey}"></script>
<script>
//<![CDATA[
function openDialog() {
Expand Down
1 change: 0 additions & 1 deletion src/main/webapp/resources/js/dropins.js

This file was deleted.

Loading
Loading