spetz commented on code in PR #2656:
URL: https://github.com/apache/iggy/pull/2656#discussion_r3017948042


##########
core/sdk/src/clients/consumer.rs:
##########
@@ -569,6 +569,9 @@ impl IggyConsumer {
                     DiagnosticEvent::Connected => {
                         trace!("Connected to the server");
                         joined_consumer_group.store(false, ORDERING);
+                        if !is_consumer_group {

Review Comment:
   Where's this change coming from?



##########
core/server/src/http/jwt/jwks.rs:
##########
@@ -0,0 +1,288 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use dashmap::DashMap;
+use iggy_common::IggyError;
+use jsonwebtoken::DecodingKey;
+use serde::Deserialize;
+use std::hash::Hash;
+use strum::{Display, EnumString};
+
+/// JWK key type enumeration
+#[derive(Debug, Clone, Copy, Display, EnumString, Deserialize, PartialEq, Eq)]
+#[strum(serialize_all = "UPPERCASE")]
+#[serde(rename_all = "UPPERCASE")]
+enum JwkKeyType {
+    /// RSA key type
+    #[strum(serialize = "RSA")]
+    Rsa,
+    /// EC (Elliptic Curve) key type
+    #[strum(serialize = "EC")]
+    Ec,
+}
+
+#[derive(Debug, Deserialize)]
+struct Jwk {
+    kty: JwkKeyType,
+    kid: Option<String>,
+    n: Option<String>,
+    e: Option<String>,
+    x: Option<String>,
+    y: Option<String>,
+    crv: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+struct JwkSet {
+    keys: Vec<Jwk>,
+}
+
+#[derive(Debug, Clone, Hash, Eq, PartialEq)]
+struct CacheKey {
+    issuer: String,
+    kid: String,
+}
+
+#[derive(Debug, Clone)]
+pub struct JwksClient {
+    cache: DashMap<CacheKey, DecodingKey>,
+}
+
+impl Default for JwksClient {
+    fn default() -> Self {
+        Self {
+            cache: DashMap::new(),
+        }
+    }
+}
+
+impl JwksClient {
+    pub async fn get_key(&self, issuer: &str, jwks_url: &str, kid: &str) -> 
Option<DecodingKey> {
+        let cache_key = CacheKey {
+            issuer: issuer.to_string(),
+            kid: kid.to_string(),
+        };
+
+        // try to get from cache first
+        if let Some(key) = self.cache.get(&cache_key) {
+            return Some(key.clone());
+        }
+
+        // fetch and cache if not found
+        if let Ok(key) = self.fetch_and_cache_key(issuer, jwks_url, kid).await 
{
+            return Some(key);
+        }
+
+        None
+    }
+
+    async fn fetch_and_cache_key(
+        &self,
+        issuer: &str,
+        jwks_url: &str,
+        kid: &str,
+    ) -> Result<DecodingKey, IggyError> {
+        if let Err(e) = self.refresh_keys(issuer, jwks_url).await {
+            return Err(IggyError::CannotFetchJwks(format!(
+                "Failed to refresh keys: {}",
+                e
+            )));
+        }
+
+        let cache_key = CacheKey {
+            issuer: issuer.to_string(),
+            kid: kid.to_string(),
+        };
+
+        self.cache
+            .get(&cache_key)
+            .map(|entry| entry.clone())
+            .ok_or(IggyError::InvalidAccessToken)
+    }
+
+    async fn refresh_keys(&self, issuer: &str, jwks_url: &str) -> Result<(), 
IggyError> {
+        let response = ureq::get(jwks_url)
+            .call()
+            .map_err(|_| IggyError::CannotFetchJwks(jwks_url.to_string()))?;
+
+        let body = response
+            .into_string()
+            .map_err(|_| IggyError::CannotFetchJwks(jwks_url.to_string()))?;
+
+        let jwks: JwkSet = serde_json::from_str(&body)
+            .map_err(|e| IggyError::CannotFetchJwks(format!("Failed to parse 
JWKS: {}", e)))?;
+
+        // Collect all current kids from the JWKS response
+        let current_kids: std::collections::HashSet<String> =
+            jwks.keys.iter().filter_map(|key| key.kid.clone()).collect();
+
+        // Remove cached keys for this issuer that are no longer in the JWKS 
response
+        // Security fix: Clean up revoked/rotated keys to prevent accepting 
tokens signed with old keys
+        let keys_to_remove: Vec<CacheKey> = self
+            .cache
+            .iter()
+            .filter(|entry| {
+                entry.key().issuer == issuer && 
!current_kids.contains(&entry.key().kid)
+            })
+            .map(|entry| entry.key().clone())
+            .collect();
+
+        for key in keys_to_remove {
+            self.cache.remove(&key);
+        }
+
+        for key in jwks.keys {
+            if let Some(kid) = key.kid {
+                let decoding_key: DecodingKey = match key.kty {
+                    JwkKeyType::Rsa => {
+                        if let (Some(n), Some(e)) = (key.n.as_deref(), 
key.e.as_deref()) {
+                            DecodingKey::from_rsa_components(n, e).map_err(|e| 
{
+                                IggyError::CannotFetchJwks(format!("Invalid 
RSA key: {}", e))
+                            })?
+                        } else {
+                            continue;
+                        }
+                    }
+                    JwkKeyType::Ec => {
+                        if let (Some(x), Some(y), Some(crv)) =
+                            (key.x.as_deref(), key.y.as_deref(), 
key.crv.as_deref())
+                        {
+                            match crv.to_ascii_uppercase().as_str() {
+                                "P-256" | "P-384" | "P-521" => {

Review Comment:
   Could `crv` (or any other part if makes sense), become an enum (with strum 
macros on top for string helpers etc.) to avoid relying on hardcoded strings?



##########
core/server/src/http/jwt/jwt_manager.rs:
##########
@@ -31,9 +32,27 @@ use iggy_common::UserId;
 use iggy_common::locking::IggyRwLock;
 use iggy_common::locking::IggyRwLockFn;
 use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, TokenData, 
Validation, encode};
+use std::collections::HashMap;
 use std::sync::Arc;
 use tracing::{debug, error, info};
 
+fn normalize_issuer_url(url: &str) -> String {

Review Comment:
   If that's a private fn, let's put it down below (so when you read the code, 
you don't jump to the top of the file), also some unit tests would be helpful.



##########
Cargo.toml:
##########
@@ -285,6 +285,7 @@ trait-variant = "0.1.2"
 tungstenite = "0.29.0"
 twox-hash = { version = "2.1.2", features = ["xxhash32"] }
 ulid = "1.2.1"
+ureq = "2.10"

Review Comment:
   Why do we need yet another HTTP client when reqwest is already there?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to