github_mcp/core/
credential_storage.rs1use std::collections::HashMap;
4use std::fs;
5use std::path::PathBuf;
6
7use aes_gcm::aead::{Aead, AeadCore, KeyInit, OsRng};
8use aes_gcm::{Aes256Gcm, Key, Nonce};
9use keyring::Entry;
10use sha2::{Digest, Sha256};
11
12const SERVICE_NAME: &str = "github-mcp";
13
14fn resolve_home_dir() -> PathBuf {
19 std::env::var_os("HOME")
20 .or_else(|| std::env::var_os("USERPROFILE"))
21 .map(PathBuf::from)
22 .unwrap_or_else(|| PathBuf::from("."))
23}
24
25fn config_dir() -> PathBuf {
26 resolve_home_dir().join(".github-mcp")
27}
28
29fn fallback_file() -> PathBuf {
30 config_dir().join("credentials.enc")
31}
32
33fn encryption_key() -> [u8; 32] {
40 let home = resolve_home_dir().to_string_lossy().into_owned();
41 let mut hasher = Sha256::new();
42 hasher.update(home.as_bytes());
43 hasher.update(SERVICE_NAME.as_bytes());
44 hasher.finalize().into()
45}
46
47fn to_hex(bytes: &[u8]) -> String {
48 bytes.iter().map(|b| format!("{b:02x}")).collect()
49}
50
51fn from_hex(input: &str) -> anyhow::Result<Vec<u8>> {
52 if !input.len().is_multiple_of(2) {
53 anyhow::bail!("odd-length hex string");
54 }
55 (0..input.len())
56 .step_by(2)
57 .map(|i| u8::from_str_radix(&input[i..i + 2], 16).map_err(anyhow::Error::from))
58 .collect()
59}
60
61fn read_store() -> HashMap<String, String> {
62 fs::read_to_string(fallback_file())
63 .ok()
64 .and_then(|contents| serde_json::from_str(&contents).ok())
65 .unwrap_or_default()
66}
67
68fn write_store(store: &HashMap<String, String>) -> anyhow::Result<()> {
69 let dir = config_dir();
70 fs::create_dir_all(&dir)?;
71 let contents = serde_json::to_string(store)?;
72 fs::write(fallback_file(), contents)?;
73
74 #[cfg(unix)]
75 {
76 use std::os::unix::fs::PermissionsExt;
77 fs::set_permissions(&dir, fs::Permissions::from_mode(0o700))?;
78 fs::set_permissions(fallback_file(), fs::Permissions::from_mode(0o600))?;
79 }
80
81 Ok(())
82}
83
84fn save_to_file(account: &str, value: &str) -> anyhow::Result<()> {
85 let key_bytes = encryption_key();
86 let key: &Key<Aes256Gcm> = (&key_bytes).into();
87 let cipher = Aes256Gcm::new(key);
88 let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
89 let ciphertext = cipher
90 .encrypt(&nonce, value.as_bytes())
91 .map_err(|_| anyhow::anyhow!("failed to encrypt credential"))?;
92
93 let mut store = read_store();
94 store.insert(
95 account.to_string(),
96 format!("{}:{}", to_hex(&nonce), to_hex(&ciphertext)),
97 );
98 write_store(&store)
99}
100
101fn load_from_file(account: &str) -> anyhow::Result<Option<String>> {
102 let store = read_store();
103 let Some(raw) = store.get(account) else {
104 return Ok(None);
105 };
106 let (nonce_hex, ciphertext_hex) = raw
107 .split_once(':')
108 .ok_or_else(|| anyhow::anyhow!("corrupt credential entry for '{account}'"))?;
109
110 let key_bytes = encryption_key();
111 let key: &Key<Aes256Gcm> = (&key_bytes).into();
112 let cipher = Aes256Gcm::new(key);
113 let nonce_bytes = from_hex(nonce_hex)?;
114 let nonce = Nonce::from_slice(&nonce_bytes);
115 let ciphertext = from_hex(ciphertext_hex)?;
116 let plaintext = cipher
117 .decrypt(nonce, ciphertext.as_ref())
118 .map_err(|_| anyhow::anyhow!("failed to decrypt credential for '{account}'"))?;
119
120 Ok(Some(String::from_utf8(plaintext)?))
121}
122
123fn delete_from_file(account: &str) -> anyhow::Result<()> {
124 let mut store = read_store();
125 if store.remove(account).is_some() {
126 write_store(&store)?;
127 }
128 Ok(())
129}
130
131pub fn save_credential(account: &str, value: &str) -> anyhow::Result<()> {
137 match Entry::new(SERVICE_NAME, account).and_then(|entry| entry.set_password(value)) {
138 Ok(()) => Ok(()),
139 Err(err) => {
140 tracing::warn!(error = %err, "OS keychain unavailable; falling back to encrypted file storage");
141 save_to_file(account, value)
142 }
143 }
144}
145
146pub fn load_credential(account: &str) -> anyhow::Result<Option<String>> {
147 match Entry::new(SERVICE_NAME, account).and_then(|entry| entry.get_password()) {
148 Ok(password) => Ok(Some(password)),
149 Err(_) => load_from_file(account),
155 }
156}
157
158pub fn delete_credential(account: &str) -> anyhow::Result<()> {
159 match Entry::new(SERVICE_NAME, account).and_then(|entry| entry.delete_credential()) {
160 Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
161 Err(_) => delete_from_file(account),
162 }
163}
164
165#[cfg(test)]
166mod tests {
167 use super::*;
168
169 #[test]
170 fn hex_round_trips_arbitrary_bytes() {
171 let bytes = [0u8, 1, 15, 16, 255, 42];
172 assert_eq!(from_hex(&to_hex(&bytes)).unwrap(), bytes);
173 }
174
175 #[test]
176 fn file_fallback_round_trips_a_credential() {
177 let dir = tempfile::tempdir().unwrap();
182 unsafe {
184 std::env::set_var("HOME", dir.path());
185 }
186
187 save_to_file("test-account", "s3cr3t").unwrap();
188 let loaded = load_from_file("test-account").unwrap();
189 assert_eq!(loaded.as_deref(), Some("s3cr3t"));
190
191 delete_from_file("test-account").unwrap();
192 assert_eq!(load_from_file("test-account").unwrap(), None);
193 }
194}