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
#[macro_use]
extern crate error_chain;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate which;

use std::env;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus};

error_chain! {
    foreign_links {
        JsonParse(::serde_json::error::Error) #[doc = "Failed to parse JSON"];
        Io(::std::io::Error)
            #[doc = "IO error while calling `op` command"];
        SessionVar(::std::env::VarError)
            #[doc = "OP session environment variable was not valid UTF-8"];
        StdErrUtf8(::std::string::FromUtf8Error)
            #[doc = "Std error output from op was not valid UTF-8"];
    }
    errors {
        #[doc = "op command not found in path."]
        MissingOpCommand {
            description("op command not found in path")
        }
        #[doc = "Could not find any session environment variable."]
        MissingSessionVariable {
            description("could not find any session environment variable")
        }
        #[doc = "More than one session environment variable found."]
        MultipleSessionVariables(domains: Vec<String>) {
            description("more than one session environment variable found")
            display("more than one session environment variable found: {:?}", domains)
        }
        #[doc = "`op get` error"]
        GetCommand(uuid: String, stderr: String, status: ExitStatus) {
            description("op get error")
            display("op get error for {} code: {}, {}", uuid, status, stderr)
        }
        #[doc = "`op --version` error"]
        VersionCommand(stderr: String, status: ExitStatus) {
            description("op --version error")
            display("op --version error code: {}, {}", status, stderr)
        }
    }
}

///
///
#[derive(Debug, Clone)]
pub struct Op {
    command: PathBuf,
}

impl Op {
    /// # Example
    ///
    /// ```
    /// # extern crate _1password;
    /// use _1password::Op;
    ///
    /// let op = Op::new("op");
    /// println!("Op Version: {}", op.version().unwrap());
    /// ```
    pub fn new<P: AsRef<Path>>(command: P) -> Op {
        Op {
            command: command.as_ref().to_owned(),
        }
    }

    /// Find `op` command line utility by search the current PATH environment variable.
    ///
    /// # Example
    ///
    /// ```
    /// # extern crate _1password;
    /// use _1password::Op;
    ///
    /// let op = Op::which().unwrap();
    /// println!("Op Version: {}", op.version().unwrap());
    /// ```
    pub fn which() -> Result<Op> {
        if let Ok(p) = which::which("op") {
            Ok(Op {
                command: p,
            })
        } else {
            Err(ErrorKind::MissingOpCommand.into())
        }
    }

    /// Path to `op` command
    pub fn command(&self) -> &Path {
        &self.command
    }

    /// Returns version of `op` that this struct uses.
    pub fn version(&self) -> Result<String> {
        let output = Command::new(&self.command)
                .arg("--version")
                .output()?;
        let stdout = String::from_utf8(output.stdout)?;
        let stderr = String::from_utf8(output.stderr)?;
        if let Some(1) = output.status.code() {
            Ok(stdout.trim().to_owned())
        } else {
            Err(ErrorKind::VersionCommand(stderr, output.status).into())
        }
    }

    /*
    pub fn signin_subdomain(&self, subdomain: &str, password: &str) -> OpSession {

    }

    pub fn signin(&self, signinaddress: &str, emailaddress: &str, secretkey: &str, password: &str) -> OpSession {

    }
    */

    /// Make new session with the specified session token.
    pub fn session(&self, session: &str) -> OpSession {
        OpSession {
            config: self.clone(),
            session: session.to_owned(),
        }
    }

    /// Lookup session token for the supplied subdomain in environment.
    /// This will look for an environment variable named `OP_SESSION_<subdomain>` and if found
    /// will return a new session that uses the session token stored in that environment variable.
    pub fn env_account_session(&self, subdomain: &str) -> Result<OpSession> {
        match env::var(format!("OP_SESSION_{}", subdomain)) {
            Err(env::VarError::NotPresent) => Err(ErrorKind::MissingSessionVariable.into()),
            Err(err) => Err(err.into()),
            Ok(session) => Ok(OpSession {
                config: self.clone(),
                session: session,
            })
        }
    }

    /// Lookup session token in environment.
    /// This will look for any environment variables matching the pattern `OP_SESSION_*` and if
    /// found will return a new session that uses the session token stored in that environment
    /// variable.
    ///
    /// If more than one environment variable matching the pattern is found and error is returned.
    pub fn env_session(&self) -> Result<OpSession> {
        let vars : Vec<(String,String)> = env::vars().filter(|(key, _)| key.starts_with("OP_SESSION_") ).collect();
        match vars.len() {
            0 => Err(ErrorKind::MissingSessionVariable.into()),
            1 => {
                Ok(OpSession {
                    config: self.clone(),
                    session: vars.into_iter().next().unwrap().1,
                })
            },
            _ => {
                let names : Vec<String> = vars.into_iter().map(|(key, _)| key).collect();
                Err(ErrorKind::MultipleSessionVariables(names).into())
            }
        }
    }
}

/// A configured session what can be used to actually lookup information in 1Password.
#[derive(Debug, Clone)]
pub struct OpSession {
    config: Op,
    session: String,
}

impl OpSession {
    /// Get item with specified UUID.
    ///
    /// This calls `op get item` and parses the returned JSON.
    pub fn get_item(&self, uuid: &str) -> Result<OpItem> {
        let output = Command::new(&self.config.command)
                .args(&["get", "item"])
                .arg(format!("--session={}", self.session))
                .arg(&uuid)
                .output()?;
        if output.status.success() {
            Ok(serde_json::from_slice(&output.stdout)?)
        } else {
            let stderr = String::from_utf8(output.stderr)?;
            Err(ErrorKind::GetCommand(uuid.to_owned(), stderr, output.status).into())
        }
    }
}

#[derive(Serialize, Deserialize, Debug)]
pub struct OpItemOverview {
    pub ainfo: String,
    pub title: String
}

#[derive(Serialize, Deserialize, Debug)]
pub struct OpItemField {
    pub designation: Option<String>,
    pub name: String,
    #[serde(rename="type")]
    pub field_type: String,
    pub value: String
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum OpItemDetails {
    Password { password: String },
    Login { fields: Vec<OpItemField> },
}

/// Item returned from `OpSession::get_item`
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct OpItem {
    pub uuid: String,
    pub vault_uuid: String,
    pub changer_uuid: String,
    pub overview: OpItemOverview,
    pub details: OpItemDetails,
}

impl OpItem {
    /// Return password of this item if any.
    pub fn password(&self) -> Option<String> {
        match &self.details {
            &OpItemDetails::Password{ ref password } => Some(password.clone()),
            &OpItemDetails::Login{ ref fields } => {
                let p : Option<String> = Some("password".to_string());
                fields.iter()
                    .find(|ref x| x.designation == p)
                    .map(|x| x.value.clone())
            }
        }
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}