aboutsummaryrefslogtreecommitdiffstats
path: root/rust
diff options
context:
space:
mode:
Diffstat (limited to 'rust')
-rw-r--r--rust/src/auth.rs106
-rw-r--r--rust/src/bin/fatcat-auth.rs109
-rw-r--r--rust/src/bin/fatcatd.rs12
-rw-r--r--rust/src/lib.rs4
4 files changed, 222 insertions, 9 deletions
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>(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<String>)> = match req.extensions.get::<AuthData>() {
+ Some(AuthData::ApiKey(header)) => {
+ let header: Vec<String> = 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>(Authorization {
+ subject: editor_id,
+ scopes: Scopes::Some(scope_set),
+ issuer: None,
+ });
+ };
+ Ok(())
+ }
+}
+
+// DUMMY: parse macaroon
+pub fn parse_macaroon_token(s: &str) -> Result<Option<(String,Vec<String>)>> {
+ 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<chrono::NaiveDateTime>) -> Result<String> {
+ unimplemented!();
+}
+
+pub fn inspect_token(token: &str) -> Result<()> {
+ unimplemented!();
+}
+
+pub fn revoke_tokens(editor_id: FatCatId) -> Result<()>{
+ unimplemented!();
+}
+
+pub fn revoke_tokens_everyone() -> Result<u64> {
+ 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 <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'"
+ )
+ )
+ .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