-
Notifications
You must be signed in to change notification settings - Fork 5
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! Update on interval #22
Open
kjellkongsvik
wants to merge
1
commit into
cdriehuys:main
Choose a base branch
from
kjellkongsvik:update_interval
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
use std::sync::Arc; | ||
|
||
use crate::key_store::JwksError; | ||
use crate::{KeyStore, TokenError}; | ||
use jsonwebtoken::{decode, decode_header, TokenData}; | ||
use serde::de::DeserializeOwned; | ||
|
||
use tokio::sync::RwLock; | ||
|
||
use tokio::time::{Duration, Instant}; | ||
use tracing::{debug, info}; | ||
|
||
#[derive(Clone)] | ||
pub struct KeyManager { | ||
authority: String, | ||
audience: String, | ||
minimal_update_interval: Option<Duration>, | ||
key_store: Arc<RwLock<KeyStore>>, | ||
client: reqwest::Client, | ||
} | ||
|
||
impl KeyManager { | ||
pub fn builder() -> KeyManagerBuilder { | ||
KeyManagerBuilder::default() | ||
} | ||
|
||
pub async fn update(&self) -> Result<(), JwksError> { | ||
let new_ks = KeyStore::new(&self.client, &self.authority, &self.audience).await?; | ||
let mut ks = self.key_store.write().await; | ||
*ks = new_ks; | ||
info!("Updated jwks from: {}", &self.authority); | ||
Ok(()) | ||
} | ||
|
||
/// Validate the token, require claims in `T` to be present | ||
/// | ||
/// Verify correct `aud` and `exp` | ||
pub async fn validate_claims<T>(&self, token: &str) -> Result<TokenData<T>, TokenError> | ||
where | ||
T: DeserializeOwned, | ||
{ | ||
let header = decode_header(token).map_err(|error| { | ||
debug!(?error, "Received token with invalid header."); | ||
TokenError::InvalidHeader(error) | ||
})?; | ||
let kid = header.kid.as_ref().ok_or_else(|| { | ||
debug!(?header, "Header is missing the `kid` attribute."); | ||
TokenError::MissingKeyId | ||
})?; | ||
|
||
self.ensure_updated_key_store().await?; | ||
|
||
let ks = self.key_store.read().await; | ||
let key = ks.keys.get(kid).ok_or_else(|| { | ||
debug!(%kid, "Token refers to an unknown key."); | ||
TokenError::UnknownKeyId(kid.to_owned()) | ||
})?; | ||
|
||
decode(token, &key.decoding, &key.validation).map_err(|error| { | ||
debug!(?error, "Token is malformed or does not pass validation."); | ||
TokenError::Invalid(error) | ||
}) | ||
} | ||
|
||
async fn ensure_updated_key_store(&self) -> Result<(), TokenError> { | ||
let Some(minimal_interval) = self.minimal_update_interval else { | ||
return Ok(()); | ||
}; | ||
{ | ||
let ks = self.key_store.read().await; | ||
let Some(last_updated) = ks.last_updated else { | ||
return Ok(()); | ||
}; | ||
if last_updated + minimal_interval > Instant::now() { | ||
return Ok(()); | ||
} | ||
} | ||
self.update().await?; | ||
Ok(()) | ||
} | ||
} | ||
|
||
#[derive(Clone, Default)] | ||
pub struct KeyManagerBuilder { | ||
authority: String, | ||
audience: String, | ||
minimal_update_interval: Option<Duration>, | ||
key_store: Arc<RwLock<KeyStore>>, | ||
client: reqwest::Client, | ||
} | ||
|
||
impl KeyManagerBuilder { | ||
/// Create a new KeyManager that can fetch jwks from an authority | ||
/// `authority`: either url of an openid_configuration or a jwks_url | ||
/// `audience`: to be checked against the `aud` claim | ||
pub fn new(authority: String, audience: String) -> Self { | ||
Self { | ||
authority, | ||
audience, | ||
minimal_update_interval: None, | ||
key_store: Arc::new(RwLock::new(KeyStore::default())), | ||
client: reqwest::Client::default(), | ||
} | ||
} | ||
|
||
/// Do not update more often than `interval` | ||
pub fn minimal_update_interval(mut self, interval: u64) -> Self { | ||
self.minimal_update_interval = Some(Duration::from_secs(interval)); | ||
self | ||
} | ||
|
||
/// Enables usage with externally provided `client` | ||
pub fn client(mut self, client: reqwest::Client) -> Self { | ||
self.client = client; | ||
self | ||
} | ||
|
||
/// Fetch updated jwks now | ||
/// Required only if `with_periodical_update` or `with_minimal_update_interval` is not used | ||
pub async fn build(self) -> Result<KeyManager, JwksError> { | ||
let km = KeyManager { | ||
authority: self.authority, | ||
audience: self.audience, | ||
minimal_update_interval: self.minimal_update_interval, | ||
key_store: self.key_store, | ||
client: self.client, | ||
}; | ||
km.update().await?; | ||
Ok(km) | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Instead of constructing an empty keystore and then waiting for the first update interval, it might make more sense to employ a builder pattern, and to fetch the keys synchronously the first time. This should make it easier to expose errors on the first fetch. I think it's much more likely that the first fetch errors (maybe a configuration issue) rather than future ones, so this should make for a better developer experience.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Considered that, wanted simplicity and being free to set it up more freely. I now agree with you. Better to make a more standard builder pattern. Users are free to create it as they wish without using the builder pattern