summaryrefslogtreecommitdiffstats
path: root/src/tools/cargo/credential/cargo-credential-macos-keychain/src/lib.rs
blob: 8a702a3620c6d736747d4f5477ec43d53881b136 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//! Cargo registry macos keychain credential process.

#![allow(clippy::print_stderr)]

#[cfg(target_os = "macos")]
mod macos {
    use cargo_credential::{
        read_token, Action, CacheControl, Credential, CredentialResponse, Error, RegistryInfo,
    };
    use security_framework::os::macos::keychain::SecKeychain;

    pub struct MacKeychain;

    /// The account name is not used.
    const ACCOUNT: &'static str = "";
    const NOT_FOUND: i32 = -25300; // errSecItemNotFound

    fn registry(index_url: &str) -> String {
        format!("cargo-registry:{}", index_url)
    }

    impl Credential for MacKeychain {
        fn perform(
            &self,
            reg: &RegistryInfo<'_>,
            action: &Action<'_>,
            _args: &[&str],
        ) -> Result<CredentialResponse, Error> {
            let keychain = SecKeychain::default().unwrap();
            let service_name = registry(reg.index_url);
            let not_found = security_framework::base::Error::from(NOT_FOUND).code();
            match action {
                Action::Get(_) => match keychain.find_generic_password(&service_name, ACCOUNT) {
                    Err(e) if e.code() == not_found => Err(Error::NotFound),
                    Err(e) => Err(Box::new(e).into()),
                    Ok((pass, _)) => {
                        let token = String::from_utf8(pass.as_ref().to_vec()).map_err(Box::new)?;
                        Ok(CredentialResponse::Get {
                            token: token.into(),
                            cache: CacheControl::Session,
                            operation_independent: true,
                        })
                    }
                },
                Action::Login(options) => {
                    let token = read_token(options, reg)?;
                    match keychain.find_generic_password(&service_name, ACCOUNT) {
                        Err(e) => {
                            if e.code() == not_found {
                                keychain
                                    .add_generic_password(
                                        &service_name,
                                        ACCOUNT,
                                        token.expose().as_bytes(),
                                    )
                                    .map_err(Box::new)?;
                            }
                        }
                        Ok((_, mut item)) => {
                            item.set_password(token.expose().as_bytes())
                                .map_err(Box::new)?;
                        }
                    }
                    Ok(CredentialResponse::Login)
                }
                Action::Logout => match keychain.find_generic_password(&service_name, ACCOUNT) {
                    Err(e) if e.code() == not_found => Err(Error::NotFound),
                    Err(e) => Err(Box::new(e).into()),
                    Ok((_, item)) => {
                        item.delete();
                        Ok(CredentialResponse::Logout)
                    }
                },
                _ => Err(Error::OperationNotSupported),
            }
        }
    }
}

#[cfg(not(target_os = "macos"))]
pub use cargo_credential::UnsupportedCredential as MacKeychain;
#[cfg(target_os = "macos")]
pub use macos::MacKeychain;