use super::bus;
use crate::context::Context;
use crate::host::Keyring;
use crate::permit::Permit;
use crate::schedule::Job;
use crate::store::{Backend, Error, RawStore};
use ::secret_service::EncryptionType;
use ::secret_service::blocking::{Collection, Item, SecretService};
use std::collections::HashMap;
const SCHEMA: (&str, &str) = ("xdg:schema", "com.usepitboard.Pitboard.Park");
const SERVICE: &str = "service";
const LABEL: &str = "Pitboard parked login";
const CONTENT_TYPE: &str = "application/json";
const LOCKED: [&str; 3] = [
"org.freedesktop.Secret.Error.IsLocked",
"org.freedesktop.DBus.Error.ServiceUnknown",
"org.freedesktop.DBus.Error.NameHasNoOwner",
];
const SECRETS: &str = "org.freedesktop.secrets";
const KWALLET: [&str; 4] = [
"org.kde.ksecretd",
"org.kde.secretservicecompat",
"org.kde.kwalletd6",
"org.kde.kwalletd5",
];
enum Items {
Parks,
GoKeyring { user: String },
}
pub(super) struct Vault {
ctx: Context,
asks: bool,
items: Items,
}
impl Vault {
pub(super) fn of(ctx: &Context) -> Vault {
let started_by_a_job = [Job::Renew, Job::Watch]
.into_iter()
.any(|job| crate::schedule::started_this_run(ctx, job));
Vault {
ctx: ctx.clone(),
asks: !started_by_a_job && ctx.in_the_desktop_session(),
items: Items::Parks,
}
}
pub(super) fn go_keyring(ctx: &Context, user: &str) -> Vault {
Vault {
items: Items::GoKeyring {
user: user.to_owned(),
},
..Vault::of(ctx)
}
}
fn attributes<'a>(&'a self, service: &'a str) -> Result<HashMap<&'a str, &'a str>, Error> {
match &self.items {
Items::Parks => Ok(HashMap::from([SCHEMA, (SERVICE, service)])),
Items::GoKeyring { user } => {
#[cfg(any(test, feature = "test-support"))]
if let Some(why) = crate::provider::names::refusal(service, &[]) {
return Err(Error::Unreadable(why));
}
Ok(HashMap::from([
("username", user.as_str()),
(SERVICE, service),
]))
}
}
}
fn label(&self, service: &str) -> String {
match &self.items {
Items::Parks => LABEL.to_owned(),
Items::GoKeyring { user } => format!("Password for '{user}' on '{service}'"),
}
}
fn content_type(&self) -> &'static str {
match self.items {
Items::Parks => CONTENT_TYPE,
Items::GoKeyring { .. } => "text/plain; charset=utf8",
}
}
fn open<T>(
&self,
otherwise: fn(String) -> Error,
then: impl FnOnce(&Collection<'_>) -> Result<T, Error>,
) -> Result<T, Error> {
let service = connected(&self.ctx, otherwise)?;
let collection = service.get_default_collection().map_err(said(otherwise))?;
if collection.is_locked().map_err(said(otherwise))? {
if !self.asks || self.ctx.unlock_was_dismissed() {
return Err(Error::Locked);
}
match collection.unlock() {
Err(::secret_service::Error::Prompt) => {
self.ctx.unlock_dismissed();
return Err(Error::Locked);
}
unlocked => unlocked.map_err(said(otherwise))?,
}
}
let answer = then(&collection)?;
if collection.is_locked().map_err(said(otherwise))? {
return Err(Error::Locked);
}
Ok(answer)
}
}
fn connected<'a>(
ctx: &Context,
otherwise: fn(String) -> Error,
) -> Result<SecretService<'a>, Error> {
let connection = bus::session(ctx).map_err(|_| Error::Locked)?;
SecretService::connect_with_existing(EncryptionType::Dh, connection).map_err(said(otherwise))
}
pub(super) fn answers(ctx: &Context) -> bool {
connected(ctx, Error::Unreadable).is_ok_and(|service| service.get_default_collection().is_ok())
}
pub(super) fn keyring(ctx: &Context) -> Keyring {
let kwallet = bus::session(ctx).ok().and_then(|connection| {
let bus = zbus::blocking::fdo::DBusProxy::new(&connection).ok()?;
let owner = |name: &str| {
let name = zbus::names::BusName::try_from(name).ok()?;
bus.get_name_owner(name).ok()
};
let answering = owner(SECRETS)?;
Some(
KWALLET
.iter()
.any(|name| owner(name).as_ref() == Some(&answering)),
)
});
if kwallet == Some(true) {
Keyring::KWallet
} else {
Keyring::Login
}
}
fn secret_of(
collection: &Collection<'_>,
attributes: HashMap<&str, &str>,
service: &str,
) -> Result<Option<String>, Error> {
let items = collection
.search_items(attributes)
.map_err(said(Error::Unreadable))?;
match items.as_slice() {
[] => Ok(None),
[item] => {
let secret = item.get_secret().map_err(said(Error::Unreadable))?;
String::from_utf8(secret)
.map(Some)
.map_err(|_| Error::Unreadable(format!("{service} does not hold text")))
}
several => Err(Error::Unreadable(format!(
"{} items of the Secret Service hold {service}",
several.len()
))),
}
}
fn said(otherwise: fn(String) -> Error) -> impl Fn(::secret_service::Error) -> Error {
use ::secret_service::Error as Said;
move |error| match &error {
Said::Locked
| Said::Prompt
| Said::PromptDisconnected
| Said::Unavailable
| Said::NoResult => Error::Locked,
Said::Zbus(zbus::Error::MethodError(name, ..)) if LOCKED.contains(&name.as_str()) => {
Error::Locked
}
Said::ZbusFdo(fdo) if LOCKED.contains(&zbus::DBusError::name(fdo).as_str()) => {
Error::Locked
}
_ => otherwise(format!("the Secret Service: {error}")),
}
}
impl RawStore for Vault {
fn kind(&self) -> Backend {
Backend::SecretService
}
fn contains(&self, service: &str) -> Result<bool, Error> {
let attributes = self.attributes(service)?;
self.open(Error::Unreadable, |collection| {
let items = collection
.search_items(attributes)
.map_err(said(Error::Unreadable))?;
Ok(!items.is_empty())
})
}
fn read(&self, service: &str) -> Result<Option<String>, Error> {
let attributes = self.attributes(service)?;
self.open(Error::Unreadable, |collection| {
secret_of(collection, attributes, service)
})
}
fn write(&self, _: Permit, service: &str, contents: &str) -> Result<(), Error> {
let attributes = self.attributes(service)?;
let label = self.label(service);
let back = self.open(Error::Write, |collection| {
collection
.create_item(
&label,
attributes.clone(),
contents.as_bytes(),
true,
self.content_type(),
)
.map_err(said(Error::Write))?;
secret_of(collection, attributes, service)
})?;
match back {
Some(back) if back == contents => Ok(()),
_ => Err(Error::NotDurable(format!(
"the Secret Service does not hold what was written to {service}"
))),
}
}
fn delete(&self, _: Permit, service: &str) -> Result<(), Error> {
let attributes = self.attributes(service)?;
self.open(Error::Write, |collection| {
let items = collection
.search_items(attributes)
.map_err(said(Error::Write))?;
items
.iter()
.try_for_each(Item::delete)
.map_err(said(Error::Write))
})
}
fn list(&self) -> Result<Option<Vec<String>>, Error> {
if let Items::GoKeyring { .. } = self.items {
return Ok(None);
}
self.open(Error::Unreadable, |collection| {
let items = collection
.search_items(HashMap::from([SCHEMA]))
.map_err(said(Error::Unreadable))?;
let mut names = Vec::new();
for item in &items {
let mut attributes = item.get_attributes().map_err(said(Error::Unreadable))?;
if let Some(name) = attributes
.remove(SERVICE)
.filter(|name| crate::park::is_park_name(name))
{
names.push(name);
}
}
names.sort();
names.dedup();
Ok(Some(names))
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::secret_service_testing::{Item as Held, SecretService as Started};
use std::collections::BTreeMap;
use std::path::Path;
const LOGIN: &str = r#"{"claudeAiOauth":{"refreshToken":"r"}}"#;
const AGAIN: &str = r#"{"claudeAiOauth":{"refreshToken":"s"}}"#;
fn started(scratch: &Path) -> Started {
Started::start(&scratch.join("keyring")).unwrap_or_else(|missing| panic!("{missing}"))
}
fn home(scratch: &Path, name: &str, on: &Started) -> Context {
Context::for_unit_test()
.with_pitboard_home(scratch.join(name))
.with_test_bus(on.address().to_owned())
}
fn at_the_desktop(scratch: &Path, name: &str, on: &Started) -> Context {
let home = scratch.join(name).to_string_lossy().into_owned();
let env = crate::context::Environment::on(
crate::host::Os::Linux,
[("HOME", home.as_str()), ("WAYLAND_DISPLAY", "wayland-0")],
);
Context::read(&env, "cli")
.with_pitboard_home(scratch.join(name).join(".pitboard"))
.with_test_bus(on.address().to_owned())
}
fn park(test: &str, at: i64) -> String {
let name = crate::park::service_name(test, 1_789_935_600_000 + at);
if let Some(why) = crate::provider::names::refusal(&name, &[]) {
panic!("{why}");
}
name
}
fn unlocks(service: &Started) -> usize {
service
.asked()
.iter()
.filter(|member| *member == "Unlock")
.count()
}
#[test]
fn a_park_round_trips_as_one_item_of_pitboards_schema() {
let scratch = tempfile::tempdir().expect("a scratch folder");
let service = started(scratch.path());
let ctx = home(scratch.path(), "home", &service);
assert!(answers(&ctx));
assert_eq!(
crate::store::new_home_form(&ctx),
Some(crate::state::VaultForm::SecretService)
);
let (vault, park, permit) = (Vault::of(&ctx), park("round-trip", 0), Permit::for_a_test());
assert_eq!(vault.kind(), Backend::SecretService);
assert_eq!(vault.read(&park).expect("read"), None);
assert!(!vault.contains(&park).expect("looked for"));
vault.write(permit, &park, LOGIN).expect("written");
assert_eq!(vault.read(&park).expect("read").as_deref(), Some(LOGIN));
vault.write(permit, &park, AGAIN).expect("written over");
assert_eq!(
service.items(),
vec![Held {
label: LABEL.into(),
attributes: BTreeMap::from([
("service".into(), park.clone()),
("xdg:schema".into(), "com.usepitboard.Pitboard.Park".into()),
]),
secret: AGAIN.into(),
}]
);
assert!(vault.contains(&park).expect("looked for"));
vault.delete(permit, &park).expect("deleted");
assert_eq!(vault.read(&park).expect("read"), None);
assert!(service.items().is_empty());
vault
.delete(permit, &park)
.expect("a park already gone is deleted");
}
#[test]
fn a_go_keyring_item_round_trips_as_go_keyring_keeps_one() {
let scratch = tempfile::tempdir().expect("a scratch folder");
let service = started(scratch.path());
let ctx = home(scratch.path(), "home", &service);
let (item, permit) = (Vault::go_keyring(&ctx, "antigravity"), Permit::for_a_test());
let name = "pitboard-citest-go-keyring";
assert_eq!(item.read(name).expect("read"), None);
item.write(permit, name, LOGIN).expect("written");
item.write(permit, name, AGAIN).expect("written over");
let items: Vec<Held> = service
.items()
.into_iter()
.map(|mut held| {
if let Some(schema) = held.attributes.remove("xdg:schema")
&& schema != "org.freedesktop.Secret.Generic"
{
held.attributes.insert("xdg:schema".into(), schema);
}
held
})
.collect();
assert_eq!(
items,
vec![Held {
label: format!("Password for 'antigravity' on '{name}'"),
attributes: BTreeMap::from([
("service".into(), name.into()),
("username".into(), "antigravity".into()),
]),
secret: AGAIN.into(),
}]
);
assert_eq!(item.list().expect("listed"), None);
item.delete(permit, name).expect("deleted");
assert!(service.items().is_empty());
assert!(
item.read("gemini").is_err(),
"a live login's name is refused"
);
}
#[test]
fn the_list_holds_every_park_on_the_bus_and_nothing_of_another_schema() {
let scratch = tempfile::tempdir().expect("a scratch folder");
let service = started(scratch.path());
let here = Vault::of(&home(scratch.path(), "here", &service));
let there = Vault::of(&home(scratch.path(), "there", &service));
let permit = Permit::for_a_test();
assert_eq!(here.list().expect("listed"), Some(Vec::new()));
here.write(permit, &park("listed", 1), LOGIN)
.expect("written");
there
.write(permit, &park("listed", 0), LOGIN)
.expect("written");
service.plant(
"Another program's",
&[
("xdg:schema", "org.example.Other"),
("service", &park("listed", 2)),
],
"theirs",
);
service.plant("Not a park", &[SCHEMA, (SERVICE, "pitboard-park-")], "x");
for vault in [&here, &there] {
assert_eq!(
vault.list().expect("listed"),
Some(vec![park("listed", 0), park("listed", 1)])
);
}
}
#[test]
#[should_panic(expected = "a test must never address")]
fn a_test_never_plants_a_name_a_real_login_may_be_kept_under() {
let scratch = tempfile::tempdir().expect("a scratch folder");
let nobody = Started::without_a_provider(&scratch.path().join("nobody"))
.unwrap_or_else(|missing| panic!("{missing}"));
nobody.plant(
"A real login",
&[("service", "Claude Code-credentials")],
"x",
);
}
fn refused_every_way(vault: &Vault, park: &str) {
let permit = Permit::for_a_test();
let locked = |what: &str, answer: Result<String, Error>| match answer {
Err(Error::Locked) => {}
other => panic!("{what}: {other:?}"),
};
locked("read", vault.read(park).map(|r| format!("{r:?}")));
locked("look", vault.contains(park).map(|c| c.to_string()));
locked("list", vault.list().map(|l| format!("{l:?}")));
locked(
"write",
vault.write(permit, park, AGAIN).map(|()| String::new()),
);
locked("delete", vault.delete(permit, park).map(|()| String::new()));
}
#[test]
fn a_locked_collection_is_locked_never_absent() {
let scratch = tempfile::tempdir().expect("a scratch folder");
let service = started(scratch.path());
let ctx = home(scratch.path(), "home", &service);
Vault::of(&ctx)
.write(Permit::for_a_test(), &park("locked", 0), LOGIN)
.expect("written");
service.lock();
for ctx in [ctx.clone(), ctx.clone().started_by_the_schedule()] {
refused_every_way(&Vault::of(&ctx), &park("locked", 0));
}
assert!(answers(&ctx), "a locked collection is one to park in");
}
#[test]
fn a_run_a_job_started_never_asks_to_unlock() {
let scratch = tempfile::tempdir().expect("a scratch folder");
let service = started(scratch.path());
let ctx = home(scratch.path(), "home", &service);
service.lock();
for job in [
ctx.clone().started_by_the_schedule(),
ctx.clone().started_by_the_watch_service(),
] {
refused_every_way(&Vault::of(&job), &park("job", 0));
}
let asked = service.asked();
assert!(
!asked
.iter()
.any(|member| member == "Unlock" || member == "Prompt"),
"{asked:?}"
);
}
#[test]
fn a_run_out_of_the_desktop_session_never_asks_to_unlock() {
let scratch = tempfile::tempdir().expect("a scratch folder");
let service = started(scratch.path());
service.lock();
let home = scratch.path().join("home").to_string_lossy().into_owned();
let read = |pairs: &[(&str, &str)]| {
let env = crate::context::Environment::on(
crate::host::Os::Linux,
[("HOME", home.as_str())].iter().chain(pairs).copied(),
);
Context::read(&env, "cli")
.with_pitboard_home(scratch.path().join("home/.pitboard"))
.with_test_bus(service.address().to_owned())
};
for away in [
read(&[]),
read(&[
("DISPLAY", "localhost:10.0"),
("SSH_CONNECTION", "10.0.0.2 50022 10.0.0.1 22"),
]),
read(&[("WAYLAND_DISPLAY", ""), ("DISPLAY", "")]),
] {
refused_every_way(&Vault::of(&away), &park("away", 0));
}
assert_eq!(unlocks(&service), 0, "{:?}", service.asked());
let at_the_desktop = read(&[("DISPLAY", ":0")]);
let read = Vault::of(&at_the_desktop).read(&park("away", 0));
assert!(matches!(read, Err(Error::Locked)), "{read:?}");
assert_eq!(unlocks(&service), 1, "{:?}", service.asked());
}
#[test]
fn a_prompt_dismissed_is_not_put_up_again_in_the_same_run() {
let scratch = tempfile::tempdir().expect("a scratch folder");
let service = started(scratch.path());
let ctx = at_the_desktop(scratch.path(), "home", &service);
service.lock();
refused_every_way(&Vault::of(&ctx), &park("dismissed", 0));
refused_every_way(&Vault::of(&ctx.clone()), &park("dismissed", 1));
assert_eq!(unlocks(&service), 1, "{:?}", service.asked());
let another_run = at_the_desktop(scratch.path(), "home", &service);
let read = Vault::of(&another_run).read(&park("dismissed", 0));
assert!(matches!(read, Err(Error::Locked)), "{read:?}");
assert_eq!(unlocks(&service), 2, "{:?}", service.asked());
}
#[test]
fn a_prompt_nobody_can_answer_is_refused_within_seconds() {
let scratch = tempfile::tempdir().expect("a scratch folder");
let service = started(scratch.path());
let vault = Vault::of(&at_the_desktop(scratch.path(), "home", &service));
service.lock();
let asking = std::time::Instant::now();
let read = vault.read(&park("nobody", 0));
let took = asking.elapsed();
assert!(matches!(read, Err(Error::Locked)), "{read:?}");
assert!(took < std::time::Duration::from_secs(5), "{took:?}");
let asked = service.asked();
assert!(
asked.iter().any(|member| member == "Unlock")
&& asked.iter().any(|member| member == "Prompt"),
"a person's run asks: {asked:?}"
);
}
#[test]
fn the_keyring_is_named_for_what_owns_the_secret_service() {
let scratch = tempfile::tempdir().expect("a scratch folder");
let gnome = started(scratch.path());
let kde = Started::ksecretd(&scratch.path().join("kde"))
.unwrap_or_else(|missing| panic!("{missing}"));
let nobody = Started::without_a_provider(&scratch.path().join("nobody"))
.unwrap_or_else(|missing| panic!("{missing}"));
assert_eq!(
keyring(&home(scratch.path(), "gnome", &gnome)),
Keyring::Login
);
let ctx = home(scratch.path(), "kde", &kde);
assert_eq!(keyring(&ctx), Keyring::KWallet);
assert!(answers(&ctx), "a closed wallet is one to park in");
assert_eq!(
keyring(&home(scratch.path(), "nobody", &nobody)),
Keyring::Login
);
let without_a_bus =
Context::for_unit_test().with_pitboard_home(scratch.path().join("bare"));
assert_eq!(keyring(&without_a_bus), Keyring::Login);
}
#[test]
fn no_secret_service_on_the_bus_is_locked_never_absent() {
let scratch = tempfile::tempdir().expect("a scratch folder");
let nobody = Started::without_a_provider(&scratch.path().join("nobody"))
.unwrap_or_else(|missing| panic!("{missing}"));
let mut stopped = started(scratch.path());
let ctx = home(scratch.path(), "home", &stopped);
Vault::of(&ctx)
.write(Permit::for_a_test(), &park("no-provider", 0), LOGIN)
.expect("written");
stopped.stop();
let without_a_bus =
Context::for_unit_test().with_pitboard_home(scratch.path().join("bare"));
for ctx in [home(scratch.path(), "nobody", &nobody), ctx, without_a_bus] {
refused_every_way(&Vault::of(&ctx), &park("no-provider", 0));
assert!(!answers(&ctx));
assert_eq!(
crate::store::new_home_form(&ctx),
Some(crate::state::VaultForm::Files)
);
}
}
}