diff --git a/docs/VERSION_HISTORY.md b/docs/VERSION_HISTORY.md new file mode 100644 index 0000000..6b8a34e --- /dev/null +++ b/docs/VERSION_HISTORY.md @@ -0,0 +1,70 @@ +# Object version history and restore + +Version history inspects one exact object key and restores an older data version by creating a new current version at that key. Restoring never deletes historical versions or delete markers. It does not enable bucket versioning automatically. + +## Workflow + +1. Open **Version history** from a file's context menu or the bucket toolbar. The toolbar also finds deleted objects that are absent from ordinary browsing. With one selected key it starts there; otherwise it starts with the current folder prefix. +2. Enter the full **Exact object key**, including folders, and choose **Load history** or press Enter. Keys are case-sensitive and must contain 1 to 1,024 bytes. This is an exact lookup, not a folder or prefix history search. A supplied file key loads automatically; a folder prefix does not. +3. Inspect the version ID, state, modification time and size. States distinguish **Current**, **Older version**, **Current deletion** and **Delete marker**. Delete markers have no content size. Missing or invalid dates show **Not provided**. +4. Use **Previous** and **Next** to inspect history. Requests ask for up to 100 entries per page, with a maximum of 100 loaded pages. Nearby keys returned by the provider's prefix listing are excluded. The interface reports the 10,000-entry limit and directs older-history inspection to provider tools. **Refresh** reloads the history. +5. Select an older data version, then check the explicit confirmation that a new current version will be created and existing versions and delete markers will remain. Current versions and delete markers cannot be selected for restore. Changing the key, loading or changing pages, or selecting another version resets confirmation. +6. Choose **Restore selected version**. Restore is available only while bucket versioning is **Enabled**. Disabled or suspended buckets remain read-only. A current delete marker allows recovery from an older readable data version without removing that marker. +7. After successful preparation, the dialog closes and a toast directs you to **Uploads**. The **Version restore** transfer group shows progress and supports the queue's cancellation and retry controls. Queueing is not completion; inspect the transfer result. + +A failed preparation clears the selection and history so that the next attempt requires loading and confirming again. A stale current version requires a fresh history lookup and confirmation. Retries retain the originally approved source version and destination guard, so they do not silently approve a newer destination. After an app restart or profile settings change, create a fresh restore from history. + +## UI conventions + +This is a narrow extension of the existing MUI interface. It uses `BaseDialog`, `StyledCheckbox`, small fully rounded buttons, and the existing theme. Secondary actions use the primary text color; the contained footer action is the restore action. + +The medium-width dialog presents the key input and lookup action first, then the `s3://` object context, status and history table, selected-version confirmation, and footer actions. The fixed-layout table wraps long keys and version IDs. Selected rows and **Selected** labels identify the choice; selection buttons also expose `aria-pressed` and a version-specific accessible name. Progress has a status role, errors and warnings use alerts, and the confirmation is explicitly labelled. Closing is disabled while restore preparation is queueing the job. + +## Contents and attributes + +The selected historical version supplies bytes and these portable content attributes: content type, cache control, content disposition, content encoding, content language, and custom metadata. + +For an existing object, the workflow reads the current destination and carries forward its ACL grants, tags, storage class, server-side encryption settings, KMS key and bucket-key setting, object-lock retention and legal-hold fields, website redirect, and expiry. Historical security settings are not copied over current settings. These are the readable, supported fields exposed by the provider; the operation does not change bucket policies. + +For a currently deleted object, only the historical bytes and portable content attributes are supplied. Ownership, security, storage and retention use the destination bucket's defaults, and historical ACLs and tags are not resurrected. + +Restoration downloads the selected object to a private temporary file on this computer and uploads it back to the same key. It requires temporary disk space for the object and uses this computer's network connection. Progress accounts for both download and upload, so the transfer total is twice the object size. Request, download, upload and storage charges may apply. The temporary file is released when the attempt ends; failed or cancelled multipart uploads attempt an abort. Cleanup depends on endpoint availability and permissions. + +## Safety checks and limits + +- History validates pagination markers, rejects missing version IDs and repeated cursors, and filters results to the exact key. History loading and restore preparation have bounded timeouts. +- Preparation requires explicit confirmation, an older version ID, a known current version, and enabled versioning. It checks the selected version with a version-specific `HeadObject`. +- Download uses both the selected `versionId` and `If-Match` with its ETag. Returned version ID, ETag and content length must match, and incomplete downloads are rejected before upload. +- The current version ID, deletion state, ETag and bucket versioning are checked before staging and again before the final write. Reading the current object's attributes also checks its version ID. +- Single-part `PutObject` and multipart completion use `If-Match` for an existing destination or `If-None-Match: *` for deleted-object recovery. No unconditional write fallback is used. +- S3 conditional writes compare ETags, not version IDs. A concurrent identical-content or metadata-only write in the gap after the final check can retain the same ETag and cannot be atomically guarded by this workflow. Attribute-only updates can also occur without creating a new version. Avoid concurrent edits while restoring. +- A change to bucket versioning after the final check cannot be atomically prevented. Do not suspend or otherwise change bucket versioning during a restore. +- A cancellation or lost response can race with a server committing the write. Inspect current history before deciding whether another restore is needed. + +These checks rely on the provider correctly implementing version listing, version-specific reads and conditional writes. They are not universal guarantees for every S3-compatible endpoint. Unsupported APIs, unreadable archived versions, access denials, missing safety information and SSE-C objects fail the operation. This workflow does not initiate archive retrieval or accept customer-provided encryption keys. + +## Permissions and provider compatibility + +History calls `GetBucketVersioning` and `ListObjectVersions`, corresponding to AWS-style `s3:GetBucketVersioning` and `s3:ListBucketVersions` access. Restore also needs version-specific `HeadObject` and `GetObject` access, normally `s3:GetObjectVersion`, and destination write access through `PutObject` or multipart upload operations. + +For an existing destination, preservation additionally reads its current `HeadObject` and version-specific `GetObjectAcl` and `GetObjectTagging`. AWS-style policies may require `s3:GetObject`, `s3:GetObjectVersionAcl` and `s3:GetObjectVersionTagging`, plus `s3:PutObjectAcl` and `s3:PutObjectTagging` to carry those values into the new object. Object-lock and encryption settings may require their corresponding read/write permissions and KMS decrypt or data-key permissions. Multipart failure cleanup needs `s3:AbortMultipartUpload`. Exact policy requirements depend on the endpoint and its bucket configuration. + +Permission errors fail closed rather than discarding current permissions or tags. Only explicitly classified unsupported ACL/tag APIs are omitted. The exact documented empty MinIO placeholder ACL is accepted as carrying no object grants. An explicit `AccessControlListNotSupported` write response can retry without ACL grants for bucket-owner-enforced behavior, retaining conditional-write protection and the other attributes. Other ACL failures are not treated as permission to weaken access. + +The production restore path does not require historical-delete permission, call `DeleteObject`, remove delete markers, or call `PutBucketVersioning`. + +## Validation and development + +The implementation passed the Rust, frontend, browser and release checks, plus lint, Clippy and build validation during this change. A disposable MinIO integration run passed restore of existing and deleted keys with payloads of 0 bytes, 5 bytes and 129 MiB. It checked restored content metadata, preservation of current tags and historical entries, rejection of stale guards, and absence of unfinished multipart uploads. This does not establish live AWS S3 or Cloudflare R2 compatibility; neither was tested live for this change. + +The Rust integration test `version_restore_real_endpoint_preserves_history_and_rejects_stale_guards` is ignored by default and explicitly opt-in through `BROWS3_VERSION_TEST_ENDPOINT`. Run it only against a dedicated temporary MinIO instance configured with the test credentials `versiontest` / `version-test-only`. It creates a unique `brows3-version-test-` bucket, enables versioning, and deletes its own test versions and bucket on successful cleanup. Never point it at user data or a production endpoint. + +Implementation sources: + +- `src/components/dialogs/VersionHistoryDialog.tsx`: interaction, confirmation and history pagination. +- `src/app/bucket/page.tsx`: toolbar and file context-menu entry points. +- `src-tauri/src/commands/versions.rs`: profile checks, preflight and queue creation. +- `src-tauri/src/s3/versions.rs`: exact-key history and restore guards. +- `src-tauri/src/transfer/remote.rs`: version-pinned reads and temporary staging. +- `src-tauri/src/transfer/manager.rs`: guarded uploads, queue integration and integration tests. +- `src-tauri/src/transfer/sync.rs`: destination attribute preservation. diff --git a/src-tauri/src/commands/cross_copy.rs b/src-tauri/src/commands/cross_copy.rs index f686cc7..cae8a1e 100644 --- a/src-tauri/src/commands/cross_copy.rs +++ b/src-tauri/src/commands/cross_copy.rs @@ -192,6 +192,7 @@ pub async fn copy_between_profiles( region: item.region.clone(), key, etag, + version_id: None, size, current_session: true, }); diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index 755828a..211a274 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -6,6 +6,7 @@ pub mod operations; pub mod profiles; pub mod sync; pub mod transfer; +pub mod versions; #[cfg(test)] pub(crate) mod test_s3; diff --git a/src-tauri/src/commands/versions.rs b/src-tauri/src/commands/versions.rs new file mode 100644 index 0000000..b473300 --- /dev/null +++ b/src-tauri/src/commands/versions.rs @@ -0,0 +1,232 @@ +use super::{profiles::ProfileState, transfer::TransferState}; +use crate::{ + credentials::Profile, + error::{AppError, Result}, + s3::{ + versions::{self, Cursor, History, RestoreGuard}, + S3State, + }, + transfer::{ + remote::{self, RemoteSource}, + TransferJob, TransferStatus, TransferType, + }, +}; +use aws_sdk_s3::{error::DisplayErrorContext, Client}; +use std::{path::PathBuf, time::Duration}; +use tauri::{AppHandle, State}; + +async fn selected(profiles: &ProfileState, expected: &str) -> Result { + let profile = profiles + .read() + .await + .get_active_profile() + .await? + .ok_or_else(|| AppError::ConfigError("Select a profile.".into()))?; + super::operations::validate_operation_profile(Some(expected), &profile.id)?; + Ok(profile) +} +async fn client(s3: &S3State, profile: &Profile, region: &str) -> Result { + Ok(s3 + .write() + .await + .get_client_for_region(profile, region) + .await? + .clone()) +} + +#[allow(clippy::too_many_arguments)] +#[tauri::command] +pub async fn list_object_versions( + bucket: String, + region: String, + key: String, + cursor: Option, + expected_profile_id: String, + profile_state: State<'_, ProfileState>, + s3_state: State<'_, S3State>, +) -> Result { + versions::validate_key(&key)?; + let profile = selected(profile_state.inner(), &expected_profile_id).await?; + let client = client(s3_state.inner(), &profile, ®ion).await?; + let result = tokio::time::timeout(Duration::from_secs(60), async { + let versioning = versions::versioning(&client, &bucket).await?; + let (versions, next) = versions::page(&client, &bucket, &key, cursor, 100).await?; + Ok::<_, AppError>(History { + versioning, + versions, + next, + }) + }) + .await + .map_err(|_| AppError::S3Error("Loading history timed out. Try again.".into()))??; + if selected(profile_state.inner(), &expected_profile_id) + .await? + .cache_identity() + != profile.cache_identity() + { + return Err(AppError::ConfigError( + "Profile settings changed. Load history again.".into(), + )); + } + Ok(result) +} + +pub(crate) async fn prepare_restore( + client: &Client, + bucket: &str, + key: &str, + version_id: &str, + expected_current_version: &str, + confirmed: bool, +) -> Result<(RestoreGuard, String, u64)> { + versions::validate_key(key)?; + if !confirmed + || version_id.is_empty() + || expected_current_version.is_empty() + || version_id == expected_current_version + { + return Err(AppError::ConfigError( + "Select an older data version and confirm the restore.".into(), + )); + } + tokio::time::timeout(Duration::from_secs(60), async { + let latest = versions::current(client, bucket, key).await?; + let guard = RestoreGuard { current_version: expected_current_version.into(), current_etag: latest.etag, deleted: latest.is_delete_marker }; + versions::validate_restore(client, bucket, key, &guard).await?; + let head = client.head_object().bucket(bucket).key(key).version_id(version_id).send().await + .map_err(|e| AppError::S3Error(format!("Cannot restore this version. Delete markers, archived or inaccessible versions cannot be read: {}", DisplayErrorContext(&e))))?; + if head.delete_marker().unwrap_or(false) || head.version_id() != Some(version_id) { + return Err(AppError::S3Error("Provider did not return the selected data version.".into())); + } + let (etag, size) = remote::validate_head(&head)?; + Ok((guard, etag, size)) + }).await.map_err(|_| AppError::S3Error("Restore preparation timed out; nothing was queued.".into()))? +} + +#[allow(clippy::too_many_arguments)] +#[tauri::command] +pub async fn restore_object_version( + bucket: String, + region: String, + key: String, + version_id: String, + expected_current_version: String, + confirmed: bool, + expected_profile_id: String, + profile_state: State<'_, ProfileState>, + s3_state: State<'_, S3State>, + transfer_state: State<'_, TransferState>, + app_handle: AppHandle, +) -> Result { + let profile = selected(profile_state.inner(), &expected_profile_id).await?; + let client = client(s3_state.inner(), &profile, ®ion).await?; + let (guard, etag, size) = prepare_restore( + &client, + &bucket, + &key, + &version_id, + &expected_current_version, + confirmed, + ) + .await?; + if selected(profile_state.inner(), &expected_profile_id) + .await? + .cache_identity() + != profile.cache_identity() + { + return Err(AppError::ConfigError( + "Profile settings changed. Refresh history and confirm again.".into(), + )); + } + let mut job = TransferJob::new( + TransferType::Upload, + profile.id.clone(), + bucket.clone(), + Some(region.clone()), + key.clone(), + PathBuf::new(), + size * 2, + ) + .with_group(uuid::Uuid::new_v4().to_string(), "Version restore".into()); + job.remote_source = Some(RemoteSource { + profile_id: profile.id.clone(), + profile_identity: profile.cache_identity(), + destination_identity: profile.cache_identity(), + bucket, + region, + key, + etag, + size, + version_id: Some(version_id), + current_session: true, + }); + job.restore_guard = Some(guard); + let id = job.id.clone(); + transfer_state.set_app_handle(app_handle).await; + transfer_state.add_job(job).await; + if let Some(job) = transfer_state.get_job(&id).await { + if let TransferStatus::Failed(error) = job.status { + return Err(AppError::IoError(error)); + } + } + transfer_state + .inner() + .clone() + .process_queue(s3_state.inner().clone(), profile_state.inner().clone()) + .await; + Ok(id) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::commands::test_s3::{response, scripted_client}; + #[tokio::test] + async fn restore_requires_confirmation_and_a_different_version_before_requests() { + let (client, server) = scripted_client(vec![]).await; + assert!( + prepare_restore(&client, "bucket", "file", "older", "current", false) + .await + .is_err() + ); + assert!( + prepare_restore(&client, "bucket", "file", "current", "current", true) + .await + .is_err() + ); + assert!(server.await.unwrap().is_empty()); + } + #[tokio::test] + async fn restore_preflight_pins_selected_version_and_never_writes() { + let listing = "falsefilecurrenttrue"now""; + for returned_version in ["old+version", "wrong"] { + let head = format!("HTTP/1.1 200 OK\r\nContent-Length: 5\r\nETag: \"old\"\r\nx-amz-version-id: {returned_version}\r\nConnection: close\r\n\r\n"); + let (client, server) = scripted_client(vec![ + response(200, "", listing), + response( + 200, + "", + "Enabled", + ), + response(200, "", listing), + head, + ]) + .await; + let prepared = + prepare_restore(&client, "bucket", "file", "old+version", "current", true).await; + if returned_version == "old+version" { + let (guard, etag, size) = prepared.unwrap(); + assert_eq!(guard.current_etag.as_deref(), Some("\"now\"")); + assert_eq!(etag, "\"old\""); + assert_eq!(size, 5); + } else { + assert!(prepared.is_err()); + } + let requests = server.await.unwrap(); + assert!(requests.last().unwrap().contains("versionId=old%2Bversion")); + assert!(requests + .iter() + .all(|r| r.starts_with("GET ") || r.starts_with("HEAD "))); + } + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index b100c46..e196142 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -317,6 +317,8 @@ pub fn run() { commands::sync::preview_folder_sync, commands::sync::start_folder_sync, commands::cross_copy::copy_between_profiles, + commands::versions::list_object_versions, + commands::versions::restore_object_version, transfer_cmd::queue_upload, transfer_cmd::queue_download, transfer_cmd::list_transfers, diff --git a/src-tauri/src/s3/mod.rs b/src-tauri/src/s3/mod.rs index c7c6cb6..7662396 100644 --- a/src-tauri/src/s3/mod.rs +++ b/src-tauri/src/s3/mod.rs @@ -2,6 +2,7 @@ pub mod client; pub mod content_type; pub mod listing; pub mod multipart; +pub mod versions; pub use client::{ format_size, get_bucket_region, list_buckets, BucketInfo, FolderContent, S3ClientManager, diff --git a/src-tauri/src/s3/versions.rs b/src-tauri/src/s3/versions.rs new file mode 100644 index 0000000..72c12a4 --- /dev/null +++ b/src-tauri/src/s3/versions.rs @@ -0,0 +1,265 @@ +use crate::error::{AppError, Result}; +use aws_sdk_s3::{error::DisplayErrorContext, Client}; +use serde::{Deserialize, Serialize}; +use std::time::Duration; + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +pub struct Cursor { + pub key_marker: String, + pub version_id_marker: String, +} +#[derive(Clone, Debug, Serialize)] +pub struct Version { + pub version_id: String, + pub is_latest: bool, + pub is_delete_marker: bool, + pub size: Option, + pub modified: Option, + pub etag: Option, +} +#[derive(Serialize)] +pub struct History { + pub versioning: String, + pub versions: Vec, + pub next: Option, +} +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct RestoreGuard { + pub current_version: String, + pub current_etag: Option, + pub deleted: bool, +} + +pub async fn versioning(client: &Client, bucket: &str) -> Result { + let output = client.get_bucket_versioning().bucket(bucket).send().await + .map_err(|e| AppError::S3Error(format!("Cannot read bucket versioning. Check GetBucketVersioning permission and provider support: {}", DisplayErrorContext(&e))))?; + Ok(output + .status() + .map_or("Disabled", |s| s.as_str()) + .to_owned()) +} +pub fn validate_key(key: &str) -> Result<()> { + if key.is_empty() || key.len() > 1024 { + return Err(AppError::ConfigError( + "Enter an exact object key of 1 to 1,024 bytes.".into(), + )); + } + Ok(()) +} +pub async fn page( + client: &Client, + bucket: &str, + key: &str, + cursor: Option, + limit: i32, +) -> Result<(Vec, Option)> { + validate_key(key)?; + if cursor + .as_ref() + .is_some_and(|c| c.key_marker != key || c.version_id_marker.is_empty()) + { + return Err(AppError::ConfigError( + "Invalid history cursor. Load the history again.".into(), + )); + } + let output = client.list_object_versions().bucket(bucket).prefix(key).max_keys(limit) + .set_key_marker(cursor.as_ref().map(|c| c.key_marker.clone())) + .set_version_id_marker(cursor.as_ref().map(|c| c.version_id_marker.clone())).send().await + .map_err(|e| AppError::S3Error(format!("Cannot list versions. Check ListBucketVersions permission and provider support: {}", DisplayErrorContext(&e))))?; + let mut versions = Vec::new(); + for v in output.versions().iter().filter(|v| v.key() == Some(key)) { + versions.push(Version { + version_id: required_id(v.version_id())?, + is_latest: v.is_latest().unwrap_or(false), + is_delete_marker: false, + size: v.size().and_then(|n| u64::try_from(n).ok()), + modified: v.last_modified().map(ToString::to_string), + etag: v.e_tag.clone(), + }); + } + for v in output + .delete_markers() + .iter() + .filter(|v| v.key() == Some(key)) + { + versions.push(Version { + version_id: required_id(v.version_id())?, + is_latest: v.is_latest().unwrap_or(false), + is_delete_marker: true, + size: None, + modified: v.last_modified().map(ToString::to_string), + etag: None, + }); + } + versions.sort_by(|a, b| { + b.is_latest + .cmp(&a.is_latest) + .then_with(|| b.modified.cmp(&a.modified)) + .then_with(|| a.version_id.cmp(&b.version_id)) + }); + let next = if output.is_truncated().unwrap_or(false) { + let marker = output + .next_key_marker() + .filter(|m| !m.is_empty()) + .ok_or_else(|| AppError::S3Error("Incomplete history: missing key marker.".into()))?; + if marker < key { + return Err(AppError::S3Error("History cursor moved backwards.".into())); + } + if marker == key { + let next = Cursor { + key_marker: marker.into(), + version_id_marker: required_id(output.next_version_id_marker())?, + }; + if cursor.as_ref() == Some(&next) { + return Err(AppError::S3Error( + "History cursor repeated. Refresh the history.".into(), + )); + } + Some(next) + } else { + None + } + } else { + None + }; + Ok((versions, next)) +} +fn required_id(id: Option<&str>) -> Result { + id.filter(|s| !s.is_empty()) + .map(str::to_owned) + .ok_or_else(|| AppError::S3Error("Provider returned a version without an ID.".into())) +} +pub async fn current(client: &Client, bucket: &str, key: &str) -> Result { + let (versions, _) = page(client, bucket, key, None, 1).await?; + let mut latest = versions.into_iter().filter(|v| v.is_latest); + let result = latest.next().ok_or_else(|| { + AppError::S3Error( + "Current version is unavailable. Refresh history before restoring.".into(), + ) + })?; + if latest.next().is_some() { + return Err(AppError::S3Error( + "Provider returned multiple current versions.".into(), + )); + } + Ok(result) +} +pub async fn validate_restore( + client: &Client, + bucket: &str, + key: &str, + guard: &RestoreGuard, +) -> Result<()> { + tokio::time::timeout(Duration::from_secs(60), async { + if versioning(client, bucket).await? != "Enabled" { + return Err(AppError::ConfigError( + "Restore requires enabled bucket versioning. Nothing was restored.".into(), + )); + } + let latest = current(client, bucket, key).await?; + if latest.version_id != guard.current_version + || latest.is_delete_marker != guard.deleted + || (!guard.deleted && latest.etag != guard.current_etag) + { + return Err(AppError::ConfigError( + "Current version changed. Refresh history and confirm the restore again.".into(), + )); + } + if !guard.deleted && guard.current_etag.as_ref().is_none_or(|e| e.is_empty()) { + return Err(AppError::S3Error( + "Current object has no ETag; safe restore is unavailable.".into(), + )); + } + Ok(()) + }) + .await + .map_err(|_| AppError::S3Error("Checking restore safety timed out.".into()))? +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::commands::test_s3::{response, scripted_client}; + pub(crate) fn listing(version: &str, deleted: bool) -> String { + let tag = if deleted { "DeleteMarker" } else { "Version" }; + format!("false<{tag}>file{version}true"current"5") + } + #[tokio::test] + async fn exact_key_history_includes_markers_and_paginates_without_nearby_keys() { + let first = "truefileold+1fileold+1false0file-otherignorefiledeletedtrue"; + let second = "truefile-otherxfilenullfalse9"; + let (client, server) = + scripted_client(vec![response(200, "", first), response(200, "", second)]).await; + let (items, next) = page(&client, "bucket", "file", None, 100).await.unwrap(); + assert_eq!(items.len(), 2); + assert!(items[0].is_delete_marker && items[0].is_latest); + assert_eq!(items[1].size, Some(0)); + let (items, next) = page(&client, "bucket", "file", next, 100).await.unwrap(); + assert_eq!(items[0].version_id, "null"); + assert!(next.is_none()); + let requests = server.await.unwrap(); + assert!(requests[1].contains("version-id-marker=old%2B1")); + assert!(requests.iter().all(|r| r.starts_with("GET "))); + } + #[tokio::test] + async fn malformed_or_repeated_history_cursors_fail() { + for body in [ + "true", + "truefilesame", + "file", + ] { + let (client, server) = scripted_client(vec![response(200, "", body)]).await; + assert!(page(&client, "bucket", "file", Some(Cursor { key_marker: "file".into(), version_id_marker: "same".into() }), 100).await.is_err()); + assert_eq!(server.await.unwrap().len(), 1); + } + } + #[tokio::test] + async fn restore_refuses_disabled_suspended_changed_and_denied_state() { + let guard = RestoreGuard { + current_version: "current-id".into(), + current_etag: Some("\"current\"".into()), + deleted: false, + }; + for status in ["Suspended", ""] { + let (client, server) = scripted_client(vec![response( + 200, + "", + &format!( + "{status}" + ), + )]) + .await; + assert!(validate_restore(&client, "bucket", "file", &guard) + .await + .is_err()); + assert_eq!(server.await.unwrap().len(), 1); + } + let (client, server) = scripted_client(vec![ + response( + 200, + "", + "Enabled", + ), + response(200, "", &listing("new-id", false)), + ]) + .await; + assert!(validate_restore(&client, "bucket", "file", &guard) + .await + .unwrap_err() + .to_string() + .contains("changed")); + assert!(server.await.unwrap().iter().all(|r| r.starts_with("GET "))); + let (client, server) = scripted_client(vec![response( + 403, + "", + "AccessDenied", + )]) + .await; + assert!(versioning(&client, "bucket") + .await + .unwrap_err() + .to_string() + .contains("AccessDenied")); + assert_eq!(server.await.unwrap().len(), 1); + } +} diff --git a/src-tauri/src/transfer/manager.rs b/src-tauri/src/transfer/manager.rs index be6b271..ab9bbcc 100644 --- a/src-tauri/src/transfer/manager.rs +++ b/src-tauri/src/transfer/manager.rs @@ -318,6 +318,7 @@ impl TransferManager { new_job.download_destination = job.download_destination.clone(); new_job.sync_source = job.sync_source.clone(); new_job.remote_source = job.remote_source.clone(); + new_job.restore_guard = job.restore_guard.clone(); // Preserve grouping info new_job.parent_group_id = job.parent_group_id.clone(); @@ -641,10 +642,7 @@ impl TransferManager { content_type: &str, attributes: Option<&super::sync::Attributes>, ) -> crate::error::Result<()> { - let expected_etag = job - .sync_source - .as_ref() - .and_then(|s| s.expected_etag.as_deref()); + let expected_etag = job.destination_etag(); let offset = job.remote_source.as_ref().map_or(0, |s| s.size); let metadata = tokio::fs::metadata(&job.local_path) .await @@ -667,6 +665,10 @@ impl TransferManager { } if file_size < MULTIPART_UPLOAD_THRESHOLD { + if let Some(guard) = &job.restore_guard { + crate::s3::versions::validate_restore(client, &job.bucket, &job.key, guard).await?; + self.ensure_multipart_job_active(&job.id).await?; + } let body = ByteStream::from_path(&job.local_path) .await .map_err(|error| crate::error::AppError::IoError(error.to_string()))?; @@ -892,10 +894,14 @@ impl TransferManager { let completed_upload = CompletedMultipartUpload::builder() .set_parts(Some(completed_parts)) .build(); + if let Some(guard) = &job.restore_guard { + crate::s3::versions::validate_restore(client, &job.bucket, &job.key, guard).await?; + self.ensure_multipart_job_active(&job.id).await?; + } let complete_send = client .complete_multipart_upload() - .set_if_none_match(job.sync_source.as_ref().and_then(|s| s.expected_etag.as_ref()).is_none().then(|| "*".into())) - .set_if_match(job.sync_source.as_ref().and_then(|s| s.expected_etag.clone())) + .set_if_none_match(job.destination_etag().is_none().then(|| "*".into())) + .set_if_match(job.destination_etag().map(str::to_owned)) .bucket(&job.bucket) .key(&job.key) .upload_id(guard.upload_id()) @@ -965,22 +971,60 @@ impl TransferManager { }; (source_client, destination_client) }; - let (temporary, attributes) = - super::remote::stage(&source_client, source, job, self).await?; + self.execute_remote_copy(&source_client, &destination_client, job) + .await?; + s3_manager + .write() + .await + .remove_bucket_cache(&destination.id, &job.bucket); + Ok(()) + } + + async fn execute_remote_copy( + &self, + source_client: &Client, + destination_client: &Client, + job: &TransferJob, + ) -> crate::error::Result<()> { + let source = job + .remote_source + .as_ref() + .ok_or_else(|| crate::error::AppError::ConfigError("Missing remote source.".into()))?; + if let Some(guard) = &job.restore_guard { + crate::s3::versions::validate_restore(destination_client, &job.bucket, &job.key, guard) + .await?; + } + let (temporary, mut attributes) = + super::remote::stage(source_client, source, job, self).await?; self.ensure_multipart_job_active(&job.id).await?; + if let Some(guard) = &job.restore_guard { + if let Some(etag) = &guard.current_etag { + let mut current = + super::sync::attributes(destination_client, &job.bucket, &job.key, etag) + .await?; + if current.head.version_id() != Some(guard.current_version.as_str()) { + return Err(crate::error::AppError::S3Error( + "Current version changed. Refresh history and confirm again.".into(), + )); + } + current.head.content_type = attributes.head.content_type; + current.head.cache_control = attributes.head.cache_control; + current.head.content_disposition = attributes.head.content_disposition; + current.head.content_encoding = attributes.head.content_encoding; + current.head.content_language = attributes.head.content_language; + current.head.metadata = attributes.head.metadata; + attributes = current; + } + } let mut prepared = job.clone(); prepared.local_path = temporary.path().to_string_lossy().into_owned(); self.upload_prepared( - &destination_client, + destination_client, &prepared, "application/octet-stream", Some(&attributes), ) .await?; - s3_manager - .write() - .await - .remove_bucket_cache(&destination.id, &job.bucket); Ok(()) } @@ -1205,6 +1249,199 @@ impl TransferManager { #[cfg(test)] mod tests { + #[tokio::test] + #[ignore = "requires a disposable versioned S3-compatible endpoint"] + async fn version_restore_real_endpoint_preserves_history_and_rejects_stale_guards() { + use aws_sdk_s3::{ + primitives::ByteStream, + types::{BucketVersioningStatus, VersioningConfiguration}, + }; + let profile = Profile::new( + "version-test".into(), + CredentialType::CustomEndpoint { + endpoint_url: std::env::var("BROWS3_VERSION_TEST_ENDPOINT") + .expect("disposable endpoint required"), + access_key_id: "versiontest".into(), + secret_access_key: "version-test-only".into(), + }, + Some("us-east-1".into()), + ); + let sdk = crate::s3::client::load_sdk_config(&profile, None).await; + let client = crate::s3::client::client_from_sdk_config(&sdk, &profile); + let bucket = format!("brows3-version-test-{}", uuid::Uuid::new_v4().simple()); + client.create_bucket().bucket(&bucket).send().await.unwrap(); + client + .put_bucket_versioning() + .bucket(&bucket) + .versioning_configuration( + VersioningConfiguration::builder() + .status(BucketVersioningStatus::Enabled) + .build(), + ) + .send() + .await + .unwrap(); + for size in [0u64, 5, 129 * 1024 * 1024] { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("old"); + std::fs::File::create(&path).unwrap().set_len(size).unwrap(); + let key = format!("nested/{size}"); + let old = client + .put_object() + .bucket(&bucket) + .key(&key) + .content_type("application/x-version-test") + .metadata("owner", "old") + .body(ByteStream::from_path(&path).await.unwrap()) + .send() + .await + .unwrap() + .version_id() + .unwrap() + .to_owned(); + let mut current = client + .put_object() + .bucket(&bucket) + .key(&key) + .tagging("keep=current") + .body(ByteStream::from_static(b"current")) + .send() + .await + .unwrap() + .version_id() + .unwrap() + .to_owned(); + for deleted in [false, true] { + if deleted { + current = client + .delete_object() + .bucket(&bucket) + .key(&key) + .send() + .await + .unwrap() + .version_id() + .unwrap() + .to_owned(); + } + let (guard, etag, length) = crate::commands::versions::prepare_restore( + &client, &bucket, &key, &old, ¤t, true, + ) + .await + .unwrap(); + assert_eq!(guard.deleted, deleted); + let manager = TransferManager::new(); + let mut job = remote_job(); + job.bucket = bucket.clone(); + job.key = key.clone(); + job.total_bytes = length * 2; + job.restore_guard = Some(guard); + let source = job.remote_source.as_mut().unwrap(); + source.bucket = bucket.clone(); + source.key = key.clone(); + source.etag = etag; + source.size = length; + source.version_id = Some(old.clone()); + manager.add_job(job.clone()).await; + manager + .execute_remote_copy(&client, &client, &job) + .await + .unwrap(); + let mut restored = client + .get_object() + .bucket(&bucket) + .key(&key) + .send() + .await + .unwrap(); + assert_ne!(restored.version_id(), Some(current.as_str())); + assert_eq!(restored.content_length(), Some(size as i64)); + assert_eq!(restored.content_type(), Some("application/x-version-test")); + assert_eq!(restored.metadata().unwrap().get("owner").unwrap(), "old"); + let mut received = 0u64; + while let Some(chunk) = restored.body.try_next().await.unwrap() { + received += chunk.len() as u64; + assert!(chunk.iter().all(|b| *b == 0)); + } + assert_eq!(received, size); + if !deleted { + let tags = client + .get_object_tagging() + .bucket(&bucket) + .key(&key) + .send() + .await + .unwrap(); + assert!(tags + .tag_set() + .iter() + .any(|t| t.key() == "keep" && t.value() == "current")); + } + assert!(manager + .execute_remote_copy(&client, &client, &job) + .await + .is_err()); + let history = client + .list_object_versions() + .bucket(&bucket) + .prefix(&key) + .send() + .await + .unwrap(); + assert!(history + .versions() + .iter() + .any(|v| v.version_id() == Some(old.as_str()))); + if deleted { + assert!(history + .delete_markers() + .iter() + .any(|v| v.version_id() == Some(current.as_str()))); + } else { + assert!(history + .versions() + .iter() + .any(|v| v.version_id() == Some(current.as_str()))); + } + assert!(client + .list_multipart_uploads() + .bucket(&bucket) + .send() + .await + .unwrap() + .uploads() + .is_empty()); + } + } + let history = client + .list_object_versions() + .bucket(&bucket) + .send() + .await + .unwrap(); + for (key, id) in history + .versions() + .iter() + .map(|v| (v.key().unwrap(), v.version_id().unwrap())) + .chain( + history + .delete_markers() + .iter() + .map(|v| (v.key().unwrap(), v.version_id().unwrap())), + ) + { + client + .delete_object() + .bucket(&bucket) + .key(key) + .version_id(id) + .send() + .await + .unwrap(); + } + client.delete_bucket().bucket(&bucket).send().await.unwrap(); + } + #[tokio::test] #[ignore = "requires two disposable S3-compatible endpoints"] async fn cross_profile_real_endpoints_round_trip_and_conflicts() { @@ -1372,6 +1609,7 @@ mod tests { region: "us-east-1".into(), key: "file".into(), etag: "\"source-etag\"".into(), + version_id: None, size: 5, current_session: true, }); @@ -1428,6 +1666,34 @@ mod tests { assert!(!path.exists()); } + #[tokio::test] + async fn restore_download_requires_the_selected_version_even_with_matching_etag() { + use crate::commands::test_s3::{response, scripted_client}; + for returned in ["old+version", "different-version"] { + let (client, server) = scripted_client(vec![response( + 200, + &format!("ETag: \"source-etag\"\r\nx-amz-version-id: {returned}\r\n"), + "hello", + )]) + .await; + let manager = TransferManager::new(); + let mut job = remote_job(); + job.remote_source.as_mut().unwrap().version_id = Some("old+version".into()); + manager.add_job(job.clone()).await; + let result = crate::transfer::remote::stage( + &client, + job.remote_source.as_ref().unwrap(), + &job, + &manager, + ) + .await; + assert_eq!(result.is_ok(), returned == "old+version"); + let requests = server.await.unwrap(); + assert!(requests[0].contains("versionId=old%2Bversion")); + assert!(requests[0].contains("if-match: \"source-etag\"")); + } + } + #[tokio::test] async fn cross_profile_source_changes_and_cancellation_prevent_staging() { use crate::commands::test_s3::{response, scripted_client}; @@ -1466,9 +1732,24 @@ mod tests { let manager = TransferManager::new(); let mut job = remote_job(); job.status = crate::transfer::TransferStatus::Failed("network".into()); + job.remote_source.as_mut().unwrap().version_id = Some("older-version".into()); + job.restore_guard = Some(crate::s3::versions::RestoreGuard { + current_version: "confirmed-current".into(), + current_etag: Some("\"current\"".into()), + deleted: false, + }); manager.add_job(job.clone()).await; let id = manager.retry_job(&job.id).await.unwrap(); let retry = manager.get_job(&id).await.unwrap(); + assert_eq!( + retry.remote_source.as_ref().unwrap().version_id.as_deref(), + Some("older-version") + ); + assert_eq!( + retry.restore_guard.as_ref().unwrap().current_version, + "confirmed-current" + ); + assert_eq!(retry.destination_etag(), Some("\"current\"")); assert_eq!( retry.remote_source.as_ref().unwrap().etag, "\"source-etag\"" @@ -1727,6 +2008,35 @@ mod tests { assert!(requests[3].starts_with("DELETE ") && requests[3].contains("uploadId=id")); } + #[tokio::test] + async fn multipart_restore_rechecks_versioning_and_aborts_before_completion() { + use crate::commands::test_s3::{response, scripted_client}; + let root = tempfile::tempdir().unwrap(); + std::fs::write(root.path().join("file"), b"hello").unwrap(); + let mut job = remote_job(); + job.local_path = root.path().join("file").to_string_lossy().into_owned(); + job.restore_guard = Some(crate::s3::versions::RestoreGuard { + current_version: "confirmed-current".into(), + current_etag: Some("\"current\"".into()), + deleted: false, + }); + let (client, server) = scripted_client(vec![ + response(200, "", "id"), + response(200, "ETag: \"part\"\r\n", ""), + response(200, "", "Suspended"), + response(204, "", ""), + ]).await; + let manager = TransferManager::new(); + manager.add_job(job.clone()).await; + assert!(manager + .multipart_upload_file(&client, &job, "text/plain", 5, None) + .await + .is_err()); + let requests = server.await.unwrap(); + assert!(requests[2].starts_with("GET ") && requests[2].contains("versioning")); + assert!(requests[3].starts_with("DELETE ") && requests[3].contains("uploadId=id")); + } + #[tokio::test] async fn stalled_download_releases_its_partial_file() { let (endpoint, received, server) = crate::commands::test_s3::stalled_endpoint( diff --git a/src-tauri/src/transfer/mod.rs b/src-tauri/src/transfer/mod.rs index d7e95b6..ad9d508 100644 --- a/src-tauri/src/transfer/mod.rs +++ b/src-tauri/src/transfer/mod.rs @@ -39,6 +39,8 @@ pub struct TransferJob { pub sync_source: Option, #[serde(default)] pub remote_source: Option, + #[serde(default)] + pub restore_guard: Option, #[serde(skip)] pub download_destination: Option>, pub transfer_type: TransferType, @@ -68,6 +70,15 @@ pub struct TransferEvent { } impl TransferJob { + pub fn destination_etag(&self) -> Option<&str> { + match &self.restore_guard { + Some(guard) => guard.current_etag.as_deref(), + None => self + .sync_source + .as_ref() + .and_then(|s| s.expected_etag.as_deref()), + } + } pub fn new( transfer_type: TransferType, profile_id: String, @@ -86,6 +97,7 @@ impl TransferJob { local_path: local_path.to_string_lossy().to_string(), sync_source: None, remote_source: None, + restore_guard: None, download_destination: None, transfer_type, status: TransferStatus::Pending, diff --git a/src-tauri/src/transfer/remote.rs b/src-tauri/src/transfer/remote.rs index 7d4f67f..67dc3e2 100644 --- a/src-tauri/src/transfer/remote.rs +++ b/src-tauri/src/transfer/remote.rs @@ -14,6 +14,8 @@ pub struct RemoteSource { pub region: String, pub key: String, pub etag: String, + #[serde(default)] + pub version_id: Option, pub size: u64, #[serde(skip)] pub current_session: bool, @@ -41,7 +43,7 @@ impl RemoteSource { pub fn validate_head(head: &HeadObjectOutput) -> Result<(String, u64)> { if head.sse_customer_algorithm().is_some() { return Err(AppError::ConfigError( - "SSE-C objects cannot be copied between profiles.".into(), + "SSE-C objects cannot be copied or restored by this workflow.".into(), )); } let etag = head @@ -71,14 +73,24 @@ pub async fn stage( .get_object() .bucket(&source.bucket) .key(&source.key) + .set_version_id(source.version_id.clone()) .if_match(&source.etag) .send(), ) .await .map_err(|_| AppError::S3Error("Reading the source timed out.".into()))? - .map_err(|e| AppError::S3Error(format!("Cannot read source object: {e}")))?; + .map_err(|e| { + AppError::S3Error(format!( + "Cannot read source object: {}", + aws_sdk_s3::error::DisplayErrorContext(&e) + )) + })?; if output.e_tag() != Some(source.etag.as_str()) || output.content_length() != Some(source.size as i64) + || source + .version_id + .as_ref() + .is_some_and(|v| output.version_id() != Some(v.as_str())) { return Err(AppError::S3Error( "Source changed since the copy was queued. Copy again.".into(), @@ -148,6 +160,7 @@ mod tests { region: "us-east-1".into(), key: "key".into(), etag: "etag".into(), + version_id: None, size: 5, current_session: true, }; diff --git a/src/app/bucket/page.tsx b/src/app/bucket/page.tsx index 9020943..717f700 100644 --- a/src/app/bucket/page.tsx +++ b/src/app/bucket/page.tsx @@ -49,6 +49,7 @@ import { ArrowDropDown as ArrowDropDownIcon, Edit as EditIcon, Lock as LockIcon, + History as HistoryIcon, } from '@mui/icons-material'; import { useObjects } from '@/hooks/useObjects'; import { operationsApi, transferApi, objectApi, S3Object, copyToClipboard } from '@/lib/tauri'; @@ -59,6 +60,7 @@ import { useProfileStore } from '@/store/profileStore'; import PropertiesDialog from '@/components/dialogs/PropertiesDialog'; import FolderSyncDialog from '@/components/dialogs/FolderSyncDialog'; import CrossProfileCopyDialog from '@/components/dialogs/CrossProfileCopyDialog'; +import VersionHistoryDialog from '@/components/dialogs/VersionHistoryDialog'; import type { ClipboardItem } from '@/store/clipboardStore'; import PermissionsDialog from '@/components/dialogs/PermissionsDialog'; import ObjectPreviewDialog from '@/components/dialogs/ObjectPreviewDialog'; @@ -283,6 +285,8 @@ function BucketContent() { const [isUploading, setIsUploading] = useState(false); const [uploadMenuAnchor, setUploadMenuAnchor] = useState(null); const [syncDestination, setSyncDestination] = useState(null); + const [versionHistory, setVersionHistory] = useState<{ viewKey: string; key: string } | null>(null); + useEffect(() => { setVersionHistory(null); }, [viewKey]); const [crossCopy, setCrossCopy] = useState<{ viewKey: string; items: ClipboardItem[] } | null>(null); useEffect(() => { setCrossCopy(null); }, [viewKey]); useEffect(() => { setSyncDestination(null); }, [viewKey]); @@ -1250,6 +1254,11 @@ function BucketContent() { )} + + setVersionHistory({ viewKey, key: selectedKeys.size === 1 ? Array.from(selectedKeys)[0] : prefix })}> + + + refresh()} @@ -1404,6 +1413,7 @@ function BucketContent() { Properties + {!selectedObject?.isFolder && { if (selectedObject) setVersionHistory({ viewKey, key: selectedObject.key }); handleMenuClose(); }}>Version history} Permissions @@ -1586,6 +1596,7 @@ function BucketContent() { {/* Properties Dialog */} {activeProfileId && syncDestination === `${activeProfileId}:${bucketName}:${prefix}` && setSyncDestination(null)} />} {activeProfileId && crossCopy?.viewKey === viewKey && setCrossCopy(null)} />} + {activeProfileId && versionHistory?.viewKey === viewKey && setVersionHistory(null)} />} setPropertiesOpen(false)} diff --git a/src/components/dialogs/VersionHistoryDialog.tsx b/src/components/dialogs/VersionHistoryDialog.tsx new file mode 100644 index 0000000..1d24361 --- /dev/null +++ b/src/components/dialogs/VersionHistoryDialog.tsx @@ -0,0 +1,97 @@ +'use client'; + +import { useCallback, useEffect, useRef, useState } from 'react'; +import { Alert, Box, Button, FormControlLabel, LinearProgress, Table, TableBody, TableCell, TableHead, TableRow, TextField, Typography } from '@mui/material'; +import { BaseDialog } from '@/components/common/BaseDialog'; +import { StyledCheckbox } from '@/components/common/StyledCheckbox'; +import { versionsApi, type ObjectVersion, type VersionHistory } from '@/lib/tauri'; +import { formatSize } from '@/lib/utils'; +import { useTransferStore } from '@/store/transferStore'; +import { toast } from '@/store/toastStore'; + +interface Props { bucket: string; region: string; profileId: string; initialKey: string; onClose: () => void } +const buttonSx = { borderRadius: '999px' }; +const secondarySx = { ...buttonSx, color: 'text.primary' }; +const dateLabel = (value: string | null) => value && !Number.isNaN(Date.parse(value)) ? new Date(value).toLocaleString() : 'Not provided'; + +export default function VersionHistoryDialog({ bucket, region, profileId, initialKey, onClose }: Props) { + const [key, setKey] = useState(initialKey); + const [pages, setPages] = useState([]); + const [page, setPage] = useState(0); + const [selected, setSelected] = useState(null); + const [confirmed, setConfirmed] = useState(false); + const [busy, setBusy] = useState<'load' | 'restore' | null>(null); + const [error, setError] = useState(''); + const alive = useRef(true); + const pending = useRef(false); + const initialized = useRef(false); + useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []); + const current = pages[0]?.versions.find(v => v.is_latest); + const versioning = pages[0]?.versioning; + const visible = pages[page]; + + const load = useCallback(async (previous: VersionHistory[] = []) => { + if (!key || pending.current) return; + pending.current = true; setBusy('load'); setError(''); setSelected(null); setConfirmed(false); + if (!previous.length) { setPages([]); setPage(0); } + try { + const result = await versionsApi.list(bucket, region, key, previous.at(-1)?.next ?? null, profileId); + if (result.next && previous.some(p => p.next?.key_marker === result.next?.key_marker && p.next?.version_id_marker === result.next?.version_id_marker)) throw new Error('History cursor repeated. Refresh history.'); + if (alive.current) { setPages([...previous, result]); setPage(previous.length); } + } catch (e) { if (alive.current) setError(String(e)); } + finally { pending.current = false; if (alive.current) setBusy(null); } + }, [bucket, region, key, profileId]); + useEffect(() => { + if (!initialized.current) { initialized.current = true; if (initialKey && !initialKey.endsWith('/')) void load(); } + }, [initialKey, load]); + + async function restore() { + if (!selected || !current || !confirmed || pending.current || versioning !== 'Enabled') return; + pending.current = true; setBusy('restore'); setError(''); + try { + await versionsApi.restore(bucket, region, key, selected.version_id, current.version_id, confirmed, profileId); + void useTransferStore.getState().refreshJobs(); + toast.success('Version restore queued. View progress in Uploads.'); + if (alive.current) onClose(); + } catch (e) { + if (alive.current) { setError(String(e)); setPages([]); setSelected(null); setConfirmed(false); setPage(0); } + } finally { pending.current = false; if (alive.current) setBusy(null); } + } + const confirmation = 'Create a new current version from the selected contents. Existing versions and delete markers will not be deleted.'; + return + + + }> + + { setKey(e.target.value); setPages([]); setPage(0); setSelected(null); setConfirmed(false); setError(''); }} onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); void load(); } }} inputProps={{ autoCapitalize: 'none', autoCorrect: 'off', spellCheck: false }} /> + + + Object: s3://{bucket}/{key} + {busy && {busy === 'load' ? 'Reading version history...' : 'Checking the selected version and queueing restore...'}} + {error && {error}} + {versioning && versioning !== 'Enabled' && Bucket versioning is {versioning.toLowerCase()}. History is read-only. Restore requires versioning to be enabled through your storage provider.} + {current?.is_delete_marker && This object is currently deleted. Select an older data version to recover its contents without removing the delete marker.} + {visible && !visible.versions.length && No versions found for this exact key on this page.} + {!!visible?.versions.length && + Version IDStateModifiedSizeRestore + {visible.versions.map(v => + {v.version_id} + {v.is_delete_marker ? (v.is_latest ? 'Current deletion' : 'Delete marker') : (v.is_latest ? 'Current' : 'Older version')} + {dateLabel(v.modified)} + {v.size === null ? N/A : formatSize(v.size)} + + )} +
} + {visible && + + Page {page + 1} + + } + {pages.length >= 100 && visible?.next && Loaded the 10,000-entry history limit. Use your provider's tools to inspect older versions.} + {selected && + Restore version: {selected.version_id} + { if (!busy) setConfirmed(e.target.checked); }} />} label={confirmation} /> + } + Restores contents and content metadata. For an existing object, current permissions, tags, encryption and retention are kept; for a deleted object, bucket defaults apply. Uses temporary disk space and this computer's connection. Request and transfer charges may apply. +
; +} diff --git a/src/lib/tauri.ts b/src/lib/tauri.ts index 79c6cf8..2a0e0b9 100644 --- a/src/lib/tauri.ts +++ b/src/lib/tauri.ts @@ -387,6 +387,27 @@ export const operationsApi = { }, }; +export interface ObjectVersion { + version_id: string; + is_latest: boolean; + is_delete_marker: boolean; + size: number | null; + modified: string | null; + etag: string | null; +} +export interface VersionCursor { key_marker: string; version_id_marker: string } +export interface VersionHistory { versioning: string; versions: ObjectVersion[]; next: VersionCursor | null } +export const versionsApi = { + async list(bucket: string, region: string, key: string, cursor: VersionCursor | null, expectedProfileId: string): Promise { + if (useProfileStore.getState().activeProfileId !== expectedProfileId) throw new Error('Profile changed. Open history again.'); + return invoke('list_object_versions', { bucket, region, key, cursor, expectedProfileId }); + }, + async restore(bucket: string, region: string, key: string, versionId: string, expectedCurrentVersion: string, confirmed: boolean, expectedProfileId: string): Promise { + if (useProfileStore.getState().activeProfileId !== expectedProfileId) throw new Error('Profile changed. Open history again.'); + return invoke('restore_object_version', { bucket, region, key, versionId, expectedCurrentVersion, confirmed, expectedProfileId }); + }, +}; + export interface ObjectMetadata { key: string; size: number; diff --git a/tests/components/version-history.test.tsx b/tests/components/version-history.test.tsx new file mode 100644 index 0000000..4c95dcd --- /dev/null +++ b/tests/components/version-history.test.tsx @@ -0,0 +1,80 @@ +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { beforeEach, expect, test, vi } from 'vitest'; +import VersionHistoryDialog from '@/components/dialogs/VersionHistoryDialog'; +import { versionsApi, type VersionHistory } from '@/lib/tauri'; + +vi.mock('@/lib/tauri', () => ({ versionsApi: { list: vi.fn(), restore: vi.fn() } })); +vi.mock('@/store/transferStore', () => ({ useTransferStore: { getState: () => ({ refreshJobs: vi.fn() }) } })); +const history: VersionHistory = { versioning: 'Enabled', next: null, versions: [ + { version_id: 'latest', is_latest: true, is_delete_marker: false, size: 5, modified: null, etag: 'current' }, + { version_id: 'old-version', is_latest: false, is_delete_marker: false, size: 0, modified: null, etag: 'old' }, + { version_id: 'marker', is_latest: false, is_delete_marker: true, size: null, modified: null, etag: null }, +] }; +const props = { bucket: 'bucket', region: 'us-east-1', profileId: 'a', initialKey: 'file', onClose: vi.fn() }; +beforeEach(() => { vi.clearAllMocks(); vi.mocked(versionsApi.list).mockResolvedValue(history); vi.mocked(versionsApi.restore).mockResolvedValue('job'); }); +async function selectOld() { await screen.findByText('old-version'); fireEvent.click(screen.getByRole('button', { name: 'Select version old-version' })); } + +test('restoring needs an older data version and explicit approval', async () => { + render(); + await selectOld(); + expect((screen.getByRole('button', { name: 'Select version latest' }) as HTMLButtonElement).disabled).toBe(true); + expect((screen.getByRole('button', { name: 'Select version marker' }) as HTMLButtonElement).disabled).toBe(true); + expect((screen.getByRole('button', { name: 'Restore selected version' }) as HTMLButtonElement).disabled).toBe(true); + fireEvent.click(screen.getByRole('checkbox')); + fireEvent.click(screen.getByRole('button', { name: 'Restore selected version' })); + await waitFor(() => expect(versionsApi.restore).toHaveBeenCalledExactlyOnceWith('bucket', 'us-east-1', 'file', 'old-version', 'latest', true, 'a')); + await waitFor(() => expect(props.onClose).toHaveBeenCalledOnce()); +}); +test('suspended versioning remains read-only and does not silently enable versioning', async () => { + vi.mocked(versionsApi.list).mockResolvedValue({ ...history, versioning: 'Suspended' }); + render(); + await screen.findByText(/Bucket versioning is suspended/); + expect((screen.getByRole('button', { name: 'Select version old-version' }) as HTMLButtonElement).disabled).toBe(true); + expect(versionsApi.restore).not.toHaveBeenCalled(); +}); +test('changing the exact key clears history and approval without normalizing spaces', async () => { + render(); await selectOld(); fireEvent.click(screen.getByRole('checkbox')); + fireEvent.change(screen.getByLabelText('Exact object key'), { target: { value: ' file ' } }); + expect(screen.queryByRole('checkbox')).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: 'Load history' })); + await waitFor(() => expect(versionsApi.list).toHaveBeenLastCalledWith('bucket', 'us-east-1', ' file ', null, 'a')); +}); +test('stale restore failure discards history and requires fresh confirmation', async () => { + vi.mocked(versionsApi.restore).mockRejectedValue(new Error('Current version changed. Refresh history.')); + render(); await selectOld(); fireEvent.click(screen.getByRole('checkbox')); + fireEvent.click(screen.getByRole('button', { name: 'Restore selected version' })); + await screen.findByText(/Current version changed/); + expect(screen.queryByRole('checkbox')).toBeNull(); + expect(screen.queryByRole('table')).toBeNull(); + expect(props.onClose).not.toHaveBeenCalled(); +}); +test('deleted objects retain their current marker as the restore guard', async () => { + vi.mocked(versionsApi.list).mockResolvedValue({ ...history, versions: [{ ...history.versions[2], is_latest: true }, history.versions[1]] }); + render(); await selectOld(); + await screen.findByText(/currently deleted/); + fireEvent.click(screen.getByRole('checkbox')); fireEvent.click(screen.getByRole('button', { name: 'Restore selected version' })); + await waitFor(() => expect(versionsApi.restore).toHaveBeenCalledWith('bucket', 'us-east-1', 'file', 'old-version', 'marker', true, 'a')); +}); +test('pagination carries both markers and Previous restores the cached page', async () => { + const cursor = { key_marker: 'file', version_id_marker: 'old-version' }; + vi.mocked(versionsApi.list).mockResolvedValueOnce({ ...history, next: cursor }).mockResolvedValueOnce({ ...history, versions: [{ ...history.versions[1], version_id: 'older' }] }); + render(); await screen.findByText('old-version'); + fireEvent.click(screen.getByRole('button', { name: 'Next' })); + await screen.findByText('older'); + expect(versionsApi.list).toHaveBeenLastCalledWith('bucket', 'us-east-1', 'file', cursor, 'a'); + fireEvent.click(screen.getByRole('button', { name: 'Previous' })); + await screen.findByText('old-version'); +}); +test('closing during a read cannot queue a late restore', async () => { + let resolve!: (value: VersionHistory) => void; + vi.mocked(versionsApi.list).mockReturnValue(new Promise(r => { resolve = r; })); + const view = render(); view.unmount(); + await act(async () => resolve(history)); + expect(versionsApi.restore).not.toHaveBeenCalled(); +}); +test('permission errors are visible rather than reported as empty history', async () => { + vi.mocked(versionsApi.list).mockRejectedValue(new Error('AccessDenied: ListBucketVersions')); + render(); + await screen.findByText(/AccessDenied/); + expect(screen.queryByText(/No versions found/)).toBeNull(); +}); diff --git a/tests/smoke/fixtures.ts b/tests/smoke/fixtures.ts index 889227a..b779aec 100644 --- a/tests/smoke/fixtures.ts +++ b/tests/smoke/fixtures.ts @@ -87,6 +87,15 @@ export class DesktopBackend { } case 'delete_objects': this.objects = this.objects.filter(item => !(args.keys as string[]).includes(item.key)); return null; case 'list_transfers': return this.transfers; + case 'list_object_versions': return { + versioning: 'Enabled', next: null, versions: [ + { version_id: 'current-delete-marker', is_latest: true, is_delete_marker: true, size: null, modified: '2026-01-03T00:00:00Z', etag: null }, + { version_id: 'older-data-version-with-a-long-identifier-0123456789', is_latest: false, is_delete_marker: false, size: 20, modified: '2026-01-02T00:00:00Z', etag: 'old' }, + ], + }; + case 'restore_object_version': + if (args.expectedProfileId !== this.activeProfile || args.confirmed !== true || args.expectedCurrentVersion !== 'current-delete-marker') throw new Error('Stale restore confirmation'); + return 'restore-job'; case 'preview_folder_sync': return { id: 'sync-plan', new_files: 1, changed_files: 1, unverified_files: 0, unchanged_files: 1, remote_only_files: 2, upload_bytes: 40, entries: [ diff --git a/tests/smoke/version-history.spec.ts b/tests/smoke/version-history.spec.ts new file mode 100644 index 0000000..6535fe2 --- /dev/null +++ b/tests/smoke/version-history.spec.ts @@ -0,0 +1,34 @@ +import { test, expect } from './fixtures'; + +test('version history recovers a deleted exact key only after approval', async ({ page, backend }) => { + await page.goto('/bucket?name=demo-bucket®ion=us-east-1'); + await page.getByRole('button', { name: 'Version history', exact: true }).click(); + const dialog = page.getByRole('dialog'); + await dialog.getByLabel('Exact object key').fill('deleted/photo.png'); + await dialog.getByRole('button', { name: 'Load history' }).click(); + await expect(dialog.getByRole('table', { name: 'Object versions' })).toBeVisible(); + await expect(dialog.getByRole('button', { name: 'Select version current-delete-marker' })).toBeDisabled(); + await dialog.getByRole('button', { name: 'Select version older-data-version-with-a-long-identifier-0123456789' }).click(); + await expect(dialog.getByRole('button', { name: 'Restore selected version' })).toBeDisabled(); + for (const width of [1440, 800]) { + await page.setViewportSize({ width, height: 900 }); + expect(await dialog.evaluate(el => el.scrollWidth <= el.clientWidth)).toBe(true); + if (process.env.CAPTURE_VERSIONS_UI && test.info().project.name === 'chromium') await page.screenshot({ path: `.impeccable/review/versions-${width}.png`, fullPage: true }); + } + expect(backend.calls.some(c => c.command === 'restore_object_version')).toBe(false); + await dialog.getByRole('checkbox').check(); + await dialog.getByRole('button', { name: 'Restore selected version' }).click(); + await expect(dialog).toHaveCount(0); + expect(backend.calls.find(c => c.command === 'restore_object_version')?.args).toMatchObject({ key: 'deleted/photo.png', expectedProfileId: 'a', confirmed: true, expectedCurrentVersion: 'current-delete-marker' }); +}); + +test('closing history leaves the object and its versions unchanged', async ({ page, backend }) => { + await page.goto('/bucket?name=demo-bucket®ion=us-east-1'); + await page.getByRole('checkbox', { name: 'Select notes.txt', exact: true }).check(); + await page.getByRole('button', { name: 'Version history', exact: true }).click(); + const dialog = page.getByRole('dialog'); + await expect(dialog.getByLabel('Exact object key')).toHaveValue('notes.txt'); + await expect(dialog.getByRole('table')).toBeVisible(); + await dialog.getByRole('button', { name: 'Close', exact: true }).click(); + expect(backend.calls.some(c => ['restore_object_version', 'delete_objects', 'put_object_content'].includes(c.command))).toBe(false); +});