keepassxc-client 0.1.0

KeePassXC browser native-messaging protocol client (associate, get-logins, set-login, ...)
Documentation
// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright (c) 2026 gaffa fix <gaffa@mafix.cc>

//! keepassxc-client — KeePassXC browser native-messaging protocol client.
//!
//! Usage sketch:
//! ```no_run
//! # async fn demo() -> Result<(), keepassxc_client::KxcError> {
//! use keepassxc_client::{KxcClient, IdKeyPair, transport::unix::UnixTransport};
//!
//! let t = UnixTransport::connect_auto().await?;
//! let mut kxc = KxcClient::new(t);
//! kxc.change_public_keys().await?;
//!
//! let id_key = IdKeyPair::generate();          // persist secret_bytes() in keyring!
//! let assoc = kxc.associate(&id_key).await?;   // user approves popup once
//! let entries = kxc.get_logins("https://vault.example.com").await?;
//! # Ok(()) }
//! ```

pub mod client;
pub mod crypto;
pub mod error;
pub mod protocol;
pub mod transport;

pub use client::{Association, KxcClient};
pub use crypto::IdKeyPair;
pub use error::{KxcError, Result};
pub use protocol::{Group, LoginEntry, Signal};

#[cfg(test)]
mod protocol_round_trip_tests {
    //! Full client round-trip against a simulated KeePassXC wired into the
    //! MockTransport responder: key exchange -> associate -> get-logins,
    //! including the nonce+1 rule and signal interleaving.

    use crate::client::KxcClient;
    use crate::crypto::{b64, increment_nonce, IdKeyPair, NONCE_LEN};
    use crate::error::KxcError;
    use crate::transport::mock::MockTransport;
    use crypto_box::{
        aead::{Aead, OsRng},
        PublicKey, SalsaBox, SecretKey,
    };
    use serde_json::{json, Value};
    use std::sync::{Arc, Mutex};

    /// Minimal in-memory KeePassXC.
    struct FakeKxc {
        secret: SecretKey,
        client_pub: Option<PublicKey>,
        associated_id: Option<String>,
        /// emit these signals before the next response
        inject_signals: Vec<&'static str>,
    }

    impl FakeKxc {
        fn new() -> Self {
            Self {
                secret: SecretKey::generate(&mut OsRng),
                client_pub: None,
                associated_id: None,
                inject_signals: Vec::new(),
            }
        }

        fn nonce_of(env: &Value) -> [u8; NONCE_LEN] {
            b64::dec(env["nonce"].as_str().unwrap()).unwrap().try_into().unwrap()
        }

        fn boxed(&self) -> SalsaBox {
            SalsaBox::new(self.client_pub.as_ref().unwrap(), &self.secret)
        }

        fn decrypt_request(&self, env: &Value) -> Value {
            let ct = b64::dec(env["message"].as_str().unwrap()).unwrap();
            let nonce = Self::nonce_of(env);
            let pt = self.boxed().decrypt(nonce.as_slice().into(), ct.as_slice()).unwrap();
            serde_json::from_slice(&pt).unwrap()
        }

        fn encrypted_reply(&self, env: &Value, body: Value) -> Value {
            let reply_nonce = increment_nonce(&Self::nonce_of(env));
            let pt = serde_json::to_vec(&body).unwrap();
            let ct = self.boxed().encrypt(reply_nonce.as_slice().into(), pt.as_slice()).unwrap();
            json!({
                "action": env["action"],
                "message": b64::enc(&ct),
                "nonce": b64::enc(&reply_nonce),
            })
        }

        /// Respond to one outgoing client frame.
        fn handle(&mut self, env: &Value) -> Vec<Value> {
            let mut out: Vec<Value> = self
                .inject_signals
                .drain(..)
                .map(|s| json!({"action": s}))
                .collect();

            match env["action"].as_str().unwrap() {
                "change-public-keys" => {
                    let raw = b64::dec(env["publicKey"].as_str().unwrap()).unwrap();
                    let arr: [u8; 32] = raw.try_into().unwrap();
                    self.client_pub = Some(PublicKey::from(arr));
                    let reply_nonce = increment_nonce(&Self::nonce_of(env));
                    out.push(json!({
                        "action": "change-public-keys",
                        "publicKey": b64::enc(self.secret.public_key().as_bytes()),
                        "nonce": b64::enc(&reply_nonce),
                        "success": "true",
                        "version": "2.7.9",
                    }));
                }
                "associate" => {
                    let req = self.decrypt_request(env);
                    assert!(req["idKey"].is_string(), "associate must carry idKey");
                    self.associated_id = Some("test-assoc-42".into());
                    let body = json!({
                        "id": "test-assoc-42",
                        "hash": "abc123",
                        "success": "true",
                        "nonce": env["nonce"],
                    });
                    out.push(self.encrypted_reply(env, body));
                }
                "test-associate" => {
                    let req = self.decrypt_request(env);
                    let ok = self.associated_id.as_deref() == req["id"].as_str();
                    let body = if ok {
                        json!({"id": req["id"], "success": "true"})
                    } else {
                        json!({"error": "association failed", "errorCode": "8"})
                    };
                    out.push(self.encrypted_reply(env, body));
                }
                "get-logins" => {
                    let req = self.decrypt_request(env);
                    assert!(req["keys"].is_array(), "get-logins must carry association keys");
                    let body = if req["url"].as_str().unwrap().contains("vault.example.com") {
                        json!({
                            "count": 1,
                            "entries": [{
                                "uuid": "0a1b2c3d4e5f60718293a4b5c6d7e8f9",
                                "name": "Vaultwarden",
                                "login": "admin@example.com",
                                "password": "hunter2",
                                "group": "Sync/VW",
                            }],
                            "success": "true",
                        })
                    } else {
                        json!({"error": "no logins found", "errorCode": "15"})
                    };
                    out.push(self.encrypted_reply(env, body));
                }
                "set-login" => {
                    let req = self.decrypt_request(env);
                    // Real KeePassXC reports a successful set-login with the
                    // sentinel error:"success" alongside success:"true"; a
                    // URL-less request is a genuine error (code 14).
                    let body = if req["url"].as_str().unwrap_or("").is_empty() {
                        json!({"error": "No URL provided", "errorCode": "14", "success": "false"})
                    } else {
                        json!({"error": "success", "success": "true", "nonce": env["nonce"]})
                    };
                    out.push(self.encrypted_reply(env, body));
                }
                other => panic!("FakeKxc: unhandled action {other}"),
            }
            out
        }
    }

    fn wired() -> (MockTransport, Arc<Mutex<FakeKxc>>) {
        let fake = Arc::new(Mutex::new(FakeKxc::new()));
        let f2 = fake.clone();
        let mock = MockTransport::with_responder(move |env| f2.lock().unwrap().handle(env));
        (mock, fake)
    }

    #[tokio::test]
    async fn full_flow_key_exchange_associate_get_logins() {
        let (mock, fake) = wired();
        let mut client = KxcClient::new(mock);

        client.change_public_keys().await.expect("key exchange");

        let id_key = IdKeyPair::generate();
        let assoc = client.associate(&id_key).await.expect("associate");
        assert_eq!(assoc.id, "test-assoc-42");

        // signal interleaving: a database-unlocked signal must be skipped + queued
        fake.lock().unwrap().inject_signals.push("database-unlocked");

        let entries = client.get_logins("https://vault.example.com").await.expect("get-logins");
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].login, "admin@example.com");
        assert_eq!(entries[0].password, "hunter2");

        let signals = client.take_signals();
        assert_eq!(signals, vec![crate::Signal::DatabaseUnlocked]);

        // "no logins found" (errorCode 15) normalizes to an empty vec
        let none = client.get_logins("https://other.example.org").await.expect("empty ok");
        assert!(none.is_empty());
    }

    #[tokio::test]
    async fn set_login_success_sentinel_is_not_an_error() {
        let (mock, _fake) = wired();
        let mut client = KxcClient::new(mock);
        client.change_public_keys().await.unwrap();

        // KeePassXC returns {"error":"success","success":"true"} on a
        // successful set-login — must be Ok, not a failure. (Regression: this
        // was misread as an error, so every socket-created entry "failed".)
        client
            .set_login("https://site.example", "user", "pw", None, None, None)
            .await
            .expect("set-login success sentinel must be Ok");

        // A URL-less set-login is still a real error (code 14).
        assert!(matches!(
            client.set_login("", "user", "pw", None, None, None).await,
            Err(KxcError::KeePassXc { code: Some(14), .. })
        ));
    }

    #[tokio::test]
    async fn reconnect_test_associate_accepts_known_and_rejects_unknown_id() {
        let (mock, fake) = wired();
        let mut client = KxcClient::new(mock);
        client.change_public_keys().await.unwrap();
        let id_key = IdKeyPair::generate();
        client.associate(&id_key).await.unwrap();

        // Same process, new client (simulates restart): fresh session keys.
        let stored_secret = id_key.secret_bytes();
        let stored_id = "test-assoc-42".to_string();
        drop(client);

        let f2 = fake.clone();
        let mock2 = MockTransport::with_responder(move |env| f2.lock().unwrap().handle(env));
        let mut client2 = KxcClient::new(mock2);
        client2.change_public_keys().await.unwrap();

        let restored = IdKeyPair::from_secret_bytes(stored_secret);
        client2.test_associate(&stored_id, &restored).await.expect("known id accepted");

        assert!(matches!(
            client2.test_associate("wrong-id", &restored).await,
            Err(KxcError::NotAssociated)
        ));
    }

    #[tokio::test]
    async fn nonce_tampering_is_detected() {
        // Responder that replies with a NON-incremented nonce -> client must reject.
        let fake = Arc::new(Mutex::new(FakeKxc::new()));
        let f2 = fake.clone();
        let mock = MockTransport::with_responder(move |env: &Value| {
            let mut replies = f2.lock().unwrap().handle(env);
            if env["action"] == "change-public-keys" {
                // tamper: echo the request nonce unchanged
                replies[0]["nonce"] = env["nonce"].clone();
            }
            replies
        });
        let mut client = KxcClient::new(mock);
        assert!(matches!(
            client.change_public_keys().await,
            Err(KxcError::NonceMismatch)
        ));
    }
}