Skip to content

Commit

Permalink
Remove reliance on rustc-serialize: intecture/api#26. Still awaiting …
Browse files Browse the repository at this point in the history
…docopt Serde support.
  • Loading branch information
petehayes102 committed Feb 27, 2017
1 parent 7e336c5 commit fbbf339
Show file tree
Hide file tree
Showing 7 changed files with 262 additions and 99 deletions.
91 changes: 91 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Expand Up @@ -22,6 +22,9 @@ chan-signal = "0.2"
czmq = "0.1"
docopt = "0.7"
rustc-serialize = "0.3"
serde = "0.9"
serde_derive = "0.9"
serde_json = "0.9"
zdaemon = "0.0.2"
zmq = "0.8"

Expand Down
113 changes: 54 additions & 59 deletions src/cli.rs
Expand Up @@ -9,9 +9,15 @@
extern crate czmq;
extern crate docopt;
extern crate rustc_serialize;
extern crate serde;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
#[cfg(test)]
extern crate tempdir;
extern crate zdaemon;
extern crate zmq;

mod cert;
mod config;
Expand All @@ -21,29 +27,33 @@ use cert::{Cert, CertType};
use config::Config;
use docopt::Docopt;
use error::{Error, Result};
use std::{env, fs};
use std::io::Read;
use std::fmt::{Debug, Display};
use std::path::{Path, PathBuf};
use std::path::Path;
use std::process::exit;
use std::result::Result as StdResult;
use zdaemon::ConfigFile;

static USAGE: &'static str = "
Intecture Auth.
Intecture Auth CLI.
Usage:
inauth_cli user add [(-s | --silent)] <username>
inauth_cli user add [(-s | --silent)] [(-c <path> | --config <path>)] <username>
inauth_cli --version
Options:
-s --silent Save private key instead of printing it.
--version Print this script's version.
-c --config <path> Path to auth.json, e.g. \"/usr/local/etc\"
-s --silent Save private key instead of printing it.
--version Print this script's version.
";

#[derive(Debug, RustcDecodable)]
struct Args {
cmd_add: bool,
cmd_user: bool,
arg_username: String,
flag_c: Option<String>,
flag_config: Option<String>,
flag_s: bool,
flag_silent: bool,
flag_version: bool,
Expand All @@ -59,7 +69,8 @@ fn main() {
exit(0);
}
else if args.cmd_user && args.cmd_add {
let config = try_exit(load_conf("auth.json", &["/usr/local/etc", "/etc"]));
let config_path = if args.flag_c.is_some() { args.flag_c.as_ref() } else { args.flag_config.as_ref() };
let config = try_exit(read_conf(config_path));
let cert = try_exit(Cert::new(&args.arg_username, CertType::User));
try_exit(cert.save_public(&format!("{}/{}.crt", &config.cert_path, &args.arg_username)));

Expand All @@ -84,25 +95,30 @@ curve
}
}

fn load_conf<P: AsRef<Path>>(path: P, default_paths: &[&str]) -> Result<Config> {
if path.as_ref().is_relative() {
for p in default_paths.iter() {
let mut pathbuf = PathBuf::from(p);
pathbuf.push("intecture");
pathbuf.push(&path);

match ConfigFile::load(&pathbuf) {
Ok(conf) => return Ok(conf),
Err(_) => continue,
}
}

Err(Error::MissingConf)
fn read_conf<P: AsRef<Path>>(path: Option<P>) -> Result<Config> {
if let Some(p) = path {
do_read_conf(p)
}
else if let Ok(p) = env::var("INAUTH_CONFIG_DIR") {
do_read_conf(p)
}
else if let Ok(c) = do_read_conf("/usr/local/etc/intecture") {
Ok(c)
} else {
Ok(try!(Config::load(&path.as_ref())))
do_read_conf("/etc/intecture")
}
}

fn do_read_conf<P: AsRef<Path>>(path: P) -> Result<Config> {
let mut path = path.as_ref().to_owned();
path.push("auth.json");

let mut fh = fs::File::open(&path)?;
let mut json = String::new();
fh.read_to_string(&mut json)?;
Ok(serde_json::from_str(&json)?)
}

fn try_exit<T, E>(r: StdResult<T, E>) -> T
where E: Into<Error> + Debug + Display {
if let Err(e) = r {
Expand All @@ -115,45 +131,24 @@ fn try_exit<T, E>(r: StdResult<T, E>) -> T

#[cfg(test)]
mod tests {
use config::Config;
use std::fs::create_dir;
use std::path::PathBuf;
use super::load_conf;
use std::{env, fs};
use std::io::Write;
use super::read_conf;
use tempdir::TempDir;
use zdaemon::ConfigFile;

#[test]
fn test_load_conf() {
let dir = TempDir::new("service_test_load_conf").unwrap();
let dir_path = dir.path().to_str().unwrap();

let config = Config {
server_cert: "/path".into(),
cert_path: "/path".into(),
api_port: 123,
update_port: 123,
};

// Relative path
let pathstr = format!("{}/intecture", dir_path);
let mut path = PathBuf::from(pathstr);
create_dir(&path).unwrap();
path.push("test_config.json");
config.save(&path).unwrap();
let c = load_conf("test_config.json", &[dir_path]).unwrap();
assert_eq!(c.api_port, 123);

// Relative nested path
let pathstr = format!("{}/intecture/nested", dir_path);
let mut path = PathBuf::from(pathstr);
create_dir(&path).unwrap();
path.push("test_config.json");
config.save(&path).unwrap();
let c = load_conf("nested/test_config.json", &[dir_path]).unwrap();
assert_eq!(c.api_port, 123);

// Absolute path
let c = load_conf(&format!("{}/intecture/test_config.json", dir_path), &["/fake/path"]).unwrap();
assert_eq!(c.api_port, 123);
fn test_read_conf() {
let tmpdir = TempDir::new("cli_test_read_conf").unwrap();
let mut path = tmpdir.path().to_owned();

path.push("auth.json");
let mut fh = fs::File::create(&path).unwrap();
fh.write_all(b"{\"server_cert\": \"/path\", \"cert_path\": \"/path\", \"api_port\": 123, \"update_port\": 123}").unwrap();
path.pop();

assert!(read_conf(Some(&path)).is_ok());
env::set_var("INAUTH_CONFIG_DIR", path.to_str().unwrap());
let none: Option<String> = None;
assert!(read_conf(none).is_ok());
}
}
18 changes: 2 additions & 16 deletions src/client.rs
Expand Up @@ -7,12 +7,9 @@
// modified, or distributed except according to those terms.

extern crate czmq;
extern crate zmq;

// XXX These crates are only required for error module to compile. In
// the future these dependencies should be removed.
extern crate rustc_serialize;
extern crate serde_json;
extern crate zdaemon;
extern crate zmq;

#[allow(dead_code)]
mod cert;
Expand All @@ -24,14 +21,3 @@ mod zap_handler;

pub use cert::CertType;
pub use zap_handler::ZapHandler;

use error::Error;
use std::convert;

// Only client.rs uses zmq crate, so our ZMQ error handlers have to
// go here.
impl convert::From<zmq::EncodeError> for Error {
fn from(e: zmq::EncodeError) -> Error {
Error::ZmqEncode(format!("{}", e))
}
}
7 changes: 1 addition & 6 deletions src/config.rs
Expand Up @@ -6,15 +6,10 @@
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distributed except according to those terms.

use zdaemon::ConfigFile;

#[derive(Debug)]
#[derive(RustcDecodable, RustcEncodable)]
#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
pub server_cert: String,
pub cert_path: String,
pub api_port: u32,
pub update_port: u32,
}

impl ConfigFile for Config {}

0 comments on commit fbbf339

Please sign in to comment.