    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
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314

    //! Cargo registry 1password credential process.

    use cargo_credential::{Credential, Error};
    use serde::Deserialize;
    use std::io::Read;
    use std::process::{Command, Stdio};

    const CARGO_TAG: &str = "cargo-registry";

    /// Implementation of 1password keychain access for Cargo registries.
    struct OnePasswordKeychain {
        account: Option<String>,
        vault: Option<String>,
    }

    /// 1password Login item type, used for the JSON output of `op item get`.
    #[derive(Deserialize)]
    struct Login {
        fields: Vec<Field>,
    }

    #[derive(Deserialize)]
    struct Field {
        id: String,
        value: Option<String>,
    }

    /// 1password item from `op items list`.
    #[derive(Deserialize)]
    struct ListItem {
        id: String,
        urls: Vec<Url>,
    }

    #[derive(Deserialize)]
    struct Url {
        href: String,
    }

    impl OnePasswordKeychain {
        fn new() -> Result<OnePasswordKeychain, Error> {
            let mut args = std::env::args().skip(1);
            let mut action = false;
            let mut account = None;
            let mut vault = None;
            while let Some(arg) = args.next() {
                match arg.as_str() {
                    "--account" => {
                        account = Some(args.next().ok_or("--account needs an arg")?);
                    }
                    "--vault" => {
                        vault = Some(args.next().ok_or("--vault needs an arg")?);
                    }
                    s if s.starts_with('-') => {
                        return Err(format!("unknown option {}", s).into());
                    }
                    _ => {
                        if action {
                            return Err("too many arguments".into());
                        } else {
                            action = true;
                        }
                    }
                }
            }
            Ok(OnePasswordKeychain { account, vault })
        }

        fn signin(&self) -> Result<Option<String>, Error> {
            // If there are any session env vars, we'll assume that this is the
            // correct account, and that the user knows what they are doing.
            if std::env::vars().any(|(name, _)| name.starts_with("OP_SESSION_")) {
                return Ok(None);
            }
            let mut cmd = Command::new("op");
            cmd.args(&["signin", "--raw"]);
            cmd.stdout(Stdio::piped());
            self.with_tty(&mut cmd)?;
            let mut child = cmd
                .spawn()
                .map_err(|e| format!("failed to spawn `op`: {}", e))?;
            let mut buffer = String::new();
            child
                .stdout
                .as_mut()
                .unwrap()
                .read_to_string(&mut buffer)
                .map_err(|e| format!("failed to get session from `op`: {}", e))?;
            if let Some(end) = buffer.find('\n') {
                buffer.truncate(end);
            }
            let status = child
                .wait()
                .map_err(|e| format!("failed to wait for `op`: {}", e))?;
            if !status.success() {
                return Err(format!("failed to run `op signin`: {}", status).into());
            }
            if buffer.is_empty() {
                // When using CLI integration, `op signin` returns no output,
                // so there is no need to set the session.
                return Ok(None);
            }
            Ok(Some(buffer))
        }

        fn make_cmd(&self, session: &Option<String>, args: &[&str]) -> Command {
            let mut cmd = Command::new("op");
            cmd.args(args);
            if let Some(account) = &self.account {
                cmd.arg("--account");
                cmd.arg(account);
            }
            if let Some(vault) = &self.vault {
                cmd.arg("--vault");
                cmd.arg(vault);
            }
            if let Some(session) = session {
                cmd.arg("--session");
                cmd.arg(session);
            }
            cmd
        }

        fn with_tty(&self, cmd: &mut Command) -> Result<(), Error> {
            #[cfg(unix)]
            const IN_DEVICE: &str = "/dev/tty";
            #[cfg(windows)]
            const IN_DEVICE: &str = "CONIN$";
            let stdin = std::fs::OpenOptions::new()
                .read(true)
                .write(true)
                .open(IN_DEVICE)?;
            cmd.stdin(stdin);
            Ok(())
        }

        fn run_cmd(&self, mut cmd: Command) -> Result<String, Error> {
            cmd.stdout(Stdio::piped());
            let mut child = cmd
                .spawn()
                .map_err(|e| format!("failed to spawn `op`: {}", e))?;
            let mut buffer = String::new();
            child
                .stdout
                .as_mut()
                .unwrap()
                .read_to_string(&mut buffer)
                .map_err(|e| format!("failed to read `op` output: {}", e))?;
            let status = child
                .wait()
                .map_err(|e| format!("failed to wait for `op`: {}", e))?;
            if !status.success() {
                return Err(format!("`op` command exit error: {}", status).into());
            }
            Ok(buffer)
        }

        fn search(&self, session: &Option<String>, index_url: &str) -> Result<Option<String>, Error> {
            let cmd = self.make_cmd(
                session,
                &[
                    "items",
                    "list",
                    "--categories",
                    "Login",
                    "--tags",
                    CARGO_TAG,
                    "--format",
                    "json",
                ],
            );
            let buffer = self.run_cmd(cmd)?;
            let items: Vec<ListItem> = serde_json::from_str(&buffer)
                .map_err(|e| format!("failed to deserialize JSON from 1password list: {}", e))?;
            let mut matches = items
                .into_iter()
                .filter(|item| item.urls.iter().any(|url| url.href == index_url));
            match matches.next() {
                Some(login) => {
                    // Should this maybe just sort on `updatedAt` and return the newest one?
                    if matches.next().is_some() {
                        return Err(format!(
                            "too many 1password logins match registry `{}`, \
                            consider deleting the excess entries",
                            index_url
                        )
                        .into());
                    }
                    Ok(Some(login.id))
                }
                None => Ok(None),
            }
        }

        fn modify(
            &self,
            session: &Option<String>,
            id: &str,
            token: &str,
            _name: Option<&str>,
        ) -> Result<(), Error> {
            let cmd = self.make_cmd(
                session,
                &["item", "edit", id, &format!("password={}", token)],
            );
            self.run_cmd(cmd)?;
            Ok(())
        }

        fn create(
            &self,
            session: &Option<String>,
            index_url: &str,
            token: &str,
            name: Option<&str>,
        ) -> Result<(), Error> {
            let title = match name {
                Some(name) => format!("Cargo registry token for {}", name),
                None => "Cargo registry token".to_string(),
            };
            let mut cmd = self.make_cmd(
                session,
                &[
                    "item",
                    "create",
                    "--category",
                    "Login",
                    &format!("password={}", token),
                    &format!("url={}", index_url),
                    "--title",
                    &title,
                    "--tags",
                    CARGO_TAG,
                ],
            );
            // For unknown reasons, `op item create` seems to not be happy if
            // stdin is not a tty. Otherwise it returns with a 0 exit code without
            // doing anything.
            self.with_tty(&mut cmd)?;
            self.run_cmd(cmd)?;
            Ok(())
        }

        fn get_token(&self, session: &Option<String>, id: &str) -> Result<String, Error> {
            let cmd = self.make_cmd(session, &["item", "get", "--format=json", id]);
            let buffer = self.run_cmd(cmd)?;
            let item: Login = serde_json::from_str(&buffer)
                .map_err(|e| format!("failed to deserialize JSON from 1password get: {}", e))?;
            let password = item.fields.into_iter().find(|item| item.id == "password");
            match password {
                Some(password) => password
                    .value
                    .ok_or_else(|| format!("missing password value for entry").into()),
                None => Err("could not find password field".into()),
            }
        }

        fn delete(&self, session: &Option<String>, id: &str) -> Result<(), Error> {
            let cmd = self.make_cmd(session, &["item", "delete", id]);
            self.run_cmd(cmd)?;
            Ok(())
        }
    }

    impl Credential for OnePasswordKeychain {
        fn name(&self) -> &'static str {
            env!("CARGO_PKG_NAME")
        }

        fn get(&self, index_url: &str) -> Result<String, Error> {
            let session = self.signin()?;
            if let Some(id) = self.search(&session, index_url)? {
                self.get_token(&session, &id)
            } else {
                return Err(format!(
                    "no 1password entry found for registry `{}`, try `cargo login` to add a token",
                    index_url
                )
                .into());
            }
        }

        fn store(&self, index_url: &str, token: &str, name: Option<&str>) -> Result<(), Error> {
            let session = self.signin()?;
            // Check if an item already exists.
            if let Some(id) = self.search(&session, index_url)? {
                self.modify(&session, &id, token, name)
            } else {
                self.create(&session, index_url, token, name)
            }
        }

        fn erase(&self, index_url: &str) -> Result<(), Error> {
            let session = self.signin()?;
            // Check if an item already exists.
            if let Some(id) = self.search(&session, index_url)? {
                self.delete(&session, &id)?;
            } else {
                eprintln!("not currently logged in to `{}`", index_url);
            }
            Ok(())
        }
    }

    fn main() {
        let op = match OnePasswordKeychain::new() {
            Ok(op) => op,
            Err(e) => {
                eprintln!("error: {}", e);
                std::process::exit(1);
            }
        };
        cargo_credential::main(op);
    }