From 802bafc92160205a2a3068b7b780a6a5eeb331d9 Mon Sep 17 00:00:00 2001 From: Bryan Newbold Date: Tue, 18 Sep 2018 11:38:34 -0700 Subject: start skeleton of auth internal bits --- rust/src/auth.rs | 106 ++++++++++++++++++++++++++++++++++++++++++ rust/src/bin/fatcat-auth.rs | 109 ++++++++++++++++++++++++++++++++++++++++++++ rust/src/bin/fatcatd.rs | 12 ++--- rust/src/lib.rs | 4 +- 4 files changed, 222 insertions(+), 9 deletions(-) create mode 100644 rust/src/auth.rs create mode 100644 rust/src/bin/fatcat-auth.rs (limited to 'rust/src') diff --git a/rust/src/auth.rs b/rust/src/auth.rs new file mode 100644 index 00000000..651f7979 --- /dev/null +++ b/rust/src/auth.rs @@ -0,0 +1,106 @@ +//! Editor bearer token authentication + +use swagger::auth::{AuthData, Authorization, Scopes}; +//use macaroon::{Macaroon, Verifier}; + +use std::collections::BTreeSet; +//use database_models::*; +//use database_schema::*; +use api_helpers::*; +use chrono; +//use diesel; +use iron; +//use diesel::prelude::*; +use errors::*; +//use serde_json; +//use std::str::FromStr; +//use uuid::Uuid; + +#[derive(Debug)] +pub struct OpenAuthMiddleware; + +impl OpenAuthMiddleware { + /// Create a middleware that authorizes with the configured subject. + pub fn new() -> OpenAuthMiddleware { + OpenAuthMiddleware + } +} +impl iron::middleware::BeforeMiddleware for OpenAuthMiddleware { + fn before(&self, req: &mut iron::Request) -> iron::IronResult<()> { + req.extensions.insert::(Authorization { + subject: "undefined".to_string(), + scopes: Scopes::All, + issuer: None, + }); + Ok(()) + } +} + +#[derive(Debug)] +pub struct MacaroonAuthMiddleware; + +impl MacaroonAuthMiddleware { + + pub fn new() -> MacaroonAuthMiddleware { + MacaroonAuthMiddleware + } +} + +impl iron::middleware::BeforeMiddleware for MacaroonAuthMiddleware { + fn before(&self, req: &mut iron::Request) -> iron::IronResult<()> { + + let res: Option<(String, Vec)> = match req.extensions.get::() { + Some(AuthData::ApiKey(header)) => { + let header: Vec = header.split_whitespace().map(|s| s.to_string()).collect(); + // TODO: error types + assert!(header.len() == 2); + assert!(header[0] == "Bearer"); + parse_macaroon_token(&header[1]).expect("valid macaroon") + }, + None => None, + _ => panic!("valid auth header, or none") + }; + if let Some((editor_id, scopes)) = res { + let mut scope_set = BTreeSet::new(); + for s in scopes { + scope_set.insert(s); + } + req.extensions.insert::(Authorization { + subject: editor_id, + scopes: Scopes::Some(scope_set), + issuer: None, + }); + }; + Ok(()) + } +} + +// DUMMY: parse macaroon +pub fn parse_macaroon_token(s: &str) -> Result)>> { + Ok(Some(("some_editor_id".to_string(), vec![]))) +} + +pub fn print_editors() -> Result<()>{ + unimplemented!(); + // iterate over all editors. format id, print flags, auth_epoch +} + +pub fn create_editor(username: String, is_admin: bool, is_bot: bool) -> Result<()> { // TODO: EditorRow or something + unimplemented!(); +} + +pub fn create_token(editor_id: FatCatId, expires: Option) -> Result { + unimplemented!(); +} + +pub fn inspect_token(token: &str) -> Result<()> { + unimplemented!(); +} + +pub fn revoke_tokens(editor_id: FatCatId) -> Result<()>{ + unimplemented!(); +} + +pub fn revoke_tokens_everyone() -> Result { + unimplemented!(); +} diff --git a/rust/src/bin/fatcat-auth.rs b/rust/src/bin/fatcat-auth.rs new file mode 100644 index 00000000..7cb8af8e --- /dev/null +++ b/rust/src/bin/fatcat-auth.rs @@ -0,0 +1,109 @@ +//! JSON Export Helper + +#[macro_use] +extern crate clap; +extern crate dotenv; +#[macro_use] +extern crate error_chain; +extern crate fatcat; +#[macro_use] +extern crate log; +extern crate env_logger; +extern crate serde_json; +extern crate uuid; + +use clap::{App, Arg, SubCommand}; +use dotenv::dotenv; +use std::env; + +use fatcat::errors::*; +use fatcat::api_helpers::FatCatId; +use std::str::FromStr; +use uuid::Uuid; + +use error_chain::ChainedError; +//use std::io::{Stdout,StdoutLock}; +use std::io::prelude::*; +use std::io::{BufReader, BufWriter}; + + +fn run() -> Result<()> { + let m = App::new("fatcat-auth") + .version(env!("CARGO_PKG_VERSION")) + .author("Bryan Newbold ") + .about("Editor authentication admin tool") + .subcommand( + SubCommand::with_name("list-editors") + .about("Prints all currently registered editors") + ) + .subcommand( + SubCommand::with_name("create-editor") + .about("Creates a new auth token (macaroon) for the given editor") + .args_from_usage( + " 'username for editor' + --admin 'creates editor with admin privs' + --bot 'this editor is a bot'" + ) + ) + .subcommand( + SubCommand::with_name("create-token") + .about("Creates a new auth token (macaroon) for the given editor") + .args_from_usage( + " 'id of the editor (fatcatid, not username)' + --env-format 'outputs in a format that shells can source'" + ) + ) + .subcommand( + SubCommand::with_name("inspect-token") + .about("Dumps token metadata (and whether it is valid)") + ) + .subcommand( + SubCommand::with_name("revoke-tokens") + .about("Resets auth_epoch for a single editor (invalidating all existing tokens)") + ) + .subcommand( + SubCommand::with_name("revoke-tokens-all") + .about("Resets auth_epoch for all editors (invalidating tokens for all users!)") + ) + .get_matches(); + +/* + value_t_or_exit!(subm, "magic", u32) + .after_help("Reads a ident table TSV dump from stdin (aka, ident_id, rev_id, redirect_id), \ + and outputs JSON (one entity per line). Database connection info read from environment \ + (DATABASE_URL, same as fatcatd).") +*/ + match m.subcommand() { + ("list-editors", Some(_subm)) => { + fatcat::auth::print_editors()?; + }, + ("create-editor", Some(subm)) => { + fatcat::auth::create_editor( + subm.value_of("username").unwrap().to_string(), + subm.is_present("admin"), + subm.is_present("bot"))?; + }, + ("create-token", Some(subm)) => { + let editor_id = FatCatId::from_str(subm.value_of("editor").unwrap())?; + fatcat::auth::create_token(editor_id, None)?; + }, + ("inspect-token", Some(subm)) => { + fatcat::auth::inspect_token(subm.value_of("token").unwrap())?; + }, + ("revoke-tokens", Some(subm)) => { + let editor_id = FatCatId::from_str(subm.value_of("editor").unwrap())?; + fatcat::auth::revoke_tokens(editor_id)?; + }, + ("revoke-tokens-everyone", Some(_subm)) => { + fatcat::auth::revoke_tokens_everyone()?; + }, + _ => { + println!("Missing or unimplemented command!"); + println!("{}", m.usage()); + ::std::process::exit(-1); + } + } + Ok(()) +} + +quick_main!(run); diff --git a/rust/src/bin/fatcatd.rs b/rust/src/bin/fatcatd.rs index 57b6a3da..e14296da 100644 --- a/rust/src/bin/fatcatd.rs +++ b/rust/src/bin/fatcatd.rs @@ -20,9 +20,7 @@ use iron::modifiers::RedirectRaw; use iron::{status, Chain, Iron, IronResult, Request, Response}; use iron_slog::{DefaultLogFormatter, LoggerMiddleware}; use slog::{Drain, Logger}; -//use dotenv::dotenv; -//use std::env; -//use swagger::auth::AllowAllMiddleware; + /// Create custom server, wire it to the autogenerated router, /// and pass it to the web server. @@ -78,11 +76,9 @@ fn main() { let mut chain = Chain::new(LoggerMiddleware::new(router, logger, formatter)); - // Auth stuff unused for now - //chain.link_before(fatcat_api_spec::server::ExtractAuthData); - // add authentication middlewares into the chain here - // for the purpose of this example, pretend we have authenticated a user - //chain.link_before(AllowAllMiddleware::new("cosmo")); + // authentication + chain.link_before(fatcat_api_spec::server::ExtractAuthData); + chain.link_before(fatcat::auth::OpenAuthMiddleware::new()); chain.link_after(fatcat::XClacksOverheadMiddleware); diff --git a/rust/src/lib.rs b/rust/src/lib.rs index 0bed3471..2a6c7203 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -11,7 +11,7 @@ extern crate futures; extern crate uuid; #[macro_use] extern crate hyper; -//extern crate swagger; +extern crate swagger; #[macro_use] extern crate error_chain; extern crate iron; @@ -24,6 +24,7 @@ extern crate regex; #[macro_use] extern crate lazy_static; extern crate sha1; +extern crate macaroon; pub mod api_entity_crud; pub mod api_helpers; @@ -31,6 +32,7 @@ pub mod api_server; pub mod api_wrappers; pub mod database_models; pub mod database_schema; +pub mod auth; pub mod errors { // Create the Error, ErrorKind, ResultExt, and Result types -- cgit v1.2.3