6 Commits
Author SHA1 Message Date
orrisroot 1cce7cf3e0 build: release 2.0.4
Release / build-linux-x86_64 (push) Successful in 2m32s
Release / build-linux-aarch64 (push) Successful in 2m30s
2026-11-27 17:23:53 +09:00
orrisroot 4069581098 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
2026-11-27 17:19:24 +09:00
orrisroot 05051dd307 feat(acl): compose access levels from their bits
Replace the fixed access-level table so new project levels are
labelled correctly and configurable through the CLI, matching the
Python client's project-aware behavior.

- Build labels from restrict, project, and password bits, and show
  meaningless values as Unknown (0x...)
- Read project names from users/current once for each ls run and use
  them in plain and JSON output
- Parse composable chacl keys, list available projects on invalid
  input, and reject public and storage before API requests
- Remove the obsolete 5kikan access-level key
2026-11-27 17:19:14 +09:00
orrisroot 22330d2b88 chore(deps): update dependencies and resolve url advisory
Refresh dependencies to resolve RUSTSEC-2026-0592 and keep the
direct dependency requirements aligned with the resolved lockfile.

- Update compatible dependencies, including url 2.5.9
- Migrate reqwest to 0.13 and dirs to 7
- Enable the reqwest form, query, and renamed rustls features
- Align Cargo.toml dependency versions with Cargo.lock
2026-11-27 16:23:29 +09:00
orrisroot a036d3ef46 fix(scripts): report Gitea API errors in release uploads
The macOS and Linux release scripts called the Gitea API with
`curl -sf`, which discards the response on failure. A rejected token
surfaced only as a JSON decode error from the release id lookup.

- Route API calls through gitea_api, which keeps the HTTP status and
  the response body
- On failure print the status and Gitea's message, with a hint about
  the token scope on 401/403, and exit
- Look up the release first and create it only on 404 instead of
  ignoring every creation error
- Check the status of each asset upload
2026-11-04 20:15:15 +09:00
orrisroot e1081aeff4 fix(scripts): keep .env values out of the PowerShell session
A .ps1 runs inside the caller's PowerShell process, so the values the
Windows release script exported from .env outlived the script. A
later run in the same session kept the old GITEA_TOKEN even after .env
was edited, because existing environment variables take precedence.

- Read .env into a script-local table and resolve settings through
  Get-Setting, with environment variables still taking precedence
- Stop changing the caller's current location; build and archive
  with paths anchored at the repository root
- Skip .env lines without "=" instead of failing under StrictMode
2026-11-04 20:15:14 +09:00
17 changed files with 1395 additions and 281 deletions
+15
View File
@@ -2,6 +2,21 @@
All notable changes to this project will be documented in this file.
## [2.0.4] - 2026-11-27
### Changed
- Updated dependencies and migrated to `reqwest` 0.13 and `dirs` 7.
- Built access-level labels from their bits and named project levels using the projects returned by the server. `chacl` accepts composable keys such as `project0_open` and `cbs_or_pw_open`, and an invalid key lists the user's available project keys. The obsolete `5kikan_open` key is no longer accepted; `public` and `storage` are refused before any request.
### 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.
### Security
- Updated `url` to 2.5.9 to resolve RUSTSEC-2026-0592.
## [2.0.3] - 2026-11-04
### Changed
Generated
+485 -119
View File
File diff suppressed because it is too large Load Diff
+21 -21
View File
@@ -1,6 +1,6 @@
[package]
name = "mdrs-client-rust"
version = "2.0.3"
version = "2.0.4"
edition = "2024"
license = "MIT"
authors = ["Neuroinformatics Unit, RIKEN CBS"]
@@ -11,26 +11,26 @@ name = "mdrs"
path = "src/main.rs"
[dependencies]
clap = { version = "4.5", features = ["derive"] }
reqwest = { version = "0.12", default-features = false, features = ["json", "multipart", "rustls-tls", "stream"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.151"
tokio = { version = "1.53.1", features = ["full"] }
tokio-util = { version = "0.7", features = ["io"] }
futures = "0.3"
dirs = "6.0.0"
anyhow = "1.0.104"
configparser = "3.2.0"
sha2 = "0.11.0"
rpassword = "7.5.4"
clap = { version = "4.6.10", features = ["derive"] }
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"] }
tokio-util = { version = "0.7.20", features = ["io"] }
futures = "0.3.34"
dirs = "7.0.0"
anyhow = "1.0.105"
configparser = "3.3.0"
sha2 = "0.11.2"
rpassword = "7.5.5"
base64 = "0.23.1"
fs2 = "0.4"
ctrlc = "3"
fs2 = "0.4.3"
ctrlc = "3.5.3"
os_info = "3.15.0"
dotenvy = "0.15"
unicode-normalization = "0.1"
self-replace = "1"
dotenvy = "0.15.7"
unicode-normalization = "0.1.26"
self-replace = "1.5.1"
tar = "0.4.46"
flate2 = "1"
zip = "9.3.0"
tempfile = "3"
flate2 = "1.1.11"
zip = "9.8.2"
tempfile = "3.27.0"
+4 -4
View File
@@ -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/
@@ -179,16 +179,16 @@ mdrs rm -r neurodata:/NIU/Repository/TEST/dataset
### chacl
Change the access level of a remote folder.
Change the access level of a remote folder. The level is `private`, `pw_open`, `cbs_open`, `project<n>_open`, or several open levels joined by `_or_`. `<n>` is the project's bit position; an invalid level lists the projects you belong to with their keys. Project names returned by the server are also used in `ls` access-level labels.
```shell
mdrs chacl private neurodata:/NIU/Repository/Private
mdrs chacl cbs_open -r neurodata:/NIU/Repository/CBS_Open
mdrs chacl pw_open -r -p SHARING_PASSWORD neurodata:/NIU/Repository/PW_Open
mdrs chacl cbs_or_pw_open -p SHARING_PASSWORD neurodata:/NIU/Repository/CBS_or_PW_Open
mdrs chacl project0_open neurodata:/NIU/Repository/Project_Open
```
Available access levels: `private`, `public`, `pw_open`, `cbs_open`, `5kikan_open`, `cbs_pw_open`, `5kikan_pw_open`
### metadata
Show metadata for a remote folder. You can also specify a DOI path.
+42 -15
View File
@@ -80,26 +80,53 @@ fi
: "${GITEA_SERVER_URL:?GITEA_SERVER_URL is required for upload}"
: "${GITEA_REPOSITORY:?GITEA_REPOSITORY is required for upload}"
echo ""
echo "==> Creating Gitea release ${TAG} ..."
curl -sf -X POST \
-H "Authorization: Bearer ${GITEA_TOKEN}" \
-H "Content-Type: application/json" \
"${GITEA_SERVER_URL}/api/v1/repos/${GITEA_REPOSITORY}/releases" \
-d "{\"tag_name\": \"${TAG}\", \"name\": \"${TAG}\"}" > /dev/null || true
API_BODY="$(mktemp)"
trap 'rm -f "${API_BODY}"' EXIT
RELEASE_ID="$(curl -sf \
-H "Authorization: Bearer ${GITEA_TOKEN}" \
"${GITEA_SERVER_URL}/api/v1/repos/${GITEA_REPOSITORY}/releases/tags/${TAG}" \
| python3 -c 'import sys,json; print(json.load(sys.stdin)["id"])')"
# Call the Gitea repository API. The HTTP status is left in API_STATUS and
# the response body in ${API_BODY}; curl itself failing (DNS, TLS, ...)
# aborts the script with curl's own message.
gitea_api() {
local method="$1" path="$2"
shift 2
API_STATUS="$(curl -sS -o "${API_BODY}" -w '%{http_code}' -X "${method}" \
-H "Authorization: Bearer ${GITEA_TOKEN}" "$@" \
"${GITEA_SERVER_URL}/api/v1/repos/${GITEA_REPOSITORY}${path}")"
}
# Abort with the HTTP status and the error message Gitea returned
api_fail() {
local message
message="$(python3 -c 'import sys,json; print(json.load(sys.stdin)["message"])' \
< "${API_BODY}" 2>/dev/null || head -c 500 "${API_BODY}")"
echo "Error: $1 failed (HTTP ${API_STATUS}): ${message}" >&2
if [[ "${API_STATUS}" == 401 || "${API_STATUS}" == 403 ]]; then
echo "Check GITEA_TOKEN: it must be valid and have the write:repository scope." >&2
fi
exit 1
}
echo ""
gitea_api GET "/releases/tags/${TAG}"
if [[ "${API_STATUS}" == 200 ]]; then
echo "==> Using existing Gitea release ${TAG}"
elif [[ "${API_STATUS}" == 404 ]]; then
echo "==> Creating Gitea release ${TAG} ..."
gitea_api POST "/releases" \
-H "Content-Type: application/json" \
-d "{\"tag_name\": \"${TAG}\", \"name\": \"${TAG}\"}"
[[ "${API_STATUS}" == 201 ]] || api_fail "Creating release ${TAG}"
else
api_fail "Looking up release ${TAG}"
fi
RELEASE_ID="$(python3 -c 'import sys,json; print(json.load(sys.stdin)["id"])' < "${API_BODY}")"
echo "==> Uploading assets (release id: ${RELEASE_ID}) ..."
for ARCHIVE in "${ARCHIVES[@]}"; do
echo " Uploading ${ARCHIVE} ..."
curl -sf -X POST \
-H "Authorization: Bearer ${GITEA_TOKEN}" \
-F "attachment=@${ARCHIVE}" \
"${GITEA_SERVER_URL}/api/v1/repos/${GITEA_REPOSITORY}/releases/${RELEASE_ID}/assets" > /dev/null
gitea_api POST "/releases/${RELEASE_ID}/assets" -F "attachment=@${ARCHIVE}"
[[ "${API_STATUS}" == 201 ]] || api_fail "Uploading ${ARCHIVE}"
echo " Done."
done
+42 -15
View File
@@ -68,26 +68,53 @@ fi
: "${GITEA_SERVER_URL:?GITEA_SERVER_URL is required for upload}"
: "${GITEA_REPOSITORY:?GITEA_REPOSITORY is required for upload}"
echo ""
echo "==> Creating Gitea release ${TAG} ..."
curl -sf -X POST \
-H "Authorization: Bearer ${GITEA_TOKEN}" \
-H "Content-Type: application/json" \
"${GITEA_SERVER_URL}/api/v1/repos/${GITEA_REPOSITORY}/releases" \
-d "{\"tag_name\": \"${TAG}\", \"name\": \"${TAG}\"}" > /dev/null || true
API_BODY="$(mktemp)"
trap 'rm -f "${API_BODY}"' EXIT
RELEASE_ID="$(curl -sf \
-H "Authorization: Bearer ${GITEA_TOKEN}" \
"${GITEA_SERVER_URL}/api/v1/repos/${GITEA_REPOSITORY}/releases/tags/${TAG}" \
| python3 -c 'import sys,json; print(json.load(sys.stdin)["id"])')"
# Call the Gitea repository API. The HTTP status is left in API_STATUS and
# the response body in ${API_BODY}; curl itself failing (DNS, TLS, ...)
# aborts the script with curl's own message.
gitea_api() {
local method="$1" path="$2"
shift 2
API_STATUS="$(curl -sS -o "${API_BODY}" -w '%{http_code}' -X "${method}" \
-H "Authorization: Bearer ${GITEA_TOKEN}" "$@" \
"${GITEA_SERVER_URL}/api/v1/repos/${GITEA_REPOSITORY}${path}")"
}
# Abort with the HTTP status and the error message Gitea returned
api_fail() {
local message
message="$(python3 -c 'import sys,json; print(json.load(sys.stdin)["message"])' \
< "${API_BODY}" 2>/dev/null || head -c 500 "${API_BODY}")"
echo "Error: $1 failed (HTTP ${API_STATUS}): ${message}" >&2
if [[ "${API_STATUS}" == 401 || "${API_STATUS}" == 403 ]]; then
echo "Check GITEA_TOKEN: it must be valid and have the write:repository scope." >&2
fi
exit 1
}
echo ""
gitea_api GET "/releases/tags/${TAG}"
if [[ "${API_STATUS}" == 200 ]]; then
echo "==> Using existing Gitea release ${TAG}"
elif [[ "${API_STATUS}" == 404 ]]; then
echo "==> Creating Gitea release ${TAG} ..."
gitea_api POST "/releases" \
-H "Content-Type: application/json" \
-d "{\"tag_name\": \"${TAG}\", \"name\": \"${TAG}\"}"
[[ "${API_STATUS}" == 201 ]] || api_fail "Creating release ${TAG}"
else
api_fail "Looking up release ${TAG}"
fi
RELEASE_ID="$(python3 -c 'import sys,json; print(json.load(sys.stdin)["id"])' < "${API_BODY}")"
echo "==> Uploading assets (release id: ${RELEASE_ID}) ..."
for ARCHIVE in "${ARCHIVES[@]}"; do
echo " Uploading ${ARCHIVE} ..."
curl -sf -X POST \
-H "Authorization: Bearer ${GITEA_TOKEN}" \
-F "attachment=@${ARCHIVE}" \
"${GITEA_SERVER_URL}/api/v1/repos/${GITEA_REPOSITORY}/releases/${RELEASE_ID}/assets" > /dev/null
gitea_api POST "/releases/${RELEASE_ID}/assets" -F "attachment=@${ARCHIVE}"
[[ "${API_STATUS}" == 201 ]] || api_fail "Uploading ${ARCHIVE}"
echo " Done."
done
+23 -16
View File
@@ -18,20 +18,28 @@ $ErrorActionPreference = "Stop"
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$RepoRoot = Split-Path -Parent $ScriptDir
# Load .env if present (existing env vars take precedence)
# Load .env if present. The values are kept in a script-local table rather
# than written to the process environment: a .ps1 runs inside the caller's
# PowerShell process, so anything set there would outlive the script and
# shadow later edits to .env in the same session.
$DotEnv = @{}
$EnvFile = Join-Path $ScriptDir ".env"
if (Test-Path $EnvFile) {
Get-Content $EnvFile | ForEach-Object {
if ($_ -match '^\s*#' -or $_ -match '^\s*$') { return }
if ($_ -match '^\s*#' -or $_ -notmatch '=') { return }
$parts = $_ -split '=', 2
$key = $parts[0].Trim()
$value = $parts[1].Trim()
if (-not [System.Environment]::GetEnvironmentVariable($key)) {
[System.Environment]::SetEnvironmentVariable($key, $value, "Process")
}
$DotEnv[$parts[0].Trim()] = $parts[1].Trim()
}
}
# Resolve a setting: an environment variable takes precedence over .env
function Get-Setting([string]$Name) {
$value = [System.Environment]::GetEnvironmentVariable($Name)
if ($value) { return $value }
if ($DotEnv.ContainsKey($Name)) { return $DotEnv[$Name] }
return $null
}
# Determine version
if (-not $Version) {
$cargoToml = Get-Content (Join-Path $RepoRoot "Cargo.toml") -Raw
@@ -46,23 +54,22 @@ if (-not $Version) {
$Tag = "v$Version"
$Target = "x86_64-pc-windows-msvc"
Set-Location $RepoRoot
Write-Host "==> Building mdrs $Version for Windows ($Target)"
rustup target add $Target
cargo build --release --target $Target
cargo build --release --target $Target --manifest-path (Join-Path $RepoRoot "Cargo.toml")
$Archive = "mdrs-$Version-$Target.zip"
Compress-Archive -Force -Path "target\$Target\release\mdrs.exe" -DestinationPath $Archive
$ArchivePath = Join-Path $RepoRoot $Archive
Compress-Archive -Force -Path (Join-Path $RepoRoot "target\$Target\release\mdrs.exe") -DestinationPath $ArchivePath
# Written alongside the archive so `mdrs selfupdate` can check what it fetched.
$Checksum = "$Archive.sha256"
$Hash = (Get-FileHash -Algorithm SHA256 -Path $Archive).Hash.ToLower()
"$Hash $Archive" | Set-Content -NoNewline -Encoding ascii $Checksum
$Hash = (Get-FileHash -Algorithm SHA256 -Path $ArchivePath).Hash.ToLower()
"$Hash $Archive" | Set-Content -NoNewline -Encoding ascii (Join-Path $RepoRoot $Checksum)
Write-Host " Created: $Archive"
# Upload to Gitea if token is provided
$GiteaToken = [System.Environment]::GetEnvironmentVariable("GITEA_TOKEN")
$GiteaToken = Get-Setting "GITEA_TOKEN"
if (-not $GiteaToken) {
Write-Host ""
Write-Host "GITEA_TOKEN not set -- skipping upload."
@@ -70,8 +77,8 @@ if (-not $GiteaToken) {
exit 0
}
$ServerUrl = [System.Environment]::GetEnvironmentVariable("GITEA_SERVER_URL")
$Repository = [System.Environment]::GetEnvironmentVariable("GITEA_REPOSITORY")
$ServerUrl = Get-Setting "GITEA_SERVER_URL"
$Repository = Get-Setting "GITEA_REPOSITORY"
if (-not $ServerUrl) { Write-Error "GITEA_SERVER_URL is required for upload"; exit 1 }
if (-not $Repository) { Write-Error "GITEA_REPOSITORY is required for upload"; exit 1 }
+61 -3
View File
@@ -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<FolderDetail, anyhow::Error> {
// 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::<FolderDetail>().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::<FolderDetail>().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::<FolderLockedError>().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);
}
}
+99 -3
View File
@@ -1,7 +1,9 @@
use crate::connection::MDRSConnection;
use crate::error::response_error;
use crate::models::folder::ProjectNames;
use crate::models::user::User as ModelUser;
use serde::Deserialize;
use std::collections::BTreeMap;
use std::time::Duration;
/// Bound the refresh on its own: the caller holds a lock that spans processes while this
@@ -17,6 +19,8 @@ struct UsersApiCurrentResponse {
username: String,
laboratories: Vec<UsersCurrentResponseLaboratory>,
is_reviewer: bool,
#[serde(default)]
projects: Vec<UsersCurrentResponseProject>,
}
#[derive(Debug, Deserialize)]
@@ -24,6 +28,12 @@ struct UsersCurrentResponseLaboratory {
id: u32,
}
#[derive(Debug, Deserialize)]
struct UsersCurrentResponseProject {
name: Option<String>,
bit_position: u32,
}
#[derive(Deserialize)]
struct TokenRefreshResponse {
access: String,
@@ -40,13 +50,17 @@ pub struct RefreshedToken {
}
impl MDRSConnection {
/// Fetch current user and return the slim 4-field model matching the Python cache format.
pub async fn get_current_user(&self) -> Result<ModelUser, anyhow::Error> {
async fn current_user_response(&self) -> Result<UsersApiCurrentResponse, anyhow::Error> {
let resp = self.get("v3/users/current/").await?;
if !resp.status().is_success() {
return Err(response_error("Get current user failed", resp).await);
}
let obj = resp.json::<UsersApiCurrentResponse>().await?;
Ok(resp.json::<UsersApiCurrentResponse>().await?)
}
/// Fetch current user and return the slim 4-field model matching the Python cache format.
pub async fn get_current_user(&self) -> Result<ModelUser, anyhow::Error> {
let obj = self.current_user_response().await?;
let laboratory_ids = obj.laboratories.into_iter().map(|l| l.id).collect();
Ok(ModelUser {
id: obj.id,
@@ -56,6 +70,28 @@ impl MDRSConnection {
})
}
/// Fetch project names by access-level bit position. Project names are visible only
/// to their members, so an anonymous connection needs no request and returns none.
pub async fn get_project_names(&self) -> Result<ProjectNames, anyhow::Error> {
if self.token.is_none() {
return Ok(ProjectNames::new());
}
let obj = self.current_user_response().await?;
let mut names: BTreeMap<u32, Vec<String>> = BTreeMap::new();
for project in obj.projects {
if let Some(name) = project.name.filter(|name| !name.is_empty()) {
names.entry(project.bit_position).or_default().push(name);
}
}
Ok(names
.into_iter()
.map(|(bit, mut names)| {
names.sort();
(bit, names.join(", "))
})
.collect())
}
/// Refresh the access token using the refresh token.
/// POST v3/users/token/refresh/ {refresh: ...} -> {access, refresh?}
///
@@ -136,4 +172,64 @@ mod tests {
assert_eq!(refreshed.access, "new-access");
assert_eq!(refreshed.refresh, None);
}
async fn project_names_against_stub(projects: Option<&str>) -> ProjectNames {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let projects = projects
.map(|projects| format!(r#","projects":{projects}"#))
.unwrap_or_default();
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 req = String::from_utf8_lossy(&buf[..n]);
assert!(req.starts_with("GET /v3/users/current/ HTTP/1.1"));
let body = format!(
r#"{{"id":1,"username":"user","laboratories":[],"is_reviewer":false{projects}}}"#
);
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();
});
let conn = MDRSConnection::new(&format!("http://{addr}")).with_token("token".to_string());
let names = conn.get_project_names().await.unwrap();
server.await.unwrap();
names
}
#[tokio::test]
async fn project_names_combines_all_names_at_a_shared_bit_position() {
let names = project_names_against_stub(Some(
r#"[
{"id":1,"name":"Brain/MINDS 2.0","bit_position":0},
{"id":2,"name":"B","bit_position":3},
{"id":3,"name":"A","bit_position":3},
{"id":4,"name":null,"bit_position":5},
{"id":5,"name":"","bit_position":5}
]"#,
))
.await;
assert_eq!(names.get(&0).map(String::as_str), Some("Brain/MINDS 2.0"));
assert_eq!(names.get(&3).map(String::as_str), Some("A, B"));
assert!(!names.contains_key(&5));
}
#[tokio::test]
async fn project_names_is_empty_when_the_server_has_no_projects_field() {
assert!(project_names_against_stub(None).await.is_empty());
}
#[tokio::test]
async fn anonymous_project_names_require_no_request() {
let conn = MDRSConnection::new("http://127.0.0.1:9");
assert!(conn.get_project_names().await.unwrap().is_empty());
}
}
+4 -2
View File
@@ -64,11 +64,13 @@ pub enum Commands {
remote: String,
},
Chacl {
/// Access level key: private, public, pw_open, cbs_open, 5kikan_open,
/// cbs_or_pw_open, 5kikan_or_pw_open, storage
/// Access level: private, pw_open, cbs_open, project<n>_open,
/// or several open levels joined by `_or_` (e.g. cbs_or_pw_open).
/// An invalid level lists the projects you belong to.
access_level_key: String,
#[arg(short, long)]
recursive: bool,
/// Password to set when the access level includes `pw` (e.g. pw_open)
#[arg(short = 'p', long)]
password: Option<String>,
remote_path: String,
+85 -11
View File
@@ -1,25 +1,28 @@
use crate::cache::{create_authenticated_conn, load_cache_with_token_refresh};
use crate::cache::{
create_authenticated_conn, create_readonly_conn, load_cache_with_token_refresh,
};
use crate::commands::shared::{find_folder, find_laboratory, parse_remote_path};
use crate::error::response_error;
use crate::models::folder::{
PUBLIC_ACCESS_LEVEL, ProjectNames, STORAGE_ACCESS_LEVEL, access_level_from_key,
};
use anyhow::bail;
const INVALID_ACCESS_LEVEL_MESSAGE: &str = "Invalid `access_level` parameter. must be `private`, `pw_open`, `cbs_open`, `project<n>_open` or open levels joined by `_or_` (e.g. `cbs_or_pw_open`).";
pub async fn chacl(
remote_path: &str,
access_level_key: &str,
recursive: bool,
password: Option<&str>,
) -> Result<(), anyhow::Error> {
let access_level_id: u32 = match access_level_key {
"private" => 0x0001,
"public" => 0x0002,
"pw_open" => 0x0004,
"cbs_open" => 0x0100,
"5kikan_open" => 0x0200,
"cbs_or_pw_open" => 0x0104,
"5kikan_or_pw_open" => 0x0204,
"storage" => 0x0000,
_ => bail!("Unknown access level key: '{}'", access_level_key),
let Some(access_level_id) = access_level_from_key(access_level_key) else {
bail!("{}", invalid_access_level_message(remote_path).await);
};
if access_level_id == STORAGE_ACCESS_LEVEL || access_level_id == PUBLIC_ACCESS_LEVEL {
// The server refuses both; report the invalid operation before making a request.
bail!("`{access_level_key}` cannot be set as an access level.");
}
let (remote, labname, folder_path) = parse_remote_path(remote_path)?;
let cache = load_cache_with_token_refresh(&remote).await?;
@@ -50,3 +53,74 @@ pub async fn chacl(
}
Ok(())
}
async fn invalid_access_level_message(remote_path: &str) -> String {
// Project numbers exist only on the server. Failure to fetch them must not hide the
// original error: the access-level key was invalid independently of the connection.
let projects = async {
let (remote, _, _) = parse_remote_path(remote_path)?;
let (conn, _) = create_readonly_conn(&remote).await?;
conn.get_project_names().await
}
.await
.unwrap_or_default();
format_invalid_access_level_message(&projects)
}
fn format_invalid_access_level_message(projects: &ProjectNames) -> String {
let mut message = INVALID_ACCESS_LEVEL_MESSAGE.to_string();
if !projects.is_empty() {
message.push_str("\nProjects you belong to:");
for (bit, name) in projects {
message.push_str(&format!("\n project{bit}_open: {name}"));
}
}
message
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
#[test]
fn invalid_level_message_lists_project_keys_and_names() {
let message = format_invalid_access_level_message(&BTreeMap::from([(
0,
"Brain/MINDS 2.0".to_string(),
)]));
assert!(message.contains("project<n>_open"));
assert!(message.contains("project0_open: Brain/MINDS 2.0"));
}
#[test]
fn invalid_level_message_stands_alone_without_project_names() {
assert_eq!(
format_invalid_access_level_message(&ProjectNames::new()),
INVALID_ACCESS_LEVEL_MESSAGE
);
}
#[tokio::test]
async fn an_invalid_key_keeps_its_own_error_without_a_usable_remote() {
let err = chacl("not-a-remote-path", "5kikan_open", false, None)
.await
.unwrap_err();
assert_eq!(err.to_string(), INVALID_ACCESS_LEVEL_MESSAGE);
}
#[tokio::test]
async fn public_and_storage_are_refused_before_using_a_remote_path() {
for level in ["public", "storage"] {
let err = chacl("not-a-remote-path", level, false, None)
.await
.unwrap_err();
assert_eq!(
err.to_string(),
format!("`{level}` cannot be set as an access level.")
);
}
}
}
+85 -1
View File
@@ -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<Result<DownloadFolderTaskResult, anyhow::Error>> =
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/<remote_folder_name>/ (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<T>(
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::<FolderLockedError>().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();
}
}
+36 -16
View File
@@ -2,7 +2,7 @@ use crate::cache::{Cache, create_readonly_conn};
use crate::commands::shared::{fmt_datetime, resolve_remote_folder};
use crate::connection::MDRSConnection;
use crate::models::file::File;
use crate::models::folder::{FolderDetail, FolderSimple};
use crate::models::folder::{FolderDetail, FolderSimple, ProjectNames};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::future::Future;
@@ -29,29 +29,32 @@ pub async fn ls(
let (folder, lab) =
resolve_remote_folder(&conn, cache.as_ref(), None, remote_path, password).await?;
let labname = lab.name;
let projects = conn.get_project_names().await?;
if is_json {
let names = laboratory_names(&conn, cache.as_ref()).await;
let output = if is_recursive {
build_folder_json_recursive(&conn, folder, &names, password).await?
build_folder_json_recursive(&conn, folder, &names, &projects, password).await?
} else {
build_folder_json_flat(&conn, &folder, &names).await?
build_folder_json_flat(&conn, &folder, &names, &projects).await?
};
println!("{}", serde_json::to_string(&output)?);
} else if is_recursive {
let prefix = format!("{}:/{}", conn.remote.as_deref().unwrap_or(""), labname);
ls_plain_recursive(&conn, folder, &labname, &prefix, password).await?;
ls_plain_recursive(&conn, folder, &labname, &prefix, &projects, password).await?;
} else {
let files = conn.list_all_files(&folder.id).await?;
let mut sub_folders = folder.sub_folders.clone();
sub_folders.sort_by(|a, b| a.name.cmp(&b.name));
let mut files_sorted = files;
files_sorted.sort_by(|a, b| a.name.cmp(&b.name));
let access = folder.access_level_label(&projects);
print_folder_plain(
&sub_folders,
&files_sorted,
folder.access_level_name(),
&access,
&labname,
&projects,
!is_quiet,
);
}
@@ -68,6 +71,7 @@ fn print_folder_plain(
files: &[File],
folder_access: &str,
labname: &str,
projects: &ProjectNames,
show_header: bool,
) {
let header = ("Type", "Access", "Laboratory", "Size", "Date", "Name");
@@ -82,7 +86,7 @@ fn print_folder_plain(
w_type = w_type.max(3);
for sf in sub_folders {
w_access = w_access.max(sf.access_level_name().len());
w_access = w_access.max(sf.access_level_label(projects).len());
w_size = w_size.max(sf.size.to_string().len());
w_date = w_date.max(fmt_datetime(&sf.updated_at).len());
w_name = w_name.max(sf.name.len());
@@ -119,7 +123,7 @@ fn print_folder_plain(
println!(
"{:<w_type$} {:<w_access$} {:<w_lab$} {:>w_size$} {:<w_date$} {:<w_name$}",
folder_type,
sf.access_level_name(),
sf.access_level_label(projects),
labname,
sf.size,
fmt_datetime(&sf.updated_at),
@@ -158,6 +162,7 @@ fn ls_plain_recursive<'a>(
folder: FolderDetail,
labname: &'a str,
prefix: &'a str,
projects: &'a ProjectNames,
password: Option<&'a str>,
) -> Pin<Box<dyn Future<Output = Result<(), anyhow::Error>> + 'a>> {
Box::pin(async move {
@@ -167,13 +172,20 @@ fn ls_plain_recursive<'a>(
println!("{}{}:", prefix, folder.path);
println!("total {}", total_size);
let access = folder.access_level_name();
let access = folder.access_level_label(projects);
let mut sub_folders = folder.sub_folders.clone();
sub_folders.sort_by(|a, b| a.name.cmp(&b.name));
let mut files_sorted = files;
files_sorted.sort_by(|a, b| a.name.cmp(&b.name));
print_folder_plain(&sub_folders, &files_sorted, access, labname, false);
print_folder_plain(
&sub_folders,
&files_sorted,
&access,
labname,
projects,
false,
);
println!();
@@ -190,7 +202,8 @@ fn ls_plain_recursive<'a>(
}
match conn.retrieve_folder(&sf.id).await {
Ok(sub_detail) => {
ls_plain_recursive(conn, sub_detail, labname, prefix, password).await?;
ls_plain_recursive(conn, sub_detail, labname, prefix, projects, password)
.await?;
}
Err(_) => continue,
}
@@ -243,12 +256,16 @@ fn file_to_json(f: &File, base_url: &str) -> Value {
})
}
fn folder_simple_to_json(sf: &FolderSimple, names: &LaboratoryNames) -> Value {
fn folder_simple_to_json(
sf: &FolderSimple,
names: &LaboratoryNames,
projects: &ProjectNames,
) -> Value {
json!({
"id": sf.id,
"pid": sf.pid,
"name": sf.name,
"access_level": sf.access_level_name(),
"access_level": sf.access_level_label(projects),
"lock": sf.lock,
"size": sf.size,
"laboratory": laboratory_name(names, sf.laboratory_id),
@@ -293,6 +310,7 @@ async fn build_folder_json_flat(
conn: &MDRSConnection,
folder: &FolderDetail,
names: &LaboratoryNames,
projects: &ProjectNames,
) -> Result<Value, anyhow::Error> {
let metadata = get_folder_metadata(conn, &folder.id).await?;
let mut files = conn.list_all_files(&folder.id).await?;
@@ -302,7 +320,7 @@ async fn build_folder_json_flat(
sub_folders.sort_by(|a, b| a.name.cmp(&b.name));
let sub_folders_json: Vec<Value> = sub_folders
.iter()
.map(|sf| folder_simple_to_json(sf, names))
.map(|sf| folder_simple_to_json(sf, names, projects))
.collect();
Ok(json!({
@@ -310,7 +328,7 @@ async fn build_folder_json_flat(
"pid": folder.pid,
"name": folder.name,
"size": folder.size,
"access_level": folder.access_level_name(),
"access_level": folder.access_level_label(projects),
"lock": folder.lock,
"laboratory": laboratory_name(names, folder.laboratory_id),
"description": folder.description,
@@ -327,6 +345,7 @@ fn build_folder_json_recursive<'a>(
conn: &'a MDRSConnection,
folder: FolderDetail,
names: &'a LaboratoryNames,
projects: &'a ProjectNames,
password: Option<&'a str>,
) -> Pin<Box<dyn Future<Output = Result<Value, anyhow::Error>> + 'a>> {
Box::pin(async move {
@@ -355,7 +374,8 @@ fn build_folder_json_recursive<'a>(
}
}
let sf_detail = conn.retrieve_folder(&sf.id).await?;
let sf_json = build_folder_json_recursive(conn, sf_detail, names, password).await?;
let sf_json =
build_folder_json_recursive(conn, sf_detail, names, projects, password).await?;
sub_folders_json.push(sf_json);
}
@@ -364,7 +384,7 @@ fn build_folder_json_recursive<'a>(
"pid": folder.pid,
"name": folder.name,
"size": folder.size,
"access_level": folder.access_level_name(),
"access_level": folder.access_level_label(projects),
"lock": folder.lock,
"laboratory": laboratory_name(names, folder.laboratory_id),
"description": folder.description,
+84 -30
View File
@@ -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
// ------------------------------------------------------------------
+56 -1
View File
@@ -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();
}
}
+30
View File
@@ -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<String>) -> 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)]
+223 -24
View File
@@ -1,4 +1,19 @@
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
/// Project names by the bit position used in their folder access levels.
pub type ProjectNames = BTreeMap<u32, String>;
// Bits 0-2 are private/public/password, bits 3-7 are reserved, bits 8-15 select
// restrict networks, and bit 16 onward selects projects by their server-assigned positions.
pub const STORAGE_ACCESS_LEVEL: i64 = 0x0000;
pub const PRIVATE_ACCESS_LEVEL: i64 = 0x0001;
pub const PUBLIC_ACCESS_LEVEL: i64 = 0x0002;
const PASSWORD_ACCESS_LEVEL: i64 = 0x0004;
const RESERVED_ACCESS_LEVEL: i64 = 0x00f8;
const RESTRICT_SHIFT: u32 = 8;
const RESTRICT_SLOTS: u32 = 8;
const PROJECT_SHIFT: u32 = 16;
/// Lightweight folder entry returned by the list endpoint (v3/folders/?path=...&laboratory_id=...)
#[derive(Debug, Serialize, Deserialize, Clone)]
@@ -6,7 +21,7 @@ pub struct FolderSimple {
pub id: String,
pub pid: Option<String>,
pub name: String,
pub access_level: u32,
pub access_level: i64,
pub lock: bool,
pub size: u64,
pub laboratory_id: u32,
@@ -16,8 +31,8 @@ pub struct FolderSimple {
}
impl FolderSimple {
pub fn access_level_name(&self) -> &'static str {
access_level_label(self.access_level)
pub fn access_level_label(&self, projects: &ProjectNames) -> String {
access_level_label_or_unknown(self.access_level, projects)
}
}
@@ -27,7 +42,7 @@ pub struct FolderDetail {
pub id: String,
pub pid: Option<String>,
pub name: String,
pub access_level: u32,
pub access_level: i64,
pub lock: bool,
pub size: u64,
pub laboratory_id: u32,
@@ -39,32 +54,216 @@ pub struct FolderDetail {
}
impl FolderDetail {
pub fn access_level_name(&self) -> &'static str {
access_level_label(self.access_level)
pub fn access_level_label(&self, projects: &ProjectNames) -> String {
access_level_label_or_unknown(self.access_level, projects)
}
}
pub fn access_level_label(level: u32) -> &'static str {
if (level & 0x0204) == 0x0204 {
return "5Kikan or PW Open";
/// Build an access-level label from its bits instead of a table of known combinations.
pub fn access_level_label(level: i64, projects: &ProjectNames) -> Option<String> {
match level {
STORAGE_ACCESS_LEVEL => return Some("Storage".to_string()),
PRIVATE_ACCESS_LEVEL => return Some("Private".to_string()),
PUBLIC_ACCESS_LEVEL => return Some("Public".to_string()),
_ => {}
}
if (level & 0x0104) == 0x0104 {
return "CBS or PW Open";
if level < 0
|| level & (PRIVATE_ACCESS_LEVEL | PUBLIC_ACCESS_LEVEL | RESERVED_ACCESS_LEVEL) != 0
{
return None;
}
if (level & 0x0200) == 0x0200 {
return "5Kikan Open";
let mut names = Vec::new();
for slot in 1..=RESTRICT_SLOTS {
if level & (1_i64 << (RESTRICT_SHIFT + slot - 1)) != 0 {
names.push(if slot == 1 {
"CBS".to_string()
} else {
format!("Restrict{slot}")
});
}
}
if (level & 0x0100) == 0x0100 {
return "CBS Open";
let project_bits = (level >> PROJECT_SHIFT) as u64;
for bit in 0..u64::BITS {
if project_bits & (1_u64 << bit) != 0 {
names.push(
projects
.get(&bit)
.filter(|name| !name.is_empty())
.cloned()
.unwrap_or_else(|| format!("Project{bit}")),
);
}
}
if (level & 0x0004) == 0x0004 {
return "PW Open";
if level & PASSWORD_ACCESS_LEVEL != 0 {
names.push("PW".to_string());
}
Some(format!("{} Open", names.join(" or ")))
}
pub fn access_level_label_or_unknown(level: i64, projects: &ProjectNames) -> String {
access_level_label(level, projects).unwrap_or_else(|| {
if level < 0 {
format!("Unknown (0x-{:x})", level.unsigned_abs())
} else {
format!("Unknown (0x{level:x})")
}
})
}
/// Parse a CLI access-level key such as `cbs_or_project0_open`.
pub fn access_level_from_key(key: &str) -> Option<i64> {
match key {
"storage" => return Some(STORAGE_ACCESS_LEVEL),
"private" => return Some(PRIVATE_ACCESS_LEVEL),
"public" => return Some(PUBLIC_ACCESS_LEVEL),
_ => {}
}
let parts = key.strip_suffix("_open")?;
let mut level = 0_i64;
for part in parts.split("_or_") {
level |= access_level_part(part)?;
}
Some(level)
}
fn access_level_part(part: &str) -> Option<i64> {
if part == "pw" {
return Some(PASSWORD_ACCESS_LEVEL);
}
if part == "cbs" {
return Some(1_i64 << RESTRICT_SHIFT);
}
if let Some(slot) = part
.strip_prefix("restrict")
.and_then(parse_canonical_unsigned)
&& slot > 0
{
if slot > RESTRICT_SLOTS {
return None;
}
return Some(1_i64 << (RESTRICT_SHIFT + slot - 1));
}
if let Some(bit) = part
.strip_prefix("project")
.and_then(parse_canonical_unsigned)
{
let shift = PROJECT_SHIFT.checked_add(bit)?;
if shift >= i64::BITS - 1 {
return None;
}
return Some(1_i64 << shift);
}
None
}
fn parse_canonical_unsigned(value: &str) -> Option<u32> {
if value.is_empty()
|| !value.bytes().all(|byte| byte.is_ascii_digit())
|| (value.len() > 1 && value.starts_with('0'))
{
return None;
}
value.parse().ok()
}
#[cfg(test)]
mod tests {
use super::*;
fn projects() -> ProjectNames {
BTreeMap::from([(0, "Brain/MINDS 2.0".to_string())])
}
#[test]
fn labels_single_and_combined_levels_from_their_bits() {
let cases = [
(0x0000, "Storage"),
(0x0001, "Private"),
(0x0002, "Public"),
(0x0004, "PW Open"),
(0x0100, "CBS Open"),
(0x0104, "CBS or PW Open"),
(0x0200, "Restrict2 Open"),
(0x8000, "Restrict8 Open"),
];
for (level, expected) in cases {
assert_eq!(
access_level_label(level, &ProjectNames::new()).as_deref(),
Some(expected),
"level {level:#x}"
);
}
}
#[test]
fn labels_projects_with_server_names_or_bit_positions() {
assert_eq!(
access_level_label(0x10004, &projects()).as_deref(),
Some("Brain/MINDS 2.0 or PW Open")
);
assert_eq!(
access_level_label(0x10000, &ProjectNames::new()).as_deref(),
Some("Project0 Open")
);
assert_eq!(
access_level_label(0x10000, &BTreeMap::from([(0, String::new())])).as_deref(),
Some("Project0 Open")
);
assert_eq!(
access_level_label(0x20000, &projects()).as_deref(),
Some("Project1 Open")
);
assert_eq!(
access_level_label(0x30304, &projects()).as_deref(),
Some("CBS or Restrict2 or Brain/MINDS 2.0 or Project1 or PW Open")
);
}
#[test]
fn meaningless_levels_are_unknown_instead_of_storage() {
for level in [0x0003, 0x0006, 0x0102, 0x10001, 0x0008, 0x0080, -1] {
assert_eq!(access_level_label(level, &ProjectNames::new()), None);
}
assert_eq!(
access_level_label_or_unknown(0x0008, &ProjectNames::new()),
"Unknown (0x8)"
);
}
#[test]
fn parses_open_level_keys_from_their_parts() {
let cases = [
("storage", 0x0000),
("private", 0x0001),
("public", 0x0002),
("pw_open", 0x0004),
("cbs_open", 0x0100),
("cbs_or_pw_open", 0x0104),
("restrict1_open", 0x0100),
("restrict2_open", 0x0200),
("project0_open", 0x10000),
("project1_or_pw_open", 0x20004),
];
for (key, expected) in cases {
assert_eq!(access_level_from_key(key), Some(expected), "key {key}");
}
}
#[test]
fn rejects_unknown_or_ambiguous_keys() {
for key in [
"5kikan_open",
"restrict9_open",
"restrict0_open",
"project01_open",
"cbs",
"_open",
"pw_or_open",
] {
assert_eq!(access_level_from_key(key), None, "key {key}");
}
}
if (level & 0x0002) == 0x0002 {
return "Public";
}
if (level & 0x0001) == 0x0001 {
return "Private";
}
"Storage"
}