use std::io;
use std::path::PathBuf;
use std::time::Duration;
use zeroize::Zeroizing;
const WAIT: Duration = Duration::from_secs(60);
enum Backend {
None,
Os,
Test(PathBuf),
}
fn backend() -> Backend {
let value = std::env::var("TETER_KEYRING").unwrap_or_default();
if value.is_empty() {
return Backend::Os;
}
if value == "file" || value == "off" {
return Backend::None;
}
if cfg!(debug_assertions)
&& let Some(path) = value.strip_prefix("test:")
{
return Backend::Test(PathBuf::from(path));
}
static WARNED: std::sync::Once = std::sync::Once::new();
WARNED.call_once(|| {
eprintln!("teter: TETER_KEYRING={value:?} is not file or off: the keys stay in the file");
});
Backend::None
}
fn kept_backend() -> Backend {
match backend() {
Backend::None => Backend::Os,
other @ (Backend::Os | Backend::Test(_)) => other,
}
}
pub(crate) fn wanted() -> bool {
!matches!(backend(), Backend::None)
}
pub(crate) async fn put(key: &str, secret: &[u8]) -> io::Result<()> {
match backend() {
Backend::None => Err(io::Error::new(
io::ErrorKind::Unsupported,
"TETER_KEYRING=file",
)),
Backend::Os => within(os::put(key, secret)).await,
Backend::Test(path) => test::put(&path, key, secret),
}
}
pub(crate) async fn get(key: &str) -> io::Result<Option<Zeroizing<Vec<u8>>>> {
match kept_backend() {
Backend::None => Err(io::Error::new(
io::ErrorKind::Unsupported,
"TETER_KEYRING=file",
)),
Backend::Os => within(os::get(key)).await,
Backend::Test(path) => test::get(&path, key),
}
}
pub(crate) async fn remove(key: &str) -> io::Result<()> {
match kept_backend() {
Backend::None => Ok(()),
Backend::Os => within(os::remove(key)).await,
Backend::Test(path) => test::remove(&path, key),
}
}
async fn within<T>(work: impl Future<Output = io::Result<T>>) -> io::Result<T> {
tokio::time::timeout(WAIT, work)
.await
.map_err(|_elapsed| io::Error::new(io::ErrorKind::TimedOut, "the keyring did not answer"))?
}
#[cfg(target_os = "linux")]
mod os {
use std::collections::HashMap;
use std::io;
use secret_service::{EncryptionType, SecretService};
use zeroize::Zeroizing;
fn failed(e: secret_service::Error) -> io::Error {
io::Error::other(format!("the Secret Service: {e}"))
}
fn attributes(key: &str) -> HashMap<&str, &str> {
HashMap::from([("application", "teter"), ("teter-account", key)])
}
pub(super) async fn put(key: &str, secret: &[u8]) -> io::Result<()> {
let service = SecretService::connect(EncryptionType::Dh)
.await
.map_err(failed)?;
let collection = service.get_default_collection().await.map_err(failed)?;
collection.ensure_unlocked().await.map_err(failed)?;
collection
.create_item(
&format!("teter account ({key})"),
attributes(key),
secret,
true,
"application/octet-stream",
)
.await
.map_err(failed)?;
Ok(())
}
pub(super) async fn get(key: &str) -> io::Result<Option<Zeroizing<Vec<u8>>>> {
let service = SecretService::connect(EncryptionType::Dh)
.await
.map_err(failed)?;
let found = service
.search_items(attributes(key))
.await
.map_err(failed)?;
let Some(item) = found.unlocked.first().or(found.locked.first()) else {
return Ok(None);
};
item.ensure_unlocked().await.map_err(failed)?;
Ok(Some(Zeroizing::new(
item.get_secret().await.map_err(failed)?,
)))
}
pub(super) async fn remove(key: &str) -> io::Result<()> {
let service = SecretService::connect(EncryptionType::Dh)
.await
.map_err(failed)?;
let found = service
.search_items(attributes(key))
.await
.map_err(failed)?;
for item in found.unlocked.iter().chain(&found.locked) {
item.delete().await.map_err(failed)?;
}
Ok(())
}
}
#[cfg(target_os = "macos")]
mod os {
use std::io;
use zeroize::Zeroizing;
const NOT_FOUND: i32 = -25300;
const SERVICE: &str = "teter";
fn failed(e: security_framework::base::Error) -> io::Error {
io::Error::other(format!("the Keychain: {e}"))
}
async fn blocking<T: Send + 'static>(
work: impl FnOnce() -> io::Result<T> + Send + 'static,
) -> io::Result<T> {
let (done, result) = tokio::sync::oneshot::channel();
#[expect(
clippy::disallowed_methods,
reason = "detached on purpose: a scoped thread would hold the caller's timeout and the exit"
)]
std::thread::spawn(move || drop(done.send(work())));
result
.await
.map_err(|_gone| io::Error::other("the Keychain's thread ended"))?
}
pub(super) async fn put(key: &str, secret: &[u8]) -> io::Result<()> {
let (key, secret) = (key.to_owned(), Zeroizing::new(secret.to_vec()));
blocking(move || {
security_framework::passwords::set_generic_password(SERVICE, &key, &secret)
.map_err(failed)
})
.await
}
pub(super) async fn get(key: &str) -> io::Result<Option<Zeroizing<Vec<u8>>>> {
let key = key.to_owned();
blocking(
move || match security_framework::passwords::get_generic_password(SERVICE, &key) {
Ok(secret) => Ok(Some(Zeroizing::new(secret))),
Err(e) if e.code() == NOT_FOUND => Ok(None),
Err(e) => Err(failed(e)),
},
)
.await
}
pub(super) async fn remove(key: &str) -> io::Result<()> {
let key = key.to_owned();
blocking(move || {
match security_framework::passwords::delete_generic_password(SERVICE, &key) {
Err(e) if e.code() != NOT_FOUND => Err(failed(e)),
_ => Ok(()),
}
})
.await
}
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
mod os {
use std::io;
use zeroize::Zeroizing;
fn none() -> io::Error {
io::Error::new(io::ErrorKind::Unsupported, "no keyring on this system")
}
pub(super) async fn put(_key: &str, _secret: &[u8]) -> io::Result<()> {
Err(none())
}
pub(super) async fn get(_key: &str) -> io::Result<Option<Zeroizing<Vec<u8>>>> {
Err(none())
}
pub(super) async fn remove(_key: &str) -> io::Result<()> {
Err(none())
}
}
mod test {
use std::collections::BTreeMap;
use std::io::{self, Write as _};
use std::os::unix::fs::OpenOptionsExt as _;
use std::path::Path;
use zeroize::Zeroizing;
fn read(path: &Path) -> io::Result<BTreeMap<String, String>> {
match std::fs::read(path) {
Ok(bytes) => serde_json::from_slice(&Zeroizing::new(bytes)).map_err(io::Error::other),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(BTreeMap::new()),
Err(e) => Err(e),
}
}
fn write(path: &Path, secrets: &BTreeMap<String, String>) -> io::Result<()> {
let temporary = path.with_extension(format!("new.{}", std::process::id()));
let mut file = std::fs::OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.mode(0o600)
.open(&temporary)?;
file.write_all(&Zeroizing::new(
serde_json::to_vec(secrets).map_err(io::Error::other)?,
))?;
std::fs::rename(&temporary, path)
}
pub(super) fn put(path: &Path, key: &str, secret: &[u8]) -> io::Result<()> {
let mut secrets = read(path)?;
secrets.insert(key.to_owned(), teter_common::account::hex(secret));
write(path, &secrets)
}
pub(super) fn get(path: &Path, key: &str) -> io::Result<Option<Zeroizing<Vec<u8>>>> {
Ok(read(path)?
.get(key)
.and_then(|hex| teter_common::account::unhex(hex))
.map(Zeroizing::new))
}
pub(super) fn remove(path: &Path, key: &str) -> io::Result<()> {
let mut secrets = read(path)?;
if secrets.remove(key).is_some() {
write(path, &secrets)?;
}
Ok(())
}
}