diff --git a/team-server/src/api.rs b/team-server/src/api.rs index aa7669401..64ea04460 100644 --- a/team-server/src/api.rs +++ b/team-server/src/api.rs @@ -96,7 +96,7 @@ use crate::model::{ }; use crate::store::{ personal_space, BlobMeta, BodyRef, Folder, FolderDelete, FolderRename, Item, Lease, Listed, - ProfileFields, ProxyFields, Refusal, Restored, SessionHead, Standing, Store, StoredItem, + ProfileFields, ProxyFields, Reader, Refusal, Restored, SessionHead, Standing, Store, StoredItem, TeamProxy, TrashItem, TrashKind, Upload, Writer, CHUNK, META_TEAM_NAME, TEAM, }; use hyper::body::{Frame, SizeHint}; @@ -463,7 +463,7 @@ impl From for ApiError { } } -/// A write the store would not make. Living in another space reads exactly +/// A guarded operation the store refused. Living in another space reads exactly /// like not being there: where an id lives is not this caller's business. impl From for ApiError { fn from(r: Refusal) -> Self { @@ -486,6 +486,7 @@ impl From for ApiError { Refusal::Forbidden => ApiError::forbidden(), Refusal::SwitchedOff => ApiError::switched_off(), Refusal::Removed => ApiError::unauthorized(), + Refusal::TokenReplaced => ApiError::token_replaced(), // Said only where the caller may see it there: see `refused_team_write`. Refusal::OtherSpace | Refusal::Missing | Refusal::InTrash(_) => ApiError::missing(), } @@ -598,8 +599,7 @@ fn allows(grants: &[Grant], action: Action, target: &Target<'_>) -> bool { decide(grants, action, target).is_allowed() } -/// The rules a guarded write is judged by: as the store read them under the -/// write's own lock, not the copy taken when the request came in. +/// The rules of a guarded operation, read by the store under its own lock. fn live(s: &Standing) -> Result<&[Grant], Refusal> { if !s.known { Err(Refusal::Removed) @@ -624,6 +624,10 @@ impl Caller { Writer { member_id: &self.member.id, device_id: self.device.id.as_deref() } } + fn reader(&self) -> Reader<'_> { + Reader { member_id: &self.member.id, token_hash: &self.token_hash } + } + /// Their own space. Grants are about the team and say nothing here. fn mine(&self) -> String { personal_space(&self.member.id) @@ -1324,12 +1328,9 @@ fn with_open_on(st: &AppState, listed: Vec) -> Result, A .collect()) } -/// One profile's row as the lists have it; missing unless it is in `space`. -fn one_row(st: &AppState, space: &str, id: &str) -> Result { - match st.store.listed_one(id)? { - Some((l, sp)) if sp == space => with_open_on(st, vec![l])?.pop().ok_or_else(ApiError::missing), - _ => Err(ApiError::missing()), - } +fn profile_detail_reply(st: &AppState, listed: Listed, data: Vec) -> Result, ApiError> { + let row = with_open_on(st, vec![listed])?.pop().ok_or_else(ApiError::missing)?; + Ok(Json(ProfileWithData { row, data: STANDARD.encode(data) })) } /// `?ids=a,b,c`: only these, at most [`MAX_IDS`]. Absent: the whole list. @@ -1369,14 +1370,18 @@ async fn profile_get( Path(id): Path, ) -> Result, ApiError> { let c = require_member(&st, &headers)?; - let profile = visible_profile(&st, &c, &id)?; - let t = Target::profile(&id, &profile.folder); - if !USES_A_PROFILE.iter().any(|a| c.may(*a, &t)) { - return Err(ApiError::forbidden()); - } - let row = one_row(&st, TEAM, &id)?; - let data = st.store.profile_data(&id)?.ok_or_else(ApiError::missing)?; - Ok(Json(ProfileWithData { row, data: STANDARD.encode(data) })) + let (row, data) = st.store.profile_detail(TEAM, &id, c.reader(), |s, p| { + let grants = live(s)?; + let target = Target::profile(&p.id, &p.folder); + if !allows(grants, Action::See, &target) { + return Err(Refusal::Missing); + } + if !USES_A_PROFILE.iter().any(|a| allows(grants, *a, &target)) { + return Err(Refusal::Forbidden); + } + Ok(()) + })??; + profile_detail_reply(&st, row, data) } async fn profile_put( @@ -2189,14 +2194,6 @@ fn proxy_args(body: &ProxyWrite) -> Result<(&str, &str, &str, Vec), ApiError Ok((name, kind, label(&body.country)?, data_arg(&body.data)?)) } -/// A team proxy the member may know about; anything else reads as missing. -fn visible_proxy(st: &AppState, c: &Caller, id: &str) -> Result { - match st.store.proxy_meta(id)? { - Some((x, space)) if space == TEAM && c.may(Action::See, &proxy_target(id)) => Ok(x), - _ => Err(ApiError::missing()), - } -} - async fn proxies_list( State(st): State, headers: HeaderMap, @@ -2218,11 +2215,16 @@ async fn proxy_get( Path(id): Path, ) -> Result, ApiError> { let c = require_member(&st, &headers)?; - let proxy = visible_proxy(&st, &c, &id)?; - if !may_use_proxy(&c.grants, &id) { - return Err(ApiError::forbidden()); - } - let data = st.store.proxy_data(&id)?.ok_or_else(ApiError::missing)?; + let (proxy, data) = st.store.proxy_detail(TEAM, &id, c.reader(), |s, proxy| { + let grants = live(s)?; + if !sees_proxy(grants, &proxy.id) { + return Err(Refusal::Missing); + } + if !may_use_proxy(grants, &proxy.id) { + return Err(Refusal::Forbidden); + } + Ok(()) + })??; Ok(Json(ProxyWithData { proxy: proxy.into(), data: STANDARD.encode(data), @@ -2539,13 +2541,6 @@ fn own_profile(st: &AppState, c: &Caller, id: &str) -> Result Result { - match st.store.proxy_meta(id)? { - Some((x, space)) if space == c.mine() => Ok(x), - _ => Err(ApiError::missing()), - } -} - async fn my_profiles_list( State(st): State, headers: HeaderMap, @@ -2561,9 +2556,8 @@ async fn my_profile_get( Path(id): Path, ) -> Result, ApiError> { let c = require_member(&st, &headers)?; - let row = one_row(&st, &c.mine(), &id)?; - let data = st.store.profile_data(&id)?.ok_or_else(ApiError::missing)?; - Ok(Json(ProfileWithData { row, data: STANDARD.encode(data) })) + let (row, data) = st.store.profile_detail(&c.mine(), &id, c.reader(), |s, _| still_on(s))??; + profile_detail_reply(&st, row, data) } async fn my_profile_put( @@ -2618,8 +2612,7 @@ async fn my_proxy_get( Path(id): Path, ) -> Result, ApiError> { let c = require_member(&st, &headers)?; - let proxy = own_proxy(&st, &c, &id)?; - let data = st.store.proxy_data(&id)?.ok_or_else(ApiError::missing)?; + let (proxy, data) = st.store.proxy_detail(&c.mine(), &id, c.reader(), |s, _| still_on(s))??; Ok(Json(ProxyWithData { proxy: proxy.into(), data: STANDARD.encode(data), @@ -2797,20 +2790,20 @@ struct Brought { impl Brought { fn of(st: &AppState, c: &Caller, id: &str) -> Result, ApiError> { - let p = match st.store.profile_meta(id)? { - Some((p, space)) if space == TEAM => p, - _ => return Ok(None), + let found = st.store.profile_settings(TEAM, id, c.reader(), |s, p| { + see_then(live(s)?, Action::Start, &Target::profile(&p.id, &p.folder)) + })?; + let (row, data) = match found { + Ok(detail) => detail, + Err(Refusal::Missing | Refusal::Forbidden) => return Ok(None), + Err(refusal) => return Err(refusal.into()), }; - if see_then(&c.grants, Action::Start, &Target::profile(id, &p.folder)).is_err() { - return Ok(None); - } - let data = st.store.profile_data(id)?.unwrap_or_default(); let named = serde_json::from_slice::(&data) .ok() .and_then(|v| v.get("_meta")?.get("extensions")?.as_array().cloned()) .unwrap_or_default(); let extensions = named.iter().filter_map(|e| e.as_str().map(str::to_owned)).collect(); - Ok(Some(Brought { id: id.to_owned(), folder: p.folder, extensions })) + Ok(Some(Brought { id: row.id, folder: row.folder, extensions })) } fn wants(&self, kind: &str, item: &StoredItem) -> bool { @@ -3153,6 +3146,10 @@ async fn my_package_put( #[cfg(test)] mod tests { + mod detail_tests { + include!("api/detail_tests.rs"); + } + use super::*; use crate::auth::verify_permission; use crate::model::Scope; diff --git a/team-server/src/api/detail_tests.rs b/team-server/src/api/detail_tests.rs new file mode 100644 index 000000000..ce1f5f786 --- /dev/null +++ b/team-server/src/api/detail_tests.rs @@ -0,0 +1,245 @@ +use super::*; + +const PROFILE: &str = "p-detail-snapshot"; +const PROXY: &str = "x-detail-snapshot"; +const READER_DEVICE: &str = "reader-device"; +const WRITER_DEVICE: &str = "writer-device"; + +#[tokio::test] +async fn a_profile_detail_read_rechecks_a_previously_authenticated_reader() { + let st = state(); + let (id, token) = member(&st, "Reader", everything()).await; + st.store + .put_profile(PROFILE, "Profile", "", b"settings", ADMIN_ID) + .unwrap(); + let caller = require_member(&st, &hdr(&token)).unwrap(); + let reader = caller.reader(); + let replacement = auth::new_member_token(); + st.store + .reissue_token(&id, &auth::token_hash(&replacement)) + .unwrap() + .unwrap(); + + let result = st.store.profile_detail(TEAM, PROFILE, reader, |_, _| { + panic!("a replaced reader must not reach authorization") + }); + assert!(matches!(result.unwrap(), Err(Refusal::TokenReplaced))); +} + +struct ProfileVersion { + name: &'static str, + folder: &'static str, + notes: &'static str, + color: &'static str, + data: &'static [u8], +} + +impl ProfileVersion { + fn card(&self) -> Card { + Card { + notes: self.notes.into(), + color: self.color.into(), + ..Default::default() + } + } + + fn body(&self) -> Value { + let mut body = profile_json(self.name, self.folder, self.data); + body["card"] = json!(self.card()); + body + } + + fn assert_detail(&self, detail: &Value, revision: u64) { + assert_eq!(detail["id"], PROFILE); + assert_eq!(detail["name"], self.name); + assert_eq!(detail["folder"], self.folder); + assert_eq!(detail["revision"], revision); + assert_eq!(detail["card"], json!(self.card())); + assert_eq!(STANDARD.decode(detail["data"].as_str().unwrap()).unwrap(), self.data); + } +} + +const PROFILE_BEFORE: ProfileVersion = ProfileVersion { + name: "Earlier profile", + folder: "Earlier folder", + notes: "Earlier notes", + color: "green", + data: br#"{"version":"before"}"#, +}; +const PROFILE_AFTER: ProfileVersion = ProfileVersion { + name: "Updated profile", + folder: "Updated folder", + notes: "Updated notes", + color: "blue", + data: br#"{"version":"after"}"#, +}; + +async fn read_profile_during_commit(st: &AppState, space: &str, uri: &str, reader: &str, writer: String) { + let put = on(ask("PUT", uri, reader), READER_DEVICE, "Reader"); + assert_eq!( + answer(st, put, Some(PROFILE_BEFORE.body())).await.0, + StatusCode::CREATED + ); + + let store = Arc::downgrade(&st.store); + let space = space.to_owned(); + st.store.after_detail_read(move || { + let store = store.upgrade().unwrap(); + let card = PROFILE_AFTER.card(); + let change = ProfileFields { + name: PROFILE_AFTER.name, + folder: PROFILE_AFTER.folder, + data: PROFILE_AFTER.data, + card: Some(&card), + created_at: None, + }; + let writer = Writer { + member_id: &writer, + device_id: Some(WRITER_DEVICE), + }; + let saved = store + .put_profile_with(&space, PROFILE, &change, writer, Some(1), |standing, _, _| { + still_on(standing) + }) + .unwrap() + .unwrap(); + assert_eq!(saved.revision, 2); + }); + + let get = || on(ask("GET", uri, reader), READER_DEVICE, "Reader"); + let (status, detail) = answer(st, get(), None).await; + assert_eq!(status, StatusCode::OK); + PROFILE_BEFORE.assert_detail(&detail, 1); + assert_eq!( + st.store.profile_meta(PROFILE).unwrap().unwrap().0.revision, + 2, + "the save committed inside the read" + ); + + let (status, detail) = answer(st, get(), None).await; + assert_eq!(status, StatusCode::OK); + PROFILE_AFTER.assert_detail(&detail, 2); +} + +#[tokio::test] +async fn team_profile_detail_uses_one_revision_during_a_teammate_save() { + let st = state(); + let (_, reader) = member(&st, "Profile reader", everything()).await; + let (writer, _) = member(&st, "Profile editor", everything()).await; + let uri = format!("/profiles/{PROFILE}"); + read_profile_during_commit(&st, TEAM, &uri, &reader, writer).await; +} + +#[tokio::test] +async fn personal_profile_detail_uses_one_revision_during_a_save_on_another_device() { + let st = state(); + let (writer, reader) = member(&st, "Profile owner", vec![]).await; + let (_, other_member) = member(&st, "Another member", everything()).await; + let uri = format!("/me/profiles/{PROFILE}"); + read_profile_during_commit(&st, &personal_space(&writer), &uri, &reader, writer).await; + + let absent = format!("{uri}-missing"); + let missing = answer(&st, ask("GET", &absent, &other_member), None).await; + assert_eq!(missing.0, StatusCode::NOT_FOUND); + assert_eq!(answer(&st, ask("GET", &uri, &other_member), None).await, missing); +} + +struct ProxyVersion { + name: &'static str, + kind: &'static str, + country: &'static str, + data: &'static [u8], +} + +impl ProxyVersion { + fn body(&self) -> Value { + json!({ "name": self.name, "kind": self.kind, "country": self.country, "data": STANDARD.encode(self.data) }) + } + + fn assert_detail(&self, detail: &Value, revision: u64) { + assert_eq!(detail["id"], PROXY); + assert_eq!(detail["name"], self.name); + assert_eq!(detail["kind"], self.kind); + assert_eq!(detail["country"], self.country); + assert_eq!(detail["revision"], revision); + assert_eq!(STANDARD.decode(detail["data"].as_str().unwrap()).unwrap(), self.data); + } +} + +const PROXY_BEFORE: ProxyVersion = ProxyVersion { + name: "Earlier proxy", + kind: "socks5", + country: "JP", + data: b"before.example:1080", +}; +const PROXY_AFTER: ProxyVersion = ProxyVersion { + name: "Updated proxy", + kind: "http", + country: "GB", + data: b"after.example:8080", +}; + +async fn read_proxy_during_commit(st: &AppState, space: &str, uri: &str, reader: &str, writer: String) { + let put = on(ask("PUT", uri, reader), READER_DEVICE, "Reader"); + assert_eq!(answer(st, put, Some(PROXY_BEFORE.body())).await.0, StatusCode::CREATED); + + let store = Arc::downgrade(&st.store); + let space = space.to_owned(); + st.store.after_detail_read(move || { + let store = store.upgrade().unwrap(); + let change = ProxyFields { + name: PROXY_AFTER.name, + kind: PROXY_AFTER.kind, + country: PROXY_AFTER.country, + data: PROXY_AFTER.data, + }; + let writer = Writer { + member_id: &writer, + device_id: Some(WRITER_DEVICE), + }; + let saved = store + .put_proxy_with(&space, PROXY, &change, writer, Some(1), |standing, _, _| { + still_on(standing) + }) + .unwrap() + .unwrap(); + assert_eq!(saved.revision, 2); + }); + + let get = || on(ask("GET", uri, reader), READER_DEVICE, "Reader"); + let (status, detail) = answer(st, get(), None).await; + assert_eq!(status, StatusCode::OK); + PROXY_BEFORE.assert_detail(&detail, 1); + assert_eq!( + st.store.proxy_meta(PROXY).unwrap().unwrap().0.revision, + 2, + "the save committed inside the read" + ); + + let (status, detail) = answer(st, get(), None).await; + assert_eq!(status, StatusCode::OK); + PROXY_AFTER.assert_detail(&detail, 2); +} + +#[tokio::test] +async fn team_proxy_detail_uses_one_revision_during_a_teammate_save() { + let st = state(); + let (_, reader) = member(&st, "Proxy reader", everything()).await; + let (writer, _) = member(&st, "Proxy editor", everything()).await; + let uri = format!("/proxies/{PROXY}"); + read_proxy_during_commit(&st, TEAM, &uri, &reader, writer).await; +} + +#[tokio::test] +async fn personal_proxy_detail_uses_one_revision_during_a_save_on_another_device() { + let st = state(); + let (writer, reader) = member(&st, "Proxy owner", vec![]).await; + let (_, other_member) = member(&st, "Another member", everything()).await; + let uri = format!("/me/proxies/{PROXY}"); + read_proxy_during_commit(&st, &personal_space(&writer), &uri, &reader, writer).await; + + let absent = format!("{uri}-missing"); + let missing = answer(&st, ask("GET", &absent, &other_member), None).await; + assert_eq!(missing.0, StatusCode::NOT_FOUND); + assert_eq!(answer(&st, ask("GET", &uri, &other_member), None).await, missing); +} diff --git a/team-server/src/store.rs b/team-server/src/store.rs index 7cea4b2b9..db3beeaaf 100644 --- a/team-server/src/store.rs +++ b/team-server/src/store.rs @@ -36,6 +36,8 @@ pub struct Store { /// When each member's `last_seen_at` was last written, and under which /// token, so a busy launcher writes it once a minute rather than on every request. seen: Mutex>, + #[cfg(test)] + after_detail_read: Mutex>>, } /// How often a member's `last_seen_at` is written at most. @@ -144,6 +146,13 @@ impl Writer<'_> { } } +/// The authenticated member and the token hash used for this read. +#[derive(Clone, Copy)] +pub struct Reader<'a> { + pub member_id: &'a str, + pub token_hash: &'a str, +} + /// What a profile write carries. No card keeps the one stored. #[derive(Debug, Clone, Copy)] pub struct ProfileFields<'a> { @@ -199,6 +208,8 @@ pub enum Refusal { SwitchedOff, /// The writer was removed before the write ran. Removed, + /// The reader's token was re-issued before the detail read. + TokenReplaced, /// A session or package move from a device that holds no live lease on it. NoLease, /// The session moved past the revision the upload was based on. @@ -519,6 +530,31 @@ fn standing_in(db: &Connection, member_id: &str) -> Result { } } +fn token_replaced_in(db: &Connection, token_hash: &str) -> Result { + Ok(db + .query_row("SELECT 1 FROM replaced_tokens WHERE token_hash = ?1", params![token_hash], |_| Ok(())) + .optional()? + .is_some()) +} + +/// Check the credential and grants in the same database view as the detail. +fn reader_standing(db: &Connection, reader: Reader<'_>) -> Result> { + if reader.member_id == ADMIN_ID { + return Ok(Ok(standing_in(db, ADMIN_ID)?)); + } + let active: Option = db.query_row( + "SELECT active FROM members WHERE id = ?1 AND token_hash = ?2", + params![reader.member_id, reader.token_hash], + |r| r.get(0), + ).optional()?; + Ok(match active { + Some(true) => Ok(Standing { known: true, active: true, grants: grants_in(db, reader.member_id)? }), + Some(false) => Err(Refusal::SwitchedOff), + None if token_replaced_in(db, reader.token_hash)? => Err(Refusal::TokenReplaced), + None => Err(Refusal::Removed), + }) +} + /// How a rule's scope is kept in the grants table. fn scope_row(scope: &Scope) -> (&'static str, &str) { match scope { @@ -1132,6 +1168,8 @@ impl Store { hold_count: AtomicU64::new(0), regranted: Mutex::default(), seen: Mutex::default(), + #[cfg(test)] + after_detail_read: Mutex::default(), } } @@ -1146,6 +1184,20 @@ impl Store { self.hold_count.swap(0, Ordering::Relaxed) } + /// Let a test commit a change after the snapshot has been captured. + #[cfg(test)] + pub fn after_detail_read(&self, run: impl FnOnce() + Send + 'static) { + assert!(self.after_detail_read.lock().unwrap().replace(Box::new(run)).is_none()); + } + + #[cfg(test)] + fn run_after_detail_read(&self) { + let run = self.after_detail_read.lock().unwrap().take(); + if let Some(run) = run { + run(); + } + } + #[cfg(test)] pub fn open_memory() -> Result { let db = Connection::open_in_memory()?; @@ -1453,11 +1505,7 @@ impl Store { /// Whether this hash was a member's token before the admin re-issued it. pub fn token_replaced(&self, token_hash: &str) -> Result { - let db = self.lock(); - Ok(db - .query_row("SELECT 1 FROM replaced_tokens WHERE token_hash = ?1", params![token_hash], |_| Ok(())) - .optional()? - .is_some()) + token_replaced_in(&self.lock(), token_hash) } pub fn member(&self, id: &str) -> Result> { @@ -1685,6 +1733,7 @@ impl Store { } /// The profile's data, opened. None when there is no such profile. + #[cfg(test)] pub fn profile_data(&self, id: &str) -> Result>> { let sealed: Option> = { let db = self.lock(); @@ -1913,6 +1962,7 @@ impl Store { } /// One profile as listed, with the space it is in. + #[cfg(test)] pub fn listed_one(&self, id: &str) -> Result> { let row = { let db = self.lock(); @@ -1930,6 +1980,62 @@ impl Store { .transpose() } + /// Capture the profile's row, card, session metadata and settings together. + pub fn profile_detail( + &self, + space: &str, + id: &str, + reader: Reader<'_>, + authorize: impl FnOnce(&Standing, &TeamProfile) -> std::result::Result<(), Refusal>, + ) -> Result), Refusal>> { + match self.read_profile(space, id, reader, authorize)? { + Ok((row, data)) => Ok(Ok((self.listed(row)?, data))), + Err(refusal) => Ok(Err(refusal)), + } + } + + /// The settings used to choose the items a Start brings with it. + pub fn profile_settings( + &self, + space: &str, + id: &str, + reader: Reader<'_>, + authorize: impl FnOnce(&Standing, &TeamProfile) -> std::result::Result<(), Refusal>, + ) -> Result), Refusal>> { + Ok(self.read_profile(space, id, reader, authorize)?.map(|(row, data)| (row.0, data))) + } + + fn read_profile( + &self, + space: &str, + id: &str, + reader: Reader<'_>, + authorize: impl FnOnce(&Standing, &TeamProfile) -> std::result::Result<(), Refusal>, + ) -> Result), Refusal>> { + let (row, sealed) = { + let mut db = self.lock(); + let tx = db.transaction()?; + let standing = match reader_standing(&tx, reader)? { + Ok(standing) => standing, + Err(refusal) => return Ok(Err(refusal)), + }; + let snapshot = tx.query_row( + &format!("SELECT {LISTED_COLUMNS}, p.sealed FROM {LISTED_FROM} WHERE p.space = ?1 AND p.id = ?2"), + params![space, id], + |r| Ok((listed_row(r)?, r.get::<_, Vec>(13)?)), + ).optional()?; + let Some((row, sealed)) = snapshot else { return Ok(Err(Refusal::Missing)) }; + if let Err(refusal) = authorize(&standing, &row.0) { + return Ok(Err(refusal)); + } + (row, sealed) + }; + #[cfg(test)] + self.run_after_detail_read(); + let data = self.vault.open(&format!("profile:{id}"), &sealed)?; + Ok(Ok((row, data))) + } + fn listed(&self, (profile, card, session, _): ListedRow) -> Result { Ok(Listed { card: self.open_card(&profile.id, card.as_deref())?, profile, session }) } @@ -1985,6 +2091,7 @@ impl Store { profile_with_space(&self.lock(), id) } + #[cfg(test)] pub fn proxy_meta(&self, id: &str) -> Result> { proxy_with_space(&self.lock(), id) } @@ -2722,7 +2829,41 @@ impl Store { Ok(rows) } + /// Capture a proxy's metadata and login from the same authorized version. + pub fn proxy_detail( + &self, + space: &str, + id: &str, + reader: Reader<'_>, + authorize: impl FnOnce(&Standing, &TeamProxy) -> std::result::Result<(), Refusal>, + ) -> Result), Refusal>> { + let (row, sealed) = { + let mut db = self.lock(); + let tx = db.transaction()?; + let standing = match reader_standing(&tx, reader)? { + Ok(standing) => standing, + Err(refusal) => return Ok(Err(refusal)), + }; + let snapshot = tx.query_row( + "SELECT id, name, kind, country, revision, updated_at, updated_by, sealed + FROM proxies WHERE space = ?1 AND id = ?2", + params![space, id], + |r| Ok((proxy_row(r)?, r.get::<_, Vec>(7)?)), + ).optional()?; + let Some((row, sealed)) = snapshot else { return Ok(Err(Refusal::Missing)) }; + if let Err(refusal) = authorize(&standing, &row) { + return Ok(Err(refusal)); + } + (row, sealed) + }; + #[cfg(test)] + self.run_after_detail_read(); + let data = self.vault.open(&format!("proxy:{id}"), &sealed)?; + Ok(Ok((row, data))) + } + /// The proxy's data, opened. None when there is no such proxy. + #[cfg(test)] pub fn proxy_data(&self, id: &str) -> Result>> { let sealed: Option> = { let db = self.lock(); @@ -3386,6 +3527,19 @@ mod tests { assert!(s.set_member_active("nobody", false).is_err()); } + #[test] + fn reading_profile_settings_for_start_does_not_need_the_card() { + let s = Store::open_memory().unwrap(); + let saved = s.put_profile("p1", "Shop", "Ads", b"settings", ADMIN_ID).unwrap(); + s.lock().execute("UPDATE profiles SET card = ?1 WHERE id = 'p1'", params![b"incomplete card".as_slice()]).unwrap(); + + let reader = Reader { member_id: ADMIN_ID, token_hash: "" }; + let (row, settings) = s.profile_settings(TEAM, "p1", reader, |_, _| Ok(())).unwrap().unwrap(); + assert_eq!(row, saved); + assert_eq!(settings, b"settings"); + assert!(s.profile_detail(TEAM, "p1", reader, |_, _| Ok(())).is_err()); + } + #[test] fn a_profile_keeps_its_sealed_bytes_and_counts_its_revisions() { let s = Store::open_memory().unwrap();