Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 43 additions & 22 deletions lore-server/src/auth/managed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -269,25 +268,20 @@ impl EffectiveGrants<'_> {
struct Holder {
path: Option<PathBuf>,
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<Vec<u8>>,
checked: Instant,
}

static POLICY: RwLock<Option<Holder>> = 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<u8>), 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.
Expand All @@ -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(),
Expand All @@ -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(),
}
}
Expand All @@ -320,6 +314,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 {
{
Expand All @@ -345,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) {
Expand All @@ -367,7 +388,7 @@ pub fn current() -> Snapshot {
);
}
holder.snapshot = Snapshot::Invalid;
holder.stamp = None;
holder.bytes = None;
}
}
}
Expand Down
57 changes: 57 additions & 0 deletions lore-server/src/grpc/storage/v1/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@ impl StorageServiceV1 for LoreStorageService {
&self,
request: Request<storage_v1::VerifyRequest>,
) -> Result<Response<storage_v1::VerifyResponse>, 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
}

Expand Down Expand Up @@ -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::<Context>();

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::<Hash>()),
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.
Expand Down
Loading
Loading