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
This commit is contained in:
@@ -2,6 +2,14 @@
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Changed
|
||||
- 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.
|
||||
|
||||
## [2.0.3] - 2026-11-04
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -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.
|
||||
|
||||
+99
-3
@@ -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
@@ -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
@@ -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.")
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+36
-16
@@ -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,
|
||||
|
||||
+223
-24
@@ -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"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user