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
40 changes: 40 additions & 0 deletions lore-server/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ pub mod jwt_interceptor;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;

use lore_base::types::KeyType;

/// Whether this process is serving with authorization enabled. Set once at server build
/// from the presence of a JWT verifier. Used as a fail-closed backstop: a mutating handler
/// reached without an authorization token denies the write when auth is enabled (rather than
Expand All @@ -25,6 +27,44 @@ pub fn auth_enabled() -> bool {
AUTH_ENABLED.load(Ordering::Relaxed)
}

/// Whether a mutable key of this type is changed only through a checked RPC: branch heads
/// by `BranchPush` (protection, locks, parent check), branch records by `BranchCreate`,
/// `BranchDelete`, `BranchProtect`/`BranchUnprotect` and `BranchMetadataSet`, repository
/// records by `RepositoryCreate` and `RepositoryMetadataSet`.
/// Under auth, the raw `MutableStore` / `MutableCompareAndSwap` RPCs refuse these types, so a
/// writer cannot move a head past those checks. The stock client never writes them through
/// the raw RPCs: it keeps its own copies in its local store.
pub fn is_checked_key_type(key_type: KeyType) -> bool {
match key_type {
KeyType::BranchMetadata
| KeyType::BranchId
| KeyType::BranchLatestPointer
| KeyType::RepositoryMetadata
| KeyType::RepositoryId => true,
KeyType::Untyped | KeyType::Instance => false,
}
}

/// Whether the server's mutable store keeps key types apart, so a key written under one type
/// can never be read back as another. Set once at server build; unset (the default) fails
/// closed. Only the local store is known to: `LocalMutableStore` stamps the key type into the
/// stored key (`Key::make_typed`) and lists by it, so relabelling a branch head `Untyped` or
/// `Instance` writes a different key. A remote store forwards to another server and a plugin
/// store's namespacing is unknown, so neither is trusted.
static MUTABLE_KEY_TYPES_ISOLATED: AtomicBool = AtomicBool::new(false);

/// Record whether the configured mutable store keeps key types apart.
pub fn set_mutable_key_types_isolated(isolated: bool) {
MUTABLE_KEY_TYPES_ISOLATED.store(isolated, Ordering::Relaxed);
}

/// Under auth, whether a raw `MutableStore` / `MutableCompareAndSwap` may write a key of this
/// type: never one a checked RPC owns, and nothing at all on a store that cannot keep key
/// types apart (a relabelled key could alias a protected one there).
pub fn raw_mutable_write_allowed(key_type: KeyType) -> bool {
MUTABLE_KEY_TYPES_ISOLATED.load(Ordering::Relaxed) && !is_checked_key_type(key_type)
}

/// The access a request needs on a repository.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Access {
Expand Down
22 changes: 22 additions & 0 deletions lore-server/src/grpc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ pub mod tower;
pub use admin_service::LoreAdminService;
pub use grpc_internal_server::GrpcInternalServerBuilder;
use lore_base::types::Context;
use lore_base::types::KeyType;
use lore_revision::lore::RepositoryId;
use lore_revision::metadata::MetadataError;
use lore_revision::repository::RepositoryWriteToken;
Expand Down Expand Up @@ -235,6 +236,27 @@ pub fn verify_write<T>(request: &tonic::Request<T>) -> Result<(), Status> {
crate::auth::jwt::verify_write_authorization(authorization, repository).map_err(|_| write_denied())
}

/// Gate for the raw `MutableStore` / `MutableCompareAndSwap` RPCs, after [`verify_write`]:
/// under auth (a token on the request, or auth enabled server-wide) a key type that a checked
/// RPC owns is refused, and every key on a store that cannot keep key types apart; see
/// [`crate::auth::raw_mutable_write_allowed`]. An unknown key type is left to the handler,
/// which rejects it as an invalid argument.
pub fn verify_raw_mutable_write<T>(
request: &tonic::Request<T>,
key_type: u32,
) -> Result<(), Status> {
let under_auth =
crate::auth::auth_enabled() || request.extensions().get::<AuthorizationToken>().is_some();
match KeyType::try_from(key_type) {
Ok(key_type) if under_auth && !crate::auth::raw_mutable_write_allowed(key_type) => {
Err(Status::permission_denied(format!(
"{key_type:?} keys cannot change through a raw store on this server"
)))
}
_ => Ok(()),
}
}

/// Authorize the repository a request names in its body, for services whose interceptor only
/// authenticates the caller. Call it before any lookup, so a caller without a grant gets the
/// same denial whether or not the repository exists. `auth_required` denies a request that
Expand Down
166 changes: 166 additions & 0 deletions lore-server/src/grpc/storage/v1/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ impl StorageServiceV1 for LoreStorageService {
request: Request<storage_v1::MutableStoreRequest>,
) -> Result<Response<storage_v1::MutableStoreResponse>, Status> {
crate::grpc::verify_write(&request)?;
let key_type = request.get_ref().key_type;
crate::grpc::verify_raw_mutable_write(&request, key_type)?;
mutable_store::handler(request, self.mutable_store().clone()).await
}

Expand All @@ -95,15 +97,179 @@ impl StorageServiceV1 for LoreStorageService {
request: Request<storage_v1::MutableCompareAndSwapRequest>,
) -> Result<Response<storage_v1::MutableCompareAndSwapResponse>, Status> {
crate::grpc::verify_write(&request)?;
let key_type = request.get_ref().key_type;
crate::grpc::verify_raw_mutable_write(&request, key_type)?;
mutable_compare_and_swap::handler(request, self.mutable_store().clone()).await
}
}

#[cfg(test)]
mod tests {
use lore_base::runtime::LORE_CONTEXT;
use lore_base::runtime::runtime;
use lore_base::types::Context;
use lore_base::types::Hash;
use lore_base::types::KeyType;
use lore_proto::lore::storage::v1 as storage_v1;
use lore_proto::lore::storage::v1::storage_service_server::StorageService as StorageServiceV1;
use lore_proto::lore::storage::v1::storage_service_server::StorageServiceServer;
use rand::random;
use tonic::Code;
use zerocopy::IntoBytes;

use crate::auth::jwt::AuthorizationToken;
use crate::auth::jwt::ResourcePermission;
use crate::grpc::storage::v1::test_utils::make_request_with_metadata;
use crate::grpc::storage_service::LoreStorageService;
use crate::store::test_store_create;

fn bytes(hash: Hash) -> bytes::Bytes {
bytes::Bytes::copy_from_slice(hash.as_bytes())
}

/// #3304: a writer must not move a branch head (or any record a checked RPC owns) through
/// the raw store RPCs. With a write-capable token on the request, every checked key type
/// is refused by `MutableStore` and `MutableCompareAndSwap`, and the protected value stays;
/// writing the same key relabelled `Untyped` or `Instance` lands on a different stored key
/// in the local store, so the protected value still stays. Untyped and instance keys stay
/// writable.
#[tokio::test]
async fn raw_mutable_writes_of_checked_key_types_are_refused_under_auth() {
let (immutable_store, mutable_store, execution) =
test_store_create().await.expect("Failed to create store");
let repository = random::<Context>();
// The local store keeps key types apart, as the server records at build.
crate::auth::set_mutable_key_types_isolated(true);
let protected = mutable_store.clone();

runtime()
.spawn(LORE_CONTEXT.scope(execution, async move {
let service = LoreStorageService::new(
immutable_store.clone(),
immutable_store,
mutable_store,
);
let writer = AuthorizationToken {
user_id: "writer".to_string(),
resources: Some(vec![ResourcePermission {
resource_id: format!("urc-{repository}"),
permission: vec!["read".to_string(), "write".to_string()],
}]),
..Default::default()
};
let load = |key: Hash, key_type: KeyType| {
let request = make_request_with_metadata(
storage_v1::MutableLoadRequest {
key: bytes(key),
key_type: key_type as u32,
},
repository,
"test-raw-mutable",
);
StorageServiceV1::mutable_load(&service, request)
};
let store = |key: Hash, value: Hash, key_type: KeyType| {
let mut request = make_request_with_metadata(
storage_v1::MutableStoreRequest {
key: bytes(key),
value: bytes(value),
key_type: key_type as u32,
},
repository,
"test-raw-mutable",
);
request.extensions_mut().insert(writer.clone());
request
};
let cas = |key: Hash, value: Hash, key_type: KeyType| {
let mut request = make_request_with_metadata(
storage_v1::MutableCompareAndSwapRequest {
key: bytes(key),
expected: bytes(Hash::default()),
value: bytes(value),
key_type: key_type as u32,
},
repository,
"test-raw-mutable",
);
request.extensions_mut().insert(writer.clone());
request
};

for key_type in [
KeyType::BranchLatestPointer,
KeyType::BranchMetadata,
KeyType::BranchId,
KeyType::RepositoryMetadata,
KeyType::RepositoryId,
] {
let key = random::<Hash>();
let original = random::<Hash>();
protected
.clone()
.store(repository.into(), key, original, key_type)
.await
.expect("seed the protected key");
let current = || async {
load(key, key_type)
.await
.expect("protected key")
.into_inner()
.value
};

let refused =
StorageServiceV1::mutable_store(&service, store(key, random(), key_type))
.await
.expect_err("raw store of a checked key type must be refused");
assert_eq!(refused.code(), Code::PermissionDenied, "{key_type:?}");

let refused = StorageServiceV1::mutable_compare_and_swap(
&service,
cas(key, random(), key_type),
)
.await
.expect_err("raw CAS of a checked key type must be refused");
assert_eq!(refused.code(), Code::PermissionDenied, "{key_type:?}");
assert_eq!(current().await.as_ref(), original.as_bytes(), "{key_type:?}");

// The same key relabelled as a type no checked RPC owns is accepted, and
// lands beside the protected key, never on it.
for alias in [KeyType::Untyped, KeyType::Instance] {
StorageServiceV1::mutable_store(&service, store(key, random(), alias))
.await
.expect("an unprotected type is writable");
assert_eq!(
current().await.as_ref(),
original.as_bytes(),
"{key_type:?} relabelled {alias:?}"
);
}
}

for key_type in [KeyType::Untyped, KeyType::Instance] {
let key = random::<Hash>();
let value = random::<Hash>();
StorageServiceV1::mutable_store(&service, store(key, value, key_type))
.await
.expect("a writer stores keys no checked RPC owns");
StorageServiceV1::mutable_compare_and_swap(
&service,
cas(random(), value, key_type),
)
.await
.expect("a writer swaps keys no checked RPC owns");
let loaded = load(key, key_type)
.await
.expect("stored")
.into_inner()
.value;
assert_eq!(loaded.as_ref(), value.as_bytes(), "{key_type:?}");
}
}))
.await
.expect("test task");
}

/// Compile-time check that `LoreStorageService` fully implements the generated
/// `StorageService` trait — wrapping it in `StorageServiceServer` requires the
Expand Down
16 changes: 16 additions & 0 deletions lore-server/src/quic/storage_service_v4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,22 @@ 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)
{
return Err(MessageHandleError::AuthorizationFailure(format!(
"{key_type:?} keys cannot change through a raw store on this server"
)));
}

// Dispatch to standalone handler functions with explicit session context
let response = match parsed {
crate::quic::storage_service::ParsedStorageRequest::Get(get) => {
Expand Down
3 changes: 3 additions & 0 deletions lore-server/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1806,6 +1806,9 @@ async fn async_main(settings: (Settings, StringHash), config: ServerConfig) -> R
let mutable_store =
configure_mutable_store_via_plugin(&plugin_registry, &settings, immutable_store.clone())
.await?;
// Only the local store is known to keep mutable key types apart; under auth, any other
// refuses every raw mutable write (`auth::raw_mutable_write_allowed`).
crate::auth::set_mutable_key_types_isolated(settings.mutable_store.mode == store_mode::LOCAL);

let lock_store = configure_lock_store_via_plugin(&plugin_registry, &settings)?;

Expand Down
Loading