Skip to content
Merged
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
17 changes: 11 additions & 6 deletions coverage.sh
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ grcov coverage-raw/combined.info \
--ignore "**/target/*" \
--ignore "**/error.rs" \
--ignore "**/main.rs" \
--ignore "**/capability.rs"
--ignore "**/capability.rs" \
--ignore "**/login.rs"

# Generate HTML report with grcov
grcov coverage-raw/combined.info \
Expand All @@ -84,20 +85,24 @@ grcov coverage-raw/combined.info \
--ignore "**/target/*" \
--ignore "**/error.rs" \
--ignore "**/main.rs" \
--ignore "**/capability.rs"
--ignore "**/capability.rs" \
--ignore "**/login.rs"

# Extract and display coverage percentage
if [ -f coverage/html/coverage.json ]; then
COVERAGE=$(jq -r '.message' coverage/html/coverage.json | sed 's/%//')
if [ -f coverage/coverage.json ]; then
COVERAGE=$(jq -r '.coveragePercent' coverage/coverage.json)
COVERED=$(jq -r '.linesCovered' coverage/coverage.json)
TOTAL=$(jq -r '.linesTotal' coverage/coverage.json)
echo ""
echo "✅ Combined coverage: ${COVERAGE}%"
echo "✅ Combined coverage: ${COVERAGE}% (${COVERED}/${TOTAL} lines)"
echo "📁 HTML report available at: coverage/html/index.html"
echo "📁 JSON report available at: coverage/coverage.json"
else
echo "⚠️ Warning: coverage.json not found"
fi

# Clean up raw files
# Keep the combined LCOV file for line-level analysis
mv coverage-raw/combined.info coverage/combined.info
rm -rf coverage-raw

echo ""
Expand Down
8 changes: 8 additions & 0 deletions server/src/collection/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,14 @@ impl Collection {
} else {
"unknown".to_string()
};
// Deleting the placeholder of a pending migration would migrate
// the legacy keyring and throw the result away
if self.service.has_pending_migration(self.name()).await {
return Err(ServiceError::IsLocked(format!(
"Collection `{}` holds a keyring awaiting migration, unlock it first.",
self.path
)));
}
// Check if collection is locked
if self.is_locked().await {
// Create a prompt to unlock and delete the collection
Expand Down
22 changes: 21 additions & 1 deletion server/src/collection/tests/deletion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,11 +134,31 @@ async fn delete_locked_pending_migration() -> Result<(), Box<dyn std::error::Err
oo7::dbus::api::Collection::new(&setup.client_conn, collection_path.clone()).await?;
assert!(collection.is_locked().await?);

// Deleting the placeholder is refused even with the correct secret, it
// stands in for the legacy keyring and deleting it would throw the
// migrated data away
setup
.set_password_queue(vec![oo7::Secret::from("test")])
.await;
collection.delete(None).await?;
let result = collection.delete(None).await;
assert!(
result.is_err(),
"Deleting a collection with a pending migration should fail"
);
assert_eq!(
setup.server.pending_migrations.lock().await.len(),
1,
"The migration should still be pending"
);

// Once unlocked, the migrated collection can be deleted
let unlocked = setup
.service_api
.unlock(std::slice::from_ref(&collection_path), None)
.await?;
assert_eq!(unlocked.len(), 1);

collection.delete(None).await?;
assert_eq!(setup.server.pending_migrations.lock().await.len(), 0);
let collections = setup.service_api.collections().await?;
assert!(
Expand Down
22 changes: 20 additions & 2 deletions server/src/collection/tests/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -576,13 +576,31 @@ async fn delete_item_pending_migration() -> Result<(), Box<dyn std::error::Error
.await?;
assert_eq!(locked.len(), 1);

// Deleting a stand-in item is refused even with the correct secret,
// it would migrate the legacy keyring and throw the item away
setup
.set_password_queue(vec![oo7::Secret::from("test")])
.await;
let result = locked[0].delete(None).await;
assert!(
result.is_err(),
"Deleting an item of a collection with a pending migration should fail"
);
assert_eq!(
setup.server.pending_migrations.lock().await.len(),
1,
"The migration should still be pending"
);
assert!(collection.is_locked().await?);

// Once unlocked, the migrated item can be deleted
let unlocked = setup
.service_api
.unlock(std::slice::from_ref(&collection_path), None)
.await?;
assert_eq!(unlocked.len(), 1);
locked[0].delete(None).await?;

// The migration completed and the item was deleted from the migrated
// keyring
assert_eq!(setup.server.pending_migrations.lock().await.len(), 0);
assert!(!collection.is_locked().await?);
assert_eq!(collection.items().await?.len(), 0);
Expand Down
10 changes: 10 additions & 0 deletions server/src/item/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,16 @@ impl Item {
};
let collection = self.collection().await?;

// Deleting a stand-in item would migrate the legacy keyring and
// throw the item away
if self.service.has_pending_migration(collection.name()).await {
return Err(ServiceError::IsLocked(format!(
"Item `{}` belongs to a collection holding a keyring awaiting \
migration, unlock the collection first.",
self.path
)));
}

// Check if item or collection is locked
if self.is_locked().await || collection.is_locked().await {
// Create a prompt to unlock and delete the item
Expand Down
134 changes: 117 additions & 17 deletions server/src/pam_listener/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,17 @@ use zgvariant::serialized::Context;

use super::*;

async fn spawn_pam_listener(server: &crate::Service) -> std::path::PathBuf {
/// Spawn the listener, returning its socket path and a clone sharing the
/// buffered secrets, for [`PamListener::replay_buffered_secrets`].
async fn spawn_pam_listener(server: &crate::Service) -> (std::path::PathBuf, PamListener) {
let pam_listener = PamListener::new(server.clone());
let socket_path = pam_listener.socket_path.clone();
let spawned = pam_listener.clone();
tokio::spawn(async move {
let _ = pam_listener.start().await;
let _ = spawned.start().await;
});
tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
socket_path
(socket_path, pam_listener)
}

fn create_pam_message(
Expand Down Expand Up @@ -40,6 +43,18 @@ async fn send_pam_message(
socket_path: &std::path::Path,
message_bytes: &[u8],
) -> Result<(), Box<dyn std::error::Error>> {
let response = send_pam_bytes(socket_path, message_bytes).await?;
if !response.success {
return Err(format!("PAM operation failed: {}", response.error_message).into());
}
Ok(())
}

/// Send raw bytes on the PAM socket and read back the response, if any.
async fn send_pam_bytes(
socket_path: &std::path::Path,
message_bytes: &[u8],
) -> Result<PamResponse, Box<dyn std::error::Error>> {
use tokio::io::{AsyncReadExt, AsyncWriteExt};

let mut stream = tokio::net::UnixStream::connect(socket_path).await?;
Expand All @@ -54,14 +69,7 @@ async fn send_pam_message(
let mut response_bytes = vec![0u8; response_length];
stream.read_exact(&mut response_bytes).await?;

let response = PamResponse::from_bytes(&response_bytes)?;

// Check if response indicates success or error
if !response.success {
return Err(format!("PAM operation failed: {}", response.error_message).into());
}

Ok(())
Ok(PamResponse::from_bytes(&response_bytes)?)
}

#[tokio::test]
Expand Down Expand Up @@ -94,7 +102,7 @@ async fn pam_migrates_v0_keyrings() -> Result<(), Box<dyn std::error::Error>> {
"V0 keyring should be pending migration"
);

let socket_path = spawn_pam_listener(&setup.server).await;
let (socket_path, _) = spawn_pam_listener(&setup.server).await;

let message = create_pam_message(PamOperation::Unlock, "testuser", &[], v0_secret.as_bytes());
send_pam_message(&socket_path, &message).await?;
Expand Down Expand Up @@ -179,7 +187,7 @@ async fn pam_migration_then_write_to_default_alias() -> Result<(), Box<dyn std::

assert_eq!(setup.server.pending_migrations.lock().await.len(), 1);

let socket_path = spawn_pam_listener(&setup.server).await;
let (socket_path, _) = spawn_pam_listener(&setup.server).await;

let message = create_pam_message(PamOperation::Unlock, "testuser", &[], v0_secret.as_bytes());
send_pam_message(&socket_path, &message).await?;
Expand Down Expand Up @@ -262,7 +270,7 @@ async fn pam_unlocks_locked_collections() -> Result<(), Box<dyn std::error::Erro
"Work collection should be locked"
);

let socket_path = spawn_pam_listener(&setup.server).await;
let (socket_path, _) = spawn_pam_listener(&setup.server).await;

let message = create_pam_message(PamOperation::Unlock, "testuser", &[], secret.as_bytes());
send_pam_message(&socket_path, &message).await?;
Expand Down Expand Up @@ -316,7 +324,7 @@ async fn pam_change_password() -> Result<(), Box<dyn std::error::Error>> {
"Work collection should be locked"
);

let socket_path = spawn_pam_listener(&setup.server).await;
let (socket_path, _) = spawn_pam_listener(&setup.server).await;

let new_secret = Secret::from("new-password");
let message = create_pam_message(
Expand Down Expand Up @@ -420,7 +428,7 @@ async fn pam_wrong_secret_keeps_pending_migration_locked() -> Result<(), Box<dyn
.expect("Legacy placeholder collection should exist");
assert!(legacy.is_locked().await);

let socket_path = spawn_pam_listener(&setup.server).await;
let (socket_path, _) = spawn_pam_listener(&setup.server).await;

let message = create_pam_message(
PamOperation::Unlock,
Expand Down Expand Up @@ -455,7 +463,7 @@ async fn pam_change_password_pending_migration() -> Result<(), Box<dyn std::erro
let (setup, data_dir, _) =
crate::tests::pending_migration_setup(Some(socket_dir.path().join("pam.sock"))).await?;

let socket_path = spawn_pam_listener(&setup.server).await;
let (socket_path, _) = spawn_pam_listener(&setup.server).await;

let new_secret = Secret::from("new-password");
let message = create_pam_message(
Expand All @@ -479,3 +487,95 @@ async fn pam_change_password_pending_migration() -> Result<(), Box<dyn std::erro

Ok(())
}

// A secret arriving before the service is initialized is buffered and
// replayed once initialization is done, like Service::run does
#[tokio::test]
async fn pam_secret_before_initialization_is_replayed() -> Result<(), Box<dyn std::error::Error>> {
let temp_dir = tempfile::tempdir()?;
let keyrings_dir = temp_dir.path().join("keyrings");
tokio::fs::create_dir_all(keyrings_dir.join("v1")).await?;

let secret = Secret::from("pam-password");
let keyring = UnlockedKeyring::open_at(temp_dir.path(), "login", Some(secret.clone())).await?;
keyring
.create_item(
"Login Item",
&[("app", "pam-replay")],
Secret::text("item-secret"),
false,
)
.await?;
keyring.write().await?;

// The service is served on the bus but not initialized yet
let (server, server_conn, _client_conn, _parts_temp) =
crate::tests::TestServiceSetup::uninitialized_service(
temp_dir.path().to_path_buf(),
Some(temp_dir.path().join("pam.sock")),
)
.await?;

// The PAM secret arrives before the keyrings are discovered
let (socket_path, listener) = spawn_pam_listener(&server).await;
let message = create_pam_message(PamOperation::Unlock, "testuser", &[], secret.as_bytes());
send_pam_message(&socket_path, &message).await?;

// Initialize like Service::run does, then replay the buffered secret
let discovered = server.discover_keyrings(None).await?;
server
.initialize(server_conn, discovered, None, false)
.await?;

let login = server
.collection_by_label("Login")
.await
.expect("Login collection should exist");
assert!(login.is_locked().await, "No secret known at this point");

listener.replay_buffered_secrets().await;

let login = server
.collection_by_label("Login")
.await
.expect("Login collection should exist");
assert!(
!login.is_locked().await,
"The buffered secret should replay"
);

Ok(())
}

// Garbage on the PAM socket fails the connection cleanly
#[tokio::test]
async fn pam_malformed_message() -> Result<(), Box<dyn std::error::Error>> {
let temp_dir = tempfile::tempdir()?;

let setup = crate::tests::TestServiceSetup::with_disk_keyrings(
temp_dir.path().to_path_buf(),
Some(temp_dir.path().join("pam.sock")),
None,
)
.await?;

let (socket_path, _) = spawn_pam_listener(&setup.server).await;

// A valid length prefix around bytes that don't parse as a message
let payload = b"definitely not a pam message";
let mut message = (payload.len() as u32).to_le_bytes().to_vec();
message.extend_from_slice(payload);

let result = send_pam_bytes(&socket_path, &message).await;
assert!(
result.is_err(),
"A malformed message should fail the connection"
);

// The listener keeps serving valid messages afterwards
let secret = Secret::from("good-password");
let message = create_pam_message(PamOperation::Unlock, "testuser", &[], secret.as_bytes());
send_pam_message(&socket_path, &message).await?;

Ok(())
}
Loading
Loading