rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The credential stores a probe reads a server's secrets and OAuth tokens
//! through, so testing a server never changes what a session would find:
//! [`UnsavedFirst`] for `env_from_secret` and `headers_from_secret` values,
//! [`ScratchTokens`] for the OAuth tokens of a draft that logs in elsewhere.

use std::{
    collections::{BTreeMap, HashMap},
    sync::{Arc, Mutex, PoisonError},
};

use rho_providers::credentials::{CredentialError, CredentialResult, CredentialStore};

use super::{
    probe_redaction::{Origin, Served},
    secrets::account_name,
};

/// Server `identity`'s secrets as a probe reads them: values a settings
/// form holds and has not stored, by name, before those `saved` holds, if
/// any. Writes are refused. Each value it hands out is kept in `served`, so
/// the probe can keep it out of what it returns. Not `Debug`: it holds
/// secret values.
pub(super) struct UnsavedFirst {
    accounts: BTreeMap<String, String>,
    saved: Option<Arc<dyn CredentialStore>>,
    served: Served,
}

impl UnsavedFirst {
    pub(super) fn new(
        identity: &str,
        unsaved: BTreeMap<String, String>,
        saved: Option<Arc<dyn CredentialStore>>,
        served: Served,
    ) -> Self {
        Self {
            accounts: unsaved
                .into_iter()
                .map(|(name, value)| (account_name(identity, &name), value))
                .collect(),
            saved,
            served,
        }
    }

    fn read(
        &self,
        account: &str,
        saved: impl FnOnce(&dyn CredentialStore) -> CredentialResult<Option<String>>,
    ) -> CredentialResult<Option<String>> {
        let value = match (self.accounts.get(account), &self.saved) {
            (Some(value), _) => Some(value.clone()),
            (None, Some(store)) => saved(store.as_ref())?,
            (None, None) => None,
        };
        if let Some(value) = &value {
            self.served.hide(value, Origin::Secret);
        }
        Ok(value)
    }
}

impl CredentialStore for UnsavedFirst {
    fn get_secret(&self, account: &str) -> CredentialResult<Option<String>> {
        self.read(account, |store| store.get_secret(account))
    }

    fn get_secret_fresh(&self, account: &str) -> CredentialResult<Option<String>> {
        self.read(account, |store| store.get_secret_fresh(account))
    }

    fn environment_variable(&self, name: &str) -> Option<String> {
        // Nothing on a server's start reads one through this store; forward
        // it as a decorator must, and answer as the trait's default does
        // without a store behind.
        match &self.saved {
            Some(store) => store.environment_variable(name),
            None => std::env::var(name).ok(),
        }
    }

    fn set_secret(&self, _account: &str, _secret: &str) -> CredentialResult<()> {
        Err(refused())
    }

    fn delete_secret(&self, _account: &str) -> CredentialResult<bool> {
        Err(refused())
    }
}

fn refused() -> CredentialError {
    CredentialError::StoreUnavailable("an MCP probe changes no stored secret".to_owned())
}

/// An empty token store whose writes last only as long as it does: a
/// draft that logs in somewhere its saved entry does not starts without the
/// saved tokens, so they are neither sent to its address nor cleared or
/// replaced by its start. `store` answers only for environment variables.
pub(super) struct ScratchTokens {
    store: Arc<dyn CredentialStore>,
    written: Mutex<HashMap<String, String>>,
}

impl ScratchTokens {
    pub(super) fn new(store: Arc<dyn CredentialStore>) -> Self {
        Self {
            store,
            written: Mutex::new(HashMap::new()),
        }
    }

    fn written(&self) -> std::sync::MutexGuard<'_, HashMap<String, String>> {
        self.written.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

impl CredentialStore for ScratchTokens {
    fn get_secret(&self, account: &str) -> CredentialResult<Option<String>> {
        Ok(self.written().get(account).cloned())
    }

    fn get_secret_fresh(&self, account: &str) -> CredentialResult<Option<String>> {
        self.get_secret(account)
    }

    fn environment_variable(&self, name: &str) -> Option<String> {
        self.store.environment_variable(name)
    }

    fn set_secret(&self, account: &str, secret: &str) -> CredentialResult<()> {
        self.written().insert(account.to_owned(), secret.to_owned());
        Ok(())
    }

    fn delete_secret(&self, account: &str) -> CredentialResult<bool> {
        Ok(self.written().remove(account).is_some())
    }
}

#[cfg(test)]
#[path = "probe_stores_tests.rs"]
mod tests;