-
Notifications
You must be signed in to change notification settings - Fork 19
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 jwt_signature_pk_urls
to state
#866
Open
esaminu
wants to merge
5
commits into
develop
Choose a base branch
from
multiple-jwks-urls
base: develop
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 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
1d95dfd
feat: add jwt_signature_pk_urls to state
esaminu 5966538
fix: integration tests value
esaminu 2c2b585
feat: change `jwt_signature_pk_urls` to HashMap
esaminu 53585bd
fix: integration test variable
esaminu 0f072c0
chore: cargo fmt
esaminu 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 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 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 |
---|---|---|
@@ -1,6 +1,8 @@ | ||
use anyhow::{Context, Result}; | ||
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _}; | ||
use jsonwebtoken::{Algorithm, DecodingKey}; | ||
use serde::{Deserialize, Serialize}; | ||
use std::collections::HashMap; | ||
use serde_json::Value; | ||
|
||
use crate::firewall::allowed::OidcProviderList; | ||
use crate::primitives::InternalAccountId; | ||
|
@@ -13,12 +15,12 @@ pub async fn verify_oidc_token( | |
token: &OidcToken, | ||
oidc_providers: Option<&OidcProviderList>, | ||
client: &reqwest::Client, | ||
jwt_signature_pk_url: &str, | ||
jwt_signature_pk_urls: &[String], | ||
) -> anyhow::Result<IdTokenClaims> { | ||
let public_keys = get_pagoda_firebase_public_keys(client, jwt_signature_pk_url) | ||
let public_keys = get_public_keys(client, jwt_signature_pk_urls) | ||
.await | ||
.map_err(|e| anyhow::anyhow!("failed to get Firebase public key: {e}"))?; | ||
tracing::info!("verify_oidc_token firebase public keys: {public_keys:?}"); | ||
.map_err(|e| anyhow::anyhow!("failed to get public keys: {e}"))?; | ||
tracing::info!("verify_oidc_token public keys: {public_keys:?}"); | ||
|
||
let mut last_occured_error = | ||
anyhow::anyhow!("Unexpected error. Firebase public keys not found"); | ||
|
@@ -99,13 +101,69 @@ impl IdTokenClaims { | |
} | ||
} | ||
|
||
pub async fn get_pagoda_firebase_public_keys( | ||
pub async fn get_public_keys( | ||
client: &reqwest::Client, | ||
jwt_signature_pk_url: &str, | ||
) -> anyhow::Result<Vec<String>> { | ||
let response = client.get(jwt_signature_pk_url).send().await?; | ||
let json: HashMap<String, String> = response.json().await?; | ||
Ok(json.into_values().collect()) | ||
jwt_signature_pk_urls: &[String], | ||
) -> Result<Vec<String>> { | ||
let mut all_keys = Vec::new(); | ||
|
||
for url in jwt_signature_pk_urls { | ||
match fetch_and_parse_keys(client, url).await { | ||
Ok(mut keys) => all_keys.append(&mut keys), | ||
Err(e) => tracing::warn!("Failed to fetch keys from {}: {}", url, e), | ||
} | ||
} | ||
|
||
if all_keys.is_empty() { | ||
anyhow::bail!("No valid public keys found from any source"); | ||
} | ||
|
||
Ok(all_keys) | ||
} | ||
|
||
async fn fetch_and_parse_keys(client: &reqwest::Client, url: &str) -> Result<Vec<String>> { | ||
let response = client | ||
.get(url) | ||
.send() | ||
.await | ||
.context("Failed to send request")?; | ||
|
||
let json: Value = response.json().await.context("Failed to parse JSON")?; | ||
|
||
match json { | ||
Value::Object(obj) if obj.contains_key("keys") => parse_jwks_format(&obj), | ||
Value::Object(obj) => parse_firebase_format(&obj), | ||
_ => { | ||
tracing::warn!("Unexpected response format from {}", url); | ||
Ok(vec![]) | ||
} | ||
} | ||
} | ||
|
||
fn parse_jwks_format(obj: &serde_json::Map<String, Value>) -> Result<Vec<String>> { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Let's test this |
||
obj["keys"] | ||
.as_array() | ||
.context("'keys' is not an array")? | ||
.iter() | ||
.filter_map(|key| match (key["n"].as_str(), key["e"].as_str()) { | ||
(Some(n), Some(e)) => Some(format_rsa_key(n, e)), | ||
_ => None, | ||
}) | ||
.collect::<Result<Vec<_>>>() | ||
} | ||
|
||
fn parse_firebase_format(obj: &serde_json::Map<String, Value>) -> Result<Vec<String>> { | ||
Ok(obj | ||
.values() | ||
.filter_map(|value| value.as_str().map(String::from)) | ||
.collect()) | ||
} | ||
|
||
fn format_rsa_key(n: &str, e: &str) -> Result<String> { | ||
Ok(format!( | ||
"-----BEGIN PUBLIC KEY-----\n{}\n-----END PUBLIC KEY-----", | ||
BASE64.encode(format!("{}:{}", n, e)) | ||
)) | ||
} | ||
|
||
#[cfg(test)] | ||
|
@@ -121,10 +179,13 @@ mod tests { | |
|
||
#[tokio::test] | ||
async fn test_get_pagoda_firebase_public_key() { | ||
let url = | ||
"https://www.googleapis.com/robot/v1/metadata/x509/[email protected]"; | ||
let urls = vec![ | ||
"https://www.googleapis.com/robot/v1/metadata/x509/[email protected]".to_string(), | ||
"https://www.googleapis.com/oauth2/v3/certs".to_string(), | ||
]; | ||
let client = reqwest::Client::new(); | ||
let pk = get_pagoda_firebase_public_keys(&client, url).await.unwrap(); | ||
let pk = get_public_keys(&client, &urls).await.unwrap(); | ||
|
||
assert!(!pk.is_empty()); | ||
} | ||
|
||
|
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
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.
It is better to create a map of keys: "provider" -> "[keys]".
Otherwise, somebody will create a token using
provider1
, but verify it with key 2.