vtcode-auth 0.188.0

Authentication and OAuth flows shared across VT Code
Documentation
//! AES-256-GCM credential encryption and key derivation.
//!
//! Pure functions — no side effects, no IO. Takes bytes, returns bytes.

use anyhow::{Context, Result, anyhow};
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use ring::aead::{self, Aad, LessSafeKey, NONCE_LEN, Nonce, UnboundKey};
use ring::rand::{SecureRandom, SystemRandom};

const ENCRYPTED_CREDENTIAL_VERSION: u8 = 2;
const LEGACY_ENCRYPTED_CREDENTIAL_VERSION: u8 = 1;

#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub(crate) struct EncryptedCredential {
    nonce: String,
    ciphertext: String,
    version: u8,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    salt: Option<String>,
}

impl EncryptedCredential {
    pub(crate) fn requires_keyring_key(&self) -> bool {
        self.version == ENCRYPTED_CREDENTIAL_VERSION
    }

    pub(crate) fn is_legacy(&self) -> bool {
        self.version == LEGACY_ENCRYPTED_CREDENTIAL_VERSION
    }
}

/// Encrypt a plaintext credential string using a key held by the OS keyring.
pub(crate) fn encrypt(value: &str, key_bytes: &[u8; 32]) -> Result<EncryptedCredential> {
    let rng = SystemRandom::new();
    let key = aead_key(key_bytes)?;
    let mut nonce_bytes = [0_u8; NONCE_LEN];
    rng.fill(&mut nonce_bytes)
        .map_err(|_| anyhow!("failed to generate credential nonce"))?;

    let mut ciphertext = value.as_bytes().to_vec();
    key.seal_in_place_append_tag(Nonce::assume_unique_for_key(nonce_bytes), Aad::empty(), &mut ciphertext)
        .map_err(|_| anyhow!("failed to encrypt credential"))?;

    Ok(EncryptedCredential {
        nonce: STANDARD.encode(nonce_bytes),
        ciphertext: STANDARD.encode(ciphertext),
        version: ENCRYPTED_CREDENTIAL_VERSION,
        salt: None,
    })
}

/// Decrypt an [`EncryptedCredential`] back into the plaintext string.
pub(crate) fn decrypt(encrypted: &EncryptedCredential, key_bytes: Option<&[u8; 32]>) -> Result<String> {
    let nonce_bytes = STANDARD.decode(&encrypted.nonce).context("failed to decode credential nonce")?;
    let nonce_array: [u8; NONCE_LEN] =
        nonce_bytes.try_into().map_err(|_| anyhow!("invalid credential nonce length"))?;
    let mut ciphertext = STANDARD
        .decode(&encrypted.ciphertext)
        .context("failed to decode credential ciphertext")?;

    let key = match encrypted.version {
        LEGACY_ENCRYPTED_CREDENTIAL_VERSION => derive_legacy_key(encrypted.salt.as_deref())?,
        ENCRYPTED_CREDENTIAL_VERSION => {
            let key_bytes = key_bytes.ok_or_else(|| anyhow!("credential encryption key is missing"))?;
            aead_key(key_bytes)?
        }
        _ => return Err(anyhow!("unsupported encrypted credential format")),
    };
    let plaintext = key
        .open_in_place(Nonce::assume_unique_for_key(nonce_array), Aad::empty(), &mut ciphertext)
        .map_err(|_| anyhow!("failed to decrypt credential"))?;

    String::from_utf8(plaintext.to_vec()).context("failed to parse decrypted credential")
}

fn aead_key(key_bytes: &[u8; 32]) -> Result<LessSafeKey> {
    let unbound =
        UnboundKey::new(&aead::AES_256_GCM, key_bytes).map_err(|_| anyhow!("invalid credential encryption key"))?;
    Ok(LessSafeKey::new(unbound))
}

/// Derive the legacy v1 key so existing credential files remain readable.
fn derive_legacy_key(salt: Option<&str>) -> Result<LessSafeKey> {
    use ring::digest::SHA256;
    use ring::digest::digest;

    let mut key_material = Vec::new();
    if let Ok(hostname) = hostname::get() {
        key_material.extend_from_slice(hostname.as_encoded_bytes());
    }

    #[cfg(unix)]
    {
        key_material.extend_from_slice(&nix::unistd::getuid().as_raw().to_le_bytes());
    }
    #[cfg(not(unix))]
    {
        if let Ok(user) = std::env::var("USER").or_else(|_| std::env::var("USERNAME")) {
            key_material.extend_from_slice(user.as_bytes());
        }
    }

    key_material.extend_from_slice(b"vtcode-credentials-v1");

    if let Some(salt) = salt {
        key_material.extend_from_slice(salt.as_bytes());
    }

    let hash = digest(&SHA256, &key_material);
    let key_bytes: &[u8; 32] = hash
        .as_ref()
        .get(..32)
        .context("credential encryption key was too short")?
        .try_into()
        .context("credential encryption key had an invalid length")?;
    aead_key(key_bytes)
}

#[cfg(test)]
pub(crate) fn encrypt_legacy_for_tests(value: &str) -> Result<EncryptedCredential> {
    let rng = SystemRandom::new();
    let mut salt_bytes = [0_u8; 16];
    rng.fill(&mut salt_bytes)
        .map_err(|_| anyhow!("failed to generate credential salt"))?;
    let salt = STANDARD.encode(salt_bytes);

    let mut key_material = Vec::new();
    if let Ok(hostname) = hostname::get() {
        key_material.extend_from_slice(hostname.as_encoded_bytes());
    }
    #[cfg(unix)]
    key_material.extend_from_slice(&nix::unistd::getuid().as_raw().to_le_bytes());
    #[cfg(not(unix))]
    if let Ok(user) = std::env::var("USER").or_else(|_| std::env::var("USERNAME")) {
        key_material.extend_from_slice(user.as_bytes());
    }
    key_material.extend_from_slice(b"vtcode-credentials-v1");
    key_material.extend_from_slice(salt.as_bytes());
    let key_digest = ring::digest::digest(&ring::digest::SHA256, &key_material);
    let key_bytes: &[u8; 32] = key_digest
        .as_ref()
        .try_into()
        .map_err(|_| anyhow!("legacy credential fixture key had an invalid length"))?;
    let unbound =
        UnboundKey::new(&aead::AES_256_GCM, key_bytes).map_err(|_| anyhow!("invalid legacy credential fixture key"))?;
    let key = LessSafeKey::new(unbound);
    let mut nonce_bytes = [0_u8; NONCE_LEN];
    rng.fill(&mut nonce_bytes)
        .map_err(|_| anyhow!("failed to generate credential nonce"))?;
    let mut ciphertext = value.as_bytes().to_vec();
    key.seal_in_place_append_tag(Nonce::assume_unique_for_key(nonce_bytes), Aad::empty(), &mut ciphertext)
        .map_err(|_| anyhow!("failed to encrypt credential"))?;

    Ok(EncryptedCredential {
        nonce: STANDARD.encode(nonce_bytes),
        ciphertext: STANDARD.encode(ciphertext),
        version: LEGACY_ENCRYPTED_CREDENTIAL_VERSION,
        salt: Some(salt),
    })
}

#[cfg(test)]
mod tests {
    use super::{decrypt, encrypt, encrypt_legacy_for_tests};

    #[test]
    fn v2_credential_requires_the_matching_keyring_key() {
        let key = [0xA5; 32];
        let encrypted = encrypt("test credential", &key).expect("encrypt");

        assert_eq!(decrypt(&encrypted, Some(&key)).expect("decrypt"), "test credential");
        assert!(decrypt(&encrypted, Some(&[0x5A; 32])).is_err());
        assert!(decrypt(&encrypted, None).is_err());
    }

    #[test]
    fn legacy_v1_credentials_remain_decryptable_without_a_keyring_key() {
        let encrypted = encrypt_legacy_for_tests("legacy credential").expect("encrypt legacy");

        assert_eq!(decrypt(&encrypted, None).expect("decrypt legacy"), "legacy credential");
    }
}