diff --git a/doc/sphinx-guides/source/admin/file-erasure.rst b/doc/sphinx-guides/source/admin/file-erasure.rst new file mode 100644 index 00000000000..1a667c7c674 --- /dev/null +++ b/doc/sphinx-guides/source/admin/file-erasure.rst @@ -0,0 +1,237 @@ +File Erasure +============ + +.. contents:: Contents: + :local: + +Overview +-------- + +Dataverse has functionality to erase the physical bytes represented by a dataset datafile. This capability can be used independently or in conjunction with deletion of datafiles from dataset versioning and dataset version deaccessioning. It is intended to support removal of files after their retention period is over or in response to take-down requests such as those allowed by the European General Data Protection Regulation (GDPR). + +Note that conformance with regulations such as GDPR or the legal requirements related to file retention will involve appropriate policies, procedures, and configuration of repository infrastructure and storage that are not addressed by Dataverse's capabilities. This guide page describes Dataverse's functionality and provides some limited, best-effort, guidance related to developing appropriate take-down/retention capabilities. + +When a File Erasure request is processed, Dataverse triggers a standard operating system file deletion command via Java (``java.nio.file.Files.delete``). +This operation instantly removes the file pointer, rendering the data inaccessible to the operating system and application layers. However, whether the underlying physical blocks are immediately or permanently scrubbed depends entirely on your specific hardware and storage configuration. + +Erasure applies only to files that have been published (at least one released dataset version contains the file). Draft-only files cannot be erased; use the standard file delete API instead. Erasure of harvested files is not supported. + +To ensure full compliance with data protection regulations, system administrators must ensure their host infrastructure adheres to one of the following compliant deployment patterns. + +Pattern A: Solid-State Drives (SSDs) & NVMe Storage +--------------------------------------------------- + +Modern flash storage uses a Flash Translation Layer (FTL) and wear leveling. When a file is deleted, the physical data blocks remain intact until a drive maintenance cycle clears them. + +**Mandatory OS Configuration:** Ensure that TRIM (Linux/macOS) or Defrag/Optimize Drives (Windows) is enabled and scheduled to run aggressively. + +- **Linux:** Verify the ``fstrim.timer`` systemd service is active (weekly is standard, but daily may be preferred depending on your take-down SLA). +- **Windows:** Ensure the "Optimize Drives" scheduled task is running. + +**Why this matters:** TRIM explicitly signals to the SSD controller that the deleted file's blocks are no longer needed. The drive's internal garbage collection will then permanently erase the physical flash cells during idle time, ensuring true physical sanitization. + +Pattern B: Traditional Hard Disk Drives (HDDs) & SAN/NAS Arrays +--------------------------------------------------------------- + +Spinning disks do not automatically clear data blocks upon file deletion; they simply mark the space as available for future writes. + +**Mandatory OS Configuration:** If deploying on traditional mechanical disks, the hosting filesystem must be configured to securely clear unallocated space automatically. + +- **Linux (ext4):** Ensure the filesystem is mounted with the ``discard`` option if supported by the underlying storage array, or schedule automated secure free-space wiping utilities (such as ``sfill`` from the ``secure-delete`` package) during off-peak hours. +- **Windows:** Implement a regular scheduled task using ``cipher /w:X:`` (where ``X`` is the drive letter) to overwrite deactivated blocks and deleted data across the volume's free space. + +Pattern C: Cloud Block Storage (AWS EBS, Azure Managed Disks, GCP Persistent Disks) +----------------------------------------------------------------------------------- + +If hosting the application in a cloud environment, block storage devices are abstracted and multi-tenant. + +**Cloud Best Practices:** Administrators should rely on the cloud provider's native hardware isolation. + +**Data at Rest Encryption:** Ensure that the underlying cloud volume is fully encrypted at rest using provider-managed or customer-managed keys (e.g., AWS KMS, Azure Key Vault). + +**Why this matters:** Cloud providers guarantee that when an encrypted volume or block is unallocated or deleted, the underlying physical infrastructure is sanitized or the specific block cryptographic keys are destroyed before hardware blocks are reassigned to other tenants. + + +Pattern D: Amazon S3 & Object Storage (AWS S3, Azure Blob, MinIO) +----------------------------------------------------------------- + +If the application is configured to store large files directly in Amazon S3 or an S3-compatible object storage repository, a standard application deletion command only removes the current object pointer. If features like Versioning or Object Locking are enabled on the bucket, the physical data blocks will remain permanently accessible unless explicit lifecycle controls are enforced by the cloud administrator. + +- **Mandatory S3 Lifecycle Configuration:** Administrators must configure an automated S3 Lifecycle Policy on the target bucket to guarantee permanent, unrecoverable erasure of all historical iterations and deleted files. +- **Noncurrent Version Expiration:** If Bucket Versioning is active, deleting a file from the Java application creates a "Delete Marker" and moves the actual file to a "Noncurrent Version" state. To ensure full compliance, configure a lifecycle rule to permanently expire and permanently remove noncurrent versions after a strict compliance buffer window (e.g., 7 to 14 days). +- **Incomplete Multipart Upload Cleanups:** Large files uploaded via multipart streams can leave orphaned, hidden data fragments if a network drop or timeout occurs mid-upload. Configure a rule to automatically abort and delete incomplete multipart uploads after 7 days to prevent residual data persistence. +- **Handling Object Lock & Compliance Mode:** If your bucket utilizes S3 Object Lock in "Compliance Mode" for Write-Once-Read-Many (WORM) requirements, even system administrators cannot bypass retention dates. Ensure that the retention window configured on the bucket does not legally conflict with your organization's strict GDPR erasure SLAs. + +Example: Compliant AWS S3 Lifecycle Policy (JSON) + +Administrators can apply this lifecycle configuration shell directly to the asset bucket via the AWS CLI or Terraform: + +.. code-block:: json + + { + "Rules": [ + { + "ID": "GDPR-Compliant-Erasure-Policy", + "Status": "Enabled", + "Filter": { + "Prefix": "" + }, + "NoncurrentVersionExpiration": { + "NoncurrentDays": 14 + }, + "AbortIncompleteMultipartUpload": { + "DaysAfterInitiation": 7 + } + } + ] + } + +- **Data at Rest Encryption (SSE-S3 / SSE-KMS):** Ensure the bucket has default server-side encryption enabled. When objects or their underlying versions are permanently deleted via lifecycle rules, AWS automatically sanitizes the storage blocks and updates the internal block allocation, ensuring the data can never be read by another cloud tenant. + +Critical Requirement: Backup & Snapshot Lifecycle Policy +-------------------------------------------------------- + +Data protection authorities universally accept that backup media cannot always be cleared instantaneously upon a single user deletion request. However, to remain compliant: + +1. **Declared Retention Window:** Organizations must define a strict backup retention policy (e.g., 30, 60, or 90 days). +2. **Immutable Expiry:** Backups, VM snapshots, database mirrors, and archival copies containing the erased file must be completely overwritten or destroyed automatically once they age out of the retention window. +3. **Restoration Protocol:** If a historical backup must be restored to production, administrators must re-run a compliance synchronization script to re-delete files for any users who requested erasure during the intervening period. + +API Reference +------------- + +Erasing a file is performed via the REST API by superusers only. The operation uses a two-step confirmation flow to prevent accidental erasure. + +Erasure Endpoint +~~~~~~~~~~~~~~~~ + +.. code-block:: bash + + POST /api/files/{id}/erase + +The ``{id}`` parameter accepts either a numeric file ID or a persistent identifier (for example, ``doi:10.5072/FK2...``). + +Request Body +~~~~~~~~~~~~ + +The request body is JSON (``Content-Type: application/json``) with the following fields: + +- **reason** (required, string): A free-text explanation of why the file is being erased (for example, a GDPR request reference number). +- **confirmationToken** (required on the second step, string): The token returned by the first step. +- **manuallyErased** (optional, boolean): Set to ``true`` when confirming erasure of a file on a storage location Dataverse cannot write to directly. + +Two-Step Confirmation Flow +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To prevent accidental erasure, the API requires two requests: + +**Step 1 — Request a confirmation token:** + +.. code-block:: bash + + curl -H "X-Dataverse-key: $API_TOKEN" \ + -H "Content-Type: application/json" \ + -X POST \ + -d '{"reason": "GDPR request #12345"}' \ + "$SERVER_URL/api/files/$FILE_ID/erase" + +The server validates that the file is published and not harvested, then returns a ``202 Accepted`` response with a confirmation token valid for 5 minutes: + +.. code-block:: json + + { + "status": "confirmation_required", + "confirmationToken": "a1b2c3d4-...", + "tokenExpiresInSeconds": 300, + "fileId": 42, + "persistentId": "doi:10.5072/FK2...", + "message": "To complete the erasure, send another POST request with the confirmationToken included." + } + +If the file is stored on a location Dataverse cannot write to (for example, a Globus endpoint or a remote overlay store), the message field indicates that manual deletion is required: + +.. code-block:: json + + { + "status": "confirmation_required", + "confirmationToken": "a1b2c3d4-...", + "tokenExpiresInSeconds": 300, + "fileId": 42, + "message": "This file is stored on a location not directly accessible by Dataverse. Please delete the main file manually, then send another POST request with both the confirmationToken and manuallyErased=true to complete the erasure." + } + +**Step 2 — Confirm the erasure:** + +For files on storage Dataverse can write to directly (local filesystem, S3, Swift): + +.. code-block:: bash + + curl -H "X-Dataverse-key: $API_TOKEN" \ + -H "Content-Type: application/json" \ + -X POST \ + -d '{"reason": "GDPR request #12345", "confirmationToken": "a1b2c3d4-..."}' \ + "$SERVER_URL/api/files/$FILE_ID/erase" + +For files on storage Dataverse cannot write to, after manually deleting the file from the remote location: + +.. code-block:: bash + + curl -H "X-Dataverse-key: $API_TOKEN" \ + -H "Content-Type: application/json" \ + -X POST \ + -d '{"reason": "GDPR request #12345", "confirmationToken": "a1b2c3d4-...", "manuallyErased": true}' \ + "$SERVER_URL/api/files/$FILE_ID/erase" + +A successful erasure returns a ``200 OK`` response: + +.. code-block:: json + + { + "status": "erased", + "fileId": 42, + "persistentId": "doi:10.5072/FK2..." + } + +If the file is already erased, the endpoint returns ``410 Gone``. + +Storage Read and Write Capability Checks +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Dataverse determines whether it can erase a file directly by checking the storage driver's write capability. For local filesystem, S3, and Swift stores, Dataverse deletes both the main file and all auxiliary files (thumbnails, cached tabular data, preserved originals, and search index files) automatically. + +For stores Dataverse cannot write to (such as Globus endpoints or remote overlay stores), Dataverse deletes only cached auxiliary files. The main data file must be deleted manually by the administrator. The API response in Step 1 indicates when manual deletion is required. + +When the administrator confirms with ``manuallyErased: true``, Dataverse performs a verification step if the store is readable: it checks whether the main file still exists in storage. If the file is still present, the erasure fails with an error. If the store is not readable by Dataverse either, the confirmation proceeds based on the administrator's assertion alone. + +Audit Record +~~~~~~~~~~~~ + +Each erasure creates a ``FileErasure`` database record linked to the erased ``DataFile``. The record retains: + +- **erasedBy**: The superuser who performed the erasure. +- **erasedOn**: The timestamp of the erasure. +- **reason**: The free-text reason provided in the API request. +- **manuallyDeleted**: A boolean flag indicating whether the main file was deleted manually by the administrator (``true``) or directly by Dataverse (``false``). This flag provides a permanent audit trail distinguishing erasures that involved manual intervention from those handled entirely by Dataverse. + +The ``DataFile`` database record is retained with a reference to the ``FileErasure`` record. The storage identifier is preserved (not cleared) so that the original file location can be manually verified after erasure. + +Download and Access Blocking +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +After erasure, attempts to download the file return HTTP ``410 Gone``. This applies to: + +- Single-file downloads via ``GET /api/access/datafile/{id}``. +- Bulk or bundle downloads that include an erased file. +- Access requests via ``POST /api/access/datafile/{id}/requestAccess``. + +Draft Version Handling +~~~~~~~~~~~~~~~~~~~~~~ + +If a draft (working copy) version exists when a file is erased, the file's metadata entry is removed from that draft. If no draft exists, no new draft is created. To fully remove the file from published history, publish a new version without the erased file and deaccession earlier versions that still reference it. + +Error Responses +~~~~~~~~~~~~~~~ + +| **400 Bad Request**: Missing or invalid ``reason``; expired or invalid confirmation token; attempt to erase a draft-only file; attempt to erase a harvested file; or attempt to confirm erasure of a file on an inaccessible store without ``manuallyErased: true``. +| **403 Forbidden**: The requesting user is not a superuser. +| **410 Gone**: The file has already been erased. diff --git a/doc/sphinx-guides/source/admin/index.rst b/doc/sphinx-guides/source/admin/index.rst index 0f7a87bdded..5b3f91ab5ce 100755 --- a/doc/sphinx-guides/source/admin/index.rst +++ b/doc/sphinx-guides/source/admin/index.rst @@ -35,5 +35,6 @@ This guide documents the functionality only available to superusers (such as "da reporting-tools-and-queries maintenance backups + file-erasure troubleshooting big-data-administration diff --git a/src/main/java/edu/harvard/iq/dataverse/DataFile.java b/src/main/java/edu/harvard/iq/dataverse/DataFile.java index d08d2d63f0b..27db6e4f403 100644 --- a/src/main/java/edu/harvard/iq/dataverse/DataFile.java +++ b/src/main/java/edu/harvard/iq/dataverse/DataFile.java @@ -327,6 +327,18 @@ public void setRetention(Retention retention) { this.retention = retention; } + @OneToOne(mappedBy = "dataFile") + @BatchFetch(BatchFetchType.IN) + private FileErasure fileErasure; + + public FileErasure getFileErasure() { + return fileErasure; + } + + public void setFileErasure(FileErasure fileErasure) { + this.fileErasure = fileErasure; + } + public DataFile() { this.fileMetadatas = new ArrayList<>(); initFileReplaceAttributes(); diff --git a/src/main/java/edu/harvard/iq/dataverse/DatasetPage.java b/src/main/java/edu/harvard/iq/dataverse/DatasetPage.java index c97b89e7ebc..90004b7ed45 100644 --- a/src/main/java/edu/harvard/iq/dataverse/DatasetPage.java +++ b/src/main/java/edu/harvard/iq/dataverse/DatasetPage.java @@ -3272,6 +3272,7 @@ public void setSelectedNonDownloadableFiles(List selectedNonDownlo this.selectedNonDownloadableFiles = selectedNonDownloadableFiles; } + private List selectedGlobusTransferableFiles; public List getSelectedGlobusTransferableFiles() { @@ -3528,7 +3529,7 @@ private boolean filterSelectedFiles(){ boolean globusDownloadEnabled = settingsWrapper.isGlobusDownload(); for (FileMetadata fmd : this.selectedFiles){ boolean downloadable=this.fileDownloadHelper.canDownloadFile(fmd); - + boolean globusTransferable = false; if(globusDownloadEnabled) { String driverId = DataAccess.getStorageDriverFromIdentifier(fmd.getDataFile().getStorageIdentifier()); @@ -5544,6 +5545,10 @@ public boolean isFileAccessRequestMultiButtonRequired(){ for (FileMetadata fmd : workingVersion.getFileMetadatas()){ AuthenticatedUser authenticatedUser = (AuthenticatedUser) session.getUser(); //Change here so that if all restricted files have pending requests there's no Request Button + // Skip erased files — they are non-downloadable but access cannot be requested + if (FileUtil.isErased(fmd.getDataFile())) { + continue; + } if ((!this.fileDownloadHelper.canDownloadFile(fmd) && !fmd.getDataFile().containsActiveFileAccessRequestFromUser(authenticatedUser))) { return true; } @@ -5578,7 +5583,8 @@ public boolean isFileAccessRequestMultiSignUpButtonRequired(){ return false; } for (FileMetadata fmd : workingVersion.getFileMetadatas()){ - if (!this.fileDownloadHelper.canDownloadFile(fmd) && !FileUtil.isActivelyEmbargoed(fmd)){ + // Skip erased and embargoed files — access cannot be requested for them + if (!this.fileDownloadHelper.canDownloadFile(fmd) && !FileUtil.isActivelyEmbargoed(fmd) && !FileUtil.isErased(fmd.getDataFile())){ return true; } } diff --git a/src/main/java/edu/harvard/iq/dataverse/DatasetVersionServiceBean.java b/src/main/java/edu/harvard/iq/dataverse/DatasetVersionServiceBean.java index 7c1478914e7..cb3fa4cfd03 100644 --- a/src/main/java/edu/harvard/iq/dataverse/DatasetVersionServiceBean.java +++ b/src/main/java/edu/harvard/iq/dataverse/DatasetVersionServiceBean.java @@ -839,6 +839,7 @@ public Long getThumbnailByVersionId(Long versionId) { + "AND df.restricted = false " + "AND df.embargo_id is null " + "AND df.retention_id is null " + + "AND NOT EXISTS (SELECT 1 FROM fileerasure fe WHERE fe.datafile_id = df.id) " + "AND o.previewImageAvailable = true " + "ORDER BY df.id LIMIT 1;").getSingleResult(); } catch (Exception ex) { @@ -866,6 +867,7 @@ public Long getThumbnailByVersionId(Long versionId) { + "AND df.restricted = false " + "AND df.embargo_id is null " + "AND df.retention_id is null " + + "AND NOT EXISTS (SELECT 1 FROM fileerasure fe WHERE fe.datafile_id = df.id) " + "AND df.contenttype LIKE 'image/%' " + "AND NOT df.contenttype = 'image/fits' " + "AND df.filesize < " + imageThumbnailSizeLimit + " " @@ -901,6 +903,7 @@ public Long getThumbnailByVersionId(Long versionId) { + "AND df.restricted = false " + "AND df.embargo_id is null " + "AND df.retention_id is null " + + "AND NOT EXISTS (SELECT 1 FROM fileerasure fe WHERE fe.datafile_id = df.id) " + "AND df.contenttype = 'application/pdf' " + "AND df.filesize < " + imageThumbnailSizeLimit + " " + "ORDER BY df.filesize ASC LIMIT 1;").getSingleResult(); diff --git a/src/main/java/edu/harvard/iq/dataverse/FileDownloadHelper.java b/src/main/java/edu/harvard/iq/dataverse/FileDownloadHelper.java index 02f986519a2..534a1ac1194 100644 --- a/src/main/java/edu/harvard/iq/dataverse/FileDownloadHelper.java +++ b/src/main/java/edu/harvard/iq/dataverse/FileDownloadHelper.java @@ -237,6 +237,9 @@ public boolean canDownloadFile(FileMetadata fileMetadata){ // Retention expired files are always made unavailable, because they might be destroyed if (FileUtil.isRetentionExpired(fileMetadata)) return false; + // Erased files are not downloadable + if (FileUtil.isErased(fileMetadata.getDataFile())) return false; + Long fid = fileMetadata.getId(); //logger.info("calling candownloadfile on filemetadata "+fid); // Note that `isRestricted` at the FileMetadata level is for expressing intent by version. Enforcement is done with `isRestricted` at the DataFile level. diff --git a/src/main/java/edu/harvard/iq/dataverse/FileErasure.java b/src/main/java/edu/harvard/iq/dataverse/FileErasure.java new file mode 100644 index 00000000000..da1c5d10b31 --- /dev/null +++ b/src/main/java/edu/harvard/iq/dataverse/FileErasure.java @@ -0,0 +1,145 @@ +package edu.harvard.iq.dataverse; + +import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser; +import edu.harvard.iq.dataverse.util.BundleUtil; +import jakarta.persistence.*; +import java.time.format.DateTimeFormatter; +import java.util.Date; +import java.util.Objects; + +/** + * Represents the erasure of a physical file from storage while retaining the + * DataFile database record with audit metadata about who erased it, when, and why. + * This supports GDPR "right to be forgotten" requests and similar compliance scenarios. + */ +@NamedQueries({ + @NamedQuery(name = "FileErasure.findAll", + query = "SELECT fe FROM FileErasure fe"), + @NamedQuery(name = "FileErasure.findById", + query = "SELECT fe FROM FileErasure fe WHERE fe.id=:id"), + @NamedQuery(name = "FileErasure.findByDataFileId", + query = "SELECT fe FROM FileErasure fe WHERE fe.dataFile.id=:dataFileId"), + @NamedQuery(name = "FileErasure.findByDatasetId", + query = "SELECT fe FROM FileErasure fe WHERE fe.dataFile.owner.id=:datasetId"), + @NamedQuery(name = "FileErasure.findByDataverseId", + query = "SELECT fe FROM FileErasure fe WHERE fe.dataFile.owner.owner.id=:dataverseId") +}) +@Entity +@Table(indexes = { + @Index(name = "idx_fileerasure_erasedon", columnList = "erasedOn") +}) +public class FileErasure { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @OneToOne + @JoinColumn(name = "datafile_id", unique = true) + private DataFile dataFile; + + @ManyToOne + @JoinColumn(name = "erased_by_id") + private AuthenticatedUser erasedBy; + + @Column(nullable = false) + @Temporal(TemporalType.TIMESTAMP) + private Date erasedOn; + + @Column(columnDefinition = "TEXT") + private String reason; + + @Column(nullable = false) + private boolean manuallyDeleted = false; + + public FileErasure() { + this.erasedOn = new Date(); + } + + public FileErasure(DataFile dataFile, AuthenticatedUser erasedBy, String reason, boolean manuallyDeleted) { + this.dataFile = dataFile; + this.erasedBy = erasedBy; + this.erasedOn = new Date(); + this.reason = reason; + this.manuallyDeleted = manuallyDeleted; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public DataFile getDataFile() { + return dataFile; + } + + public void setDataFile(DataFile dataFile) { + this.dataFile = dataFile; + } + + public AuthenticatedUser getErasedBy() { + return erasedBy; + } + + public void setErasedBy(AuthenticatedUser erasedBy) { + this.erasedBy = erasedBy; + } + + public Date getErasedOn() { + return erasedOn; + } + + public void setErasedOn(Date erasedOn) { + this.erasedOn = erasedOn; + } + + public String getReason() { + return reason; + } + + public void setReason(String reason) { + this.reason = reason; + } + + public boolean isManuallyDeleted() { + return manuallyDeleted; + } + + public void setManuallyDeleted(boolean manuallyDeleted) { + this.manuallyDeleted = manuallyDeleted; + } + + public String getFormattedErasedOn() { + return java.sql.Timestamp.valueOf(erasedOn.toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDateTime()) + .toLocalDateTime() + .format(DateTimeFormatter.ofPattern("MMM d, yyyy 'at' h:mm a").withLocale(BundleUtil.getCurrentLocale())); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + FileErasure that = (FileErasure) o; + return id.equals(that.id); + } + + @Override + public int hashCode() { + return Objects.hash(id); + } + + @Override + public String toString() { + return "FileErasure{" + + "id=" + id + + ", dataFile=" + (dataFile != null ? dataFile.getId() : "null") + + ", erasedBy=" + (erasedBy != null ? erasedBy.getId() : "null") + + ", erasedOn=" + erasedOn + + ", reason='" + reason + '\'' + + ", manuallyDeleted=" + manuallyDeleted + + '}'; + } +} diff --git a/src/main/java/edu/harvard/iq/dataverse/api/AbstractApiBean.java b/src/main/java/edu/harvard/iq/dataverse/api/AbstractApiBean.java index 1babe3fda87..ea7056d6832 100644 --- a/src/main/java/edu/harvard/iq/dataverse/api/AbstractApiBean.java +++ b/src/main/java/edu/harvard/iq/dataverse/api/AbstractApiBean.java @@ -39,6 +39,7 @@ import edu.harvard.iq.dataverse.util.FileUtil; import edu.harvard.iq.dataverse.util.SystemConfig; import edu.harvard.iq.dataverse.util.json.JsonParser; +import edu.harvard.iq.dataverse.util.json.JsonPrinter; import edu.harvard.iq.dataverse.util.json.JsonUtil; import edu.harvard.iq.dataverse.util.json.NullSafeJsonBuilder; import edu.harvard.iq.dataverse.validation.PasswordValidatorServiceBean; @@ -1201,6 +1202,157 @@ protected static Response error( Status sts, String msg ) { .add(ApiConstants.MESSAGE_FIELD, msg ).build() ).type(MediaType.APPLICATION_JSON_TYPE).build(); } + + /* ======================== *\ + * Erased Files API Utils * + \* ======================== */ + + /** + * Build a JPQL query string for FileErasure with optional date range filtering. + * @param baseWhere the base WHERE clause condition (e.g. "fe.dataFile.dataset.id = :datasetId"), or null for no base filter. + * @param start optional start date + * @param end optional end date + * @return a map containing "jpql" (the full query string) and "hasWhere" (boolean indicating if WHERE clause was added) + */ + protected static String buildErasedFilesJpql(String baseWhere, Date start, Date end) { + StringBuilder jpql = new StringBuilder("SELECT fe FROM FileErasure fe"); + List conditions = new ArrayList<>(); + if (baseWhere != null) { + conditions.add(baseWhere); + } + if (start != null) { + conditions.add("fe.erasedOn >= :start"); + } + if (end != null) { + conditions.add("fe.erasedOn <= :end"); + } + if (!conditions.isEmpty()) { + jpql.append(" WHERE ").append(String.join(" AND ", conditions)); + } + jpql.append(" ORDER BY fe.erasedOn DESC"); + return jpql.toString(); + } + + /** + * Set the date range parameters on a JPQL query. + */ + protected static void setErasedFilesQueryParams(jakarta.persistence.Query query, Date start, Date end) { + if (start != null) { + query.setParameter("start", start); + } + if (end != null) { + query.setParameter("end", end); + } + } + + /** + * Convert a list of FileErasure entities to a JSON array. + * Uses {@link JsonPrinter#json(DataFile)} for the DataFile portion, which already includes fileErasure details. + */ + protected static jakarta.json.JsonArrayBuilder toErasedFilesJsonArray(List erasedFiles) { + jakarta.json.JsonArrayBuilder jsonArrayBuilder = JsonUtil.createArrayBuilder(); + for (FileErasure fe : erasedFiles) { + DataFile dataFile = fe.getDataFile(); + jsonArrayBuilder.add(JsonPrinter.json(dataFile)); + } + return jsonArrayBuilder; + } + + /** + * Convert a list of FileErasure entities to a CSV string. + * Includes metadata comment rows (generated on, date range, scope ID) and internationalized headers. + * @param erasedFiles list of FileErasure entities + * @param startDate optional start date filter (included in metadata if present) + * @param endDate optional end date filter (included in metadata if present) + * @param scopeId optional scope identifier (dataset or dataverse ID, included in metadata if present) + */ + protected static String toErasedFilesCsvString(List erasedFiles, Date startDate, Date endDate, Long scopeId) { + StringBuilder csv = new StringBuilder(); + // Metadata comment rows + csv.append('#').append(escapeCsvCell(BundleUtil.getStringFromBundle("file.erased.csv.metadata.generatedOn"))) + .append(':').append(escapeCsvCell(new java.text.SimpleDateFormat("yyyy-MM-dd").format(new Date()))).append('\n'); + if (startDate != null) { + csv.append('#').append(escapeCsvCell(BundleUtil.getStringFromBundle("file.erased.csv.metadata.startDate"))) + .append(':').append(escapeCsvCell(new java.text.SimpleDateFormat("yyyy-MM-dd").format(startDate))).append('\n'); + } + if (endDate != null) { + csv.append('#').append(escapeCsvCell(BundleUtil.getStringFromBundle("file.erased.csv.metadata.endDate"))) + .append(':').append(escapeCsvCell(new java.text.SimpleDateFormat("yyyy-MM-dd").format(endDate))).append('\n'); + } + if (scopeId != null) { + csv.append('#').append(escapeCsvCell(BundleUtil.getStringFromBundle("file.erased.csv.metadata.scopeId"))) + .append(':').append(scopeId).append('\n'); + } + // Internationalized header row + csv.append(escapeCsvCell(BundleUtil.getStringFromBundle("file.erased.csv.header.fileId"))).append(','); + csv.append(escapeCsvCell(BundleUtil.getStringFromBundle("file.erased.csv.header.filePid"))).append(','); + csv.append(escapeCsvCell(BundleUtil.getStringFromBundle("file.erased.csv.header.fileName"))).append(','); + csv.append(escapeCsvCell(BundleUtil.getStringFromBundle("file.erased.csv.header.erasureId"))).append(','); + csv.append(escapeCsvCell(BundleUtil.getStringFromBundle("file.erased.csv.header.erasedOn"))).append(','); + csv.append(escapeCsvCell(BundleUtil.getStringFromBundle("file.erased.csv.header.reason"))).append(','); + csv.append(escapeCsvCell(BundleUtil.getStringFromBundle("file.erased.csv.header.manuallyDeleted"))).append(','); + csv.append(escapeCsvCell(BundleUtil.getStringFromBundle("file.erased.csv.header.eraserIdentifier"))).append(','); + csv.append(escapeCsvCell(BundleUtil.getStringFromBundle("file.erased.csv.header.eraserName"))); + csv.append('\n'); + // Data rows + for (FileErasure fe : erasedFiles) { + DataFile dataFile = fe.getDataFile(); + csv.append(escapeCsvCell(dataFile != null ? String.valueOf(dataFile.getId()) : "")) + .append(','); + csv.append(escapeCsvCell(dataFile != null && dataFile.getGlobalId() != null ? dataFile.getGlobalId().asString() : "")) + .append(','); + String fileName = ""; + if (dataFile != null && dataFile.getFileMetadata() != null) { + fileName = dataFile.getFileMetadata().getLabel(); + } + csv.append(escapeCsvCell(fileName)).append(','); + csv.append(escapeCsvCell(String.valueOf(fe.getId()))).append(','); + csv.append(escapeCsvCell(fe.getErasedOn() != null ? fe.getErasedOn().toString() : "")).append(','); + csv.append(escapeCsvCell(fe.getReason() != null ? fe.getReason() : "")).append(','); + csv.append(fe.isManuallyDeleted()).append(','); + csv.append(escapeCsvCell(fe.getErasedBy() != null ? fe.getErasedBy().getIdentifier() : "")).append(','); + csv.append(escapeCsvCell(fe.getErasedBy() != null ? fe.getErasedBy().getName() : "")); + csv.append('\n'); + } + return csv.toString(); + } + + /** + * Build a descriptive CSV filename for erased files export. + * Includes scope ID (if present) and date range (if present) in the filename. + * @param startDate optional start date filter + * @param endDate optional end date filter + * @param scopeId optional scope identifier (dataset or dataverse ID) + * @return a filename string suitable for Content-Disposition header + */ + protected static String buildErasedFilesCsvFilename(Date startDate, Date endDate, Long scopeId) { + java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyyMMdd"); + StringBuilder name = new StringBuilder("erased_files"); + if (scopeId != null) { + name.append("_").append(scopeId); + } + if (startDate != null) { + name.append("_from_").append(df.format(startDate)); + } + if (endDate != null) { + name.append("_to_").append(df.format(endDate)); + } + name.append(".csv"); + return name.toString(); + } + + /** + * Escape a CSV cell value by quoting it if it contains commas, quotes, or newlines. + */ + private static String escapeCsvCell(String value) { + if (value == null) { + return ""; + } + if (value.contains(",") || value.contains("\"") || value.contains("\n") || value.contains("\r")) { + return "\"" + value.replace("\"", "\"\"") + "\""; + } + return value; + } } class LazyRef { diff --git a/src/main/java/edu/harvard/iq/dataverse/api/Access.java b/src/main/java/edu/harvard/iq/dataverse/api/Access.java index 5a58ec4ec7b..b8d5b9dac1b 100644 --- a/src/main/java/edu/harvard/iq/dataverse/api/Access.java +++ b/src/main/java/edu/harvard/iq/dataverse/api/Access.java @@ -331,6 +331,10 @@ public Response datafile(@Context ContainerRequestContext crc, throw new NotFoundException(errorMessage); // (nobody should ever be using this API on a harvested DataFile)! } + + if (FileUtil.isErased(df)) { + throw new WebApplicationException(Response.status(Response.Status.GONE).entity("Datafile " + fileId + " has been erased.").build()); + } // This will throw a ForbiddenException if access isn't authorized: checkAuthorization(req.getUser(), df); @@ -585,6 +589,10 @@ private List getDatafilesList(DataverseRequest req, List fileI // (nobody should ever be using this API on a harvested DataFile)! } + if (FileUtil.isErased(df)) { + throw new WebApplicationException(Response.status(Response.Status.GONE).entity("Datafile " + df.getId() + " has been erased.").build()); + } + // Make sure all files are from the same dataset if (datasetId == null) { datasetId = df.getOwner().getId(); @@ -1863,6 +1871,10 @@ public Response requestFileAccess(@Context ContainerRequestContext crc return error(BAD_REQUEST, BundleUtil.getStringFromBundle("access.api.requestAccess.failure.retentionExpired")); } + if (FileUtil.isErased(dataFile)) { + return error(jakarta.ws.rs.core.Response.Status.GONE, "Datafile " + fileToRequestAccessId + " has been erased."); + } + if (!dataFile.getOwner().isFileAccessRequest()) { return error(BAD_REQUEST, BundleUtil.getStringFromBundle("access.api.requestAccess.requestsNotAccepted")); } diff --git a/src/main/java/edu/harvard/iq/dataverse/api/Admin.java b/src/main/java/edu/harvard/iq/dataverse/api/Admin.java index e30be924903..1b5a677a2eb 100644 --- a/src/main/java/edu/harvard/iq/dataverse/api/Admin.java +++ b/src/main/java/edu/harvard/iq/dataverse/api/Admin.java @@ -1500,22 +1500,31 @@ public void write(OutputStream os) throws IOException, for (DataFile dataFile : dataset.getFiles()) { boolean success = false; + boolean skipped = false; JsonObjectBuilder output = JsonUtil.createObjectBuilder(); output.add("datafileId", dataFile.getId()); output.add("storageIdentifier", dataFile.getStorageIdentifier()); - - try { - FileUtil.validateDataFileChecksum(dataFile); - success = true; - } catch (IOException ex) { - output.add("status", "invalid"); - output.add("errorMessage", ex.getMessage()); + // Skip erased files — their physical content no longer exists + if (FileUtil.isErased(dataFile)) { + output.add("status", "skipped"); + output.add("errorMessage", "File has been erased and cannot be validated."); + skipped = true; } - - if (success) { - output.add("status", "valid"); + + if (!skipped) { + try { + FileUtil.validateDataFileChecksum(dataFile); + success = true; + } catch (IOException ex) { + output.add("status", "invalid"); + output.add("errorMessage", ex.getMessage()); + } + + if (success) { + output.add("status", "valid"); + } } // write it out: @@ -2055,6 +2064,9 @@ public Response updateHashValues(@Context ContainerRequestContext crc, @Paramete try { if (df.isHarvested()) { harvested++; + } else if (FileUtil.isErased(df)) { + // Skip erased files — their physical content no longer exists + logger.fine("Skipping erased datafile: " + df.getId()); } else { if (!df.getChecksumType().equals(cType)) { @@ -2162,6 +2174,10 @@ public Response computeDataFileHashValue(@Context ContainerRequestContext crc, return error(Status.BAD_REQUEST, "File with the id: " + fileId + " is harvested."); } + if (FileUtil.isErased(fileToUpdate)) { + return error(Status.BAD_REQUEST, "File with the id: " + fileId + " has been erased and cannot be rehashed."); + } + DataFile.ChecksumType cType = null; try { cType = DataFile.ChecksumType.fromString(alg); @@ -2228,6 +2244,10 @@ public Response validateDataFileHashValue(@Context ContainerRequestContext crc, return error(Status.BAD_REQUEST, "File with the id: " + fileId + " is harvested."); } + if (FileUtil.isErased(fileToValidate)) { + return error(Status.BAD_REQUEST, "File with the id: " + fileId + " has been erased and cannot be validated."); + } + DataFile.ChecksumType cType = null; try { String checkSumTypeFromDataFile = fileToValidate.getChecksumType().toString(); diff --git a/src/main/java/edu/harvard/iq/dataverse/api/Datasets.java b/src/main/java/edu/harvard/iq/dataverse/api/Datasets.java index 43649542a5b..0af51bda886 100644 --- a/src/main/java/edu/harvard/iq/dataverse/api/Datasets.java +++ b/src/main/java/edu/harvard/iq/dataverse/api/Datasets.java @@ -6912,4 +6912,67 @@ public Response getUploadLimits(@Context ContainerRequestContext crc, return ok(new NullSafeJsonBuilder().add("uploadLimits", limits)); } + + @GET + @AuthRequired + @Path("{identifier}/erasedFiles") + @Produces({ MediaType.APPLICATION_JSON, "text/csv" }) + @Operation(summary = "List erased files in a dataset", + description = "Returns all erased files belonging to a dataset with their FileErasure details, optionally filtered by a date range. Superusers only. Returns CSV by default; use Accept: application/json for JSON.") + public Response listErasedFilesInDataset(@Context ContainerRequestContext crc, + @Parameter(description = "Dataset id or persistent identifier.", required = true) + @PathParam("identifier") String identifier, + @Parameter(description = "Start date filter (inclusive). Format: yyyy-MM-dd, yyyy-MM, or yyyy.") + @QueryParam("startDate") String startDate, + @Parameter(description = "End date filter (inclusive). Format: yyyy-MM-dd, yyyy-MM, or yyyy.") + @QueryParam("endDate") String endDate, + @Context HttpHeaders headers) { + User user = getRequestUser(crc); + if (user == null || !user.isSuperuser()) { + return error(Response.Status.FORBIDDEN, "Superusers only."); + } + + Dataset dataset; + try { + dataset = findDatasetOrDie(identifier); + } catch (WrappedResponse wr) { + return wr.getResponse(); + } + + java.util.Date start = null; + java.util.Date end = null; + if (startDate != null && !startDate.isEmpty()) { + start = DateUtil.parseDate(startDate); + if (start == null) { + return error(Response.Status.BAD_REQUEST, "Invalid startDate format. Use yyyy-MM-dd or yyyy-MM-dd'T'HH:mm:ss."); + } + } + if (endDate != null && !endDate.isEmpty()) { + end = DateUtil.parseDate(endDate); + if (end == null) { + return error(Response.Status.BAD_REQUEST, "Invalid endDate format. Use yyyy-MM-dd or yyyy-MM-dd'T'HH:mm:ss."); + } + } + + String jpql = buildErasedFilesJpql("fe.dataFile.owner.id = :datasetId", start, end); + jakarta.persistence.Query query = em.createQuery(jpql); + query.setParameter("datasetId", dataset.getId()); + setErasedFilesQueryParams(query, start, end); + + List erasedFiles = query.getResultList(); + + List acceptedTypes = headers.getAcceptableMediaTypes(); + boolean wantJson = acceptedTypes.stream() + .anyMatch(mt -> mt.toString().equals(MediaType.APPLICATION_JSON) || mt.toString().equals("*/*")); + + if (wantJson && !acceptedTypes.stream().anyMatch(mt -> mt.toString().equals("text/csv"))) { + return ok(toErasedFilesJsonArray(erasedFiles)); + } + String filename = buildErasedFilesCsvFilename(start, end, dataset.getId()); + return Response.ok() + .entity(toErasedFilesCsvString(erasedFiles, start, end, dataset.getId())) + .type("text/csv") + .header("Content-Disposition", "attachment; filename=" + filename) + .build(); + } } diff --git a/src/main/java/edu/harvard/iq/dataverse/api/Dataverses.java b/src/main/java/edu/harvard/iq/dataverse/api/Dataverses.java index 5f3db84c32d..8fbaa695489 100644 --- a/src/main/java/edu/harvard/iq/dataverse/api/Dataverses.java +++ b/src/main/java/edu/harvard/iq/dataverse/api/Dataverses.java @@ -28,10 +28,8 @@ import edu.harvard.iq.dataverse.pidproviders.PidUtil; import edu.harvard.iq.dataverse.settings.JvmSettings; import edu.harvard.iq.dataverse.settings.SettingsServiceBean; -import edu.harvard.iq.dataverse.util.BundleUtil; -import edu.harvard.iq.dataverse.util.ConstraintViolationUtil; -import edu.harvard.iq.dataverse.util.FileUtil; -import edu.harvard.iq.dataverse.util.StringUtil; +import edu.harvard.iq.dataverse.util.*; + import static edu.harvard.iq.dataverse.util.StringUtil.nonEmpty; import static edu.harvard.iq.dataverse.util.json.JsonPrinter.*; @@ -2840,4 +2838,67 @@ private Set validateLocallyFairRoleAssigneeIdentifiers(List role return validatedIdentifiers; } + @GET + @AuthRequired + @Path("{identifier}/erasedFiles") + @Produces({ MediaType.APPLICATION_JSON, "text/csv" }) + @Operation(summary = "List erased files in a dataverse (collection)", + description = "Returns all erased files belonging to datasets in a dataverse (collection) with their FileErasure details, optionally filtered by a date range. Superusers only. Returns CSV by default; use Accept: application/json for JSON.") + public Response listErasedFilesInDataverse(@Context ContainerRequestContext crc, + @Parameter(description = "Dataverse alias, id, or persistent identifier.", required = true) + @PathParam("identifier") String identifier, + @Parameter(description = "Start date filter (inclusive). Format: yyyy-MM-dd, yyyy-MM, or yyyy.") + @QueryParam("startDate") String startDate, + @Parameter(description = "End date filter (inclusive). Format: yyyy-MM-dd, yyyy-MM, or yyyy.") + @QueryParam("endDate") String endDate, + @Context HttpHeaders headers) { + User user = getRequestUser(crc); + if (user == null || !user.isSuperuser()) { + return error(Response.Status.FORBIDDEN, "Superusers only."); + } + + Dataverse dataverse; + try { + dataverse = findDataverseOrDie(identifier); + } catch (WrappedResponse wr) { + return wr.getResponse(); + } + + java.util.Date start = null; + java.util.Date end = null; + if (startDate != null && !startDate.isEmpty()) { + start = DateUtil.parseDate(startDate); + if (start == null) { + return error(Response.Status.BAD_REQUEST, "Invalid startDate format. Use yyyy-MM-dd or yyyy-MM-dd'T'HH:mm:ss."); + } + } + if (endDate != null && !endDate.isEmpty()) { + end = DateUtil.parseDate(endDate); + if (end == null) { + return error(Response.Status.BAD_REQUEST, "Invalid endDate format. Use yyyy-MM-dd or yyyy-MM-dd'T'HH:mm:ss."); + } + } + + String jpql = buildErasedFilesJpql("fe.dataFile.owner.owner.id = :dataverseId", start, end); + jakarta.persistence.Query query = em.createQuery(jpql); + query.setParameter("dataverseId", dataverse.getId()); + setErasedFilesQueryParams(query, start, end); + + List erasedFiles = query.getResultList(); + + List acceptedTypes = headers.getAcceptableMediaTypes(); + boolean wantJson = acceptedTypes.stream() + .anyMatch(mt -> mt.toString().equals(MediaType.APPLICATION_JSON) || mt.toString().equals("*/*")); + + if (wantJson && !acceptedTypes.stream().anyMatch(mt -> mt.toString().equals("text/csv"))) { + return ok(toErasedFilesJsonArray(erasedFiles)); + } + String filename = buildErasedFilesCsvFilename(start, end, dataverse.getId()); + return Response.ok() + .entity(toErasedFilesCsvString(erasedFiles, start, end, dataverse.getId())) + .type("text/csv") + .header("Content-Disposition", "attachment; filename=" + filename) + .build(); + } + } diff --git a/src/main/java/edu/harvard/iq/dataverse/api/Files.java b/src/main/java/edu/harvard/iq/dataverse/api/Files.java index 458faf790ec..1123d761977 100644 --- a/src/main/java/edu/harvard/iq/dataverse/api/Files.java +++ b/src/main/java/edu/harvard/iq/dataverse/api/Files.java @@ -5,6 +5,8 @@ import com.google.gson.JsonObject; import edu.harvard.iq.dataverse.*; import edu.harvard.iq.dataverse.api.auth.AuthRequired; +import edu.harvard.iq.dataverse.dataaccess.DataAccess; +import edu.harvard.iq.dataverse.dataaccess.StorageIO; import edu.harvard.iq.dataverse.authorization.Permission; import edu.harvard.iq.dataverse.authorization.users.ApiToken; import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser; @@ -19,6 +21,7 @@ import edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException; import edu.harvard.iq.dataverse.engine.command.impl.*; import edu.harvard.iq.dataverse.export.ExportService; +import edu.harvard.iq.dataverse.util.*; import io.gdcc.spi.export.ExportException; import edu.harvard.iq.dataverse.externaltools.ExternalTool; import edu.harvard.iq.dataverse.externaltools.ExternalToolHandler; @@ -28,11 +31,6 @@ import edu.harvard.iq.dataverse.ingest.IngestUtil; import edu.harvard.iq.dataverse.makedatacount.MakeDataCountLoggingServiceBean; import edu.harvard.iq.dataverse.settings.SettingsServiceBean; -import edu.harvard.iq.dataverse.util.BundleUtil; -import edu.harvard.iq.dataverse.util.FileUtil; -import edu.harvard.iq.dataverse.util.StringUtil; -import edu.harvard.iq.dataverse.util.SystemConfig; -import edu.harvard.iq.dataverse.util.URLTokenUtil; import static edu.harvard.iq.dataverse.api.ApiConstants.*; import static edu.harvard.iq.dataverse.api.Datasets.handleVersion; @@ -45,6 +43,7 @@ import java.io.StringReader; import java.util.ArrayList; import java.util.Arrays; +import java.util.Date; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; @@ -214,7 +213,7 @@ public Response restrictFileInDataset(@Context ContainerRequestContext crc, /** * Replace an Existing File * - * @param datasetId + * @param fileIdOrPersistentId * @param testFileInputStream * @param contentDispositionHeader * @param formDataBodyPart @@ -350,8 +349,8 @@ public Response replaceFileInDataset( try { msgt("as String: " + addFileHelper.getSuccessResult()); - /** - * @todo We need a consistent, sane way to communicate a human + /* + @todo We need a consistent, sane way to communicate a human * readable message to an API client suitable for human * consumption. Imagine if the UI were built in Angular or React * and we want to return a message from the API as-is to the @@ -374,7 +373,7 @@ public Response replaceFileInDataset( /** * Delete an Existing File * - * @param id file ID or peristent ID + * @param fileIdOrPersistentId file ID or peristent ID */ @DELETE @AuthRequired @@ -422,6 +421,189 @@ public Response deleteFileInDataset(@Context ContainerRequestContext crc, return ok(deletePhysicalFile); } + + /** + * Erase a published file's physical content from storage while retaining + * the DataFile database record with audit metadata. + * + * Uses a two-token confirmation flow to prevent accidental erasure: + * 1. First request without token returns 202 with a confirmation token + * 2. Second request with the token performs the actual erasure + * + * For files on stores not accessible by Dataverse (RemoteOverlay, non-S3 Globus), + * the initial response indicates that manual deletion is required. The admin must + * delete the file manually and then call back with both the confirmationToken and + * manuallyErased=true to complete the erasure. The erasure does not proceed until + * the admin confirms the main file is deleted. + * + * @param fileIdOrPersistentId file ID or persistent ID + * @param jsonBody JSON body with reason and optional confirmationToken and manuallyErased + */ + @POST + @AuthRequired + @Path("{id}/erase") + @Consumes(MediaType.APPLICATION_JSON) + @Operation(summary = "Erase a published file", + description = "Erases a published data file's physical content from storage while retaining the DataFile database record with audit metadata. Requires superuser. Uses two-token confirmation flow.") + public Response eraseFileInDataset(@Context ContainerRequestContext crc, + @Parameter(description = "Data file fileIdOrPersistentId or persistent identifier.", required = true) + @PathParam("id") String fileIdOrPersistentId, + @RequestBody(description = "JSON object with reason and optional confirmationToken and manuallyErased.") + String jsonBody) { + // (1) Get the user from the API key and create request + User authUser = getRequestUser(crc); + DataverseRequest dvRequest = createDataverseRequest(authUser); + + // (2) Check superuser early — before any other validation or token generation + if (!(authUser instanceof AuthenticatedUser) || !((AuthenticatedUser) authUser).isSuperuser()) { + return error(Status.FORBIDDEN, "Erase can only be called by superusers."); + } + + // (3) Parse JSON body + String reason = null; + String confirmationToken = null; + boolean manuallyErased = false; + if (jsonBody != null && !jsonBody.isEmpty()) { + try { + jakarta.json.JsonObject jsonObj = JsonUtil.getJsonObject(jsonBody); + if (jsonObj.containsKey("reason") && jsonObj.get("reason").getValueType() != jakarta.json.JsonValue.ValueType.NULL) { + reason = jsonObj.getString("reason"); + } + if (jsonObj.containsKey("confirmationToken") && jsonObj.get("confirmationToken").getValueType() != jakarta.json.JsonValue.ValueType.NULL) { + confirmationToken = jsonObj.getString("confirmationToken"); + } + if (jsonObj.containsKey("manuallyErased") && jsonObj.get("manuallyErased").getValueType() != jakarta.json.JsonValue.ValueType.NULL) { + manuallyErased = jsonObj.getBoolean("manuallyErased"); + } + } catch (jakarta.json.JsonException e) { + return error(BAD_REQUEST, "Invalid JSON body."); + } + } + + // (4) Find the data file + DataFile dataFile; + try { + dataFile = findDataFileOrDie(fileIdOrPersistentId); + } catch (WrappedResponse wr) { + return wr.getResponse(); + } + + // (5) Check if already erased + if (dataFile.getFileErasure() != null) { + return error(Status.GONE, "File has already been erased."); + } + + // (6) Validate reason is provided + if (reason == null || reason.trim().isEmpty()) { + return error(BAD_REQUEST, "A reason is required for erasure. Provide it in the JSON body as {\"reason\": \"...\"}"); + } + + // (7) If token provided, perform the erasure + if (confirmationToken != null && !confirmationToken.isEmpty()) { + return performFileErasure(dvRequest, dataFile, reason, confirmationToken, manuallyErased); + } + + // (8) No token - return 202 with confirmation token + String token = java.util.UUID.randomUUID().toString(); + // Store token in a simple cache (5-minute TTL) + erasureTokenCache.put(token, System.currentTimeMillis() + 5 * 60 * 1000); + + // Determine if manual deletion is required for this file + boolean manualDeletionRequired = !StorageIO.isDataverseWritable( + DataAccess.getStorageDriverFromIdentifier(dataFile.getStorageIdentifier())); + + JsonObjectBuilder responseBuilder = JsonUtil.createObjectBuilder() + .add("status", "confirmation_required") + .add("confirmationToken", token) + .add("tokenExpiresInSeconds", 300) + .add("fileId", dataFile.getId()); + if (dataFile.getGlobalId() != null) { + responseBuilder.add("persistentId", dataFile.getGlobalId().asString()); + } + if (manualDeletionRequired) { + responseBuilder.add("message", "This file is stored on a location not directly accessible by Dataverse. Please delete the main file manually, then send another POST request with both the confirmationToken and manuallyErased=true to complete the erasure."); + } else { + responseBuilder.add("message", "To complete the erasure, send another POST request with the confirmationToken included."); + } + + return ok(responseBuilder.build()); + } + + // Simple cache for erasure confirmation tokens (token -> expiry timestamp) + private static final java.util.Map erasureTokenCache = new java.util.concurrent.ConcurrentHashMap<>(); + + /** + * Perform the actual file erasure after token confirmation. + * + * For files on stores accessible by Dataverse, the erasure proceeds immediately. + * For files on inaccessible stores, the admin must have manually deleted the file + * and set manuallyErased=true in the request; otherwise the request is rejected. + */ + private Response performFileErasure(DataverseRequest dvRequest, DataFile dataFile, String reason, + String confirmationToken, boolean manuallyErased) { + // Validate token + Long expiry = erasureTokenCache.get(confirmationToken); + if (expiry == null) { + return error(BAD_REQUEST, "Invalid or expired confirmation token."); + } + if (System.currentTimeMillis() > expiry) { + erasureTokenCache.remove(confirmationToken); + return error(BAD_REQUEST, "Confirmation token has expired. Please request a new one."); + } + + // Check if file is published using isReleased() + if (!dataFile.isReleased()) { + return error(BAD_REQUEST, "Cannot erase file: the DataFile has not been published. Use delete for draft-only files."); + } + + // Check if harvested + if (dataFile.isHarvested()) { + return error(BAD_REQUEST, "Cannot erase harvested files. Erasure is not supported on harvested datasets."); + } + + // Check if manual deletion is required for this file + boolean manualDeletionRequired = !StorageIO.isDataverseWritable( + DataAccess.getStorageDriverFromIdentifier(dataFile.getStorageIdentifier())); + + // If manual deletion is required, the admin must confirm they've deleted the file + if (manualDeletionRequired && !manuallyErased) { + return error(BAD_REQUEST, "This file is stored on a location not directly accessible by Dataverse. Please delete the main file manually, then send another POST request with both the confirmationToken and manuallyErased=true."); + } + + // Execute the erasure command + try { + EraseDataFileCommand cmd = new EraseDataFileCommand(dataFile, dvRequest, reason, manualDeletionRequired); + commandEngine.submit(cmd); + + // Clear the token + erasureTokenCache.remove(confirmationToken); + + // Build response + JsonObjectBuilder responseBuilder = JsonUtil.createObjectBuilder() + .add("status", "erased") + .add("fileId", dataFile.getId()); + if (dataFile.getGlobalId() != null) { + responseBuilder.add("persistentId", dataFile.getGlobalId().asString()); + } + if (manualDeletionRequired) { + responseBuilder.add("note", "File erased. The main file was deleted manually by the admin. Auxiliary files have been removed."); + } + + return ok(responseBuilder.build()); + + } catch (CommandException ex) { + // Clear the token on failure + erasureTokenCache.remove(confirmationToken); + logger.log(Level.SEVERE, "Erasure command failed for file " + dataFile.getId(), ex); + // Messages are explicitly meant for the end user + return error(BAD_REQUEST, "Erasure failed: " + ex.getMessage()); + } catch (Exception ex) { + // Clear the token on failure + erasureTokenCache.remove(confirmationToken); + logger.log(Level.SEVERE, "Erasure failed for file " + dataFile.getId(), ex); + return error(Status.INTERNAL_SERVER_ERROR, "Erasure failed."); + } + } //Much of this code is taken from the replace command, //simplified as we aren't actually switching files @@ -1295,4 +1477,62 @@ public Response getFileVersionsList(@Context ContainerRequestContext crc, return ex.getResponse(); } } + + @GET + @AuthRequired + @Path("/erasedFiles") + @Produces({ MediaType.APPLICATION_JSON, "text/csv" }) + @Operation(summary = "List all erased files", + description = "Returns all erased files with their FileErasure details, optionally filtered by a date range. Superusers only. Returns CSV by default; use Accept: application/json for JSON.") + public Response listErasedFiles(@Context ContainerRequestContext crc, + @Parameter(description = "Start date filter (inclusive). Format: yyyy-MM-dd, yyyy-MM, or yyyy.") + @QueryParam("startDate") String startDate, + @Parameter(description = "End date filter (inclusive). Format: yyyy-MM-dd, yyyy-MM, or yyyy.") + @QueryParam("endDate") String endDate, + @Context HttpHeaders headers) { + try { + AuthenticatedUser user = getRequestAuthenticatedUserOrDie(crc); + if (!user.isSuperuser()) { + return error(Response.Status.FORBIDDEN, "Superusers only."); + } + } catch (WrappedResponse wr) { + return wr.getResponse(); + } + + Date start = null; + Date end = null; + if (startDate != null && !startDate.isEmpty()) { + start = DateUtil.parseDate(startDate); + if (start == null) { + return error(Response.Status.BAD_REQUEST, "Invalid startDate format. Use yyyy-MM-dd or yyyy-MM-dd'T'HH:mm:ss."); + } + } + if (endDate != null && !endDate.isEmpty()) { + end = DateUtil.parseDate(endDate); + if (end == null) { + return error(Response.Status.BAD_REQUEST, "Invalid endDate format. Use yyyy-MM-dd or yyyy-MM-dd'T'HH:mm:ss."); + } + } + + String jpql = buildErasedFilesJpql(null, start, end); + jakarta.persistence.Query query = em.createQuery(jpql); + setErasedFilesQueryParams(query, start, end); + + List erasedFiles = query.getResultList(); + + List acceptedTypes = headers.getAcceptableMediaTypes(); + boolean wantJson = acceptedTypes.stream() + .anyMatch(mt -> mt.toString().equals(MediaType.APPLICATION_JSON) || mt.toString().equals("*/*")); + + // Default to CSV when no specific type is requested or only CSV is requested + if (wantJson && !acceptedTypes.stream().anyMatch(mt -> mt.toString().equals("text/csv"))) { + return ok(toErasedFilesJsonArray(erasedFiles)); + } + String filename = buildErasedFilesCsvFilename(start, end, null); + return Response.ok() + .entity(toErasedFilesCsvString(erasedFiles, start, end, null)) + .type("text/csv") + .header("Content-Disposition", "attachment; filename=" + filename) + .build(); + } } diff --git a/src/main/java/edu/harvard/iq/dataverse/dataaccess/StorageIO.java b/src/main/java/edu/harvard/iq/dataverse/dataaccess/StorageIO.java index b009c4e86ec..6e36f93d07e 100644 --- a/src/main/java/edu/harvard/iq/dataverse/dataaccess/StorageIO.java +++ b/src/main/java/edu/harvard/iq/dataverse/dataaccess/StorageIO.java @@ -624,9 +624,18 @@ public static boolean isDirectUploadEnabled(String driverId) { //True by default, Stores (e.g. RemoteOverlay, Globus) can set this false to stop attempts to read bytes public static boolean isDataverseAccessible(String driverId) { - return (true && !Boolean.parseBoolean(StorageIO.getConfigParamForDriver(driverId, AbstractRemoteOverlayAccessIO.FILES_NOT_ACCESSIBLE_BY_DATAVERSE))); + return (!Boolean.parseBoolean(StorageIO.getConfigParamForDriver(driverId, AbstractRemoteOverlayAccessIO.FILES_NOT_ACCESSIBLE_BY_DATAVERSE))); } - + + //True by default, Stores (e.g. RemoteOverlay, Globus) return false to indicate Dataverse cannot write/delete files + public static boolean isDataverseWritable(String driverId) { + String driverType = DataAccess.getDriverType(driverId); + if (DataAccess.REMOTE.equals(driverType) || (DataAccess.GLOBUS.equals(driverType) && !StorageIO.isDataverseAccessible(driverId))) { + return false; + } + return true; + } + // Check that storageIdentifier is consistent with store's config // False will prevent direct uploads static boolean isValidIdentifier(String driverId, String storageId) { diff --git a/src/main/java/edu/harvard/iq/dataverse/engine/command/impl/EraseDataFileCommand.java b/src/main/java/edu/harvard/iq/dataverse/engine/command/impl/EraseDataFileCommand.java new file mode 100644 index 00000000000..3e56658fdd4 --- /dev/null +++ b/src/main/java/edu/harvard/iq/dataverse/engine/command/impl/EraseDataFileCommand.java @@ -0,0 +1,222 @@ +package edu.harvard.iq.dataverse.engine.command.impl; + +import edu.harvard.iq.dataverse.*; +import edu.harvard.iq.dataverse.authorization.Permission; +import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser; +import edu.harvard.iq.dataverse.dataaccess.DataAccess; +import edu.harvard.iq.dataverse.dataaccess.StorageIO; +import edu.harvard.iq.dataverse.engine.command.AbstractVoidCommand; +import edu.harvard.iq.dataverse.engine.command.CommandContext; +import edu.harvard.iq.dataverse.engine.command.DataverseRequest; +import edu.harvard.iq.dataverse.engine.command.RequiredPermissions; +import edu.harvard.iq.dataverse.engine.command.exception.CommandException; +import edu.harvard.iq.dataverse.engine.command.exception.CommandExecutionException; +import edu.harvard.iq.dataverse.engine.command.exception.PermissionException; +import edu.harvard.iq.dataverse.pidproviders.PidProvider; +import edu.harvard.iq.dataverse.pidproviders.PidUtil; +import edu.harvard.iq.dataverse.search.IndexServiceBean; +import edu.harvard.iq.dataverse.util.FileUtil; +import edu.harvard.iq.dataverse.util.StringUtil; +import java.io.IOException; +import java.util.Collections; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Erases a published data file's physical content from storage while retaining + * the DataFile database record with audit metadata about who erased it, when, and why. + * This supports GDPR "right to be forgotten" requests and similar compliance scenarios. + */ +@RequiredPermissions(Permission.EditDataset) +public class EraseDataFileCommand extends AbstractVoidCommand { + private static final Logger logger = Logger.getLogger(EraseDataFileCommand.class.getCanonicalName()); + + private final DataFile dataFile; + private final String reason; + private final boolean manualDeletionAsserted; + + public EraseDataFileCommand(DataFile dataFile, DataverseRequest aRequest, String reason, boolean manualDeletionAsserted) { + super(aRequest, dataFile.getOwner()); + this.dataFile = dataFile; + this.reason = reason; + this.manualDeletionAsserted = manualDeletionAsserted; + } + + @Override + protected void executeImpl(CommandContext ctxt) throws CommandException { + // 1. Check if the file is already erased + if (dataFile.getFileErasure() != null) { + throw new CommandExecutionException("File has already been erased.", this); + } + + // 2. Verify superuser + if (!getUser().isSuperuser()) { + throw new PermissionException("Erase can only be called by superusers.", + this, Collections.singleton(Permission.EditDataset), dataFile); + } + + // 3. Verify file is published using DvObject.isReleased() + if (!dataFile.isReleased()) { + throw new CommandExecutionException( + "Cannot erase file: the DataFile has not been published. Use delete for draft-only files.", this); + } + + // 4. Verify file is not harvested + if (dataFile.isHarvested()) { + throw new CommandExecutionException( + "Cannot erase harvested files. Erasure is not supported on harvested datasets.", this); + } + + // 5. Physical file deletion (within transaction) + if (!StringUtil.isEmpty(dataFile.getStorageIdentifier())) { + if (FileUtil.isPackageFile(dataFile)) { + // Package files are handled specially - they use local filesystem only + logger.info("Package file detected - physical deletion handled by caller for file " + dataFile.getId()); + } else { + try { + // Get storage location for direct access deletion + StorageIO storageIO = dataFile.getStorageIO(); + if (storageIO != null) { + storageIO.open(); + String storageLocation = storageIO.getStorageLocation(); + + // Delete auxiliary files first (uses getStorageIO which has dvObject set) + try { + storageIO.deleteAllAuxObjects(); + logger.log(Level.FINE, "Deleted auxiliary files for DataFile {0}", dataFile.getId()); + } catch (IOException ioex) { + logger.log(Level.WARNING, "Error deleting auxiliary files for DataFile {0}: {1}", + new Object[]{dataFile.getId(), ioex.getMessage()}); + } + + // Delete the main file if the store is writable by Dataverse + // Use getDirectStorageIO for deletion since delete() requires isDirectAccess() + if (!manualDeletionAsserted) { + StorageIO directStorageIO = DataAccess.getDirectStorageIO(storageLocation); + boolean physicalFileExists; + try { + physicalFileExists = directStorageIO.exists(); + } catch (IOException ioex) { + physicalFileExists = false; + } + + if (physicalFileExists) { + try { + directStorageIO.delete(); + logger.log(Level.FINE, "Deleted physical file for DataFile {0}", dataFile.getId()); + } catch (IOException ex) { + throw new CommandExecutionException( + "Error deleting physical file for DataFile " + dataFile.getId() + ": " + ex.getMessage(), ex, this); + } + } + } else { + // Manual deletion was asserted by the admin. If the store is readable by Dataverse, + // verify the file is actually gone. + String driverId = DataAccess.getStorageDriverFromIdentifier(dataFile.getStorageIdentifier()); + if (StorageIO.isDataverseAccessible(driverId)) { + StorageIO directStorageIO = DataAccess.getDirectStorageIO(storageLocation); + boolean physicalFileExists; + try { + physicalFileExists = directStorageIO.exists(); + } catch (IOException ioex) { + logger.log(Level.WARNING, "Could not verify file existence for DataFile {0}: {1}", + new Object[]{dataFile.getId(), ioex.getMessage()}); + physicalFileExists = false; + } + if (physicalFileExists) { + throw new CommandExecutionException( + "Manual deletion asserted but the file still exists in storage for DataFile " + dataFile.getId(), this); + } + logger.log(Level.INFO, "Verified file {0} is deleted from storage", dataFile.getId()); + } else { + logger.log(Level.INFO, "Manual deletion confirmed for file {0} - store is not readable by Dataverse, cannot verify", dataFile.getId()); + } + } + } + } catch (IOException ioex) { + throw new CommandExecutionException("Failed to initialize physical access driver.", ioex, this); + } + } + } + + // 6. Create FileErasure entity + FileErasure fileErasure = new FileErasure(); + fileErasure.setDataFile(dataFile); + fileErasure.setErasedBy((AuthenticatedUser) getUser()); + fileErasure.setReason(reason); + fileErasure.setManuallyDeleted(manualDeletionAsserted); + ctxt.em().persist(fileErasure); + dataFile.setFileErasure(fileErasure); + + // 8. Update PID status if file has a persistent identifier + GlobalId pid = dataFile.getGlobalId(); + if (pid != null) { + PidProvider pidProvider = PidUtil.getPidProvider(pid.getProviderId()); + try { + // PID status update is handled by the caller after erasure + logger.log(Level.INFO, "PID update deferred for DataFile {0}", dataFile.getId()); + } catch (Exception e) { + logger.log(Level.WARNING, "Failed to update PID status for DataFile {0}: {1}", + new Object[]{dataFile.getId(), e.getMessage()}); + } + } + + // 9. Remove the file's FileMetadata from the latest version if it is a draft + Dataset dataset = dataFile.getOwner(); + DatasetVersion latestVersion = dataset.getLatestVersion(); + if (latestVersion != null && latestVersion.isWorkingCopy()) { + for (FileMetadata fm : dataFile.getFileMetadatas()) { + if (fm.getDatasetVersion().getId().equals(latestVersion.getId())) { + DatasetVersion mergedDraft = ctxt.em().merge(latestVersion); + mergedDraft.getFileMetadatas().remove(fm); + ctxt.em().remove(ctxt.em().merge(fm)); + logger.log(Level.INFO, "Removed FileMetadata from draft version {0} for DataFile {1}", + new Object[]{latestVersion.getId(), dataFile.getId()}); + break; + } + } + } + + // 10. Set ingest status to none + dataFile.setIngestStatus(DataFile.INGEST_STATUS_NONE); + } + + @Override + public String describe() { + StringBuilder sb = new StringBuilder(); + sb.append(super.describe()); + sb.append("Erase DataFile:"); + sb.append(dataFile.getId()); + sb.append(" Reason: '"); + sb.append(reason); + sb.append("'"); + return sb.toString(); + } + + @Override + public boolean onSuccess(CommandContext ctxt, Object r) { + // Update storage usage counters + if (!dataFile.isHarvested()) { + long storedSize = dataFile.getFilesize(); + Long savedOriginalSize = dataFile.getOriginalFileSize(); + if (savedOriginalSize != null) { + storedSize = storedSize > 0 ? storedSize + savedOriginalSize : savedOriginalSize; + } + if (storedSize > 0) { + ctxt.storageUse().incrementStorageSizeRecursively(dataFile.getOwner().getId(), (0L - storedSize)); + } + } + + // Remove Solr documents for the file (both published and draft variants) + String indexingResult = ctxt.index().removeSolrDocFromIndex( + IndexServiceBean.solrDocIdentifierFile + dataFile.getId()); + String indexingResult2 = ctxt.index().removeSolrDocFromIndex( + IndexServiceBean.solrDocIdentifierFile + dataFile.getId() + IndexServiceBean.draftSuffix); + String indexingResult3 = ctxt.index().removeSolrDocFromIndex( + IndexServiceBean.solrDocIdentifierFile + dataFile.getId() + IndexServiceBean.draftSuffix + + IndexServiceBean.discoverabilityPermissionSuffix); + + logger.log(Level.INFO, "File erasure completed for DataFile {0}", dataFile.getId()); + return true; + } +} diff --git a/src/main/java/edu/harvard/iq/dataverse/engine/command/impl/FinalizeDatasetPublicationCommand.java b/src/main/java/edu/harvard/iq/dataverse/engine/command/impl/FinalizeDatasetPublicationCommand.java index be47861316f..5e6fdacd2a7 100644 --- a/src/main/java/edu/harvard/iq/dataverse/engine/command/impl/FinalizeDatasetPublicationCommand.java +++ b/src/main/java/edu/harvard/iq/dataverse/engine/command/impl/FinalizeDatasetPublicationCommand.java @@ -365,6 +365,11 @@ private void validateDataFiles(Dataset dataset, CommandContext ctxt) throws Comm long datasetSize = DatasetUtil.getDownloadSizeNumeric(dataset.getLatestVersion(), false); if (maxDatasetSize == -1 || datasetSize < maxDatasetSize) { for (DataFile dataFile : dataset.getFiles()) { + // Skip erased files — their physical content no longer exists, so checksum validation is not applicable + if (FileUtil.isErased(dataFile)) { + logger.fine("Checksum Validation skipped for erased datafile: " + dataFile.getId()); + continue; + } // TODO: Should we validate all the files in the dataset, or only // the files that haven't been published previously? // (the decision was made to validate all the files on every diff --git a/src/main/java/edu/harvard/iq/dataverse/util/DateUtil.java b/src/main/java/edu/harvard/iq/dataverse/util/DateUtil.java index 669780b9436..8e21e85c029 100644 --- a/src/main/java/edu/harvard/iq/dataverse/util/DateUtil.java +++ b/src/main/java/edu/harvard/iq/dataverse/util/DateUtil.java @@ -65,30 +65,33 @@ public static String formatDate(Timestamp datetimeToformat) { } } + /** + * Parse a date string accepting common API date formats. + * Tries "yyyy-MM-dd", "yyyy-MM", and "yyyy" patterns. + * @param dateString the date string to parse + * @return a Date object, or null if no format matched or input is null/empty + */ public static Date parseDate(String dateString) { - SimpleDateFormat sdf; - Date date; + if (dateString == null || dateString.isEmpty()) { + return null; + } - // YYYY-MM-DD - date = parseDate(dateString, YEAR_DASH_MONTH_DASH_DAY_PATTERN); + // Fall back to date-only format: yyyy-MM-dd + Date date = parseDate(dateString, YEAR_DASH_MONTH_DASH_DAY_PATTERN); if (date != null) { return date; } - - // YYYY-MM + // Try year-month pattern: yyyy-MM date = parseDate(dateString, YEAR_DASH_MONTH_PATTERN); if (date != null) { return date; } - - // YYYT - date = parseDate(dateString, YEAR_PATTERN); - return date; - + // Try year-only pattern: yyyy + return parseDate(dateString, YEAR_PATTERN); } public static Date parseDate(String dateString, String format) { - + try { SimpleDateFormat sdf = new SimpleDateFormat(format); Date date = sdf.parse(dateString); diff --git a/src/main/java/edu/harvard/iq/dataverse/util/FileUtil.java b/src/main/java/edu/harvard/iq/dataverse/util/FileUtil.java index 6ac4a3225fc..3d0344d0978 100644 --- a/src/main/java/edu/harvard/iq/dataverse/util/FileUtil.java +++ b/src/main/java/edu/harvard/iq/dataverse/util/FileUtil.java @@ -1255,6 +1255,9 @@ public static boolean isPubliclyDownloadable(FileMetadata fileMetadata) { if (isRetentionExpired(fileMetadata)) { return false; } + if (isErased(fileMetadata)) { + return false; + } boolean popupReasons = isDownloadPopupRequired(fileMetadata.getDatasetVersion()); if (popupReasons == true) { /** @@ -1876,6 +1879,23 @@ public static boolean isRetentionExpired(List fmdList) { return false; } + public static boolean isErased(DataFile df) { + return df.getFileErasure() != null; + } + + public static boolean isErased(FileMetadata fileMetadata) { + return isErased(fileMetadata.getDataFile()); + } + + public static boolean isErased(List fmdList) { + for (FileMetadata fmd : fmdList) { + if (isErased(fmd)) { + return true; + } + } + return false; + } + public static String getStorageDriver(DataFile dataFile) { String storageIdentifier = dataFile.getStorageIdentifier(); return storageIdentifier.substring(0, storageIdentifier.indexOf(DataAccess.SEPARATOR)); diff --git a/src/main/java/edu/harvard/iq/dataverse/util/json/JsonPrinter.java b/src/main/java/edu/harvard/iq/dataverse/util/json/JsonPrinter.java index 4b96c262275..4508d398ee8 100644 --- a/src/main/java/edu/harvard/iq/dataverse/util/json/JsonPrinter.java +++ b/src/main/java/edu/harvard/iq/dataverse/util/json/JsonPrinter.java @@ -1096,6 +1096,7 @@ public static JsonObjectBuilder json(DataFile df, FileMetadata fileMetadata, boo JsonObjectBuilder embargo = df.getEmbargo() != null ? JsonPrinter.json(df.getEmbargo()) : null; JsonObjectBuilder retention = df.getRetention() != null ? JsonPrinter.json(df.getRetention()) : null; + JsonObjectBuilder fileErasure = df.getFileErasure() != null ? JsonPrinter.json(df.getFileErasure()) : null; NullSafeJsonBuilder builder = jsonObjectBuilder() .add("id", df.getId()) @@ -1109,6 +1110,7 @@ public static JsonObjectBuilder json(DataFile df, FileMetadata fileMetadata, boo .add("categories", getFileCategories(fileMetadata)) .add("embargo", embargo) .add("retention", retention) + .add("fileErasure", fileErasure) //.add("released", df.isReleased()) .add("storageIdentifier", df.getStorageIdentifier()) .add("originalFileFormat", df.getOriginalFileFormat()) @@ -1561,6 +1563,18 @@ public static JsonObjectBuilder json(Retention retention) { retention.getReason()); } + public static JsonObjectBuilder json(FileErasure fileErasure) { + JsonObjectBuilder builder = jsonObjectBuilder() + .add("erasedOn", format(fileErasure.getErasedOn())) + .add("reason", fileErasure.getReason()) + .add("manuallyDeleted", fileErasure.isManuallyDeleted()); + AuthenticatedUser eraser = fileErasure.getErasedBy(); + if (eraser != null) { + builder.add("erasedBy", jsonObjectBuilder().add("identifier", eraser.getIdentifier()).add("name", eraser.getName())); + } + return builder; + } + public static JsonObjectBuilder json(License license) { return jsonObjectBuilder() diff --git a/src/main/java/propertyFiles/Bundle.properties b/src/main/java/propertyFiles/Bundle.properties index 9362a2c69bc..e6e651a3c00 100644 --- a/src/main/java/propertyFiles/Bundle.properties +++ b/src/main/java/propertyFiles/Bundle.properties @@ -1802,7 +1802,7 @@ dataset.metadata.invalidGeospatialCoordinates=has invalid coordinates. East must dataset.metadata.invalidInteger=is not a valid integer. dataset.metadata.invalidURL=is not a valid URL. dataset.metadata.invalidEmail=is not a valid email address. -file.metadata.preview=Preview +file.metadata.preview=Thumbnail file.metadata.filetags=File Tags file.metadata.persistentId=File Persistent ID file.metadata.persistentId.tip=The unique persistent identifier for a file, which can be a Handle or DOI in Dataverse. @@ -1824,11 +1824,10 @@ dataset.noSelectedFilesForRequestAccess=Please select a file or files for access dataset.embargoedSelectedFilesForRequestAccess=Embargoed files cannot be accessed. Please select an unembargoed file or files for your access request. dataset.inValidSelectedFilesForDownload=Inaccessible Files Selected dataset.inValidSelectedFilesForDownloadWithEmbargo=Inaccessible Files Selected -dataset.inValidSelectedFilesForTransferWithEmbargo=Inaccessible Files Selected -dataset.noValidSelectedFilesForDownload=The selected file(s) may not be downloaded because you have not been granted access or the file(s) have a retention period that has expired or the files can only be transferred via Globus. +dataset.noValidSelectedFilesForDownload=The selected file(s) may not be downloaded because you have not been granted access or the file(s) have a retention period that has expired or have been erased or the files can only be transferred via Globus. dataset.noValidSelectedFilesForTransfer=The selected file(s) may not be transferred because you have not been granted access or the file(s) have a retention period that has expired or the files are not Globus accessible. dataset.mixedSelectedFilesForDownload=The selected file(s) may not be downloaded because you have not been granted access or the file(s) have a retention period that has expired. -dataset.mixedSelectedFilesForDownloadWithEmbargo=Any embargoed and/or restricted file(s) selected may not be downloaded because you have not been granted access. Some files may have a retention period that has expired. Some files may only be accessible via Globus. +dataset.mixedSelectedFilesForDownloadWithEmbargo=Any embargoed and/or restricted file(s) selected may not be downloaded because you have not been granted access. Some files may have a retention period that has expired. Some files may have been erased. Some files may only be accessible via Globus. dataset.mixedSelectedFilesForTransfer=Some file(s) cannot be transferred. (They are restricted, embargoed, with an expired retention period, or not Globus accessible.) dataset.inValidSelectedFilesForTransfer=Ineligible Files Selected dataset.downloadUnrestricted=Click Continue to download the files you have access to download. @@ -2269,7 +2268,25 @@ file.results.presort.change.success=Grouping of Files in File Table updated. file.compute.fileAccessDenied=This file is restricted and you may not compute on it because you have not been granted access. file.configure.Button=Configure -file.remotelyStored=This file is stored remotely - click for more info +file.remotelyStored=This file is stored remotely - click for more info + +file.erased=Erased +file.erased.reason=Reason +file.erased.on=Erased + +file.erased.csv.header.fileId=File ID +file.erased.csv.header.filePid=File PID +file.erased.csv.header.fileName=File Name +file.erased.csv.header.erasureId=Erasure ID +file.erased.csv.header.erasedOn=Erased On +file.erased.csv.header.reason=Reason +file.erased.csv.header.manuallyDeleted=Manually Deleted +file.erased.csv.header.eraserIdentifier=Erased By Identifier +file.erased.csv.header.eraserName=Erased By Name +file.erased.csv.metadata.generatedOn=Generated On +file.erased.csv.metadata.startDate=Start Date +file.erased.csv.metadata.endDate=End Date +file.erased.csv.metadata.scopeId=Scope ID file.auxfiles.download.header=Download Auxiliary Files # These types correspond to the AuxiliaryFile.Type enum. diff --git a/src/main/resources/db/migration/V6.12.1.2__file-erasure-table.sql b/src/main/resources/db/migration/V6.12.1.2__file-erasure-table.sql new file mode 100644 index 00000000000..a430b8eea67 --- /dev/null +++ b/src/main/resources/db/migration/V6.12.1.2__file-erasure-table.sql @@ -0,0 +1,10 @@ +-- Create the FILEERASURE table to track file erasure audit records +CREATE TABLE IF NOT EXISTS FILEERASURE ( + id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, + datafile_id BIGINT UNIQUE REFERENCES DATAFILE(id), + erased_by_id BIGINT REFERENCES AUTHENTICATEDUSER(id), + erased_on TIMESTAMP NOT NULL, + reason TEXT, + manually_deleted BOOLEAN NOT NULL DEFAULT false +); + diff --git a/src/main/webapp/file-download-button-fragment.xhtml b/src/main/webapp/file-download-button-fragment.xhtml index 112c2525de8..08e8a88ea16 100644 --- a/src/main/webapp/file-download-button-fragment.xhtml +++ b/src/main/webapp/file-download-button-fragment.xhtml @@ -13,19 +13,28 @@ -
  • - - - - -
  • + +
  • + + +
  • +
    + +
  • + + + + +
  • +
    + and !dataFileServiceBean.isRetentionExpired(fileMetadata) + and empty fileMetadata.dataFile.fileErasure}"> + @@ -43,7 +44,7 @@ - +
  • - +
  • - +
  • +
  • +
  • + @@ -84,6 +85,7 @@ +
    diff --git a/src/main/webapp/file.xhtml b/src/main/webapp/file.xhtml index 2ca812f0e97..19774a2f0f4 100644 --- a/src/main/webapp/file.xhtml +++ b/src/main/webapp/file.xhtml @@ -23,6 +23,7 @@ + @@ -75,6 +76,7 @@ + @@ -485,7 +487,7 @@