teter 26.11.7

teter: persistent terminal sessions on your machines, reachable through a relay that cannot read them
//! The account's secrets (its login token and unlocked private keys) in the
//! OS keyring (#126): the Secret Service on Linux (over zbus, pure Rust, so the
//! release binary stays static), the Keychain on macOS. `account.json` keeps
//! the rest; when no keyring answers, the secrets stay in it (mode 0600) and
//! the caller says so.
//!
//! `TETER_KEYRING` picks: unset, the OS keyring; `file` (or `off`), none for
//! new secrets, which stay in `account.json` as before #126 (a device whose
//! file says its secrets are in the OS keyring still reads and removes them
//! there); in a debug build, `test:<path>`, a stand-in kept in the file at
//! `<path>`, for tests that must not touch the user's keyring (cargo's `[env]`
//! sets `file` for every test run, `.cargo/config.toml`). Any other value
//! counts as `file`, said once.

use std::io;
use std::path::PathBuf;
use std::time::Duration;

use zeroize::Zeroizing;

/// How long a keyring may take, an unlock prompt included, before the file
/// is used instead.
const WAIT: Duration = Duration::from_secs(60);

/// Where the secrets go.
enum Backend {
    /// No keyring: the secrets stay in `account.json`.
    None,
    /// The OS keyring.
    Os,
    /// The tests' stand-in, a JSON file of hex secrets by key.
    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;
    }
    // The stand-in only in a debug build (the tests'): a release never
    // writes the keys where an environment variable says.
    if cfg!(debug_assertions)
        && let Some(path) = value.strip_prefix("test:")
    {
        return Backend::Test(PathBuf::from(path));
    }
    // A value it does not know keeps the keys out of the keyring, said once.
    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
}

/// Where secrets already kept go: with `TETER_KEYRING=file`, a device whose
/// secrets went to the OS keyring before still finds (and removes) them.
fn kept_backend() -> Backend {
    match backend() {
        Backend::None => Backend::Os,
        other @ (Backend::Os | Backend::Test(_)) => other,
    }
}

/// Whether a keyring is to be tried at all.
pub(crate) fn wanted() -> bool {
    !matches!(backend(), Backend::None)
}

/// Keeps `secret` under `key`, replacing what was there.
///
/// # Errors
///
/// No keyring, or one that refused or did not answer in time.
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),
    }
}

/// The secret under `key`, `None` when there is none.
///
/// # Errors
///
/// No keyring, or one that refused or did not answer in time.
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),
    }
}

/// Removes the secret under `key`, if any.
///
/// # Errors
///
/// No keyring, or one that refused or did not answer in time.
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),
    }
}

/// `work`, or a timeout after [`WAIT`].
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;

    /// The Keychain's "item not found".
    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}"))
    }

    /// `work` on a detached thread of its own: the Keychain's calls block (an
    /// unlock prompt, say), and the caller's timeout must still end the wait,
    /// and the process exit (a runtime's blocking task would hold it).
    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())
    }
}

/// The tests' stand-in keyring: a JSON object of hex secrets by key, in a
/// file closed to others.
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(())
    }
}