Fetch upstream configuration
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2023-04-25 16:35:32 +02:00
parent 16ef969e29
commit 2fe1b4a8b2
7 changed files with 384 additions and 8 deletions

View File

@@ -0,0 +1,75 @@
use std::cell::RefCell;
use std::collections::HashMap;
use crate::constants::OIDC_PROVIDERS_LIFETIME;
use crate::data::jwt_signer::JsonWebKey;
use crate::data::provider::Provider;
use crate::utils::err::Res;
use crate::utils::time::time;
#[derive(Debug, Clone, serde::Deserialize)]
pub struct ProviderDiscovery {
pub issuer: String,
pub authorization_endpoint: String,
pub token_endpoint: String,
pub userinfo_endpoint: Option<String>,
pub jwks_uri: String,
pub claims_supported: Option<Vec<String>>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ProviderJWKs {
pub keys: Vec<JsonWebKey>,
}
/// Provider configuration
#[derive(Debug, Clone)]
pub struct ProviderConfiguration {
pub discovery: ProviderDiscovery,
pub keys: ProviderJWKs,
pub expire: u64,
}
thread_local! {
static THREAD_CACHE: RefCell<HashMap<String, ProviderConfiguration>> = RefCell::new(Default::default());
}
pub struct ProviderConfigurationHelper {}
impl ProviderConfigurationHelper {
/// Get or refresh the configuration for a provider
pub async fn get_configuration(provider: &Provider) -> Res<ProviderConfiguration> {
let config = THREAD_CACHE.with(|i| i.borrow().get(&provider.configuration_url).cloned());
// Refresh config cache if needed
if config.is_none() || config.as_ref().unwrap().expire < time() {
let conf = Self::fetch_configuration(provider).await?;
THREAD_CACHE.with(|i| {
i.borrow_mut()
.insert(provider.configuration_url.clone(), conf.clone())
});
return Ok(conf);
}
// We can return immediately previously extracted value
Ok(config.unwrap())
}
/// Get fresh configuration from provider
async fn fetch_configuration(provider: &Provider) -> Res<ProviderConfiguration> {
let discovery: ProviderDiscovery = reqwest::get(&provider.configuration_url)
.await?
.json()
.await?;
let keys: ProviderJWKs = reqwest::get(&discovery.jwks_uri).await?.json().await?;
Ok(ProviderConfiguration {
discovery,
keys,
expire: time() + OIDC_PROVIDERS_LIFETIME,
})
}
}