use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use ring::aead::{self, Aad, LessSafeKey, Nonce, UnboundKey, CHACHA20_POLY1305};
use ring::rand::{SecureRandom, SystemRandom};
use super::Preset;
pub const SERVICE: &str = "BigText AI";
pub const ENV_ANY: &str = "BIGTEXT_AI_KEY";
pub fn from_env(p: &Preset) -> Option<(String, &'static str)> {
[p.env, ENV_ANY]
.into_iter()
.filter(|v| !v.is_empty())
.find_map(|v| {
let k = std::env::var(v).ok()?;
let k = k.trim();
(!k.is_empty()).then(|| (k.to_string(), v))
})
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum KeyError {
NeedPassphrase,
WrongPassphrase,
Other(String),
}
impl std::fmt::Display for KeyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
KeyError::NeedPassphrase => f.write_str("The keys are locked with a passphrase."),
KeyError::WrongPassphrase => f.write_str("The passphrase is not right."),
KeyError::Other(e) => f.write_str(e),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Kind {
Keychain,
File(PathBuf),
}
#[derive(Clone, Debug)]
pub struct KeyStore {
pub kind: Kind,
pub passphrase: Option<String>,
}
pub fn file_in(dir: &Path) -> PathBuf {
dir.join("ai-keys.dat")
}
impl KeyStore {
pub fn for_this_copy() -> KeyStore {
let kind = match crate::settings_file::portable_dir() {
Some(d) => Kind::File(file_in(&d)),
None => Kind::Keychain,
};
KeyStore {
kind,
passphrase: None,
}
}
fn fallback() -> Option<PathBuf> {
Some(file_in(crate::settings_file::state_file()?.parent()?))
}
pub fn get(&self, account: &str) -> Result<Option<String>, KeyError> {
match &self.kind {
Kind::File(p) => FileKeys::read(p, self.passphrase.as_deref()).map(|f| f.get(account)),
Kind::Keychain => match os::get(account) {
Ok(Some(k)) => Ok(Some(k)),
r => match Self::fallback().filter(|p| p.exists()) {
Some(p) => FileKeys::read(&p, self.passphrase.as_deref())
.map(|f| f.get(account))
.or(r.map_err(KeyError::Other)),
None => r.map_err(KeyError::Other),
},
},
}
}
pub fn set(&self, account: &str, key: &str) -> Result<Kind, KeyError> {
let key = key.trim();
match &self.kind {
Kind::File(p) => {
let mut f = FileKeys::read(p, self.passphrase.as_deref())?;
f.keys.insert(account.to_string(), key.to_string());
f.write(p)?;
Ok(self.kind.clone())
}
Kind::Keychain => match os::set(account, key) {
Ok(()) => Ok(Kind::Keychain),
Err(e) => {
let p = Self::fallback().ok_or(KeyError::Other(e))?;
let mut f = FileKeys::read(&p, self.passphrase.as_deref())?;
f.keys.insert(account.to_string(), key.to_string());
f.write(&p)?;
Ok(Kind::File(p))
}
},
}
}
pub fn delete(&self, account: &str) -> Result<(), KeyError> {
let file = match &self.kind {
Kind::File(p) => Some(p.clone()),
Kind::Keychain => {
os::delete(account).map_err(KeyError::Other)?;
Self::fallback().filter(|p| p.exists())
}
};
if let Some(p) = file {
let mut f = FileKeys::read(&p, self.passphrase.as_deref())?;
if f.keys.remove(account).is_some() {
f.write(&p)?;
}
}
Ok(())
}
pub fn locked_file(&self) -> bool {
match &self.kind {
Kind::File(p) => FileKeys::mode(p) == Some(Mode::Passphrase),
Kind::Keychain => false,
}
}
pub fn set_passphrase(&mut self, passphrase: Option<String>) -> Result<(), KeyError> {
let Kind::File(p) = &self.kind else {
return Err(KeyError::Other(
"Only the key file has a passphrase.".into(),
));
};
let mut f = FileKeys::read(p, self.passphrase.as_deref())?;
f.passphrase = passphrase.clone().filter(|s| !s.is_empty());
f.write(p)?;
self.passphrase = f.passphrase;
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Mode {
KeyFile = 0,
Passphrase = 1,
}
const MAGIC: &[u8; 4] = b"BTAK";
const VERSION: u8 = 1;
const PBKDF2_ROUNDS: u32 = 300_000;
#[derive(Default)]
struct FileKeys {
keys: BTreeMap<String, String>,
passphrase: Option<String>,
}
fn random<const N: usize>() -> Result<[u8; N], KeyError> {
let mut b = [0u8; N];
SystemRandom::new()
.fill(&mut b)
.map_err(|_| KeyError::Other("No random numbers from the system.".into()))?;
Ok(b)
}
fn key_path(data: &Path) -> PathBuf {
data.with_extension("key")
}
fn write_private(path: &Path, bytes: &[u8]) -> Result<(), KeyError> {
let io = |e: std::io::Error| KeyError::Other(format!("{}: {e}", path.display()));
if let Some(d) = path.parent() {
std::fs::create_dir_all(d).map_err(io)?;
}
let tmp = path.with_extension("tmp");
std::fs::write(&tmp, bytes).map_err(io)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600));
}
std::fs::rename(&tmp, path).map_err(io)
}
impl FileKeys {
fn mode(path: &Path) -> Option<Mode> {
let b = std::fs::read(path).ok()?;
(b.len() > 6 && &b[..4] == MAGIC).then(|| {
if b[5] == Mode::Passphrase as u8 {
Mode::Passphrase
} else {
Mode::KeyFile
}
})
}
fn cipher_key(
mode: Mode,
salt: &[u8],
passphrase: Option<&str>,
data: &Path,
create: bool,
) -> Result<LessSafeKey, KeyError> {
let mut key = [0u8; 32];
match mode {
Mode::Passphrase => {
let pw = passphrase.ok_or(KeyError::NeedPassphrase)?;
ring::pbkdf2::derive(
ring::pbkdf2::PBKDF2_HMAC_SHA256,
std::num::NonZeroU32::new(PBKDF2_ROUNDS).unwrap(),
salt,
pw.as_bytes(),
&mut key,
);
}
Mode::KeyFile => {
let kp = key_path(data);
match std::fs::read(&kp) {
Ok(b) if b.len() == 32 => key.copy_from_slice(&b),
_ if create => {
key = random::<32>()?;
write_private(&kp, &key)?;
}
_ => {
return Err(KeyError::Other(format!(
"{} is missing: the keys cannot be read.",
kp.display()
)))
}
}
}
}
Ok(LessSafeKey::new(
UnboundKey::new(&CHACHA20_POLY1305, &key)
.map_err(|_| KeyError::Other("bad key".into()))?,
))
}
fn read(path: &Path, passphrase: Option<&str>) -> Result<FileKeys, KeyError> {
let b = match std::fs::read(path) {
Ok(b) => b,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
return Ok(FileKeys {
keys: BTreeMap::new(),
passphrase: passphrase.map(str::to_string),
})
}
Err(e) => return Err(KeyError::Other(format!("{}: {e}", path.display()))),
};
let bad = || KeyError::Other(format!("{} is damaged.", path.display()));
if b.len() < 6 + 16 + 12 + aead::MAX_TAG_LEN || &b[..4] != MAGIC || b[4] != VERSION {
return Err(bad());
}
let mode = if b[5] == Mode::Passphrase as u8 {
Mode::Passphrase
} else {
Mode::KeyFile
};
let salt = &b[6..22];
let nonce: [u8; 12] = b[22..34].try_into().map_err(|_| bad())?;
let key = Self::cipher_key(mode, salt, passphrase, path, false)?;
let mut sealed = b[34..].to_vec();
let plain = key
.open_in_place(
Nonce::assume_unique_for_key(nonce),
Aad::from(&b[..6]),
&mut sealed,
)
.map_err(|_| match mode {
Mode::Passphrase => KeyError::WrongPassphrase,
Mode::KeyFile => bad(),
})?;
let keys = serde_json::from_slice(plain).map_err(|_| bad())?;
Ok(FileKeys {
keys,
passphrase: match mode {
Mode::Passphrase => passphrase.map(str::to_string),
Mode::KeyFile => None,
},
})
}
fn get(&self, account: &str) -> Option<String> {
self.keys.get(account).cloned()
}
fn write(&self, path: &Path) -> Result<(), KeyError> {
let mode = if self.passphrase.is_some() {
Mode::Passphrase
} else {
Mode::KeyFile
};
let salt = random::<16>()?;
let nonce = random::<12>()?;
let key = Self::cipher_key(mode, &salt, self.passphrase.as_deref(), path, true)?;
let mut head = MAGIC.to_vec();
head.extend([VERSION, mode as u8]);
let mut data = serde_json::to_vec(&self.keys).unwrap_or_default();
key.seal_in_place_append_tag(
Nonce::assume_unique_for_key(nonce),
Aad::from(&head[..]),
&mut data,
)
.map_err(|_| KeyError::Other("encryption failed".into()))?;
let mut out = head;
out.extend(salt);
out.extend(nonce);
out.extend(data);
write_private(path, &out)?;
if mode == Mode::Passphrase {
let _ = std::fs::remove_file(key_path(path));
}
Ok(())
}
}
#[cfg(windows)]
mod os {
use windows_sys::Win32::Foundation::{GetLastError, ERROR_NOT_FOUND, FILETIME};
use windows_sys::Win32::Security::Credentials::{
CredDeleteW, CredFree, CredReadW, CredWriteW, CREDENTIALW, CRED_PERSIST_LOCAL_MACHINE,
CRED_TYPE_GENERIC,
};
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain(std::iter::once(0)).collect()
}
fn target(account: &str) -> Vec<u16> {
wide(&format!("{}/{account}", super::SERVICE))
}
pub fn get(account: &str) -> Result<Option<String>, String> {
let t = target(account);
let mut p: *mut CREDENTIALW = std::ptr::null_mut();
let ok = unsafe { CredReadW(t.as_ptr(), CRED_TYPE_GENERIC, 0, &mut p) };
if ok == 0 {
let e = unsafe { GetLastError() };
return if e == ERROR_NOT_FOUND {
Ok(None)
} else {
Err(format!("Windows Credential Manager error {e}"))
};
}
let key = unsafe {
let c = &*p;
let blob = if c.CredentialBlob.is_null() {
&[][..]
} else {
std::slice::from_raw_parts(c.CredentialBlob, c.CredentialBlobSize as usize)
};
let k = String::from_utf8_lossy(blob).into_owned();
CredFree(p as *const _);
k
};
Ok(Some(key))
}
pub fn set(account: &str, key: &str) -> Result<(), String> {
let mut t = target(account);
let mut user = wide("BigText");
let mut blob = key.as_bytes().to_vec();
let c = CREDENTIALW {
Flags: 0,
Type: CRED_TYPE_GENERIC,
TargetName: t.as_mut_ptr(),
Comment: std::ptr::null_mut(),
LastWritten: FILETIME {
dwLowDateTime: 0,
dwHighDateTime: 0,
},
CredentialBlobSize: blob.len() as u32,
CredentialBlob: blob.as_mut_ptr(),
Persist: CRED_PERSIST_LOCAL_MACHINE,
AttributeCount: 0,
Attributes: std::ptr::null_mut(),
TargetAlias: std::ptr::null_mut(),
UserName: user.as_mut_ptr(),
};
if unsafe { CredWriteW(&c, 0) } == 0 {
return Err(format!("Windows Credential Manager error {}", unsafe {
GetLastError()
}));
}
Ok(())
}
pub fn delete(account: &str) -> Result<(), String> {
let t = target(account);
if unsafe { CredDeleteW(t.as_ptr(), CRED_TYPE_GENERIC, 0) } == 0 {
let e = unsafe { GetLastError() };
if e != ERROR_NOT_FOUND {
return Err(format!("Windows Credential Manager error {e}"));
}
}
Ok(())
}
}
#[cfg(unix)]
fn safe_for_input(key: &str) -> Result<(), String> {
if key.contains(['"', '\\', '\n', '\r']) {
Err("The key has characters a key does not have.".into())
} else {
Ok(())
}
}
#[cfg(target_os = "macos")]
mod os {
use std::io::Write;
use std::process::{Command, Stdio};
const SECURITY: &str = "/usr/bin/security";
const NOT_FOUND: i32 = 44;
pub fn get(account: &str) -> Result<Option<String>, String> {
let out = Command::new(SECURITY)
.args([
"find-generic-password",
"-s",
super::SERVICE,
"-a",
account,
"-w",
])
.output()
.map_err(|e| e.to_string())?;
if out.status.success() {
return Ok(Some(
String::from_utf8_lossy(&out.stdout).trim().to_string(),
));
}
if out.status.code() == Some(NOT_FOUND) {
return Ok(None);
}
Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
}
pub fn set(account: &str, key: &str) -> Result<(), String> {
super::safe_for_input(key)?;
let mut child = Command::new(SECURITY)
.arg("-i")
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| e.to_string())?;
let cmd = format!(
"add-generic-password -U -s \"{}\" -a \"{account}\" -w \"{key}\"\n",
super::SERVICE
);
if let Some(mut i) = child.stdin.take() {
i.write_all(cmd.as_bytes()).map_err(|e| e.to_string())?;
}
let out = child.wait_with_output().map_err(|e| e.to_string())?;
if !out.status.success() || !out.stderr.is_empty() {
return Err(String::from_utf8_lossy(&out.stderr).trim().to_string());
}
Ok(())
}
pub fn delete(account: &str) -> Result<(), String> {
let out = Command::new(SECURITY)
.args([
"delete-generic-password",
"-s",
super::SERVICE,
"-a",
account,
])
.output()
.map_err(|e| e.to_string())?;
if out.status.success() || out.status.code() == Some(NOT_FOUND) {
Ok(())
} else {
Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
}
}
}
#[cfg(all(unix, not(target_os = "macos")))]
mod os {
use std::io::Write;
use std::process::{Command, Stdio};
fn tool() -> Command {
Command::new("secret-tool")
}
fn missing(e: std::io::Error) -> String {
if e.kind() == std::io::ErrorKind::NotFound {
"secret-tool is not installed (package libsecret-tools or libsecret)".into()
} else {
e.to_string()
}
}
pub fn get(account: &str) -> Result<Option<String>, String> {
let out = tool()
.args(["lookup", "service", super::SERVICE, "account", account])
.output()
.map_err(missing)?;
let key = String::from_utf8_lossy(&out.stdout).trim().to_string();
if out.status.success() && !key.is_empty() {
return Ok(Some(key));
}
if out.stderr.is_empty() {
return Ok(None);
}
Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
}
pub fn set(account: &str, key: &str) -> Result<(), String> {
super::safe_for_input(key)?;
let label = format!("{}: {account}", super::SERVICE);
let mut child = tool()
.args([
"store",
"--label",
&label,
"service",
super::SERVICE,
"account",
account,
])
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
.map_err(missing)?;
if let Some(mut i) = child.stdin.take() {
i.write_all(key.as_bytes()).map_err(|e| e.to_string())?;
}
let out = child.wait_with_output().map_err(|e| e.to_string())?;
if out.status.success() {
Ok(())
} else {
Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
}
}
pub fn delete(account: &str) -> Result<(), String> {
let out = tool()
.args(["clear", "service", super::SERVICE, "account", account])
.output()
.map_err(missing)?;
if out.status.success() || out.stderr.is_empty() {
Ok(())
} else {
Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
}
}
}
#[cfg(not(any(windows, unix)))]
mod os {
pub fn get(_: &str) -> Result<Option<String>, String> {
Err("no keychain".into())
}
pub fn set(_: &str, _: &str) -> Result<(), String> {
Err("no keychain".into())
}
pub fn delete(_: &str) -> Result<(), String> {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn file_store(dir: &Path) -> KeyStore {
KeyStore {
kind: Kind::File(file_in(dir)),
passphrase: None,
}
}
#[test]
fn file_keys_round_trip_encrypted() {
let dir = tempfile::tempdir().unwrap();
let s = file_store(dir.path());
assert_eq!(s.get("anthropic").unwrap(), None);
assert_eq!(s.set("anthropic", " sk-ant-secret-1 ").unwrap(), s.kind);
s.set("openai", "sk-openai-2").unwrap();
assert_eq!(
s.get("anthropic").unwrap().as_deref(),
Some("sk-ant-secret-1")
);
let raw = std::fs::read(file_in(dir.path())).unwrap();
assert!(
!raw.windows(6).any(|w| w == b"sk-ant"),
"stored in the clear"
);
assert!(dir.path().join("ai-keys.key").exists());
s.delete("anthropic").unwrap();
assert_eq!(s.get("anthropic").unwrap(), None);
assert_eq!(s.get("openai").unwrap().as_deref(), Some("sk-openai-2"));
}
#[test]
fn a_passphrase_locks_the_file() {
let dir = tempfile::tempdir().unwrap();
let mut s = file_store(dir.path());
s.set("groq", "gsk-123456").unwrap();
s.set_passphrase(Some("correct horse".into())).unwrap();
assert!(s.locked_file());
assert!(!dir.path().join("ai-keys.key").exists());
let locked = file_store(dir.path());
assert_eq!(locked.get("groq"), Err(KeyError::NeedPassphrase));
let wrong = KeyStore {
passphrase: Some("wrong".into()),
..file_store(dir.path())
};
assert_eq!(wrong.get("groq"), Err(KeyError::WrongPassphrase));
assert_eq!(s.get("groq").unwrap().as_deref(), Some("gsk-123456"));
s.set_passphrase(None).unwrap();
assert_eq!(
file_store(dir.path()).get("groq").unwrap().as_deref(),
Some("gsk-123456")
);
}
#[test]
fn a_damaged_file_is_an_error_not_a_panic() {
let dir = tempfile::tempdir().unwrap();
let s = file_store(dir.path());
s.set("a", "k-123456").unwrap();
let p = file_in(dir.path());
let mut b = std::fs::read(&p).unwrap();
let last = b.len() - 1;
b[last] ^= 1;
std::fs::write(&p, b).unwrap();
assert!(matches!(s.get("a"), Err(KeyError::Other(_))));
std::fs::write(&p, b"xx").unwrap();
assert!(matches!(s.get("a"), Err(KeyError::Other(_))));
}
#[test]
fn environment_keys() {
let p = Preset {
env: "BIGTEXT_TEST_KEY_VAR_XYZ",
..*super::super::preset("openai").unwrap()
};
std::env::set_var("BIGTEXT_TEST_KEY_VAR_XYZ", " sk-env ");
assert_eq!(
from_env(&p),
Some(("sk-env".into(), "BIGTEXT_TEST_KEY_VAR_XYZ"))
);
std::env::remove_var("BIGTEXT_TEST_KEY_VAR_XYZ");
}
#[test]
#[ignore]
fn keychain_round_trip() {
let s = KeyStore {
kind: Kind::Keychain,
passphrase: None,
};
let acct = "bigtext-test-account";
s.set(acct, "sk-test-keychain").unwrap();
assert_eq!(s.get(acct).unwrap().as_deref(), Some("sk-test-keychain"));
s.delete(acct).unwrap();
assert_eq!(os::get(acct).unwrap(), None);
}
}