From c7d50ab87bf40ed7f275557a3040d46e973007d9 Mon Sep 17 00:00:00 2001 From: Geordie Moffatt Date: Sun, 22 Nov 2026 13:15:41 -0800 Subject: [PATCH 1/2] lore-server: an open QUIC storage session asks again before every write A QUIC storage session decided write once, at AuthorizeStart, and kept that answer until its token expired. A session opened before its repository became managed, or before the policy dropped its publisher, kept uploading. The session now keeps its verified token, and every mutating command (put, copy, mutable store, CAS) asks again under the managed-repository policy in force. With no policy configured nothing can change while the server runs, so the answer from the start stands. Refs GenRobo/GRID#3445. Signed-off-by: Geordie Moffatt --- lore-server/src/auth/managed.rs | 22 +++ lore-server/src/protocol/storage/session.rs | 85 +++++++--- lore-server/src/quic/storage_service_v4.rs | 163 +++++++++++++++++--- 3 files changed, 224 insertions(+), 46 deletions(-) diff --git a/lore-server/src/auth/managed.rs b/lore-server/src/auth/managed.rs index 025a1351c..bacefaebc 100644 --- a/lore-server/src/auth/managed.rs +++ b/lore-server/src/auth/managed.rs @@ -320,6 +320,28 @@ pub fn configure(path: Option<&Path>) -> Result<(), PolicyError> { Ok(()) } +/// Whether a policy file is configured. Fixed at startup: an unconfigured server never starts +/// managing a repository, so a decision taken without a policy stays valid. +pub fn is_configured() -> bool { + POLICY + .read() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .as_ref() + .is_some_and(|holder| holder.path.is_some()) +} + +/// Make the next [`current`] look at the file now, as it would after [`RECHECK`]. +#[cfg(test)] +pub(crate) fn recheck_now() { + if let Some(holder) = POLICY + .write() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .as_mut() + { + holder.checked = Instant::now() - RECHECK; + } +} + /// The policy in force, re-read first when the file may have changed. pub fn current() -> Snapshot { { diff --git a/lore-server/src/protocol/storage/session.rs b/lore-server/src/protocol/storage/session.rs index 245710035..bb6e22356 100644 --- a/lore-server/src/protocol/storage/session.rs +++ b/lore-server/src/protocol/storage/session.rs @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2026 Epic Games, Inc. // SPDX-License-Identifier: MIT +use std::sync::Arc; use std::sync::atomic::AtomicU32; use std::sync::atomic::Ordering; use std::time::SystemTime; @@ -8,15 +9,48 @@ use std::time::UNIX_EPOCH; use dashmap::DashMap; use lore_revision::lore::RepositoryId; +use crate::auth::jwt::AuthorizationToken; +use crate::auth::jwt::verify_write_authorization; +use crate::auth::managed; + pub(crate) const MAX_CONCURRENT_SESSIONS: u32 = 10_000; +/// What lets a session's mutating commands write. +#[derive(Clone)] +pub enum WriteGrant { + /// Auth off server-wide: every session writes. + Open, + /// Under auth: the verified token that started the session, and whether it granted write + /// then. Each mutating command asks again under the managed-repository policy in force, so + /// a repository that becomes managed, a publisher the policy drops, or a policy that breaks + /// stops an open session's writes at once rather than at token expiry. + Token { + authorization: Arc, + at_start: bool, + }, +} + +impl WriteGrant { + /// Whether a mutating command on `repository` may run now. + pub fn allows(&self, repository: RepositoryId) -> bool { + match self { + WriteGrant::Open => true, + // No policy configured: nothing can become managed while the server runs, so the + // answer from the session's start still holds. + WriteGrant::Token { at_start, .. } if !managed::is_configured() => *at_start, + WriteGrant::Token { authorization, .. } => { + verify_write_authorization(authorization, repository).is_ok() + } + } + } +} + pub struct SessionEntry { pub repository: RepositoryId, pub correlation_id: String, pub user_id: String, - /// Whether the session's token grants write on the repository (mutating commands are - /// refused otherwise). Auth-off servers always grant it. - pub write_allowed: bool, + /// What lets the session's mutating commands write; see [`WriteGrant::allows`]. + pub write: WriteGrant, /// The session token's `exp` (Unix seconds); commands are refused once it passes, so a /// long-lived connection cannot outlive the token that authorized it. 0 means no expiry /// (auth-off sessions). @@ -85,7 +119,7 @@ impl SessionMap { repository: RepositoryId, correlation_id: String, user_id: String, - write_allowed: bool, + write: WriteGrant, expires_at: u64, ) -> Result<(u32, String), SessionError> { if self.entries.len() >= MAX_CONCURRENT_SESSIONS as usize { @@ -120,7 +154,7 @@ impl SessionMap { repository, correlation_id: correlation_id.clone(), user_id, - write_allowed, + write, expires_at, }, ); @@ -197,12 +231,13 @@ pub enum SourceAuthorization { mod tests { use rand::random; + use super::WriteGrant::Open; use super::*; #[test] fn start_assigns_session_id_from_one() { let map = SessionMap::default(); - let (id, _) = map.start(random(), "corr-1".into(), String::new(), true, 0).unwrap(); + let (id, _) = map.start(random(), "corr-1".into(), String::new(), Open, 0).unwrap(); assert_eq!(id, 1); } @@ -210,8 +245,8 @@ mod tests { fn start_increments_session_id() { let map = SessionMap::default(); let repo = random::(); - let (id1, _) = map.start(repo, "corr-1".into(), String::new(), true, 0).unwrap(); - let (id2, _) = map.start(repo, "corr-2".into(), String::new(), true, 0).unwrap(); + let (id1, _) = map.start(repo, "corr-1".into(), String::new(), Open, 0).unwrap(); + let (id2, _) = map.start(repo, "corr-2".into(), String::new(), Open, 0).unwrap(); assert_eq!(id1, 1); assert_eq!(id2, 2); } @@ -220,8 +255,8 @@ mod tests { fn start_always_allocates_new_id() { let map = SessionMap::default(); let repo = random::(); - let (id1, _) = map.start(repo, "corr-1".into(), String::new(), true, 0).unwrap(); - let (id2, _) = map.start(repo, "corr-1".into(), String::new(), true, 0).unwrap(); + let (id1, _) = map.start(repo, "corr-1".into(), String::new(), Open, 0).unwrap(); + let (id2, _) = map.start(repo, "corr-1".into(), String::new(), Open, 0).unwrap(); assert_ne!(id1, id2); } @@ -229,8 +264,8 @@ mod tests { fn start_empty_correlation_generates_uuid() { let map = SessionMap::default(); let repo = random::(); - let (id1, corr1) = map.start(repo, String::new(), String::new(), true, 0).unwrap(); - let (id2, corr2) = map.start(repo, String::new(), String::new(), true, 0).unwrap(); + let (id1, corr1) = map.start(repo, String::new(), String::new(), Open, 0).unwrap(); + let (id2, corr2) = map.start(repo, String::new(), String::new(), Open, 0).unwrap(); assert_ne!(id1, id2); assert!(!corr1.is_empty()); assert!(!corr2.is_empty()); @@ -241,7 +276,7 @@ mod tests { fn stop_removes_session() { let map = SessionMap::default(); let repo = random::(); - let (id, _) = map.start(repo, "corr-1".into(), String::new(), true, 0).unwrap(); + let (id, _) = map.start(repo, "corr-1".into(), String::new(), Open, 0).unwrap(); assert!(map.get(id).is_some()); map.stop(id).unwrap(); assert!(map.get(id).is_none()); @@ -256,7 +291,7 @@ mod tests { #[test] fn stop_already_stopped_returns_not_found() { let map = SessionMap::default(); - let (id, _) = map.start(random(), "corr-1".into(), String::new(), true, 0).unwrap(); + let (id, _) = map.start(random(), "corr-1".into(), String::new(), Open, 0).unwrap(); map.stop(id).unwrap(); assert_eq!(map.stop(id), Err(SessionError::NotFound)); } @@ -265,9 +300,9 @@ mod tests { fn start_after_stop_allocates_new_id() { let map = SessionMap::default(); let repo = random::(); - let (id1, _) = map.start(repo, "corr-1".into(), String::new(), true, 0).unwrap(); + let (id1, _) = map.start(repo, "corr-1".into(), String::new(), Open, 0).unwrap(); map.stop(id1).unwrap(); - let (id2, _) = map.start(repo, "corr-1".into(), String::new(), true, 0).unwrap(); + let (id2, _) = map.start(repo, "corr-1".into(), String::new(), Open, 0).unwrap(); assert_ne!(id1, id2); } @@ -275,7 +310,7 @@ mod tests { fn get_returns_entry_with_user_id() { let map = SessionMap::default(); let repo = random::(); - let (id, _) = map.start(repo, "corr-1".into(), "user-42".into(), true, 0).unwrap(); + let (id, _) = map.start(repo, "corr-1".into(), "user-42".into(), Open, 0).unwrap(); let entry = map.get(id).unwrap(); assert_eq!(entry.repository, repo); assert_eq!(entry.correlation_id, "corr-1"); @@ -293,7 +328,7 @@ mod tests { let map = SessionMap::default(); let repo_a = random::(); let repo_b = random::(); - map.start(repo_a, "corr-1".into(), String::new(), true, 0).unwrap(); + map.start(repo_a, "corr-1".into(), String::new(), Open, 0).unwrap(); assert!(map.is_repository_authorized(repo_a, "", NOW)); assert!(!map.is_repository_authorized(repo_b, "", NOW)); @@ -304,7 +339,7 @@ mod tests { /// Start a session for `user` whose token expires a minute after `NOW`. fn start_for(map: &SessionMap, repo: RepositoryId, user: &str) -> u32 { let (id, _) = map - .start(repo, String::new(), user.to_string(), true, NOW + 60) + .start(repo, String::new(), user.to_string(), Open, NOW + 60) .unwrap(); id } @@ -351,7 +386,7 @@ mod tests { let map = SessionMap::default(); let repo = random::(); let (id, _) = map - .start(repo, String::new(), String::new(), true, 0) + .start(repo, String::new(), String::new(), Open, 0) .unwrap(); assert!(map.get(id).unwrap().is_live(u64::MAX)); assert!(map.is_repository_authorized(repo, "", u64::MAX)); @@ -362,10 +397,10 @@ mod tests { let map = SessionMap::default(); let repo = random::(); for i in 0..MAX_CONCURRENT_SESSIONS { - map.start(repo, format!("corr-{i}"), String::new(), true, 0).unwrap(); + map.start(repo, format!("corr-{i}"), String::new(), Open, 0).unwrap(); } assert_eq!( - map.start(repo, "one-more".into(), String::new(), true, 0), + map.start(repo, "one-more".into(), String::new(), Open, 0), Err(SessionError::LimitReached) ); } @@ -376,14 +411,14 @@ mod tests { let repo = random::(); let mut ids = Vec::new(); for i in 0..MAX_CONCURRENT_SESSIONS { - let (id, _) = map.start(repo, format!("corr-{i}"), String::new(), true, 0).unwrap(); + let (id, _) = map.start(repo, format!("corr-{i}"), String::new(), Open, 0).unwrap(); ids.push(id); } assert_eq!( - map.start(repo, "blocked".into(), String::new(), true, 0), + map.start(repo, "blocked".into(), String::new(), Open, 0), Err(SessionError::LimitReached) ); map.stop(ids[0]).unwrap(); - map.start(repo, "freed".into(), String::new(), true, 0).unwrap(); + map.start(repo, "freed".into(), String::new(), Open, 0).unwrap(); } } diff --git a/lore-server/src/quic/storage_service_v4.rs b/lore-server/src/quic/storage_service_v4.rs index 769bb8b86..7c069dfe1 100644 --- a/lore-server/src/quic/storage_service_v4.rs +++ b/lore-server/src/quic/storage_service_v4.rs @@ -34,6 +34,7 @@ use crate::protocol::storage::put::handle_put; use crate::protocol::storage::query::handle_query; use crate::protocol::storage::session::SessionError; use crate::protocol::storage::session::SessionMap; +use crate::protocol::storage::session::WriteGrant; use crate::protocol::storage::session::unix_now; use crate::protocol::storage::verify::handle_verify; use crate::quic::NO_CONNECTION_ID; @@ -174,7 +175,7 @@ impl QuicService for StorageServiceV4 { // Fail-closed by construction: write is granted only by an explicit // write-capable token, or when auth is disabled server-wide (no verifier). // There is no standalone `true` default that a skipped branch could leak. - let (user_id, write_allowed, expires_at) = match self.jwt_verifier.as_ref() { + let (user_id, write, expires_at) = match self.jwt_verifier.as_ref() { Some(jwt_verifier) => { let token_str = String::from_utf8(auth_token).map_err(|err| { MessageHandleError::AuthorizationFailure(format!( @@ -194,7 +195,7 @@ impl QuicService for StorageServiceV4 { .map_err(|err| { MessageHandleError::AuthorizationFailure(err.to_string()) })?; - let write_allowed = crate::auth::jwt::verify_write_authorization( + let at_start = crate::auth::jwt::verify_write_authorization( &authorization, repository, ) @@ -204,17 +205,22 @@ impl QuicService for StorageServiceV4 { let expires_at = authorization.expires; ( - crate::util::get_user_id_from_token(Some(authorization)), - write_allowed, + crate::util::get_user_id_from_token_ref(Some(&authorization)), + // Kept so each mutating command asks again under the managed + // repository policy then in force (see `WriteGrant::allows`). + WriteGrant::Token { + authorization: Arc::new(authorization), + at_start, + }, expires_at, ) } // Auth disabled server-wide: no gate, no expiry. - None => (String::new(), true, 0), + None => (String::new(), WriteGrant::Open, 0), }; let session_map = self.session_map.clone(); - match session_map.start(repository, correlation_id, user_id, write_allowed, expires_at) { + match session_map.start(repository, correlation_id, user_id, write, expires_at) { Ok((session_id, correlation_id)) => { debug!( session_id, @@ -255,7 +261,7 @@ impl QuicService for StorageServiceV4 { let repository = session.repository; let correlation_id = session.correlation_id.clone(); let user_id = session.user_id.clone(); - let write_allowed = session.write_allowed; + let write = session.write.clone(); let live = session.is_live(unix_now()); drop(session); @@ -274,16 +280,24 @@ impl QuicService for StorageServiceV4 { })?; // Mutating storage commands require a write-capable grant on the session's - // repository; a read-scoped token can fetch but never store. - if !write_allowed - && matches!( + // repository; a read-scoped token can fetch but never store. Asked on every such + // command, under the managed-repository policy in force now. + let mutable_key_type = match &parsed { + crate::quic::storage_service::ParsedStorageRequest::MutableStoreOp(store) => { + Some(store.key_type) + } + crate::quic::storage_service::ParsedStorageRequest::MutableCas(cas) => { + Some(cas.key_type) + } + _ => None, + }; + let mutating = mutable_key_type.is_some() + || matches!( parsed, crate::quic::storage_service::ParsedStorageRequest::Put(_) | crate::quic::storage_service::ParsedStorageRequest::Copy(_) - | crate::quic::storage_service::ParsedStorageRequest::MutableStoreOp(_) - | crate::quic::storage_service::ParsedStorageRequest::MutableCas(_) - ) - { + ); + if mutating && !write.allows(repository) { return Err(MessageHandleError::AuthorizationFailure( "write access to the repository is required for this operation" .to_string(), @@ -293,13 +307,8 @@ impl QuicService for StorageServiceV4 { // Under auth, a raw store never writes a key a checked RPC owns, nor any key on a // store that cannot keep key types apart. if self.jwt_verifier.is_some() - && let crate::quic::storage_service::ParsedStorageRequest::MutableStoreOp( - crate::protocol::storage::requests::MutableStoreOp { key_type, .. }, - ) - | crate::quic::storage_service::ParsedStorageRequest::MutableCas( - crate::protocol::storage::requests::MutableCas { key_type, .. }, - ) = &parsed - && !crate::auth::raw_mutable_write_allowed(*key_type) + && let Some(key_type) = mutable_key_type + && !crate::auth::raw_mutable_write_allowed(key_type) { return Err(MessageHandleError::AuthorizationFailure(format!( "{key_type:?} keys cannot change through a raw store on this server" @@ -514,9 +523,121 @@ mod tests { use rand::random; use super::*; + use crate::auth::managed; use crate::protocol::storage::session::MAX_CONCURRENT_SESSIONS; use crate::quic::QuicService; use crate::store::test_store_create; + use crate::test_support; + + async fn authorize( + service: &StorageServiceV4, + repository: lore_revision::lore::RepositoryId, + token: &str, + ) -> u32 { + let response = service + .run_request_handler( + AttributeMap::default().into(), + ParsedStorageRequestV4::AuthorizeStart { + repository, + correlation_id: String::new(), + auth_token: token.as_bytes().to_vec(), + }, + ) + .await + .expect("authorize"); + u32::from_le_bytes(response[0][..4].try_into().expect("session id")) + } + + /// A raw `MutableStore` (untyped) or `MutableCas` on an open session. + async fn mutate( + service: &StorageServiceV4, + session_id: u32, + command: Command, + ) -> Result, MessageHandleError> { + let mut payload = Vec::new(); + payload.extend_from_slice(&random::<[u8; 32]>()); // key + if command == Command::MutableCas { + payload.extend_from_slice(&[0; 32]); // expected + } + payload.extend_from_slice(&random::<[u8; 32]>()); // value + payload.push(lore_base::types::KeyType::Untyped as u8); + service + .run_request_handler( + AttributeMap::default().into(), + ParsedStorageRequestV4::StorageCommand { + session_id, + opcode: command.into(), + payload: Bytes::from(payload), + }, + ) + .await + } + + /// Write on a session is asked again on every mutating command, under the managed + /// repository policy in force then: a session opened before its repository became managed + /// writes nothing afterwards, a listed publisher's session writes while it is listed and + /// stops the moment the policy drops it, without waiting for any token to expire. + #[tokio::test] + async fn open_sessions_follow_the_managed_policy_in_force() { + let (immutable_store, mutable_store, _execution) = + test_store_create().await.expect("Failed to create stores"); + crate::auth::set_mutable_key_types_isolated(true); + let service = StorageServiceV4::new( + Arc::new(Some(test_support::verifier())), + immutable_store.clone(), + immutable_store, + mutable_store, + ); + let repository = random::(); + let id = format!("urc-{repository}"); + // Only this random repository is ever managed, so tests running beside this one see + // no change; the policy is unconfigured again at the end. + let policy = std::env::temp_dir().join(format!("managed-{repository}.json")); + let set_policy = |managed: &str| { + std::fs::write(&policy, format!(r#"{{"version":1,"managed":[{managed}]}}"#)) + .expect("write policy"); + managed::recheck_now(); + }; + set_policy(""); + managed::configure(Some(&policy)).expect("valid policy"); + + let (writer, _) = test_support::mint("dev", &[("urc-*", &["read", "write"])], 600); + let (publisher, _) = + test_support::mint("gdam-publisher", &[(id.as_str(), &["read", "publish"])], 600); + let writer = authorize(&service, repository, &writer).await; + let publisher = authorize(&service, repository, &publisher).await; + let denied = |result: Result, MessageHandleError>| { + matches!(result, Err(MessageHandleError::AuthorizationFailure(_))) + }; + + // Unmanaged: the wildcard writer writes; `publish` writes nothing here. + for command in [Command::MutableStore, Command::MutableCas] { + mutate(&service, writer, command).await.expect("unmanaged write"); + assert!(denied(mutate(&service, publisher, command).await)); + } + + // The repository becomes managed with its publisher listed: the writer's session, + // opened before, writes nothing; the publisher's writes. + set_policy(&format!( + r#"{{"resource_id":"{id}","publishers":["gdam-publisher"],"authors":[]}}"# + )); + for command in [Command::MutableStore, Command::MutableCas] { + assert!(denied(mutate(&service, writer, command).await), "{command:?}"); + mutate(&service, publisher, command).await.expect("listed publisher"); + } + + // The policy drops the publisher: its open session writes nothing more. + set_policy(&format!( + r#"{{"resource_id":"{id}","publishers":[],"authors":["someone-else"]}}"# + )); + for command in [Command::MutableStore, Command::MutableCas] { + assert!(denied(mutate(&service, publisher, command).await), "{command:?}"); + assert!(denied(mutate(&service, writer, command).await), "{command:?}"); + } + + managed::configure(None).expect("unconfigure"); + let _ = std::fs::remove_file(&policy); + } /// Fill the session map to capacity then attempt one more `AuthorizeStart`, /// verifying the handler returns `SlowDown` and that `transform_protocol_error` From 0ff3d3ca60bd4b0556e001214d269c20b2030210 Mon Sep 17 00:00:00 2001 From: Geordie Moffatt Date: Sun, 22 Nov 2026 14:47:40 -0800 Subject: [PATCH 2/2] lore-server: a policy change counts by content, and a healing verify is a write The managed-repository policy was re-read only when the file's size or modification time changed. A replacement that keeps both (a copy that preserves times, an equal-length edit within the clock's resolution) left a removed publisher able to write for as long as the server ran. The file is small, so the server now reads it at every recheck and compares its contents. A storage Verify with the heal flag rewrites index entries and flushes the bucket, but neither transport asked for write: a read grant could reach it, on a managed repository too. gRPC and QUIC now check write for a healing verify and leave a reporting verify open to readers. Tests: the open-session test swaps in a policy of equal size and modification time (it fails on the old reload), and covers healing and reporting verifies on a session; a gRPC test covers the same three callers. Signed-off-by: Geordie Moffatt --- lore-server/src/auth/managed.rs | 43 ++++++++-------- lore-server/src/grpc/storage/v1/service.rs | 57 ++++++++++++++++++++++ lore-server/src/quic/storage_service_v4.rs | 54 ++++++++++++++++++-- 3 files changed, 128 insertions(+), 26 deletions(-) diff --git a/lore-server/src/auth/managed.rs b/lore-server/src/auth/managed.rs index bacefaebc..b82955357 100644 --- a/lore-server/src/auth/managed.rs +++ b/lore-server/src/auth/managed.rs @@ -28,7 +28,6 @@ use std::sync::Arc; use std::sync::RwLock; use std::time::Duration; use std::time::Instant; -use std::time::SystemTime; use serde::Deserialize; use thiserror::Error; @@ -269,25 +268,20 @@ impl EffectiveGrants<'_> { struct Holder { path: Option, snapshot: Snapshot, - stamp: Option<(SystemTime, u64)>, + /// The bytes the valid snapshot was parsed from. The file's contents decide whether it + /// changed: a replacement that keeps its size and modification time must still take effect. + bytes: Option>, checked: Instant, } static POLICY: RwLock> = RwLock::new(None); -fn stamp(path: &Path) -> std::io::Result<(SystemTime, u64)> { - let metadata = std::fs::metadata(path)?; - Ok((metadata.modified()?, metadata.len())) -} - -fn load(path: &Path) -> Result<(ManagedPolicy, (SystemTime, u64)), PolicyError> { - let read = |source| PolicyError::Read { +fn load(path: &Path) -> Result<(ManagedPolicy, Vec), PolicyError> { + let bytes = std::fs::read(path).map_err(|source| PolicyError::Read { path: path.to_path_buf(), source, - }; - let stamp = stamp(path).map_err(read)?; - let bytes = std::fs::read(path).map_err(read)?; - Ok((ManagedPolicy::parse(&bytes)?, stamp)) + })?; + Ok((ManagedPolicy::parse(&bytes)?, bytes)) } /// Load the configured policy at startup. An error must stop the server. @@ -296,11 +290,11 @@ pub fn configure(path: Option<&Path>) -> Result<(), PolicyError> { None => Holder { path: None, snapshot: Snapshot::Unconfigured, - stamp: None, + bytes: None, checked: Instant::now(), }, Some(path) => { - let (policy, stamp) = load(path)?; + let (policy, bytes) = load(path)?; info!( path = %path.display(), managed = policy.len(), @@ -309,7 +303,7 @@ pub fn configure(path: Option<&Path>) -> Result<(), PolicyError> { Holder { path: Some(path.to_path_buf()), snapshot: Snapshot::Valid(Arc::new(policy)), - stamp: Some(stamp), + bytes: Some(bytes), checked: Instant::now(), } } @@ -367,18 +361,23 @@ pub fn current() -> Snapshot { }; if holder.checked.elapsed() >= RECHECK { holder.checked = Instant::now(); - let unchanged = - matches!(holder.snapshot, Snapshot::Valid(_)) && stamp(&path).ok() == holder.stamp; + // Read the file every time: it is small, and its metadata does not prove it unchanged. + let read = std::fs::read(&path).map_err(|source| PolicyError::Read { + path: path.clone(), + source, + }); + let unchanged = matches!(holder.snapshot, Snapshot::Valid(_)) + && read.as_ref().ok() == holder.bytes.as_ref(); if !unchanged { - match load(&path) { - Ok((policy, stamp)) => { + match read.and_then(|bytes| Ok((ManagedPolicy::parse(&bytes)?, bytes))) { + Ok((policy, bytes)) => { info!( path = %path.display(), managed = policy.len(), "Reloaded managed repositories policy" ); holder.snapshot = Snapshot::Valid(Arc::new(policy)); - holder.stamp = Some(stamp); + holder.bytes = Some(bytes); } Err(err) => { if !matches!(holder.snapshot, Snapshot::Invalid) { @@ -389,7 +388,7 @@ pub fn current() -> Snapshot { ); } holder.snapshot = Snapshot::Invalid; - holder.stamp = None; + holder.bytes = None; } } } diff --git a/lore-server/src/grpc/storage/v1/service.rs b/lore-server/src/grpc/storage/v1/service.rs index 63a9db7ba..9e44a8e14 100644 --- a/lore-server/src/grpc/storage/v1/service.rs +++ b/lore-server/src/grpc/storage/v1/service.rs @@ -72,6 +72,11 @@ impl StorageServiceV1 for LoreStorageService { &self, request: Request, ) -> Result, Status> { + // A verify that heals rewrites store entries, so it is a write; one that only reports + // stays a read. + if request.get_ref().heal { + crate::grpc::verify_write(&request)?; + } verify::handler(request, self.local_immutable_store().clone()).await } @@ -271,6 +276,58 @@ mod tests { .expect("test task"); } + /// A verify that heals rewrites store entries, so a read grant must not reach it; a verify + /// that only reports stays open to a reader, and a writer may heal. + #[tokio::test] + async fn a_healing_verify_needs_write() { + let (immutable_store, mutable_store, execution) = + test_store_create().await.expect("Failed to create store"); + let repository = random::(); + + runtime() + .spawn(LORE_CONTEXT.scope(execution, async move { + let service = LoreStorageService::new( + immutable_store.clone(), + immutable_store, + mutable_store, + ); + let token = |permission: &[&str]| AuthorizationToken { + user_id: "caller".to_string(), + resources: Some(vec![ResourcePermission { + resource_id: format!("urc-{repository}"), + permission: permission.iter().map(|p| (*p).to_string()).collect(), + }]), + ..Default::default() + }; + let verify = |permission: &[&str], heal: bool| { + let mut request = make_request_with_metadata( + storage_v1::VerifyRequest { + address: Some(lore_proto::lore::model::v1::Address { + hash: bytes(random::()), + context: bytes::Bytes::copy_from_slice(repository.as_bytes()), + }), + heal, + }, + repository, + "test-verify-heal", + ); + request.extensions_mut().insert(token(permission)); + StorageServiceV1::verify(&service, request) + }; + let denied = |result: Result<_, tonic::Status>| { + result.is_err_and(|status: tonic::Status| { + status.code() == Code::PermissionDenied + }) + }; + + assert!(denied(verify(&["read"], true).await.map(|_| ()))); + assert!(!denied(verify(&["read"], false).await.map(|_| ()))); + assert!(!denied(verify(&["read", "write"], true).await.map(|_| ()))); + })) + .await + .expect("test task"); + } + /// Compile-time check that `LoreStorageService` fully implements the generated /// `StorageService` trait — wrapping it in `StorageServiceServer` requires the /// trait bound to hold. Per-handler behavior is tested in each handler module. diff --git a/lore-server/src/quic/storage_service_v4.rs b/lore-server/src/quic/storage_service_v4.rs index 7c069dfe1..dc362a829 100644 --- a/lore-server/src/quic/storage_service_v4.rs +++ b/lore-server/src/quic/storage_service_v4.rs @@ -291,11 +291,18 @@ impl QuicService for StorageServiceV4 { } _ => None, }; + // A verify that heals rewrites store entries, so it is a write; one that only + // reports stays a read. let mutating = mutable_key_type.is_some() || matches!( - parsed, + &parsed, crate::quic::storage_service::ParsedStorageRequest::Put(_) | crate::quic::storage_service::ParsedStorageRequest::Copy(_) + ) + || matches!( + &parsed, + crate::quic::storage_service::ParsedStorageRequest::Verify(verify) + if verify.heal != 0 ); if mutating && !write.allows(repository) { return Err(MessageHandleError::AuthorizationFailure( @@ -573,6 +580,27 @@ mod tests { .await } + /// A `Verify` of a random address on an open session, healing or only reporting. + async fn verify( + service: &StorageServiceV4, + session_id: u32, + heal: bool, + ) -> Result, MessageHandleError> { + let size = std::mem::size_of::(); + let mut payload: Vec = (1..size).map(|_| random()).collect(); // address + payload.push(u8::from(heal)); + service + .run_request_handler( + AttributeMap::default().into(), + ParsedStorageRequestV4::StorageCommand { + session_id, + opcode: Command::Verify.into(), + payload: Bytes::from(payload), + }, + ) + .await + } + /// Write on a session is asked again on every mutating command, under the managed /// repository policy in force then: a session opened before its repository became managed /// writes nothing afterwards, a listed publisher's session writes while it is listed and @@ -625,11 +653,29 @@ mod tests { assert!(denied(mutate(&service, writer, command).await), "{command:?}"); mutate(&service, publisher, command).await.expect("listed publisher"); } - - // The policy drops the publisher: its open session writes nothing more. + // A verify that heals is a write; one that only reports stays a read. + assert!(denied(verify(&service, writer, true).await)); + assert!(!denied(verify(&service, writer, false).await)); + assert!(!denied(verify(&service, publisher, true).await)); + + // The policy drops the publisher: its open session writes nothing more. The new file + // has the size and the modification time of the one it replaces (the subject only + // moves to `authors`), so its contents alone say that it changed. + let replaced = std::fs::metadata(&policy).expect("policy metadata"); set_policy(&format!( - r#"{{"resource_id":"{id}","publishers":[],"authors":["someone-else"]}}"# + r#"{{"resource_id":"{id}","publishers":[],"authors":["gdam-publisher"]}}"# )); + std::fs::File::options() + .write(true) + .open(&policy) + .and_then(|file| file.set_modified(replaced.modified()?)) + .expect("restore modification time"); + let now = std::fs::metadata(&policy).expect("policy metadata"); + assert_eq!( + (now.len(), now.modified().expect("modified")), + (replaced.len(), replaced.modified().expect("modified")) + ); + managed::recheck_now(); for command in [Command::MutableStore, Command::MutableCas] { assert!(denied(mutate(&service, publisher, command).await), "{command:?}"); assert!(denied(mutate(&service, writer, command).await), "{command:?}");