From 4069581098afbbb6164b82bd2f1cb0716a314906 Mon Sep 17 00:00:00 2001 From: Yoshihiro OKUMURA Date: Fri, 27 Nov 2026 17:19:24 +0900 Subject: [PATCH] fix(folders): handle locked folder access consistently Recognize the server's short locked-folder response and preserve the password proof required by subsequent folder and file requests. - Report locked short records with a typed folder error - Share the folder-auth cookie across connections and token refreshes - Authenticate a locked folder selected as the root of a recursive download - Remove DOI-specific password authentication in favor of common folder access routines --- CHANGELOG.md | 3 ++ Cargo.lock | 79 +++++++++++++++++++++++++++ Cargo.toml | 2 +- README.md | 2 +- src/api/folders.rs | 64 ++++++++++++++++++++-- src/commands/download.rs | 86 ++++++++++++++++++++++++++++- src/commands/shared.rs | 114 ++++++++++++++++++++++++++++----------- src/connection.rs | 57 +++++++++++++++++++- src/error.rs | 30 +++++++++++ 9 files changed, 400 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2364936..05b54a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,9 @@ All notable changes to this project will be documented in this file. ### Fixed - Labelled meaningless access levels as `Unknown (0x…)` rather than `Storage` or an unrelated combination. +- Recognized a locked folder's short retrieve response as a lock instead of malformed JSON. DOI resolution only maps the DOI to a folder id; subsequent access uses the same folder and file routines as ordinary paths, without DOI-specific password authentication. +- Preserved the cookie returned by folder-password authentication for subsequent folder and file requests, including connections using refreshed access tokens. +- Authenticated a locked folder selected as the root of a recursive download, rather than authenticating only its descendants. ## [2.0.3] - 2026-11-04 diff --git a/Cargo.lock b/Cargo.lock index 15515e2..d50284c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -303,6 +303,35 @@ dependencies = [ "rustversion", ] +[[package]] +name = "cookie" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + +[[package]] +name = "cookie_store" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206" +dependencies = [ + "cookie", + "document-features", + "idna", + "log", + "publicsuffix", + "serde", + "serde_derive", + "serde_json", + "time", + "url", +] + [[package]] name = "core-foundation" version = "0.10.1" @@ -441,6 +470,15 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + [[package]] name = "dotenvy" version = "0.15.7" @@ -1013,6 +1051,12 @@ version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + [[package]] name = "lock_api" version = "0.4.14" @@ -1425,6 +1469,22 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "psl-types" +version = "2.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33cb294fe86a74cbcf50d4445b37da762029549ebeea341421c7c70370f86cac" + +[[package]] +name = "publicsuffix" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f42ea446cab60335f76979ec15e12619a2165b5ae2c12166bef27d283a9fadf" +dependencies = [ + "idna", + "psl-types", +] + [[package]] name = "quinn" version = "0.11.12" @@ -1550,6 +1610,8 @@ checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" dependencies = [ "base64", "bytes", + "cookie", + "cookie_store", "futures-core", "futures-util", "http", @@ -2051,6 +2113,7 @@ dependencies = [ "powerfmt", "serde_core", "time-core", + "time-macros", ] [[package]] @@ -2059,6 +2122,16 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tinystr" version = "0.8.5" @@ -2268,6 +2341,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + [[package]] name = "walkdir" version = "2.5.1" diff --git a/Cargo.toml b/Cargo.toml index 81ad2e0..747d65c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ path = "src/main.rs" [dependencies] clap = { version = "4.6.10", features = ["derive"] } -reqwest = { version = "0.13.5", default-features = false, features = ["form", "json", "multipart", "query", "rustls", "stream"] } +reqwest = { version = "0.13.5", default-features = false, features = ["cookies", "form", "json", "multipart", "query", "rustls", "stream"] } serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" tokio = { version = "1.54.1", features = ["full"] } diff --git a/README.md b/README.md index 3bdb590..06691fa 100644 --- a/README.md +++ b/README.md @@ -103,7 +103,7 @@ mdrs labs neurodata: ### ls -List the contents of a remote folder. You can also specify a DOI path in the form `remote:10.xxxx/yyy.ID[/optional/subpath]`. +List the contents of a remote folder. You can also specify a DOI path in the form `remote:10.xxxx/yyy.ID[/optional/subpath]`. DOI paths always refer to public datasets and do not use folder passwords. ```shell mdrs ls neurodata:/NIU/Repository/ diff --git a/src/api/folders.rs b/src/api/folders.rs index e4647e4..1264dbe 100644 --- a/src/api/folders.rs +++ b/src/api/folders.rs @@ -1,8 +1,23 @@ use crate::connection::{ApiRequestLimiter, MDRSConnection}; -use crate::error::response_error; +use crate::error::{FolderLockedError, response_error}; pub use crate::models::folder::{FolderDetail, FolderSimple}; use anyhow::{anyhow, bail}; +fn parse_folder_response(data: serde_json::Value, id: &str) -> Result { + // Without its password, a locked folder comes back with 200 and only its listing + // fields. It is not a malformed full folder: the caller must authenticate and retry. + if data.get("lock").and_then(serde_json::Value::as_bool) == Some(true) + && data.get("sub_folders").is_none() + { + let name = data + .get("name") + .and_then(serde_json::Value::as_str) + .unwrap_or(id); + return Err(FolderLockedError::new(name).into()); + } + Ok(serde_json::from_value(data)?) +} + impl MDRSConnection { /// List folders matching the given path under a laboratory (GET v3/folders/?path=...&laboratory_id=...) pub async fn list_folders_by_path( @@ -46,7 +61,7 @@ impl MDRSConnection { if !resp.status().is_success() { return Err(response_error("Retrieve folder failed", resp).await); } - Ok(resp.json::().await?) + parse_folder_response(resp.json().await?, id) } /// Retrieve folder details while consuming the shared API concurrency budget. @@ -60,7 +75,7 @@ impl MDRSConnection { if !resp.status().is_success() { return Err(response_error("Retrieve folder failed", resp).await); } - Ok(resp.json::().await?) + parse_folder_response(resp.json().await?, id) } /// Create a new folder under `parent_id` (POST v3/folders/). @@ -150,3 +165,46 @@ impl MDRSConnection { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn short_locked_record() -> serde_json::Value { + json!({ + "id": "f1", + "pid": null, + "name": "root", + "access_level": 4, + "lock": true, + "size": 0, + "laboratory_id": 1, + "description": "", + "created_at": "2026-01-01T00:00:00+09:00", + "updated_at": "2026-01-01T00:00:00+09:00", + "restrict_opened_at": null, + "application": {"id": 0, "status": 0} + }) + } + + #[test] + fn short_record_of_a_locked_folder_is_reported_as_locked() { + let err = parse_folder_response(short_locked_record(), "f1").unwrap_err(); + + assert!(err.downcast_ref::().is_some()); + assert_eq!(err.to_string(), "Folder `root` is locked."); + } + + #[test] + fn full_record_of_a_locked_folder_still_deserializes() { + let mut data = short_locked_record(); + data["metadata"] = json!([]); + data["sub_folders"] = json!([]); + data["path"] = json!("/root/"); + + let folder = parse_folder_response(data, "f1").unwrap(); + assert_eq!(folder.path, "/root/"); + assert!(folder.lock); + } +} diff --git a/src/commands/download.rs b/src/commands/download.rs index 34e9e68..70a7415 100644 --- a/src/commands/download.rs +++ b/src/commands/download.rs @@ -4,6 +4,8 @@ use crate::commands::shared::{ find_subfolder_by_name, is_doi, parse_doi_remote_path, parse_remote_path, }; use crate::connection::{ApiRequestLimiter, MDRSConnection}; +use crate::error::FolderLockedError; +use crate::models::folder::FolderSimple; use anyhow::{anyhow, bail}; use std::path::PathBuf; use std::sync::Arc; @@ -30,7 +32,7 @@ pub async fn download( if is_doi(remote_path.split_once(':').map(|x| x.1).unwrap_or("")) { let (remote, doi, subpath) = parse_doi_remote_path(remote_path)?; let (raw_conn, _cache) = create_readonly_conn(&remote).await?; - let (doi_folder, lab) = find_folder_by_doi(&raw_conn, &doi, password).await?; + let (doi_folder, lab) = find_folder_by_doi(&raw_conn, &doi).await?; let abs_path = format!("{}{}", doi_folder.path.trim_end_matches('/'), subpath); let abs_path_clean = abs_path.trim_end_matches('/'); @@ -158,6 +160,7 @@ pub async fn download( if !recursive { bail!("Cannot download `{}`: Is a folder.", abs_path_clean); } + authenticate_download_root(&conn, &limiter, sub, password).await?; let top_local = local_real.join(&sub.name); let mut folder_tasks: JoinSet> = JoinSet::new(); @@ -245,6 +248,7 @@ pub async fn download( if !recursive { bail!("Cannot download `{}`: Is a folder.", r_path_clean); } + authenticate_download_root(&conn, &limiter, sub, password).await?; // Python downloads into local_path// (not directly into local_path). // We create that subdirectory first, then recurse into it. let top_local = local_real.join(&sub.name); @@ -283,6 +287,23 @@ pub async fn download( Err(anyhow!("File or folder `{}` not found.", r_path_clean)) } +/// The recursive workers authenticate descendants, but the selected root is not a +/// descendant of itself and must be opened before its first retrieve. +async fn authenticate_download_root( + conn: &MDRSConnection, + limiter: &ApiRequestLimiter, + folder: &FolderSimple, + password: Option<&str>, +) -> Result<(), anyhow::Error> { + if !folder.lock { + return Ok(()); + } + let password = + password.ok_or_else(|| FolderLockedError::new(&folder.name).with_password_hint())?; + conn.folder_auth_limited(&folder.id, password, limiter) + .await +} + /// Return true if the given lab/folder/file path matches any exclude pattern. /// Constructs: `/{lab_name}{folder_path}{file_name}` lowercased, trailing slash stripped. /// `folder_path` is expected to already start (and end) with "/". @@ -551,3 +572,66 @@ fn flatten_join_result( Err(err) => Err(anyhow!("Task join failed: {}", err)), } } + +#[cfg(test)] +mod tests { + use super::*; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::TcpListener; + + fn folder(lock: bool) -> FolderSimple { + FolderSimple { + id: "locked-root".to_string(), + pid: None, + name: "dataset".to_string(), + access_level: 4, + lock, + size: 0, + laboratory_id: 1, + description: String::new(), + created_at: "2026-01-01T00:00:00+09:00".to_string(), + updated_at: "2026-01-01T00:00:00+09:00".to_string(), + } + } + + #[tokio::test] + async fn download_root_authentication_is_needed_only_for_a_locked_folder() { + let conn = MDRSConnection::new("http://127.0.0.1:9"); + let limiter = ApiRequestLimiter::new(1); + authenticate_download_root(&conn, &limiter, &folder(false), None) + .await + .unwrap(); + + let err = authenticate_download_root(&conn, &limiter, &folder(true), None) + .await + .unwrap_err(); + assert!(err.downcast_ref::().is_some()); + } + + #[tokio::test] + async fn locked_download_root_is_authenticated_before_its_worker_starts() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.unwrap(); + let mut buf = [0u8; 4096]; + let n = stream.read(&mut buf).await.unwrap(); + let request = String::from_utf8_lossy(&buf[..n]); + assert!(request.starts_with("POST /v3/folders/locked-root/auth/ HTTP/1.1")); + assert!(request.contains(r#"{"password":"secret"}"#)); + stream + .write_all( + b"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: 2\r\nconnection: close\r\n\r\n{}", + ) + .await + .unwrap(); + }); + + let conn = MDRSConnection::new(&format!("http://{addr}")); + let limiter = ApiRequestLimiter::new(1); + authenticate_download_root(&conn, &limiter, &folder(true), Some("secret")) + .await + .unwrap(); + server.await.unwrap(); + } +} diff --git a/src/commands/shared.rs b/src/commands/shared.rs index 63f6698..d4b61d6 100644 --- a/src/commands/shared.rs +++ b/src/commands/shared.rs @@ -1,6 +1,7 @@ use crate::cache::{Cache, CacheLaboratory}; use crate::connection::ApiRequestLimiter; use crate::connection::MDRSConnection; +use crate::error::FolderLockedError; use crate::models::file::File; use crate::models::folder::{FolderDetail, FolderSimple}; use crate::models::laboratory::Laboratory; @@ -94,14 +95,11 @@ pub fn parse_doi_remote_path(remote_path: &str) -> Result<(String, String, Strin Ok((remote, doi.to_string(), subpath.to_string())) } -/// Resolve a DOI string to a (FolderDetail, Laboratory) pair. -/// -/// Calls GET v3/doi/{id}/ to look up the folder ID, then fetches the full -/// folder detail (which carries `laboratory_id`) and resolves the laboratory. +/// Resolve a DOI string to a (FolderDetail, Laboratory) pair. Only the DOI-to-folder-id +/// lookup is DOI-specific; subsequent folder and file access uses the common API methods. pub async fn find_folder_by_doi( conn: &MDRSConnection, doi: &str, - password: Option<&str>, ) -> Result<(FolderDetail, Laboratory), anyhow::Error> { // Strip any trailing slash from the DOI before extracting the suffix ID. let doi_clean = doi.trim_end_matches('/'); @@ -120,26 +118,11 @@ pub async fn find_folder_by_doi( } let folder_id = &doi_resp.folder.id; - - // Fetch the full folder detail; laboratory_id is available here. let folder = conn .retrieve_folder(folder_id) .await .map_err(|e| anyhow!("Failed to retrieve folder for DOI `{}`: {}", doi_clean, e))?; - // Handle password-locked folder. - if folder.lock { - match password { - None => { - bail!( - "Folder for DOI `{}` is locked. Use -p/--password to provide a password.", - doi_clean - ); - } - Some(pw) => conn.folder_auth(folder_id, pw).await?, - } - } - // Resolve laboratory using the laboratory_id from the folder detail. let lab_id = folder.laboratory_id; let lab = conn @@ -271,10 +254,7 @@ pub async fn find_folder( if folder_simple.lock { match password { None => { - bail!( - "Folder `{}` is locked. Use -p/--password to provide a password.", - path - ); + return Err(FolderLockedError::new(path).with_password_hint().into()); } Some(pw) => conn.folder_auth(&folder_simple.id, pw).await?, } @@ -309,10 +289,7 @@ pub async fn find_folder_limited( if folder_simple.lock { match password { None => { - bail!( - "Folder `{}` is locked. Use -p/--password to provide a password.", - path - ); + return Err(FolderLockedError::new(path).with_password_hint().into()); } Some(pw) => { conn.folder_auth_limited(&folder_simple.id, pw, limiter) @@ -378,7 +355,7 @@ pub async fn resolve_remote_folder( let path_component = remote_path.split_once(':').map(|x| x.1).unwrap_or(""); if is_doi(path_component) { let (_, doi, subpath) = parse_doi_remote_path(remote_path)?; - let (doi_folder, lab) = find_folder_by_doi(conn, &doi, password).await?; + let (doi_folder, lab) = find_folder_by_doi(conn, &doi).await?; if subpath.is_empty() { Ok((doi_folder, lab)) } else { @@ -412,7 +389,7 @@ pub async fn resolve_remote_file( let path_component = remote_path.split_once(':').map(|x| x.1).unwrap_or(""); if is_doi(path_component) { let (_, doi, subpath) = parse_doi_remote_path(remote_path)?; - let (doi_folder, lab) = find_folder_by_doi(conn, &doi, password).await?; + let (doi_folder, lab) = find_folder_by_doi(conn, &doi).await?; let subpath_clean = subpath.trim_end_matches('/'); if subpath_clean.is_empty() { bail!("DOI path must point to a file, not a folder."); @@ -455,6 +432,51 @@ mod tests { use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpListener; + fn json_server( + exchanges: Vec<(&'static str, &'static str)>, + ) -> (MDRSConnection, tokio::task::JoinHandle<()>) { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let addr = listener.local_addr().unwrap(); + let listener = TcpListener::from_std(listener).unwrap(); + let server = tokio::spawn(async move { + for (request_line, body) in exchanges { + let (mut stream, _) = listener.accept().await.unwrap(); + let mut buf = [0u8; 8192]; + let n = stream.read(&mut buf).await.unwrap(); + let request = String::from_utf8_lossy(&buf[..n]); + assert!(request.starts_with(request_line), "request was: {request}"); + let response = format!( + "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}", + body.len(), + body + ); + stream.write_all(response.as_bytes()).await.unwrap(); + } + }); + (MDRSConnection::new(&format!("http://{addr}")), server) + } + + const DOI: &str = "10.60178/cbs.20260429-001"; + const DOI_RESPONSE: &str = + r#"{"id":"20260429-001","doi":"10.60178/cbs.20260429-001","folder":{"id":"f1"}}"#; + const LABORATORIES_RESPONSE: &str = + r#"[{"id":1,"name":"mylab","pi_name":"PI","full_name":"My Laboratory"}]"#; + const LOCKED_DOI_FOLDER: &str = r#"{ + "id":"f1","pid":null,"name":"root","access_level":4,"lock":true, + "size":0,"laboratory_id":1,"description":"", + "created_at":"2026-01-01T00:00:00+09:00", + "updated_at":"2026-01-01T00:00:00+09:00" + }"#; + + const PUBLIC_DOI_FOLDER: &str = r#"{ + "id":"f1","pid":null,"name":"root","access_level":2,"lock":false, + "size":0,"laboratory_id":1,"description":"", + "created_at":"2026-01-01T00:00:00+09:00", + "updated_at":"2026-01-01T00:00:00+09:00", + "sub_folders":[],"path":"/mylab/root/" + }"#; + #[tokio::test] async fn find_laboratory_falls_back_to_api_without_authorization() { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -487,6 +509,38 @@ mod tests { server.await.unwrap(); } + #[tokio::test] + async fn public_doi_folder_is_returned_without_folder_authentication() { + let (conn, server) = json_server(vec![ + ("GET /v3/doi/20260429-001/ HTTP/1.1", DOI_RESPONSE), + ("GET /v3/folders/f1/ HTTP/1.1", PUBLIC_DOI_FOLDER), + ("GET /v3/laboratories/ HTTP/1.1", LABORATORIES_RESPONSE), + ]); + + let (folder, lab) = find_folder_by_doi(&conn, DOI).await.unwrap(); + server.await.unwrap(); + + assert_eq!(folder.id, "f1"); + assert_eq!(folder.path, "/mylab/root/"); + assert_eq!(lab.name, "mylab"); + } + + #[tokio::test] + async fn short_locked_record_after_doi_lookup_uses_the_common_folder_error() { + let (conn, server) = json_server(vec![ + ("GET /v3/doi/20260429-001/ HTTP/1.1", DOI_RESPONSE), + ("GET /v3/folders/f1/ HTTP/1.1", LOCKED_DOI_FOLDER), + ]); + + let err = find_folder_by_doi(&conn, DOI).await.unwrap_err(); + server.await.unwrap(); + + assert_eq!( + err.to_string(), + "Failed to retrieve folder for DOI `10.60178/cbs.20260429-001`: Folder `root` is locked." + ); + } + // ------------------------------------------------------------------ // Remote path parsing // ------------------------------------------------------------------ diff --git a/src/connection.rs b/src/connection.rs index c1fb5ab..aadc138 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -69,7 +69,12 @@ impl MDRSConnection { MDRSConnection { remote: None, url: url.to_string(), - client: Client::new(), + // Folder authentication is returned in a cookie and must survive subsequent + // retrieves. Clones share the client, and therefore its cookie store. + client: Client::builder() + .cookie_store(true) + .build() + .expect("failed to build the HTTP client"), token: None, } } @@ -292,4 +297,54 @@ mod retry_tests { assert_eq!(response.status(), reqwest::StatusCode::UNAUTHORIZED); } + + #[tokio::test] + async fn folder_auth_cookie_is_shared_with_a_fresh_token_connection() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.unwrap(); + let mut buf = [0u8; 4096]; + let _ = stream.read(&mut buf).await.unwrap(); + stream + .write_all( + b"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\nset-cookie: dirtoken=unlocked; Path=/\r\ncontent-length: 2\r\nconnection: close\r\n\r\n{}", + ) + .await + .unwrap(); + + let (mut stream, _) = listener.accept().await.unwrap(); + let n = stream.read(&mut buf).await.unwrap(); + let request = String::from_utf8_lossy(&buf[..n]); + assert!( + request + .to_ascii_lowercase() + .contains("cookie: dirtoken=unlocked"), + "the folder-auth cookie must be sent on the next retrieve: {request}" + ); + stream + .write_all( + b"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: 2\r\nconnection: close\r\n\r\n{}", + ) + .await + .unwrap(); + }); + + let conn = MDRSConnection::new(&format!("http://{addr}")); + let auth = conn + .post_json( + "v3/folders/f1/auth/", + &serde_json::json!({"password": "secret"}), + ) + .await + .unwrap(); + assert!(auth.status().is_success()); + let response = conn + .with_token("new-access-token".to_string()) + .get("v3/folders/f1/") + .await + .unwrap(); + assert!(response.status().is_success()); + server.await.unwrap(); + } } diff --git a/src/error.rs b/src/error.rs index 246d59e..0370bac 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,5 +1,35 @@ use anyhow::anyhow; use serde::Deserialize; +use std::fmt; + +/// A folder that cannot be opened until its password has been supplied. The retrieve +/// endpoint can also report this with a successful response containing only listing fields. +#[derive(Debug)] +pub struct FolderLockedError { + message: String, +} + +impl FolderLockedError { + pub fn new(name: impl Into) -> Self { + Self { + message: format!("Folder `{}` is locked.", name.into()), + } + } + + pub fn with_password_hint(mut self) -> Self { + self.message + .push_str(" Use -p/--password to provide a password."); + self + } +} + +impl fmt::Display for FolderLockedError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.message) + } +} + +impl std::error::Error for FolderLockedError {} /// The error envelope the API answers with (drf-standardized-errors). #[derive(Deserialize)]