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

fix: Uses token cache when resolving token from request #99

Merged
merged 1 commit into from
Mar 8, 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
1 change: 1 addition & 0 deletions examples/hostedexample.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"version":2,"features":[{"strategies":[{"name":"flexibleRollout","constraints":[],"parameters":{"groupId":"projectStatusApi","rollout":"25","stickiness":"clientId"}},{"name":"flexibleRollout","constraints":[{"values":["hosted"],"inverted":false,"operator":"IN","contextName":"clientId","caseInsensitive":false}],"parameters":{"groupId":"projectStatusApi","rollout":"100","stickiness":"default"}}],"impressionData":false,"enabled":true,"name":"projectStatusApi","description":"","project":"dx","stale":false,"type":"release","variants":[]},{"strategies":[{"name":"flexibleRollout","constraints":[],"parameters":{"groupId":"showProjectApiAccess","rollout":"25","stickiness":"clientId"}}],"impressionData":false,"enabled":true,"name":"showProjectApiAccess","description":"Turns on Project API tokens","project":"dx","stale":false,"type":"release","variants":[]},{"strategies":[],"impressionData":false,"enabled":false,"name":"maintenanceMode","description":"This toggle forces customer's Unleash into maintenance mode.","project":"dx","stale":false,"type":"kill-switch","variants":[]},{"strategies":[],"impressionData":false,"enabled":false,"name":"caseInsensitiveInOperators","description":"Allow case insensitive LIST operator","project":"dx","stale":false,"type":"release","variants":[]},{"strategies":[{"name":"default","constraints":[{"values":["hosted"],"inverted":false,"operator":"IN","contextName":"clientId","caseInsensitive":false}],"parameters":{}}],"impressionData":false,"enabled":true,"name":"newProjectOverview","description":"","project":"dx","stale":false,"type":"release","variants":[]},{"strategies":[],"impressionData":false,"enabled":false,"name":"bulkOperations","description":"This flag enabled/disables all the bulk operations.","project":"dx","stale":false,"type":"release","variants":[]},{"strategies":[{"name":"flexibleRollout","constraints":[],"parameters":{"groupId":"serviceAccounts","rollout":"100","stickiness":"default"}},{"name":"default","constraints":[{"values":["hosted","ushosted","eubb7023"],"inverted":false,"operator":"IN","contextName":"clientId","caseInsensitive":false}],"parameters":{}}],"impressionData":false,"enabled":true,"name":"serviceAccounts","description":"Controls the release of \"service account\" feature. This is an enterprise-only feature for now","project":"eg","stale":false,"type":"release","variants":[]},{"strategies":[{"name":"default","constraints":[{"values":["red","lloydsbanking","eubb1049","ushosted","mdsol","light","demo","hosted"],"inverted":false,"operator":"IN","contextName":"clientId","caseInsensitive":false}],"parameters":{}}],"impressionData":false,"enabled":true,"name":"crOnVariants","description":"This controls whether Change Requests include variants or not","project":"eg","stale":false,"type":"release","variants":[]},{"strategies":[{"name":"default","constraints":[{"values":["eubb7017","hosted","ushosted","camel","usbb1006","aqua","eubb1003"],"inverted":false,"operator":"IN","contextName":"clientId","caseInsensitive":false}],"parameters":{}},{"name":"default","constraints":[{"values":["eubb1033"],"inverted":false,"operator":"NOT_IN","contextName":"clientId","caseInsensitive":false}],"parameters":{}}],"impressionData":false,"enabled":true,"name":"responseTimeWithAppName","description":"Add \"appName\" to the response time metric in promethues for /api/client calls. ","project":"eg","stale":false,"type":"permission","variants":[]},{"strategies":[{"name":"default","constraints":[],"parameters":{}}],"impressionData":false,"enabled":true,"name":"maintenance","description":"This toggle enables if the maintenance features is enabled for customer.","project":"dx","stale":false,"type":"release","variants":[]},{"strategies":[{"name":"flexibleRollout","constraints":[{"values":["ushosted"],"inverted":false,"operator":"IN","contextName":"clientId","caseInsensitive":false}],"parameters":{"groupId":"ENABLE_DARK_MODE_SUPPORT","rollout":"100","stickiness":"default"}}],"impressionData":false,"enabled":true,"name":"ENABLE_DARK_MODE_SUPPORT","description":"","project":"dx","stale":false,"type":"release","variants":[]},{"strategies":[],"impressionData":false,"enabled":false,"name":"anonymiseEventLog","description":"Used to annomise the event log in Unleash Cloud offering. ","project":"unleash-cloud","stale":false,"type":"permission","variants":[]},{"strategies":[],"impressionData":false,"enabled":false,"name":"projectScopedSegments","description":"Controls the rollout of segments scoped to a project which gives the ability to create a segment that's only available in a specific project","project":"eg","stale":false,"type":"release","variants":[]},{"strategies":[{"name":"default","constraints":[{"values":["eubb1033"],"inverted":false,"operator":"IN","contextName":"clientId","caseInsensitive":false}],"parameters":{}}],"impressionData":false,"enabled":true,"name":"responseTimeWithAppNameKillSwitch","description":"Disables \"appName\" to the response time metric in promethues for /api/client calls. ","project":"eg","stale":false,"type":"kill-switch","variants":[]},{"strategies":[{"name":"default","constraints":[{"values":["red","lloydsbanking"],"inverted":false,"operator":"IN","contextName":"clientId","caseInsensitive":false}],"parameters":{}},{"name":"flexibleRollout","constraints":[],"parameters":{"groupId":"featuresExportImport","rollout":"100","stickiness":"default"}}],"impressionData":false,"enabled":true,"name":"featuresExportImport","description":"","project":"dx","stale":false,"type":"release","variants":[]},{"strategies":[{"name":"default","constraints":[],"parameters":{}},{"name":"default","constraints":[{"values":["eudd","euee","usgg"],"inverted":false,"operator":"STR_STARTS_WITH","contextName":"clientId","caseInsensitive":false}],"parameters":{}},{"name":"default","constraints":[{"values":["hosted","demo","eubb1019","cadet","brown","usdd0005","usdd0015","usee0001","usee0004","eubb1000","eubb1003","usbb1006","plum","eubb1024","usdd0016","usee0024","usee0015","usee0016","usee0017","usff0002","nash","usff0006","eucc0020"],"inverted":false,"operator":"IN","contextName":"clientId","caseInsensitive":false}],"parameters":{}}],"impressionData":false,"enabled":true,"name":"batchMetrics","description":"","project":"dx","stale":false,"type":"release","variants":[]},{"strategies":[{"name":"default","constraints":[{"values":["eudd","euee","usgg"],"inverted":false,"operator":"STR_STARTS_WITH","contextName":"clientId","caseInsensitive":false}],"parameters":{}},{"name":"default","constraints":[],"parameters":{}}],"impressionData":false,"enabled":true,"name":"embedProxy","description":"This toggle is defaulted to true, but we need to have it because we turn it off for selected enterprise customers with an environment variable. We can archive and remove these feature flags once all enterprise customers are migrated to new contracts.","project":"dx","stale":false,"type":"kill-switch","variants":[]},{"strategies":[{"name":"default","constraints":[],"parameters":{}},{"name":"default","constraints":[{"values":["eudd","euee","usgg"],"inverted":false,"operator":"STR_STARTS_WITH","contextName":"clientId","caseInsensitive":false}],"parameters":{}}],"impressionData":false,"enabled":true,"name":"embedProxyFrontend","description":"This toggle is defaulted to true, but we need to have it because we turn it off for selected enterprise customers with an environment variable. We can archive and remove these feature flags once all enterprise customers are migrated to new contracts.","project":"dx","stale":false,"type":"kill-switch","variants":[]},{"strategies":[{"name":"default","constraints":[{"values":["vizlib.com","eubb1049","ushosted","mdsol","light","demo","hosted","lloydsbanking","red","gray"],"inverted":false,"operator":"IN","contextName":"clientId","caseInsensitive":false}],"parameters":{}},{"name":"flexibleRollout","constraints":[{"values":["pro"],"inverted":false,"operator":"IN","contextName":"plan","caseInsensitive":false}],"parameters":{"groupId":"variantsPerEnvironment","rollout":"100","stickiness":"clientId"}}],"impressionData":false,"enabled":true,"name":"variantsPerEnvironment","description":"Controls the release of variants per environment","project":"eg","stale":false,"type":"release","variants":[]},{"strategies":[{"name":"flexibleRollout","constraints":[],"parameters":{"groupId":"networkView","rollout":"100","stickiness":"clientId"}}],"impressionData":false,"enabled":true,"name":"networkView","description":"This feature controls the display of the new traffic tab under instance configuration. It also requires an environment variable PROMETHEUS_API to be configured for this feature to work properly","project":"eg","stale":false,"type":"release","variants":[]},{"strategies":[{"name":"flexibleRollout","constraints":[{"values":["ushosted","hosted"],"inverted":false,"operator":"IN","contextName":"clientId","caseInsensitive":false}],"parameters":{"groupId":"notifications","rollout":"100","stickiness":"default"}},{"name":"flexibleRollout","constraints":[],"parameters":{"groupId":"notifications","rollout":"25","stickiness":"clientId"}}],"impressionData":true,"enabled":true,"name":"notifications","description":"User specific notifications experimental feature","project":"dx","stale":false,"type":"release","variants":[]},{"strategies":[{"name":"default","constraints":[{"values":["eubb7004","usab1005"],"inverted":false,"operator":"NOT_IN","contextName":"clientId","caseInsensitive":false}],"parameters":{}}],"impressionData":true,"enabled":true,"name":"proPlanAutoCharge","description":"Display auto-charge UI in Unleash.","project":"dx","stale":false,"type":"release","variants":[]},{"strategies":[{"name":"default","constraints":[{"values":["eubb7004","usab1005"],"inverted":false,"operator":"NOT_IN","contextName":"clientId","caseInsensitive":false},{"value":"15","values":[],"inverted":false,"operator":"NUM_LTE","contextName":"authAppExtraUsers","caseInsensitive":false}],"parameters":{}}],"impressionData":false,"enabled":true,"name":"proPlanAutoChargeSubscriptions","description":"This flag checks based on context field, if it is possible to update customers stripe subscription.","project":"dx","stale":false,"type":"operational","variants":[]},{"strategies":[{"name":"flexibleRollout","constraints":[],"parameters":{"groupId":"proxyReturnAllToggles","rollout":"25","stickiness":"clientId"}}],"impressionData":false,"enabled":false,"name":"proxyReturnAllToggles","description":"Return all feature toggles","project":"dx","stale":false,"type":"release","variants":[]}],"query":{"project":["eg","unleash-cloud","dx"],"environment":"production","inlineSegmentConstraints":true}}
38 changes: 38 additions & 0 deletions server/src/client_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ mod tests {
use std::{collections::HashMap, fs, sync::Arc};

use crate::metrics::client_metrics::MetricsKey;
use crate::types::{TokenType, TokenValidationStatus};

use super::*;

Expand Down Expand Up @@ -204,6 +205,13 @@ mod tests {
.to_request()
}

async fn make_features_request_with_eg_dx_unleash_cloud_project_token() -> Request {
test::TestRequest::get()
.uri("/api/client/features")
.insert_header(("Authorization", "[]:production.puff_the_magic_dragon"))
.to_request()
}

#[actix_web::test]
async fn metrics_endpoint_correctly_aggregates_data() {
let metrics_cache = Arc::new(MetricsCache::default());
Expand Down Expand Up @@ -413,9 +421,39 @@ mod tests {
features_cache.insert("production".into(), example_features.clone());
let req = make_features_request_with_demo_app_production_token().await;
let res: ClientFeatures = test::call_and_read_body_json(&app, req).await;
assert_eq!(res.features.len(), 5);
assert!(res
.features
.iter()
.all(|t| t.project == Some("demo-app".into())));
}

#[tokio::test]
async fn client_features_endpoint_filters_when_multiple_projects_in_token() {
let features_cache: Arc<DashMap<String, ClientFeatures>> = Arc::new(DashMap::default());
let token_cache: Arc<DashMap<String, EdgeToken>> = Arc::new(DashMap::default());
let app = test::init_service(
App::new()
.app_data(Data::from(features_cache.clone()))
.app_data(Data::from(token_cache.clone()))
.service(web::scope("/api").service(features)),
)
.await;
let mut token =
EdgeToken::try_from("[]:production.puff_the_magic_dragon".to_string()).unwrap();
token.projects = vec!["dx".into(), "eg".into(), "unleash-cloud".into()];
token.status = TokenValidationStatus::Validated;
token.token_type = Some(TokenType::Client);
token_cache.insert(token.token.clone(), token.clone());

let example_features = features_from_disk(PathBuf::from("../examples/hostedexample.json"));
features_cache.insert("production".into(), example_features.clone());
let req = make_features_request_with_eg_dx_unleash_cloud_project_token().await;
let res: ClientFeatures = test::call_and_read_body_json(&app, req).await;
assert_eq!(res.features.len(), 24);
assert!(res
.features
.iter()
.all(|f| token.projects.contains(&f.project.clone().unwrap())));
}
}
28 changes: 27 additions & 1 deletion server/src/tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use actix_web::http::header::HeaderValue;
use actix_web::web::Data;
use actix_web::FromRequest;
use actix_web::HttpRequest;
use dashmap::DashMap;
use std::future::{ready, Ready};
use std::str::FromStr;

Expand Down Expand Up @@ -77,10 +78,35 @@ impl FromRequest for EdgeToken {
None => Err(EdgeError::AuthorizationDenied),
},
};
let key = match key {
Ok(k) => {
let token_cache = req.app_data::<Data<DashMap<String, EdgeToken>>>();
if let Some(cache) = token_cache {
cache
.get(&k.token)
.map(|e| e.value().clone())
.ok_or(EdgeError::AuthorizationDenied)
} else {
Ok(k)
}
}
Err(e) => Err(e),
};

ready(key)
} else {
let key = match value {
Some(v) => EdgeToken::try_from(v.clone()),
Some(v) => EdgeToken::try_from(v.clone()).and_then(|k| {
let token_cache = req.app_data::<Data<DashMap<String, EdgeToken>>>();
if let Some(cache) = token_cache {
cache
.get(&k.token)
.map(|e| e.value().clone())
.ok_or(EdgeError::AuthorizationDenied)
} else {
Ok(k)
}
}),
None => Err(EdgeError::AuthorizationDenied),
};
ready(key)
Expand Down