diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ac19c0..2364936 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index 1c59bad..3bdb590 100644 --- a/README.md +++ b/README.md @@ -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_open`, or several open levels joined by `_or_`. `` 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. diff --git a/src/api/users.rs b/src/api/users.rs index db77a6a..10d87f7 100644 --- a/src/api/users.rs +++ b/src/api/users.rs @@ -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, is_reviewer: bool, + #[serde(default)] + projects: Vec, } #[derive(Debug, Deserialize)] @@ -24,6 +28,12 @@ struct UsersCurrentResponseLaboratory { id: u32, } +#[derive(Debug, Deserialize)] +struct UsersCurrentResponseProject { + name: Option, + 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 { + async fn current_user_response(&self) -> Result { 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::().await?; + Ok(resp.json::().await?) + } + + /// Fetch current user and return the slim 4-field model matching the Python cache format. + pub async fn get_current_user(&self) -> Result { + 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 { + if self.token.is_none() { + return Ok(ProjectNames::new()); + } + let obj = self.current_user_response().await?; + let mut names: BTreeMap> = 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()); + } } diff --git a/src/cli.rs b/src/cli.rs index 8abc4e1..6e018cc 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -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_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, remote_path: String, diff --git a/src/commands/chacl.rs b/src/commands/chacl.rs index cf64f4d..6f91f95 100644 --- a/src/commands/chacl.rs +++ b/src/commands/chacl.rs @@ -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_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_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.") + ); + } + } +} diff --git a/src/commands/ls.rs b/src/commands/ls.rs index 7e411a5..46d1d13 100644 --- a/src/commands/ls.rs +++ b/src/commands/ls.rs @@ -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_size$} {:( folder: FolderDetail, labname: &'a str, prefix: &'a str, + projects: &'a ProjectNames, password: Option<&'a str>, ) -> Pin> + '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 { 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 = 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> + '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, diff --git a/src/models/folder.rs b/src/models/folder.rs index 9ccfeb8..731bdb3 100644 --- a/src/models/folder.rs +++ b/src/models/folder.rs @@ -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; + +// 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, 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, 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 { + 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 { + 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 { + 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 { + 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" }