diff options
Diffstat (limited to 'rust/src/bin')
-rw-r--r-- | rust/src/bin/fatcat-auth.rs | 134 | ||||
-rw-r--r-- | rust/src/bin/fatcat-export.rs | 18 | ||||
-rw-r--r-- | rust/src/bin/fatcatd.rs | 24 |
3 files changed, 151 insertions, 25 deletions
diff --git a/rust/src/bin/fatcat-auth.rs b/rust/src/bin/fatcat-auth.rs new file mode 100644 index 00000000..addd2b66 --- /dev/null +++ b/rust/src/bin/fatcat-auth.rs @@ -0,0 +1,134 @@ +//! JSON Export Helper + +//#[macro_use] +extern crate clap; +extern crate diesel; +extern crate dotenv; +#[macro_use] +extern crate error_chain; +extern crate fatcat; +//#[macro_use] +extern crate env_logger; +extern crate log; +extern crate serde_json; +extern crate uuid; + +use clap::{App, SubCommand}; + +use diesel::prelude::*; +use fatcat::api_helpers::FatCatId; +use fatcat::errors::*; +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 <bnewbold@archive.org>") + .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> '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( + "<editor-id> 'id of the editor (fatcatid, not username)' + --env-format 'outputs in a format that shells can source'", // TODO + ), + ) + .subcommand( + SubCommand::with_name("inspect-token") + .about("Dumps token metadata (and whether it is valid)") + .args_from_usage("<token> 'base64-encoded token (macaroon)'"), + ) + .subcommand( + SubCommand::with_name("create-key") + .about("Creates a new auth secret key (aka, root/signing key for tokens)") + .args_from_usage( + "--env-format 'outputs in a format that shells can source'", // TODO + ), + ) + .subcommand( + SubCommand::with_name("revoke-tokens") + .about("Resets auth_epoch for a single editor (invalidating all existing tokens)") + .args_from_usage("<editor-id> 'identifier (fcid) of editor'"), + ) + .subcommand( + SubCommand::with_name("revoke-tokens-everyone") + .about("Resets auth_epoch for all editors (invalidating tokens for all users!)"), + ) + .get_matches(); + + // First, the commands with no db or confectionary needed + match m.subcommand() { + ("create-key", Some(_subm)) => { + println!("{}", fatcat::auth::create_key()); + return Ok(()); + } + _ => (), + } + + // Then the ones that do + let db_conn = fatcat::database_worker_pool()? + .get() + .expect("database pool"); + let confectionary = fatcat::env_confectionary()?; + match m.subcommand() { + ("list-editors", Some(_subm)) => { + fatcat::auth::print_editors(&db_conn)?; + } + ("create-editor", Some(subm)) => { + let editor = fatcat::api_helpers::create_editor( + &db_conn, + subm.value_of("username").unwrap().to_string(), + subm.is_present("admin"), + subm.is_present("bot"), + )?; + //println!("{:?}", editor); + println!("{}", FatCatId::from_uuid(&editor.id).to_string()); + } + ("create-token", Some(subm)) => { + let editor_id = FatCatId::from_str(subm.value_of("editor-id").unwrap())?; + // check that editor exists + let _ed: fatcat::database_models::EditorRow = fatcat::database_schema::editor::table + .find(&editor_id.to_uuid()) + .get_result(&db_conn)?; + println!("{}", confectionary.create_token(editor_id, None)?); + } + ("inspect-token", Some(subm)) => { + confectionary.inspect_token(&db_conn, subm.value_of("token").unwrap())?; + } + ("revoke-tokens", Some(subm)) => { + let editor_id = FatCatId::from_str(subm.value_of("editor-id").unwrap())?; + fatcat::auth::revoke_tokens(&db_conn, editor_id)?; + println!("success!"); + } + ("revoke-tokens-everyone", Some(_subm)) => { + fatcat::auth::revoke_tokens_everyone(&db_conn)?; + println!("success!"); + } + _ => { + println!("Missing or unimplemented command!"); + println!("{}", m.usage()); + ::std::process::exit(-1); + } + } + Ok(()) +} + +quick_main!(run); diff --git a/rust/src/bin/fatcat-export.rs b/rust/src/bin/fatcat-export.rs index ec66ed4c..e1b930fc 100644 --- a/rust/src/bin/fatcat-export.rs +++ b/rust/src/bin/fatcat-export.rs @@ -17,15 +17,10 @@ extern crate serde_json; extern crate uuid; use clap::{App, Arg}; -use dotenv::dotenv; -use std::env; -use diesel::prelude::*; -use diesel::r2d2::ConnectionManager; use fatcat::api_entity_crud::*; use fatcat::api_helpers::*; use fatcat::errors::*; -use fatcat::ConnectionPool; use fatcat_api_spec::models::*; use std::str::FromStr; use uuid::Uuid; @@ -59,17 +54,6 @@ struct IdentRow { redirect_id: Option<FatCatId>, } -/// Instantiate a new API server with a pooled database connection -pub fn database_worker_pool() -> Result<ConnectionPool> { - dotenv().ok(); - let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); - let manager = ConnectionManager::<PgConnection>::new(database_url); - let pool = diesel::r2d2::Pool::builder() - .build(manager) - .expect("Failed to create database pool."); - Ok(pool) -} - macro_rules! generic_loop_work { ($fn_name:ident, $entity_model:ident) => { fn $fn_name( @@ -183,7 +167,7 @@ pub fn do_export( entity_type: ExportEntityType, redirects: bool, ) -> Result<()> { - let db_pool = database_worker_pool()?; + let db_pool = fatcat::database_worker_pool()?; let buf_input = BufReader::new(std::io::stdin()); let (row_sender, row_receiver) = channel::bounded(CHANNEL_BUFFER_LEN); let (output_sender, output_receiver) = channel::bounded(CHANNEL_BUFFER_LEN); diff --git a/rust/src/bin/fatcatd.rs b/rust/src/bin/fatcatd.rs index 57b6a3da..682f5038 100644 --- a/rust/src/bin/fatcatd.rs +++ b/rust/src/bin/fatcatd.rs @@ -20,9 +20,6 @@ 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. @@ -42,6 +39,19 @@ fn main() { let formatter = DefaultLogFormatter; let server = fatcat::server().unwrap(); + info!( + logger, + "using primary auth key: {}", server.auth_confectionary.identifier, + ); + info!( + logger, + "all auth keys: {:?}", + server + .auth_confectionary + .root_keys + .keys() + .collect::<Vec<&String>>(), + ); let mut router = fatcat_api_spec::router(server); router.get("/", root_handler, "root-redirect"); @@ -78,11 +88,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::MacaroonAuthMiddleware::new()); chain.link_after(fatcat::XClacksOverheadMiddleware); |