1pub mod client;
22pub mod crypto;
23pub mod error;
24pub mod protocol;
25pub mod transport;
26
27pub use client::{Association, KxcClient};
28pub use crypto::IdKeyPair;
29pub use error::{KxcError, Result};
30pub use protocol::{Group, LoginEntry, Signal};
31
32#[cfg(test)]
33mod protocol_round_trip_tests {
34 use crate::client::KxcClient;
39 use crate::crypto::{b64, increment_nonce, IdKeyPair, NONCE_LEN};
40 use crate::error::KxcError;
41 use crate::transport::mock::MockTransport;
42 use crypto_box::{
43 aead::{Aead, OsRng},
44 PublicKey, SalsaBox, SecretKey,
45 };
46 use serde_json::{json, Value};
47 use std::sync::{Arc, Mutex};
48
49 struct FakeKxc {
51 secret: SecretKey,
52 client_pub: Option<PublicKey>,
53 associated_id: Option<String>,
54 inject_signals: Vec<&'static str>,
56 }
57
58 impl FakeKxc {
59 fn new() -> Self {
60 Self {
61 secret: SecretKey::generate(&mut OsRng),
62 client_pub: None,
63 associated_id: None,
64 inject_signals: Vec::new(),
65 }
66 }
67
68 fn nonce_of(env: &Value) -> [u8; NONCE_LEN] {
69 b64::dec(env["nonce"].as_str().unwrap()).unwrap().try_into().unwrap()
70 }
71
72 fn boxed(&self) -> SalsaBox {
73 SalsaBox::new(self.client_pub.as_ref().unwrap(), &self.secret)
74 }
75
76 fn decrypt_request(&self, env: &Value) -> Value {
77 let ct = b64::dec(env["message"].as_str().unwrap()).unwrap();
78 let nonce = Self::nonce_of(env);
79 let pt = self.boxed().decrypt(nonce.as_slice().into(), ct.as_slice()).unwrap();
80 serde_json::from_slice(&pt).unwrap()
81 }
82
83 fn encrypted_reply(&self, env: &Value, body: Value) -> Value {
84 let reply_nonce = increment_nonce(&Self::nonce_of(env));
85 let pt = serde_json::to_vec(&body).unwrap();
86 let ct = self.boxed().encrypt(reply_nonce.as_slice().into(), pt.as_slice()).unwrap();
87 json!({
88 "action": env["action"],
89 "message": b64::enc(&ct),
90 "nonce": b64::enc(&reply_nonce),
91 })
92 }
93
94 fn handle(&mut self, env: &Value) -> Vec<Value> {
96 let mut out: Vec<Value> = self
97 .inject_signals
98 .drain(..)
99 .map(|s| json!({"action": s}))
100 .collect();
101
102 match env["action"].as_str().unwrap() {
103 "change-public-keys" => {
104 let raw = b64::dec(env["publicKey"].as_str().unwrap()).unwrap();
105 let arr: [u8; 32] = raw.try_into().unwrap();
106 self.client_pub = Some(PublicKey::from(arr));
107 let reply_nonce = increment_nonce(&Self::nonce_of(env));
108 out.push(json!({
109 "action": "change-public-keys",
110 "publicKey": b64::enc(self.secret.public_key().as_bytes()),
111 "nonce": b64::enc(&reply_nonce),
112 "success": "true",
113 "version": "2.7.9",
114 }));
115 }
116 "associate" => {
117 let req = self.decrypt_request(env);
118 assert!(req["idKey"].is_string(), "associate must carry idKey");
119 self.associated_id = Some("test-assoc-42".into());
120 let body = json!({
121 "id": "test-assoc-42",
122 "hash": "abc123",
123 "success": "true",
124 "nonce": env["nonce"],
125 });
126 out.push(self.encrypted_reply(env, body));
127 }
128 "test-associate" => {
129 let req = self.decrypt_request(env);
130 let ok = self.associated_id.as_deref() == req["id"].as_str();
131 let body = if ok {
132 json!({"id": req["id"], "success": "true"})
133 } else {
134 json!({"error": "association failed", "errorCode": "8"})
135 };
136 out.push(self.encrypted_reply(env, body));
137 }
138 "get-logins" => {
139 let req = self.decrypt_request(env);
140 assert!(req["keys"].is_array(), "get-logins must carry association keys");
141 let body = if req["url"].as_str().unwrap().contains("vault.example.com") {
142 json!({
143 "count": 1,
144 "entries": [{
145 "uuid": "0a1b2c3d4e5f60718293a4b5c6d7e8f9",
146 "name": "Vaultwarden",
147 "login": "admin@example.com",
148 "password": "hunter2",
149 "group": "Sync/VW",
150 }],
151 "success": "true",
152 })
153 } else {
154 json!({"error": "no logins found", "errorCode": "15"})
155 };
156 out.push(self.encrypted_reply(env, body));
157 }
158 "set-login" => {
159 let req = self.decrypt_request(env);
160 let body = if req["url"].as_str().unwrap_or("").is_empty() {
164 json!({"error": "No URL provided", "errorCode": "14", "success": "false"})
165 } else {
166 json!({"error": "success", "success": "true", "nonce": env["nonce"]})
167 };
168 out.push(self.encrypted_reply(env, body));
169 }
170 other => panic!("FakeKxc: unhandled action {other}"),
171 }
172 out
173 }
174 }
175
176 fn wired() -> (MockTransport, Arc<Mutex<FakeKxc>>) {
177 let fake = Arc::new(Mutex::new(FakeKxc::new()));
178 let f2 = fake.clone();
179 let mock = MockTransport::with_responder(move |env| f2.lock().unwrap().handle(env));
180 (mock, fake)
181 }
182
183 #[tokio::test]
184 async fn full_flow_key_exchange_associate_get_logins() {
185 let (mock, fake) = wired();
186 let mut client = KxcClient::new(mock);
187
188 client.change_public_keys().await.expect("key exchange");
189
190 let id_key = IdKeyPair::generate();
191 let assoc = client.associate(&id_key).await.expect("associate");
192 assert_eq!(assoc.id, "test-assoc-42");
193
194 fake.lock().unwrap().inject_signals.push("database-unlocked");
196
197 let entries = client.get_logins("https://vault.example.com").await.expect("get-logins");
198 assert_eq!(entries.len(), 1);
199 assert_eq!(entries[0].login, "admin@example.com");
200 assert_eq!(entries[0].password, "hunter2");
201
202 let signals = client.take_signals();
203 assert_eq!(signals, vec![crate::Signal::DatabaseUnlocked]);
204
205 let none = client.get_logins("https://other.example.org").await.expect("empty ok");
207 assert!(none.is_empty());
208 }
209
210 #[tokio::test]
211 async fn set_login_success_sentinel_is_not_an_error() {
212 let (mock, _fake) = wired();
213 let mut client = KxcClient::new(mock);
214 client.change_public_keys().await.unwrap();
215
216 client
220 .set_login("https://site.example", "user", "pw", None, None, None)
221 .await
222 .expect("set-login success sentinel must be Ok");
223
224 assert!(matches!(
226 client.set_login("", "user", "pw", None, None, None).await,
227 Err(KxcError::KeePassXc { code: Some(14), .. })
228 ));
229 }
230
231 #[tokio::test]
232 async fn reconnect_test_associate_accepts_known_and_rejects_unknown_id() {
233 let (mock, fake) = wired();
234 let mut client = KxcClient::new(mock);
235 client.change_public_keys().await.unwrap();
236 let id_key = IdKeyPair::generate();
237 client.associate(&id_key).await.unwrap();
238
239 let stored_secret = id_key.secret_bytes();
241 let stored_id = "test-assoc-42".to_string();
242 drop(client);
243
244 let f2 = fake.clone();
245 let mock2 = MockTransport::with_responder(move |env| f2.lock().unwrap().handle(env));
246 let mut client2 = KxcClient::new(mock2);
247 client2.change_public_keys().await.unwrap();
248
249 let restored = IdKeyPair::from_secret_bytes(stored_secret);
250 client2.test_associate(&stored_id, &restored).await.expect("known id accepted");
251
252 assert!(matches!(
253 client2.test_associate("wrong-id", &restored).await,
254 Err(KxcError::NotAssociated)
255 ));
256 }
257
258 #[tokio::test]
259 async fn nonce_tampering_is_detected() {
260 let fake = Arc::new(Mutex::new(FakeKxc::new()));
262 let f2 = fake.clone();
263 let mock = MockTransport::with_responder(move |env: &Value| {
264 let mut replies = f2.lock().unwrap().handle(env);
265 if env["action"] == "change-public-keys" {
266 replies[0]["nonce"] = env["nonce"].clone();
268 }
269 replies
270 });
271 let mut client = KxcClient::new(mock);
272 assert!(matches!(
273 client.change_public_keys().await,
274 Err(KxcError::NonceMismatch)
275 ));
276 }
277}