Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add edge-token extractor to lock down access #4

Merged
merged 3 commits into from
Jan 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 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 server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,6 @@ tracing-opentelemetry = "0.18.0"
tracing-subscriber = { version = "0.3.16", features = ["json", "env-filter"] }
unleash-types = "0.4.1"
unleash-yggdrasil = "0.2.0"

[dev-dependencies]
test-case = "2.2.2"
3 changes: 3 additions & 0 deletions server/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ pub struct CliArgs {

#[clap(short, long, env)]
pub bootstrap_file: Option<PathBuf>,

#[clap(short, long, env)]
pub client_keys: Vec<String>,
}

impl CliArgs {
Expand Down
5 changes: 3 additions & 2 deletions server/src/client_api.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use crate::types::{EdgeJsonResult, FeaturesProvider};
use crate::types::{EdgeJsonResult, EdgeProvider, EdgeToken};
use actix_web::get;
use actix_web::web::{self, Json};
use unleash_types::client_features::ClientFeatures;

#[get("/client/features")]
async fn features(
features_source: web::Data<dyn FeaturesProvider>,
_edge_token: EdgeToken,
features_source: web::Data<dyn EdgeProvider>,
) -> EdgeJsonResult<ClientFeatures> {
let client_features = features_source.get_client_features();
Ok(Json(client_features))
Expand Down
29 changes: 27 additions & 2 deletions server/src/edge_api.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,28 @@
use actix_web::web;
use actix_web::{
get,
web::{self, Json},
};

pub fn configure_edge_api(_cfg: &mut web::ServiceConfig) {}
use crate::types::{EdgeJsonResult, EdgeToken, TokenProvider, TokenStrings, ValidatedTokens};

#[get("/validate")]
async fn validate(
_client_token: EdgeToken,
token_provider: web::Data<dyn TokenProvider>,
tokens: Json<TokenStrings>,
) -> EdgeJsonResult<ValidatedTokens> {
let valid_tokens: Vec<EdgeToken> = tokens
.into_inner()
.tokens
.into_iter()
.filter(|t| token_provider.secret_is_valid(t))
.map(|t| token_provider.token_details(t).unwrap()) // Guaranteed because we just checked that the secret exists
.collect();
Ok(Json(ValidatedTokens {
tokens: valid_tokens,
}))
}

pub fn configure_edge_api(cfg: &mut web::ServiceConfig) {
cfg.service(validate);
}
9 changes: 9 additions & 0 deletions server/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@ use actix_web::{http::StatusCode, HttpResponseBuilder, ResponseError};

#[derive(Debug)]
pub enum EdgeError {
AuthorizationDenied,
InvalidBackupFile(String, String),
NoFeaturesFile,
NoTokenProvider,
TokenParseError,
TlsError,
}

Expand All @@ -22,6 +25,9 @@ impl Display for EdgeError {
),
EdgeError::TlsError => write!(f, "Could not configure TLS"),
EdgeError::NoFeaturesFile => write!(f, "No features file located"),
EdgeError::AuthorizationDenied => write!(f, "Not allowed to access"),
EdgeError::NoTokenProvider => write!(f, "Could not get a TokenProvider"),
EdgeError::TokenParseError => write!(f, "Could not parse edge token"),
}
}
}
Expand All @@ -32,6 +38,9 @@ impl ResponseError for EdgeError {
EdgeError::InvalidBackupFile(_, _) => StatusCode::INTERNAL_SERVER_ERROR,
EdgeError::TlsError => StatusCode::INTERNAL_SERVER_ERROR,
EdgeError::NoFeaturesFile => StatusCode::INTERNAL_SERVER_ERROR,
EdgeError::AuthorizationDenied => StatusCode::FORBIDDEN,
EdgeError::NoTokenProvider => StatusCode::INTERNAL_SERVER_ERROR,
EdgeError::TokenParseError => StatusCode::UNAUTHORIZED,
}
}

Expand Down
9 changes: 6 additions & 3 deletions server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use actix_web::{middleware, web, App, HttpServer};
use actix_web_opentelemetry::RequestTracing;
use clap::Parser;
use cli::CliArgs;
use types::FeaturesProvider;
use types::EdgeProvider;

mod cli;
mod client_api;
Expand All @@ -25,11 +25,14 @@ async fn main() -> Result<(), anyhow::Error> {
let args = CliArgs::parse();
let (metrics_handler, request_metrics) = metrics::instantiate(None);
let client_provider = match args.mode {
EdgeMode::Offline => OfflineProvider::instantiate_provider(args.clone().bootstrap_file),
EdgeMode::Offline => OfflineProvider::instantiate_provider(
args.clone().bootstrap_file,
args.clone().client_keys,
),
}
.map_err(anyhow::Error::new)?;
let server = HttpServer::new(move || {
let client_provider_arc: Arc<dyn FeaturesProvider> = Arc::new(client_provider.clone());
let client_provider_arc: Arc<dyn EdgeProvider> = Arc::new(client_provider.clone());
let client_provider_data = web::Data::from(client_provider_arc);
App::new()
.app_data(client_provider_data)
Expand Down
36 changes: 32 additions & 4 deletions server/src/offline_provider.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::error::EdgeError;
use crate::types::FeaturesProvider;
use crate::types::{EdgeProvider, EdgeToken, FeaturesProvider, TokenProvider};
use std::fs::File;
use std::io::BufReader;
use std::path::PathBuf;
Expand All @@ -8,6 +8,7 @@ use unleash_types::client_features::ClientFeatures;
#[derive(Debug, Clone)]
pub struct OfflineProvider {
pub features: ClientFeatures,
pub valid_tokens: Vec<EdgeToken>,
}

impl FeaturesProvider for OfflineProvider {
Expand All @@ -16,9 +17,29 @@ impl FeaturesProvider for OfflineProvider {
}
}

impl TokenProvider for OfflineProvider {
fn get_known_tokens(&self) -> Vec<EdgeToken> {
self.valid_tokens.clone()
}

fn secret_is_valid(&self, secret: &str) -> bool {
self.valid_tokens.iter().any(|t| t.secret == secret)
}

fn token_details(&self, secret: String) -> Option<EdgeToken> {
self.valid_tokens
.clone()
.into_iter()
.find(|t| t.secret == secret)
}
}

impl EdgeProvider for OfflineProvider {}

impl OfflineProvider {
pub fn instantiate_provider(
bootstrap_file: Option<PathBuf>,
valid_tokens: Vec<String>,
) -> Result<OfflineProvider, EdgeError> {
if let Some(bootstrap) = bootstrap_file {
let file = File::open(bootstrap.clone()).map_err(|_| EdgeError::NoFeaturesFile)?;
Expand All @@ -27,12 +48,19 @@ impl OfflineProvider {
let path = format!("{}", bootstrap.clone().display());
EdgeError::InvalidBackupFile(path, e.to_string())
})?;
Ok(OfflineProvider::new(client_features))
Ok(OfflineProvider::new(client_features, valid_tokens))
} else {
Err(EdgeError::NoFeaturesFile)
}
}
pub fn new(features: ClientFeatures) -> Self {
OfflineProvider { features }
pub fn new(features: ClientFeatures, valid_tokens: Vec<String>) -> Self {
OfflineProvider {
features,
valid_tokens: valid_tokens
.into_iter()
.map(EdgeToken::try_from)
.filter_map(|t| t.ok())
.collect(),
}
}
}
Loading