vtcode-auth 0.188.0

Authentication and OAuth flows shared across VT Code
Documentation
//! OS keyring integration — entry creation, liveness probe, and disable detection.
//!
//! All keyring access goes through [`entry`] so that [`is_disabled`] and
//! [`ensure_native_store`] are always applied consistently.

use anyhow::{Context, Result, anyhow};
use base64::Engine;
use base64::engine::general_purpose::STANDARD;

const FILE_ENCRYPTION_KEY_SERVICE: &str = "vtcode";
const FILE_ENCRYPTION_KEY_USER: &str = "_credential_file_encryption_key_v2";

pub(crate) struct FileEncryptionKey {
    pub(crate) bytes: [u8; 32],
    pub(crate) persistent: bool,
}

pub(crate) fn file_encryption_key(create_if_missing: bool) -> Result<Option<FileEncryptionKey>> {
    if cfg!(test) {
        return ephemeral_file_encryption_key(true).map(Some);
    }
    if cfg!(debug_assertions) && is_disabled() {
        return ephemeral_file_encryption_key(false).map(Some);
    }

    use ring::rand::{SecureRandom, SystemRandom};

    let entry = entry(FILE_ENCRYPTION_KEY_SERVICE, FILE_ENCRYPTION_KEY_USER)
        .context("failed to access OS keyring for credential-file encryption key")?;
    if let Some(key) = read_file_encryption_key(&entry)? {
        return Ok(Some(FileEncryptionKey { bytes: key, persistent: true }));
    }
    if !create_if_missing {
        return Ok(None);
    }

    let _lock = lock_file_encryption_key()?;
    if let Some(key) = read_file_encryption_key(&entry)? {
        return Ok(Some(FileEncryptionKey { bytes: key, persistent: true }));
    }

    let mut key = [0_u8; 32];
    SystemRandom::new()
        .fill(&mut key)
        .map_err(|_| anyhow!("failed to generate credential-file encryption key"))?;
    entry
        .set_password(&STANDARD.encode(key))
        .context("failed to store credential-file encryption key in OS keyring")?;
    let key =
        read_file_encryption_key(&entry)?.ok_or_else(|| anyhow!("credential-file encryption key was not persisted"))?;
    Ok(Some(FileEncryptionKey { bytes: key, persistent: true }))
}

fn ephemeral_file_encryption_key(persistent: bool) -> Result<FileEncryptionKey> {
    use ring::rand::{SecureRandom, SystemRandom};
    use std::sync::OnceLock;

    static KEY: OnceLock<std::result::Result<[u8; 32], &'static str>> = OnceLock::new();
    let result = KEY.get_or_init(|| {
        let mut key = [0_u8; 32];
        SystemRandom::new()
            .fill(&mut key)
            .map(|()| key)
            .map_err(|_| "failed to generate temporary credential-file encryption key")
    });
    match result {
        Ok(key) => Ok(FileEncryptionKey { bytes: *key, persistent }),
        Err(message) => Err(anyhow!(*message)),
    }
}

fn read_file_encryption_key(entry: &keyring_core::Entry) -> Result<Option<[u8; 32]>> {
    let encoded = match entry.get_password() {
        Ok(encoded) => encoded,
        Err(keyring_core::Error::NoEntry) => return Ok(None),
        Err(error) => return Err(anyhow!("failed to read credential-file encryption key: {error}")),
    };
    let key = STANDARD
        .decode(encoded)
        .context("credential-file encryption key in OS keyring is not valid base64")?;
    let key: [u8; 32] = key
        .try_into()
        .map_err(|_| anyhow!("credential-file encryption key in OS keyring has an invalid length"))?;
    Ok(Some(key))
}

fn lock_file_encryption_key() -> Result<std::fs::File> {
    use fs2::FileExt;
    use std::fs::OpenOptions;

    let lock_path = crate::storage_paths::auth_storage_dir()?.join(".credential-file-key.lock");
    let file = OpenOptions::new()
        .create(true)
        .read(true)
        .write(true)
        .truncate(false)
        .open(lock_path)
        .context("failed to open credential-file encryption-key lock")?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        file.set_permissions(std::fs::Permissions::from_mode(0o600))
            .context("failed to restrict credential-file encryption-key lock permissions")?;
    }
    file.lock_exclusive()
        .context("failed to acquire credential-file encryption-key lock")?;
    Ok(file)
}

/// Check if the OS keyring is functional by attempting a test operation.
///
/// On macOS, this skips the write/read test — every Keychain operation triggers
/// an authorization popup. Instead, it just checks that the keyring crate can
/// create an Entry handle (which does not touch the keychain yet). The first
/// real `set_password`/`get_password` call will prompt the user once per binary,
/// which is acceptable since this check is only reached when the user has
/// explicitly opted into keyring via `Auto` or `Keyring` mode.
///
/// On other platforms, this creates a test entry, verifies it can be written
/// and read, then deletes it. This is more reliable than just checking if
/// Entry creation succeeds.
///
/// The result is cached after the first call so that repeated checks (e.g. from
/// `Auto` mode resolution) do not trigger additional OS keyring round trips.
pub(crate) fn is_functional() -> bool {
    use std::sync::OnceLock;

    static FUNCTIONAL: OnceLock<bool> = OnceLock::new();

    *FUNCTIONAL.get_or_init(|| {
        #[cfg(target_os = "macos")]
        {
            keyring_core::Entry::new("vtcode", "_probe").is_ok()
        }

        #[cfg(not(target_os = "macos"))]
        {
            let test_user = format!("test_{}", std::process::id());
            let entry = match entry("vtcode", &test_user) {
                Ok(e) => e,
                Err(_) => return false,
            };

            if entry.set_password("test").is_err() {
                return false;
            }

            let functional = entry.get_password().is_ok();

            // Best-effort cleanup; the test user is unique per process, so a leftover is harmless.
            let _cleanup = entry.delete_credential();

            functional
        }
    })
}

/// Whether `VTCODE_DISABLE_KEYRING` explicitly re-enables the keyring.
///
/// The empty value and the canonical falsy values (`0`, `false`, `no`, `off`)
/// opt back in; any other value — including unrecognized ones — leaves the
/// keyring disabled. Delegating the falsy set keeps this in step with the
/// canonical env parser instead of repeating a literal list.
fn keyring_explicitly_enabled(value: &str) -> bool {
    value.trim().is_empty() || vtcode_commons::utils::parse_bool_env_value(value) == Some(false)
}

/// Returns `true` when access to the OS keyring should be skipped.
///
/// The native keyring (e.g. macOS Keychain) prompts the user for authorization
/// the first time each distinct binary touches it. Debug and test binaries are
/// recompiled with a new code signature on every build, so they would prompt on
/// every run. To avoid this, keyring access is disabled in debug builds, during
/// tests, and whenever the `VTCODE_DISABLE_KEYRING` or `CI` environment
/// variables are set. Debug builds use a process-local file key in this case;
/// production file storage still requires a persistent OS keyring key.
///
/// The result is cached after the first call so that repeated checks (e.g. from
/// [`entry`]) do not re-read environment variables on every invocation.
fn is_disabled() -> bool {
    use std::sync::OnceLock;

    static DISABLED: OnceLock<bool> = OnceLock::new();

    *DISABLED.get_or_init(|| {
        if cfg!(debug_assertions) {
            if let Ok(value) = std::env::var("VTCODE_DISABLE_KEYRING") {
                if keyring_explicitly_enabled(&value) {
                    return false;
                }
            }
            return true;
        }

        if cfg!(test) {
            return true;
        }

        if let Ok(value) = std::env::var("VTCODE_DISABLE_KEYRING") {
            return !keyring_explicitly_enabled(&value);
        }

        std::env::var_os("CI").is_some()
    })
}

/// Create a keyring entry for the given service and user, respecting the
/// disabled check and ensuring a native store is configured.
pub(crate) fn entry(service: &str, user: &str) -> keyring_core::Result<keyring_core::Entry> {
    if is_disabled() {
        return Err(keyring_core::Error::NotSupportedByStore(
            "VT Code keyring access is disabled (test run or VTCODE_DISABLE_KEYRING/CI set)".to_string(),
        ));
    }

    if keyring_core::get_default_store().is_none() {
        ensure_native_store()?;
    }

    keyring_core::Entry::new(service, user)
}

fn ensure_native_store() -> keyring_core::Result<()> {
    if keyring_core::get_default_store().is_some() {
        return Ok(());
    }

    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
    let store = dbus_secret_service_keyring_store::Store::new_with_configuration(&std::collections::HashMap::new())?;

    #[cfg(target_os = "macos")]
    let store = apple_native_keyring_store::keychain::Store::new_with_configuration(&std::collections::HashMap::new())?;

    #[cfg(target_os = "windows")]
    let store = windows_native_keyring_store::Store::new_with_configuration(&std::collections::HashMap::new())?;

    #[cfg(not(any(
        target_os = "linux",
        target_os = "freebsd",
        target_os = "macos",
        target_os = "windows"
    )))]
    {
        return Err(keyring_core::Error::NotSupportedByStore(
            "VT Code does not have a native keyring store configured for this platform".to_string(),
        ));
    }

    keyring_core::set_default_store(store);
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn keyring_explicit_enable_accepts_the_canonical_falsy_set() {
        for value in ["", "   ", "0", "false", "NO", " off ", "FALSE"] {
            assert!(keyring_explicitly_enabled(value), "{value:?} should re-enable the keyring");
        }

        // Unrecognized values (including `debug`, which `env_flag_enabled` treats
        // as truthy) do not opt in.
        for value in ["1", "true", "yes", "on", "debug", "banana"] {
            assert!(!keyring_explicitly_enabled(value), "{value:?} should leave the keyring disabled");
        }
    }
}