use secret_service::EncryptionType;
use secret_service::blocking::SecretService as Client;
use std::collections::{BTreeMap, HashMap};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
const SECRETS: &str = "org.freedesktop.secrets";
const ASKED_SO_FAR: &str = "pitboard-test-asked-so-far";
const STARTED_WITHIN: Duration = Duration::from_secs(20);
pub struct SecretService {
address: String,
folder: PathBuf,
bus: Child,
keyring: Option<Child>,
ksecretd: Option<zbus::blocking::Connection>,
asked: Arc<Mutex<Vec<String>>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Item {
pub label: String,
pub attributes: BTreeMap<String, String>,
pub secret: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Missing {
program: &'static str,
package: &'static str,
}
impl std::fmt::Display for Missing {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"the Secret Service the tests start needs `{}`, which is not installed: install the \
`{}` package",
self.program, self.package
)
}
}
impl std::error::Error for Missing {}
impl SecretService {
pub fn start(scratch: &Path) -> Result<SecretService, Missing> {
let mut service = SecretService::without_a_provider(scratch)?;
service.keyring = Some(service.keyring()?);
service.wait_for_the_default_collection();
Ok(service)
}
pub fn ksecretd(scratch: &Path) -> Result<SecretService, Missing> {
let mut service = SecretService::without_a_provider(scratch)?;
service.ksecretd = Some(ksecretd::serve(&service.address));
Ok(service)
}
pub fn without_a_provider(scratch: &Path) -> Result<SecretService, Missing> {
assert!(
scratch.is_absolute(),
"a test named its scratch folder {} relative to wherever it runs",
scratch.display()
);
let folder = scratch.to_path_buf();
std::fs::create_dir_all(&folder).expect("the Secret Service's folder");
let config = folder.join("bus.conf");
std::fs::write(&config, bus_config(&folder.join("bus"))).expect("the bus's config");
let mut bus = Command::new("dbus-daemon")
.arg(format!("--config-file={}", config.display()))
.args(["--nofork", "--print-address=1"])
.env_clear()
.env("PATH", "/usr/bin:/bin")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(log(&folder, "dbus-daemon.log"))
.spawn()
.map_err(|e| missing(&e, "dbus-daemon", "dbus-daemon"))?;
let mut line = String::new();
std::io::BufRead::read_line(
&mut std::io::BufReader::new(bus.stdout.take().expect("its output")),
&mut line,
)
.expect("dbus-daemon says where it listens");
let address = line.trim().to_owned();
assert!(
!address.is_empty(),
"dbus-daemon did not start: {}",
folder.display()
);
let asked = Arc::new(Mutex::new(Vec::new()));
watch(&address, Arc::clone(&asked));
Ok(SecretService {
address,
folder,
bus,
keyring: None,
ksecretd: None,
asked,
})
}
pub fn address(&self) -> &str {
&self.address
}
pub fn lock(&self) {
let client = self.client();
client
.get_default_collection()
.and_then(|collection| collection.lock())
.expect("the default collection locks");
}
pub fn stop(&mut self) {
drop(self.ksecretd.take());
if let Some(mut keyring) = self.keyring.take() {
let _ = keyring.kill();
let _ = keyring.wait();
}
let start = Instant::now();
while self.owned() {
assert!(
start.elapsed() < STARTED_WITHIN,
"the keyring stays on the bus"
);
std::thread::sleep(Duration::from_millis(20));
}
}
pub fn items(&self) -> Vec<Item> {
let client = self.client();
let collection = client
.get_default_collection()
.expect("a default collection");
let mut items: Vec<Item> = collection
.get_all_items()
.expect("its items")
.iter()
.map(|item| Item {
label: item.get_label().expect("its label"),
attributes: item
.get_attributes()
.expect("its attributes")
.into_iter()
.collect(),
secret: String::from_utf8(item.get_secret().expect("its secret")).expect("text"),
})
.collect();
items.sort_by(|a, b| a.attributes.cmp(&b.attributes));
items
}
pub fn names(&self) -> Vec<String> {
let client = self.client();
let collection = client
.get_default_collection()
.expect("a default collection");
let mut names: Vec<String> = collection
.get_all_items()
.expect("its items")
.iter()
.filter_map(|item| {
item.get_attributes()
.expect("its attributes")
.remove("service")
})
.collect();
names.sort();
names
}
pub fn plant(&self, label: &str, attributes: &[(&str, &str)], secret: &str) {
for (_, value) in attributes {
if let Some(why) = crate::provider::names::refusal(value, &[]) {
panic!("{why}");
}
}
let client = self.client();
let collection = client
.get_default_collection()
.expect("a default collection");
collection
.create_item(
label,
attributes.iter().copied().collect::<HashMap<_, _>>(),
secret.as_bytes(),
true,
"text/plain",
)
.expect("an item planted");
}
pub fn asked(&self) -> Vec<String> {
let marks = || {
self.recorded()
.iter()
.filter(|m| *m == ASKED_SO_FAR)
.count()
};
let before = marks();
let _ = zbus::blocking::Proxy::new(
&self.connection(),
SECRETS,
"/org/freedesktop/secrets",
"org.freedesktop.Secret.Service",
)
.and_then(|service| {
service.call::<_, _, zbus::zvariant::OwnedObjectPath>("ReadAlias", &(ASKED_SO_FAR,))
});
let start = Instant::now();
while marks() == before {
assert!(
start.elapsed() < STARTED_WITHIN,
"the bus's monitor fell behind"
);
std::thread::sleep(Duration::from_millis(5));
}
self.recorded()
.into_iter()
.filter(|member| member != ASKED_SO_FAR)
.collect()
}
fn recorded(&self) -> Vec<String> {
self.asked
.lock()
.expect("a poisoned record is a failed test")
.clone()
}
fn keyring(&self) -> Result<Child, Missing> {
let mut folders = Vec::new();
for name in ["home", "data", "runtime"] {
let folder = self.folder.join(name);
std::fs::create_dir_all(&folder).expect("a keyring folder");
folders.push(folder);
}
crate::host::fs::testing::make_private(&folders[2]).expect("a private runtime folder");
let mut keyring = Command::new("gnome-keyring-daemon")
.args(["--foreground", "--components=secrets", "--unlock"])
.env_clear()
.env("PATH", "/usr/bin:/bin")
.env("HOME", &folders[0])
.env("XDG_DATA_HOME", &folders[1])
.env("XDG_RUNTIME_DIR", &folders[2])
.env("DBUS_SESSION_BUS_ADDRESS", &self.address)
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(log(&self.folder, "gnome-keyring-daemon.log"))
.spawn()
.map_err(|e| missing(&e, "gnome-keyring-daemon", "gnome-keyring"))?;
let mut input = keyring.stdin.take().expect("its input");
input
.write_all(b"pitboard-test")
.expect("the keyring's password");
drop(input);
Ok(keyring)
}
fn connection(&self) -> zbus::blocking::Connection {
zbus::blocking::connection::Builder::address(self.address.as_str())
.and_then(zbus::blocking::connection::Builder::build)
.expect("the test's bus answers")
}
fn client<'a>(&self) -> Client<'a> {
Client::connect_with_existing(EncryptionType::Dh, self.connection())
.expect("the test's Secret Service answers")
}
fn owned(&self) -> bool {
zbus::blocking::fdo::DBusProxy::new(&self.connection())
.expect("the bus")
.name_has_owner(SECRETS.try_into().expect("a bus name"))
.expect("the bus says who owns a name")
}
fn wait_for_the_default_collection(&self) {
let start = Instant::now();
while !(self.owned() && self.client().get_default_collection().is_ok()) {
assert!(
start.elapsed() < STARTED_WITHIN,
"gnome-keyring made no default collection: {}",
self.folder.join("gnome-keyring-daemon.log").display()
);
std::thread::sleep(Duration::from_millis(20));
}
}
}
impl Drop for SecretService {
fn drop(&mut self) {
drop(self.ksecretd.take());
for child in self
.keyring
.iter_mut()
.chain(std::iter::once(&mut self.bus))
{
let _ = child.kill();
let _ = child.wait();
}
}
}
mod ksecretd {
use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value};
const NAMES: [&str; 3] = [
"org.kde.ksecretd",
"org.kde.secretservicecompat",
super::SECRETS,
];
const WALLET: &str = "/org/freedesktop/secrets/collection/kdewallet";
struct Service;
#[zbus::interface(name = "org.freedesktop.Secret.Service")]
impl Service {
fn open_session(
&self,
_algorithm: &str,
_input: OwnedValue,
) -> zbus::fdo::Result<(OwnedValue, OwnedObjectPath)> {
let key = OwnedValue::try_from(Value::from(vec![2_u8]))
.map_err(|e| zbus::fdo::Error::Failed(e.to_string()))?;
Ok((key, path("/org/freedesktop/secrets/session/1")))
}
fn read_alias(&self, name: &str) -> OwnedObjectPath {
path(if name == "default" { WALLET } else { "/" })
}
}
struct Wallet;
#[zbus::interface(name = "org.freedesktop.Secret.Collection")]
impl Wallet {
#[zbus(property)]
fn label(&self) -> String {
"kdewallet".into()
}
#[zbus(property)]
fn locked(&self) -> bool {
true
}
}
fn path(path: &str) -> OwnedObjectPath {
OwnedObjectPath::try_from(path).expect("an object path")
}
pub(super) fn serve(bus: &str) -> zbus::blocking::Connection {
let mut builder = zbus::blocking::connection::Builder::address(bus)
.and_then(|builder| builder.serve_at("/org/freedesktop/secrets", Service))
.and_then(|builder| builder.serve_at(WALLET, Wallet))
.expect("the stand-in's objects");
for name in NAMES {
builder = builder.name(name).expect("a bus name");
}
builder
.build()
.expect("the stand-in for ksecretd on the test's bus")
}
}
fn bus_config(socket: &Path) -> String {
format!(
r#"<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<type>session</type>
<listen>unix:path={}</listen>
<auth>EXTERNAL</auth>
<policy context="default">
<allow send_destination="*" eavesdrop="true"/>
<allow eavesdrop="true"/>
<allow own="*"/>
</policy>
</busconfig>
"#,
socket.display()
)
}
fn log(folder: &Path, name: &str) -> Stdio {
std::fs::File::create(folder.join(name)).map_or_else(|_| Stdio::null(), Stdio::from)
}
fn missing(error: &std::io::Error, program: &'static str, package: &'static str) -> Missing {
assert_eq!(
error.kind(),
std::io::ErrorKind::NotFound,
"{program} did not start: {error}"
);
Missing { program, package }
}
fn watch(address: &str, asked: Arc<Mutex<Vec<String>>>) {
let connection = zbus::blocking::connection::Builder::address(address)
.and_then(zbus::blocking::connection::Builder::build)
.expect("the test's bus answers");
let messages = zbus::blocking::MessageIterator::from(&connection);
zbus::blocking::fdo::MonitoringProxy::new(&connection)
.expect("a monitor")
.become_monitor(&[], 0)
.expect("the bus lets its own user watch it");
std::thread::spawn(move || {
for message in messages.flatten() {
let header = message.header();
if header.message_type() != zbus::message::Type::MethodCall {
continue;
}
let (Some(interface), Some(member)) = (header.interface(), header.member()) else {
continue;
};
if !interface.as_str().starts_with("org.freedesktop.Secret.") {
continue;
}
let marked = member.as_str() == "ReadAlias"
&& message.body().deserialize::<&str>().ok() == Some(ASKED_SO_FAR);
asked
.lock()
.expect("a poisoned record is a failed test")
.push(
if marked {
ASKED_SO_FAR
} else {
member.as_str()
}
.to_owned(),
);
}
});
}