You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@james.apache.org by bt...@apache.org on 2025/06/27 13:34:26 UTC

(james-project) branch master updated (340a3becc2 -> acdf99a41e)

This is an automated email from the ASF dual-hosted git repository.

btellier pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git


    from 340a3becc2 [UPDATE] Update kvrocks image 2.12.1
     new 7135565860 [DOCUMENTATION] improve JWT documentation
     new 767aefd506 [ENHANCEMENT] add token expiration test
     new 18a1e9795c [UPGRADE] upgrade jwks-rsa to 0.22.1
     new 3e9a98b148 [UPGRADE] upgrade jjwt to 0.12.6
     new acdf99a41e [ENHANCEMENT] implement DefaultPublicKeyProvider kid calculation using the JWK Thumbprint of the key (RFC 7638)

The 5 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 pom.xml                                            |   2 +-
 server/protocols/jwt/pom.xml                       |   2 +-
 .../apache/james/jwt/DefaultPublicKeyProvider.java |  71 ++++++++++++++
 .../apache/james/jwt/JwksPublicKeyProvider.java    |  21 ++---
 .../org/apache/james/jwt/JwtTokenVerifier.java     | 105 +++++++++++++++------
 .../org/apache/james/jwt/OidcJwtTokenVerifier.java |  30 +-----
 .../org/apache/james/jwt/PublicKeyProvider.java    |  17 ++++
 .../james/jwt/DefaultPublicKeyProviderTest.java    |  36 ++++++-
 .../james/jwt/JwksPublicKeyProviderTest.java       |  16 ++--
 .../org/apache/james/jwt/JwtTokenVerifierTest.java |  53 ++++++++++-
 .../apache/james/jwt/OidcJwtTokenVerifierTest.java |  40 +++++---
 .../james/webadmin/authentication/JwtFilter.java   |   4 +-
 src/site/markdown/server/manage-webadmin.md        |   8 +-
 src/site/xdoc/server/config-webadmin.xml           |  60 +++++++++++-
 14 files changed, 356 insertions(+), 109 deletions(-)


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org


(james-project) 04/05: [UPGRADE] upgrade jjwt to 0.12.6

Posted by bt...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

btellier pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git

commit 3e9a98b148a7500a9b0f877be90037afd6a6921d
Author: Amichai Rothman <am...@amichais.net>
AuthorDate: Wed Jun 25 19:33:42 2025 +0300

    [UPGRADE] upgrade jjwt to 0.12.6
---
 pom.xml                                            |   2 +-
 .../apache/james/jwt/DefaultPublicKeyProvider.java |   9 ++
 .../apache/james/jwt/JwksPublicKeyProvider.java    |  21 ++---
 .../org/apache/james/jwt/JwtTokenVerifier.java     | 105 +++++++++++++++------
 .../org/apache/james/jwt/OidcJwtTokenVerifier.java |  30 +-----
 .../org/apache/james/jwt/PublicKeyProvider.java    |  17 ++++
 .../james/jwt/JwksPublicKeyProviderTest.java       |  16 ++--
 .../apache/james/jwt/OidcJwtTokenVerifierTest.java |  40 +++++---
 8 files changed, 144 insertions(+), 96 deletions(-)

diff --git a/pom.xml b/pom.xml
index 6d1f31ae8b..dc7bd4b7ed 100644
--- a/pom.xml
+++ b/pom.xml
@@ -651,7 +651,7 @@
         <jackson.databind.version>2.19.1</jackson.databind.version>
         <feign.version>13.6</feign.version>
         <feign-form.version>3.8.0</feign-form.version>
-        <jjwt.version>0.11.5</jjwt.version>
+        <jjwt.version>0.12.6</jjwt.version>
         <metrics.version>4.2.32</metrics.version>
         <testcontainers.version>1.21.1</testcontainers.version>
         <es-reporter.version>6.0.0-RC3</es-reporter.version>
diff --git a/server/protocols/jwt/src/main/java/org/apache/james/jwt/DefaultPublicKeyProvider.java b/server/protocols/jwt/src/main/java/org/apache/james/jwt/DefaultPublicKeyProvider.java
index 2d4ecd739c..8627b1526b 100644
--- a/server/protocols/jwt/src/main/java/org/apache/james/jwt/DefaultPublicKeyProvider.java
+++ b/server/protocols/jwt/src/main/java/org/apache/james/jwt/DefaultPublicKeyProvider.java
@@ -20,6 +20,7 @@ package org.apache.james.jwt;
 
 import java.security.PublicKey;
 import java.util.List;
+import java.util.Optional;
 
 import com.google.common.collect.ImmutableList;
 
@@ -45,4 +46,12 @@ public class DefaultPublicKeyProvider implements PublicKeyProvider {
         return keys;
     }
 
+    @Override
+    public Optional<PublicKey> get(String kid) throws MissingOrInvalidKeyException {
+        // TODO: pick a simple or standard way of calculating a unique kid for each public key
+        // that can be calculated by the user when generating the JWT
+        // and calculated or looked up here for comparison.
+        return Optional.empty();
+    }
+
 }
diff --git a/server/protocols/jwt/src/main/java/org/apache/james/jwt/JwksPublicKeyProvider.java b/server/protocols/jwt/src/main/java/org/apache/james/jwt/JwksPublicKeyProvider.java
index 0074981c9f..a9ca63fe53 100644
--- a/server/protocols/jwt/src/main/java/org/apache/james/jwt/JwksPublicKeyProvider.java
+++ b/server/protocols/jwt/src/main/java/org/apache/james/jwt/JwksPublicKeyProvider.java
@@ -38,35 +38,28 @@ import com.google.common.collect.ImmutableList;
 public class JwksPublicKeyProvider implements PublicKeyProvider {
     private static final Logger LOGGER = LoggerFactory.getLogger(JwksPublicKeyProvider.class);
 
-    public static JwksPublicKeyProvider of(URL jwksURL, String kid) {
-        return new JwksPublicKeyProvider(jwksURL, Optional.of(kid));
-    }
-
     public static JwksPublicKeyProvider of(URL jwksURL) {
-        return new JwksPublicKeyProvider(jwksURL, Optional.empty());
+        return new JwksPublicKeyProvider(jwksURL);
     }
 
     private final UrlJwkProvider jwkProvider;
-    private final Optional<String> kid;
 
-    private JwksPublicKeyProvider(URL jwksURL, Optional<String> kid) {
+    private JwksPublicKeyProvider(URL jwksURL) {
         Preconditions.checkNotNull(jwksURL);
-        Preconditions.checkNotNull(kid);
         this.jwkProvider = new UrlJwkProvider(jwksURL);
-        this.kid = kid;
     }
 
     @Override
     public List<PublicKey> get() throws MissingOrInvalidKeyException {
-        return kid.map(this::get)
-            .orElse(getAllFromProvider());
+        return getAllFromProvider();
     }
 
-    public List<PublicKey> get(String kid) throws MissingOrInvalidKeyException {
+    @Override
+    public Optional<PublicKey> get(String kid) throws MissingOrInvalidKeyException {
         try {
-            return ImmutableList.of(jwkProvider.get(kid).getPublicKey());
+            return Optional.of(jwkProvider.get(kid).getPublicKey());
         } catch (SigningKeyNotFoundException notFoundException) {
-            return ImmutableList.of();
+            return Optional.empty();
         } catch (JwkException e) {
             LOGGER.error("Can't get publicKeys has kid = {} from jwksURL.", kid, e);
             throw new MissingOrInvalidKeyException();
diff --git a/server/protocols/jwt/src/main/java/org/apache/james/jwt/JwtTokenVerifier.java b/server/protocols/jwt/src/main/java/org/apache/james/jwt/JwtTokenVerifier.java
index 878a8a6c76..ae197d8e68 100644
--- a/server/protocols/jwt/src/main/java/org/apache/james/jwt/JwtTokenVerifier.java
+++ b/server/protocols/jwt/src/main/java/org/apache/james/jwt/JwtTokenVerifier.java
@@ -18,43 +18,75 @@
  ****************************************************************/
 package org.apache.james.jwt;
 
-import java.security.PublicKey;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.security.Key;
 import java.util.List;
+import java.util.Objects;
 import java.util.Optional;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.annotations.VisibleForTesting;
 import com.google.common.collect.ImmutableList;
 
 import io.jsonwebtoken.Claims;
-import io.jsonwebtoken.CompressionCodecResolver;
 import io.jsonwebtoken.Jws;
 import io.jsonwebtoken.JwtException;
 import io.jsonwebtoken.JwtParser;
 import io.jsonwebtoken.Jwts;
+import io.jsonwebtoken.Locator;
 import io.jsonwebtoken.MalformedJwtException;
-import io.jsonwebtoken.impl.compression.DefaultCompressionCodecResolver;
+import io.jsonwebtoken.io.CompressionAlgorithm;
 
 public class JwtTokenVerifier {
-    private static final CompressionCodecResolver DEFAULT_COMPRESSION_CODEC_RESOLVER = new DefaultCompressionCodecResolver();
-    private static final CompressionCodecResolver SECURE_COMPRESSION_CODEC_RESOLVER = header -> {
-        if (Optional.ofNullable(header.getCompressionAlgorithm()).isPresent()) {
-            throw new RuntimeException("Rejecting a ZIP JWT. Usage of ZIPPED JWT can result in " +
-                "excessive memory usage with malicious JWT tokens. To activate support for ZIPPed" +
-                "JWT please run James with the -Djames.jwt.zip.allow=true system property.");
-        }
-        return DEFAULT_COMPRESSION_CODEC_RESOLVER.resolveCompressionCodec(header);
-    };
-    private static final boolean allowZipJWT = Optional.ofNullable(System.getProperty("james.jwt.zip.allow"))
+    static boolean allowZipJWT = Optional.ofNullable(System.getProperty("james.jwt.zip.allow"))
         .map(Boolean::parseBoolean)
         .orElse(false);
-    @VisibleForTesting
-    static CompressionCodecResolver CONFIGURED_COMPRESSION_CODEC_RESOLVER = Optional.of(allowZipJWT)
-        .filter(b -> b)
-        .map(any -> DEFAULT_COMPRESSION_CODEC_RESOLVER)
-        .orElse(SECURE_COMPRESSION_CODEC_RESOLVER);
+
+    /**
+     * A CompressionAlgorithm that delegates to another compression algorithm
+     * if compression is allowed, or throws exceptions if not.
+     */
+    private static class SecureCompressionAlgorithm implements CompressionAlgorithm {
+        String id;
+        CompressionAlgorithm delegate;
+
+        public SecureCompressionAlgorithm(String id, CompressionAlgorithm delegate) {
+            this.id = id;
+            this.delegate = delegate;
+        }
+
+        private void validate() {
+            if (!allowZipJWT) {
+                throw new RuntimeException("Rejecting a ZIP JWT. Usage of ZIPPED JWT can result in " +
+                    "excessive memory usage with malicious JWT tokens. To activate support for ZIPPed" +
+                    "JWT please run James with the -Djames.jwt.zip.allow=true system property.");
+            }
+        }
+
+        @Override
+        public String getId() {
+            return id;
+        }
+
+        @Override
+        public OutputStream compress(OutputStream out) {
+            validate();
+            return delegate.compress(out);
+        }
+
+        @Override
+        public InputStream decompress(InputStream in) {
+            validate();
+            return delegate.decompress(in);
+        }
+    }
+
+    // wrap all supported compression algorithms with 'secure' ones that throw exception if disabled
+    private static final List<SecureCompressionAlgorithm> SECURE_COMPRESSION_ALGORITHMS =
+        Jwts.ZIP.get().values().stream().map(c -> new SecureCompressionAlgorithm(c.getId(), c)).toList();
 
     public interface Factory {
         JwtTokenVerifier create();
@@ -67,12 +99,19 @@ public class JwtTokenVerifier {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenVerifier.class);
 
+    private final JwtParser kidJwtParser;
     private final List<JwtParser> jwtParsers;
 
     public JwtTokenVerifier(PublicKeyProvider pubKeyProvider) {
+        // one parser that performs key lookup by kid
+        this.kidJwtParser = toImmutableJwtParser(jwtHeaders -> {
+            String kid = Objects.requireNonNull((String)jwtHeaders.get("kid"));
+            return pubKeyProvider.get(kid).orElse(null);
+        });
+        // a list of parsers, one for each of the provider's keys
         this.jwtParsers = pubKeyProvider.get()
             .stream()
-            .map(this::toImmutableJwtParser)
+            .map(key -> toImmutableJwtParser(jwtHeaders -> key))
             .collect(ImmutableList.toImmutableList());
     }
 
@@ -82,22 +121,28 @@ public class JwtTokenVerifier {
     }
 
     public <T> Optional<T> verifyAndExtractClaim(String token, String claimName, Class<T> returnType) {
-        return jwtParsers.stream()
-            .flatMap(parser -> verifyAndExtractClaim(token, claimName, returnType, parser).stream())
-            .findFirst();
+        try {
+            // if the token contains a kid, verify only with the corresponding key (or fail)
+            return verifyAndExtractClaim(token, claimName, returnType, kidJwtParser);
+        } catch (NullPointerException npe) { // our own key locator throws NPE when there is no kid
+            // if token does not specify kid, fallback to trying all keys
+            return jwtParsers.stream()
+                .flatMap(parser -> verifyAndExtractClaim(token, claimName, returnType, parser).stream())
+                .findFirst();
+        }
     }
 
     private <T> Optional<T> verifyAndExtractClaim(String token, String claimName, Class<T> returnType, JwtParser parser) {
         try {
-            Jws<Claims> jws = parser.parseClaimsJws(token);
+            Jws<Claims> jws = parser.parseSignedClaims(token);
             T claim = jws
-                .getBody()
+                .getPayload()
                 .get(claimName, returnType);
             if (claim == null) {
                 throw new MalformedJwtException("'" + claimName + "' field in token is mandatory");
             }
             return Optional.of(claim);
-        } catch (JwtException e) {
+        } catch (JwtException e) { // also if kid was given but our locator didn't find the corresponding key
             LOGGER.info("Failed Jwt verification", e);
             return Optional.empty();
         }
@@ -114,10 +159,10 @@ public class JwtTokenVerifier {
         }
     }
 
-    private JwtParser toImmutableJwtParser(PublicKey publicKey) {
-        return Jwts.parserBuilder()
-            .setSigningKey(publicKey)
-            .setCompressionCodecResolver(CONFIGURED_COMPRESSION_CODEC_RESOLVER)
+    private JwtParser toImmutableJwtParser(Locator<Key> keyLocator) {
+        return Jwts.parser()
+            .keyLocator(keyLocator)
+            .zip().add(SECURE_COMPRESSION_ALGORITHMS).and()
             .build();
     }
 }
diff --git a/server/protocols/jwt/src/main/java/org/apache/james/jwt/OidcJwtTokenVerifier.java b/server/protocols/jwt/src/main/java/org/apache/james/jwt/OidcJwtTokenVerifier.java
index 35ba364dca..63124ca253 100644
--- a/server/protocols/jwt/src/main/java/org/apache/james/jwt/OidcJwtTokenVerifier.java
+++ b/server/protocols/jwt/src/main/java/org/apache/james/jwt/OidcJwtTokenVerifier.java
@@ -26,40 +26,14 @@ import org.apache.james.jwt.introspection.IntrospectionEndpoint;
 import org.apache.james.jwt.introspection.TokenIntrospectionResponse;
 import org.reactivestreams.Publisher;
 
-import io.jsonwebtoken.Claims;
-import io.jsonwebtoken.Header;
-import io.jsonwebtoken.Jwt;
-import io.jsonwebtoken.JwtException;
-import io.jsonwebtoken.Jwts;
 import reactor.core.publisher.Mono;
 
 public class OidcJwtTokenVerifier {
     public static final CheckTokenClient CHECK_TOKEN_CLIENT = new DefaultCheckTokenClient();
 
     public static Optional<String> verifySignatureAndExtractClaim(String jwtToken, URL jwksURL, String claimName) {
-        Optional<String> unverifiedClaim = getClaimWithoutSignatureVerification(jwtToken, "kid");
-        PublicKeyProvider jwksPublicKeyProvider = unverifiedClaim
-            .map(kidValue -> JwksPublicKeyProvider.of(jwksURL, kidValue))
-            .orElse(JwksPublicKeyProvider.of(jwksURL));
-        return new JwtTokenVerifier(jwksPublicKeyProvider).verifyAndExtractClaim(jwtToken, claimName, String.class);
-    }
-
-    public static <T> Optional<T> getClaimWithoutSignatureVerification(String token, String claimName) {
-        int signatureIndex = token.lastIndexOf('.');
-        if (signatureIndex <= 0) {
-            return Optional.empty();
-        }
-        String nonSignedToken = token.substring(0, signatureIndex + 1);
-        try {
-            Jwt<Header, Claims> headerClaims = Jwts.parserBuilder().build().parseClaimsJwt(nonSignedToken);
-            T claim = (T) headerClaims.getHeader().get(claimName);
-            if (claim == null) {
-                return Optional.empty();
-            }
-            return Optional.of(claim);
-        } catch (JwtException e) {
-            return Optional.empty();
-        }
+        return new JwtTokenVerifier(JwksPublicKeyProvider.of(jwksURL))
+            .verifyAndExtractClaim(jwtToken, claimName, String.class);
     }
 
     public static Publisher<String> verifyWithIntrospection(String jwtToken, URL jwksURL, String claimName, IntrospectionEndpoint introspectionEndpoint) {
diff --git a/server/protocols/jwt/src/main/java/org/apache/james/jwt/PublicKeyProvider.java b/server/protocols/jwt/src/main/java/org/apache/james/jwt/PublicKeyProvider.java
index c87f25bfe2..b5cd772771 100644
--- a/server/protocols/jwt/src/main/java/org/apache/james/jwt/PublicKeyProvider.java
+++ b/server/protocols/jwt/src/main/java/org/apache/james/jwt/PublicKeyProvider.java
@@ -21,7 +21,24 @@ package org.apache.james.jwt;
 
 import java.security.PublicKey;
 import java.util.List;
+import java.util.Optional;
 
 public interface PublicKeyProvider {
+
+    /**
+     * Returns all keys managed by this provider.
+     *
+     * @return all keys managed by this provider
+     * @throws MissingOrInvalidKeyException if an error occurred while getting the keys
+     */
     List<PublicKey> get() throws MissingOrInvalidKeyException;
+
+    /**
+     * Returns the key corresponding to the given kid.
+     *
+     * @param kid the kid value
+     * @return the key corresponding to the given kid, or empty if not found
+     * @throws MissingOrInvalidKeyException if an error occurred while getting the key
+     */
+    Optional<PublicKey> get(String kid) throws MissingOrInvalidKeyException;
 }
diff --git a/server/protocols/jwt/src/test/java/org/apache/james/jwt/JwksPublicKeyProviderTest.java b/server/protocols/jwt/src/test/java/org/apache/james/jwt/JwksPublicKeyProviderTest.java
index 68da3f5845..7351d4bcf3 100644
--- a/server/protocols/jwt/src/test/java/org/apache/james/jwt/JwksPublicKeyProviderTest.java
+++ b/server/protocols/jwt/src/test/java/org/apache/james/jwt/JwksPublicKeyProviderTest.java
@@ -29,7 +29,6 @@ import java.net.URL;
 import java.nio.charset.StandardCharsets;
 import java.security.PublicKey;
 import java.security.interfaces.RSAPublicKey;
-import java.util.List;
 
 import org.assertj.core.api.SoftAssertions;
 import org.junit.jupiter.api.BeforeEach;
@@ -93,18 +92,17 @@ class JwksPublicKeyProviderTest {
 
     @Test
     void getShouldSuccessWhenKeyProvided() {
-        PublicKeyProvider testee = JwksPublicKeyProvider.of(getJwksURL(), "wu-9VZEr0gHF986PYPVzvU-5IP1q26EzzQVK_sjG29Q");
-        List<PublicKey> publicKeys = testee.get();
+        PublicKeyProvider testee = JwksPublicKeyProvider.of(getJwksURL());
+        PublicKey publicKey = testee.get("wu-9VZEr0gHF986PYPVzvU-5IP1q26EzzQVK_sjG29Q").get();
         SoftAssertions.assertSoftly(softly -> {
-            softly.assertThat(publicKeys).hasSize(1);
-            softly.assertThat(publicKeys.get(0)).isInstanceOf(RSAPublicKey.class);
+            softly.assertThat(publicKey).isInstanceOf(RSAPublicKey.class);
         });
     }
 
     @Test
     void getShouldReturnEmptyWhenKeyNotProvided() {
-        PublicKeyProvider testee = JwksPublicKeyProvider.of(getJwksURL(), "notfound");
-        assertThat(testee.get()).isEmpty();
+        PublicKeyProvider testee = JwksPublicKeyProvider.of(getJwksURL());
+        assertThat(testee.get("notfound")).isEmpty();
     }
 
     @Test
@@ -114,8 +112,8 @@ class JwksPublicKeyProviderTest {
             .respond(HttpResponse.response().withStatusCode(200)
                 .withBody("invalid body", StandardCharsets.UTF_8));
 
-        PublicKeyProvider testee = JwksPublicKeyProvider.of(new URI(String.format("http://127.0.0.1:%s/invalid", mockServer.getLocalPort())).toURL(),
-            "wu-9VZEr0gHF986PYPVzvU-5IP1q26EzzQVK_sjG29Q");
+        PublicKeyProvider testee = JwksPublicKeyProvider.of(
+            new URI(String.format("http://127.0.0.1:%s/invalid", mockServer.getLocalPort())).toURL());
         assertThatThrownBy(testee::get)
             .isInstanceOf(MissingOrInvalidKeyException.class);
     }
diff --git a/server/protocols/jwt/src/test/java/org/apache/james/jwt/OidcJwtTokenVerifierTest.java b/server/protocols/jwt/src/test/java/org/apache/james/jwt/OidcJwtTokenVerifierTest.java
index 9446aa69b5..0c9c1f597a 100644
--- a/server/protocols/jwt/src/test/java/org/apache/james/jwt/OidcJwtTokenVerifierTest.java
+++ b/server/protocols/jwt/src/test/java/org/apache/james/jwt/OidcJwtTokenVerifierTest.java
@@ -30,6 +30,11 @@ import java.net.URI;
 import java.net.URISyntaxException;
 import java.net.URL;
 import java.nio.charset.StandardCharsets;
+import java.security.KeyFactory;
+import java.security.NoSuchAlgorithmException;
+import java.security.PrivateKey;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.PKCS8EncodedKeySpec;
 import java.util.Optional;
 
 import org.apache.james.jwt.introspection.IntrospectionEndpoint;
@@ -43,10 +48,8 @@ import org.mockserver.integration.ClientAndServer;
 import org.mockserver.model.HttpRequest;
 import org.mockserver.model.HttpResponse;
 
-import io.jsonwebtoken.CompressionCodecs;
 import io.jsonwebtoken.Jwts;
-import io.jsonwebtoken.SignatureAlgorithm;
-import io.jsonwebtoken.impl.compression.DefaultCompressionCodecResolver;
+import io.jsonwebtoken.io.Decoders;
 import reactor.core.publisher.Mono;
 
 class OidcJwtTokenVerifierTest {
@@ -93,12 +96,18 @@ class OidcJwtTokenVerifierTest {
         });
     }
 
+    private static PrivateKey toPrivateKey(String base64Key) throws NoSuchAlgorithmException, InvalidKeySpecException {
+        byte[] keyBytes = Decoders.BASE64.decode(base64Key.replace("\n", ""));
+        KeyFactory kf = KeyFactory.getInstance("RSA"); // or "EC" or whatever
+        return kf.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
+    }
+
     @Test
-    void shouldRejectZippedJWTByDefault() {
+    void shouldRejectZippedJWTByDefault() throws NoSuchAlgorithmException, InvalidKeySpecException {
         String jws = Jwts.builder()
             .claim("kid", "a".repeat(100))
-            .compressWith(CompressionCodecs.DEFLATE)
-            .signWith(SignatureAlgorithm.HS256, OidcTokenFixture.PRIVATE_KEY_BASE64.replace("\n", ""))
+            .compressWith(Jwts.ZIP.DEF)
+            .signWith(toPrivateKey(OidcTokenFixture.PRIVATE_KEY_BASE64), Jwts.SIG.RS256)
             .compact();
 
         assertThatThrownBy(() -> OidcJwtTokenVerifier.verifySignatureAndExtractClaim(jws, getJwksURL(), "kid"))
@@ -107,17 +116,21 @@ class OidcJwtTokenVerifierTest {
     }
 
     @Test
-    void shouldAcceptZippedJWTWhenConfigured() {
+    void shouldAcceptZippedJWTWhenConfigured() throws NoSuchAlgorithmException, InvalidKeySpecException {
         String jws = Jwts.builder()
             .claim("kid", "a".repeat(100))
-            .compressWith(CompressionCodecs.DEFLATE)
-            .signWith(SignatureAlgorithm.HS256, OidcTokenFixture.PRIVATE_KEY_BASE64.replace("\n", ""))
+            .compressWith(Jwts.ZIP.DEF)
+            .signWith(toPrivateKey(OidcTokenFixture.PRIVATE_KEY_BASE64), Jwts.SIG.RS256)
             .compact();
 
-        JwtTokenVerifier.CONFIGURED_COMPRESSION_CODEC_RESOLVER = new DefaultCompressionCodecResolver();
-
-        assertThatCode(() -> OidcJwtTokenVerifier.verifySignatureAndExtractClaim(jws, getJwksURL(), "kid"))
-            .doesNotThrowAnyException();
+        boolean prev = JwtTokenVerifier.allowZipJWT;
+        JwtTokenVerifier.allowZipJWT = true;
+        try {
+            assertThatCode(() -> OidcJwtTokenVerifier.verifySignatureAndExtractClaim(jws, getJwksURL(), "kid"))
+                .doesNotThrowAnyException();
+        } finally {
+            JwtTokenVerifier.allowZipJWT = prev;
+        }
     }
 
     @Test
@@ -132,7 +145,6 @@ class OidcJwtTokenVerifierTest {
             .isEmpty();
     }
 
-
     @Test
     void verifyAndClaimShouldReturnEmptyWhenInvalidToken() {
         assertThat(OidcJwtTokenVerifier.verifySignatureAndExtractClaim(OidcTokenFixture.INVALID_TOKEN, getJwksURL(), "email_address"))


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org


(james-project) 02/05: [ENHANCEMENT] add token expiration test

Posted by bt...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

btellier pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git

commit 767aefd50676170ee7e4b19b6ae90f090d3bcbe5
Author: Amichai Rothman <am...@amichais.net>
AuthorDate: Sun Jun 15 18:30:32 2025 +0300

    [ENHANCEMENT] add token expiration test
---
 .../org/apache/james/jwt/JwtTokenVerifierTest.java | 53 +++++++++++++++++++++-
 .../james/webadmin/authentication/JwtFilter.java   |  4 +-
 2 files changed, 54 insertions(+), 3 deletions(-)

diff --git a/server/protocols/jwt/src/test/java/org/apache/james/jwt/JwtTokenVerifierTest.java b/server/protocols/jwt/src/test/java/org/apache/james/jwt/JwtTokenVerifierTest.java
index 8e6e0b1e9a..f9e7f32005 100644
--- a/server/protocols/jwt/src/test/java/org/apache/james/jwt/JwtTokenVerifierTest.java
+++ b/server/protocols/jwt/src/test/java/org/apache/james/jwt/JwtTokenVerifierTest.java
@@ -47,7 +47,19 @@ class JwtTokenVerifierTest {
             "NZ3DUR3lfBFbvYGQyFyib+e4MY1yWkj3sumMl1wdUB4lKLHLIRv9X1xCqvbSHEtq\n" +
             "zoZF4vgBYx0VmuJslwIDAQAB\n" +
             "-----END PUBLIC KEY-----";
-    
+
+    public static final String PRIVATE_PEM_KEY_EC = // use to generate tokens for future tests
+            "-----BEGIN EC PRIVATE KEY-----\n" +
+            "MHcCAQEEIL3oeBhM7D1DttaWfGUOsurEuFG1XcN1JDLijqTOcTuqoAoGCCqGSM49\n" +
+            "AwEHoUQDQgAE35E+lPVu46nAdTySey4ilUxO76RGG62SxqAdZb8B57t1ShzKC8U8\n" +
+            "qG+azeT9edpTao7dSRmgK3V83GAPAI88Ag==\n" +
+            "-----END EC PRIVATE KEY-----\n";
+    public static final String PUBLIC_PEM_KEY_EC =
+            "-----BEGIN PUBLIC KEY-----\n" +
+            "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE35E+lPVu46nAdTySey4ilUxO76RG\n" +
+            "G62SxqAdZb8B57t1ShzKC8U8qG+azeT9edpTao7dSRmgK3V83GAPAI88Ag==\n" +
+            "-----END PUBLIC KEY-----\n";
+
     private static final String VALID_TOKEN_WITHOUT_ADMIN = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIn0.T04BTk" +
             "LXkJj24coSZkK13RfG25lpvmSl2MJ7N10KpBk9_-95EGYZdog-BDAn3PJzqVw52z-Bwjh4VOj1-j7cURu0cT4jXehhUrlCxS4n7QHZD" +
             "N_bsEYGu7KzjWTpTsUiHe-rN7izXVFxDGG1TGwlmBCBnPW-EFCf9ylUsJi0r2BKNdaaPRfMIrHptH1zJBkkUziWpBN1RNLjmvlAUf49" +
@@ -59,17 +71,32 @@ class JwtTokenVerifierTest {
         "4H0a6L87BYppxVW701zaZ6dNxRMvHnjLBBWnPsC2B0rkkr2hEL2zfz7sb-iNGV-J4ICx97t8-TfQ5rz3VOX0FwdusPL_rJtmlGEGRivPkR6_aBe1" +
         "kQnvMlwpqF_3ox58EUqYJk6lK_6rjKEV3Xfre31IMpuQUy6c7TKc95sL2-13cknelTierBEmZ00RzTtv9SHIEfzZTfaUK2Wm0PvnQjmU2nIdEvU" +
         "EqE-jrM3yYXcQzoO-YTQnEhdl-iqbCfmEpYkl2Bx3eIq7gRxxnr7BPsX6HrCB0w";
+
     private static final String VALID_TOKEN_ADMIN_FALSE = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhZG1pbkBvcGVu" +
         "LXBhYXMub3JnIiwiYWRtaW4iOmZhbHNlLCJpYXQiOjE0ODkwNDA4Njd9.reQc3DiVvbQHF08oW1qOUyDJyv3tfzDNk8jhVZequiCdOI9vXnRlOe" +
         "-yDYktd4WT8MYhqY7MgS-wR0vO9jZFv8ZCgd_MkKCvCO0HmMjP5iQPZ0kqGkgWUH7X123tfR38MfbCVAdPDba-K3MfkogV1xvDhlkPScFr_6MxE" +
         "xtedOK2JnQZn7t9sUzSrcyjWverm7gZkPptkIVoS8TsEeMMME5vFXe_nqkEG69q3kuBUm_33tbR5oNS0ZGZKlG9r41lHBjyf9J1xN4UYV8n866d" +
         "a7RPPCzshIWUtO0q9T2umWTnp-6OnOdBCkndrZmRR6pPxsD5YL0_77Wq8KT_5__fGA";
+
+    private static final String VALID_TOKEN_NO_EXPIRATION = "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyQGV4YW" +
+        "1wbGUuY29tIiwiYWRtaW4iOnRydWV9.YSIWBGBcNv0-9ztJI2toAY5c6lgUo445l4C4smDlwVxIqe7N3lmgpwvq1BPI7NQFtNrJ6M2ZzMTK" +
+        "DUr1SlV0fQ";
+
+    private static final String VALID_TOKEN_EXPIRED = "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyQGV4YW1wbGUu" +
+        "Y29tIiwiYWRtaW4iOnRydWUsImV4cCI6OTQ2Njg0ODAwfQ.j12z_REiEdMAgmZT4_XTZ-bsn8Yh-61f2ibraLU-7Pp9JTKPsmr63Ah5c5Zn" +
+        "gnqVwBKE6wuNPNnIh3E3GqA5Yg";
+
+    private static final String VALID_TOKEN_NOT_EXPIRED = "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyQGV4YW1w" +
+        "bGUuY29tIiwiYWRtaW4iOnRydWUsImV4cCI6NDA3MDkwODgwMH0.BNa7bF8twlRycfz_8K8IPLd-0kNPAIe1DozKtibX6JR1PIpaHlRJT1U" +
+        "NdNc7Xw-qFJrLt8aepNN7Bu7C-EjKJQ";
+
     // Generated on https://jwt.io/
     private static final String TOKEN_NONE_ALGORITHM = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiIxMjM0NTY3ODkwIiwi" +
         "bmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.2XijNOVI9LXP9nWf-oj2SEWWNlcwmxzlQNGK1WdaWcQ";
     private static final String TOKEN_NONE_ALGORITHM_NO_SIGNATURE = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiIxMjM0NTY3ODkwIiwi" +
         "bmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.";
     private JwtTokenVerifier sut;
+    private JwtTokenVerifier sutEc;
 
     @BeforeAll
     static void init() {
@@ -80,6 +107,9 @@ class JwtTokenVerifierTest {
     void setup() {
         DefaultPublicKeyProvider pubKeyProvider = new DefaultPublicKeyProvider(new JwtConfiguration(ImmutableList.of(PUBLIC_PEM_KEY)), new PublicKeyReader());
         sut = new JwtTokenVerifier(pubKeyProvider);
+
+        pubKeyProvider = new DefaultPublicKeyProvider(new JwtConfiguration(ImmutableList.of(PUBLIC_PEM_KEY_EC)), new PublicKeyReader());
+        sutEc = new JwtTokenVerifier(pubKeyProvider);
     }
 
     @Test
@@ -220,4 +250,25 @@ class JwtTokenVerifierTest {
         assertThat(authorized).isFalse();
     }
 
+    @Test
+    void verifyShouldWorkIfNoExpiration() {
+        boolean authorized = sutEc.verifyAndExtractLogin(VALID_TOKEN_NO_EXPIRATION).isPresent();
+
+        assertThat(authorized).isTrue();
+    }
+
+    @Test
+    void verifyShouldWorkIfNotExpired() {
+        boolean authorized = sutEc.verifyAndExtractLogin(VALID_TOKEN_NOT_EXPIRED).isPresent();
+
+        assertThat(authorized).isTrue();
+    }
+
+    @Test
+    void verifyShouldFailIfExpired() {
+        boolean authorized = sutEc.verifyAndExtractLogin(VALID_TOKEN_EXPIRED).isPresent();
+
+        assertThat(authorized).isFalse();
+    }
+
 }
diff --git a/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/authentication/JwtFilter.java b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/authentication/JwtFilter.java
index 43bb410775..9464e8235f 100644
--- a/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/authentication/JwtFilter.java
+++ b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/authentication/JwtFilter.java
@@ -52,7 +52,7 @@ public class JwtFilter implements AuthenticationFilter {
                 .map(value -> value.substring(AUTHORIZATION_HEADER_PREFIX.length()));
 
             checkHeaderPresent(bearer);
-            String login = retrieveUser(bearer);
+            String login = retrieveUser(bearer); // includes standard token verification: format, signature, expiration, etc.
             checkIsAdmin(bearer);
 
             request.attribute(LOGIN, login);
@@ -67,7 +67,7 @@ public class JwtFilter implements AuthenticationFilter {
 
     private String retrieveUser(Optional<String> bearer) {
         return jwtTokenVerifier.verifyAndExtractLogin(bearer.get())
-            .orElseThrow(() -> halt(HttpStatus.UNAUTHORIZED_401, "Invalid Bearer header."));
+            .orElseThrow(() -> halt(HttpStatus.UNAUTHORIZED_401, "Invalid token."));
     }
 
     private void checkIsAdmin(Optional<String> bearer) {


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org


(james-project) 05/05: [ENHANCEMENT] implement DefaultPublicKeyProvider kid calculation using the JWK Thumbprint of the key (RFC 7638)

Posted by bt...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

btellier pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git

commit acdf99a41ed43d0bd05dea9bd469b48c227500e1
Author: Amichai Rothman <am...@amichais.net>
AuthorDate: Wed Jun 25 19:39:02 2025 +0300

    [ENHANCEMENT] implement DefaultPublicKeyProvider kid calculation using the JWK Thumbprint of the key (RFC 7638)
---
 .../apache/james/jwt/DefaultPublicKeyProvider.java | 70 ++++++++++++++++++++--
 .../james/jwt/DefaultPublicKeyProviderTest.java    | 36 ++++++++++-
 src/site/xdoc/server/config-webadmin.xml           |  4 +-
 3 files changed, 104 insertions(+), 6 deletions(-)

diff --git a/server/protocols/jwt/src/main/java/org/apache/james/jwt/DefaultPublicKeyProvider.java b/server/protocols/jwt/src/main/java/org/apache/james/jwt/DefaultPublicKeyProvider.java
index 8627b1526b..0085645f6f 100644
--- a/server/protocols/jwt/src/main/java/org/apache/james/jwt/DefaultPublicKeyProvider.java
+++ b/server/protocols/jwt/src/main/java/org/apache/james/jwt/DefaultPublicKeyProvider.java
@@ -18,7 +18,14 @@
  ****************************************************************/
 package org.apache.james.jwt;
 
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
 import java.security.PublicKey;
+import java.security.interfaces.ECPublicKey;
+import java.security.interfaces.EdECPublicKey;
+import java.security.interfaces.RSAPublicKey;
+import java.util.Base64;
 import java.util.List;
 import java.util.Optional;
 
@@ -48,10 +55,65 @@ public class DefaultPublicKeyProvider implements PublicKeyProvider {
 
     @Override
     public Optional<PublicKey> get(String kid) throws MissingOrInvalidKeyException {
-        // TODO: pick a simple or standard way of calculating a unique kid for each public key
-        // that can be calculated by the user when generating the JWT
-        // and calculated or looked up here for comparison.
-        return Optional.empty();
+        return get().stream().filter(k -> computeKid(k).equals(kid)).findFirst();
     }
 
+    protected static byte[] unpad(byte[] bytes) {
+        return (bytes.length > 1 && bytes[0] == 0x00 && (bytes[1] & 0x80) != 0)
+            ? java.util.Arrays.copyOfRange(bytes, 1, bytes.length)
+            : bytes;
+    }
+
+    protected static String b64u(byte[] bytes) {
+        return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
+    }
+
+    protected static String toCanonicalJwkJson(PublicKey key) {
+        // json, only required keys, lexicographically sorted keys,
+        // no whitespace, UTF8, base64url encoded unmodified raw values
+        if (key instanceof RSAPublicKey rsa) {
+            String n = b64u(unpad(rsa.getModulus().toByteArray()));
+            String e = b64u(unpad(rsa.getPublicExponent().toByteArray()));
+            return String.format("{\"e\":\"%s\",\"kty\":\"RSA\",\"n\":\"%s\"}", e, n);
+        }
+
+        if (key instanceof ECPublicKey ec) {
+            String crv = "P-" + ec.getParams().getCurve().getField().getFieldSize();
+            String x = b64u(unpad(ec.getW().getAffineX().toByteArray()));
+            String y = b64u(unpad(ec.getW().getAffineY().toByteArray()));
+            return String.format("{\"crv\":\"%s\",\"kty\":\"EC\",\"x\":\"%s\",\"y\":\"%s\"}", crv, x, y);
+        }
+
+        // ED key bits are more complicated to get from BigInteger
+        // (reversing, adding x bit, adding/removing padding to exact size,
+        // but we don't know the key size itself form the java instance)
+        // so we do very basic ASN.1 parsing ourselves to find the
+        // position and length of the raw bits (which differ in different curves)
+        if (key instanceof EdECPublicKey ed) {
+            String crv = ed.getParams().getName();
+            byte[] encoded = key.getEncoded(); // SubjectPublicKeyInfo structure, encoded using ASN.1 DER
+            int pos = 2; // skip outer SEQUENCE header
+            pos += 2 + encoded[pos + 1] + 1; // skip AlgorithmIdentifier SEQUENCE and BIT STRING tag (0x03)
+            int len = encoded[pos++]; // BIT STRING length (assume short form - less than 128 raw bytes)
+            pos++; // skip unused bits byte
+            byte[] raw = new byte[len - 1];
+            System.arraycopy(encoded, pos, raw, 0, raw.length);
+            String x = b64u(raw);
+            return String.format("{\"crv\":\"%s\",\"kty\":\"OKP\",\"x\":\"%s\"}", crv, x);
+        }
+
+        throw new IllegalArgumentException("Unsupported key algorithm: " + key.getAlgorithm());
+    }
+
+    public static String computeKid(PublicKey key) {
+        // calculate the JWK Thumbprint of the key (RFC 7638),
+        // which is base64url(sha256(canonicalJson(jwk(key))))
+        String jwk = toCanonicalJwkJson(key);
+        byte[] jwkBytes = jwk.getBytes(StandardCharsets.UTF_8);
+        try {
+            return b64u(MessageDigest.getInstance("SHA-256").digest(jwkBytes));
+        } catch (NoSuchAlgorithmException e) {
+            throw new RuntimeException("SHA-256 not available", e);
+        }
+    }
 }
diff --git a/server/protocols/jwt/src/test/java/org/apache/james/jwt/DefaultPublicKeyProviderTest.java b/server/protocols/jwt/src/test/java/org/apache/james/jwt/DefaultPublicKeyProviderTest.java
index 4c59934cb3..13e743fb75 100644
--- a/server/protocols/jwt/src/test/java/org/apache/james/jwt/DefaultPublicKeyProviderTest.java
+++ b/server/protocols/jwt/src/test/java/org/apache/james/jwt/DefaultPublicKeyProviderTest.java
@@ -63,4 +63,38 @@ class DefaultPublicKeyProviderTest {
 
         assertThat(sut.get()).isEmpty();
     }
-}
\ No newline at end of file
+
+    private static void testKid(String exptected, String pem) {
+        JwtConfiguration configWithPEMKey = new JwtConfiguration(ImmutableList.of(pem));
+        PublicKeyProvider sut = new DefaultPublicKeyProvider(configWithPEMKey, new PublicKeyReader());
+        String kid = DefaultPublicKeyProvider.computeKid(sut.get().get(0));
+        assertThat(kid).isEqualTo(exptected);
+    }
+
+    @Test
+    void computeKidShouldComputeJWKThumbprintCorrectly() {
+        testKid("2iUdFiYTvwSzAzJuMRwvr70CLKKmYdbfDz0TpNQs0tc", PUBLIC_PEM_KEY);
+
+        String pemRSA = "-----BEGIN PUBLIC KEY-----\n" +
+            "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0vx7agoebGcQSuuPiLJX\n" +
+            "ZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tS\n" +
+            "oc/BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ/2W+5JsGY4Hc5n9yBXArwl93lqt\n" +
+            "7/RN5w6Cf0h4QyQ5v+65YGjQR0/FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0\n" +
+            "zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt+bFTWhAI4vMQFh6WeZu0f\n" +
+            "M4lFd2NcRwr3XPksINHaQ+G/xBniIqbw0Ls1jF44+csFCur+kEgU8awapJzKnqDK\n" +
+            "gwIDAQAB\n" +
+            "-----END PUBLIC KEY-----";
+        testKid("NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs", pemRSA);
+
+        String pemEc = "-----BEGIN PUBLIC KEY-----\n" +
+            "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7d1Se1rTIqVTXszA8gIHagLlqPH8\n" +
+            "a98VUCRHWaWW8S3J+WnwJsJVy/4qgZx6yFoJN7zAOIBcseO95zVrbet4gg==\n" +
+            "-----END PUBLIC KEY-----\n";
+        testKid("WdX4yCEsy0Xx48ZfI_4DV0RPhFMdydNFqqwEqiAFAc8", pemEc);
+
+        String pemEd = "-----BEGIN PUBLIC KEY-----\n" +
+            "MCowBQYDK2VwAyEA11qYAYKxCrfVS/7TyWQHOg7hcvPapiMlrwIaaPcHURo=\n" +
+            "-----END PUBLIC KEY-----";
+        testKid("kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k", pemEd);
+    }
+}
diff --git a/src/site/xdoc/server/config-webadmin.xml b/src/site/xdoc/server/config-webadmin.xml
index 77b821c69c..5810a8c8c2 100644
--- a/src/site/xdoc/server/config-webadmin.xml
+++ b/src/site/xdoc/server/config-webadmin.xml
@@ -89,9 +89,11 @@
                       <ul>
                           <li><strong>alg</strong> (header) - the signing algorithm, which must correspond
                               to the key type, e.g. <code>RS256</code> for RSA or <code>ES256</code> for EC.</li>
+                          <li><strong>kid</strong> (header, optional) - identifies the key used
+                              to sign and verify the JWT. This is the JWK thumbprint of the key (as defined in RFC 7638).</li>
                           <li><strong>sub</strong> - the address of the user, e.g. <code>admin@example.com</code>.</li>
                           <li><strong>admin</strong> - must be true (boolean literal, not string) to access admin operations.</li>
-                          <li><strong>exp</strong> - the token expiration time, as the number of seconds (not milliseconds)
+                          <li><strong>exp</strong> - (optional) the token expiration time, as the number of seconds (not milliseconds)
                               since the epoch, a.k.a "unix time". If this claim is omitted, the token never expires.</li>
                       </ul>
                       For example, a token might have the header <code>{"alg":"ES256","typ":"JWT"}</code>


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org


(james-project) 01/05: [DOCUMENTATION] improve JWT documentation

Posted by bt...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

btellier pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git

commit 713556586000d2e0fb2a9959b1db8b0b459b9b66
Author: Amichai Rothman <am...@amichais.net>
AuthorDate: Sun Jun 15 18:26:05 2025 +0300

    [DOCUMENTATION] improve JWT documentation
---
 src/site/markdown/server/manage-webadmin.md |  8 ++--
 src/site/xdoc/server/config-webadmin.xml    | 58 +++++++++++++++++++++++++++--
 2 files changed, 58 insertions(+), 8 deletions(-)

diff --git a/src/site/markdown/server/manage-webadmin.md b/src/site/markdown/server/manage-webadmin.md
index 47acb46356..b87c3bb03b 100644
--- a/src/site/markdown/server/manage-webadmin.md
+++ b/src/site/markdown/server/manage-webadmin.md
@@ -4,13 +4,13 @@ Web administration for JAMES
 The web administration supports for now the CRUD operations on the domains, the users, their mailboxes and their quotas,
  managing mail repositories, performing cassandra migrations, and much more, as described in the following sections.
 
-**WARNING**: This API allow authentication only via the use of JWT. If not configured with JWT, an administrator should ensure an attacker can not use this API.
+**WARNING**: This API supports authentication only via the use of JWT. If JWT is disabled (the default), an administrator should ensure an attacker cannot use this API.
 
-By the way, some endpoints are not filtered by authentication. Those endpoints are not related to data stored in James, for example: Swagger documentation & James health checks.
+By the way, some endpoints are not filtered by authentication. Those endpoints are not related to data stored in James, such as Swagger documentation and James health checks.
 
-Please also note **webadmin** is only enabled with **Guice**. You can not use it when using James with **Spring**, as the required injections are not implemented.
+Please also note **webadmin** is only enabled with **Guice**. You cannot use it when using James with **Spring**, as the required injections are not implemented.
 
-In case of any error, the system will return an error message which is json format like this:
+In case of any error, the response will contain a JSON error message in the following format:
 
 ```
 {
diff --git a/src/site/xdoc/server/config-webadmin.xml b/src/site/xdoc/server/config-webadmin.xml
index 228f1c585f..77b821c69c 100644
--- a/src/site/xdoc/server/config-webadmin.xml
+++ b/src/site/xdoc/server/config-webadmin.xml
@@ -29,7 +29,7 @@
 
     <p>Consult <a href="https://github.com/apache/james-project/blob/master/server/apps/distributed-app/sample-configuration/webadmin.properties">webadmin.properties</a> in GIT to get some examples and hints.</p>
 
-    <p>Use this configuration to define the WebAdmin's responding host and port.</p>
+    <p>The following settings are available in webadmin.properties to configure the WebAdmin HTTP server:</p>
 
     <dl>
         <dt><strong>enabled</strong></dt>
@@ -43,9 +43,11 @@
         <dt><strong>cors.origin</strong></dt>
         <dd>Specify ths CORS origin (default: null)</dd>
         <dt><strong>jwt.enable</strong></dt>
-        <dd>Allow JSON Web Token (default: false)</dd>
+        <dd>Require JWT (JSON Web Token) authentication (default: false)</dd>
+        <dt><strong>jwt.publickeypem.url</strong></dt>
+        <dd>Specify the public key used to verify JWT tokens. Must be a url pointing to a PEM file, e.g. file://conf/jwt.public.pem.</dd>
         <dt><strong>https.enable</strong></dt>
-        <dd>Use https (default: false)</dd>
+        <dd>Use HTTPS (default: false)</dd>
         <dt><strong>https.keystore</strong></dt>
         <dd>Specify a keystore file for https (default: null)</dd>
         <dt><strong>https.password</strong></dt>
@@ -63,11 +65,59 @@
         <dd>Minimum threads used by the underlying Jetty server. Optional.</dd>
     </dl>
 
-      <subsection name="Reverse-proxy set up">
+      <subsection name="Reverse Proxy Setup">
           <p>WebAdmin adds the value of <code>X-Real-IP</code> header as part of the logging MDC.</p>
 
           <p>This allows for reverse proxies to cary other the IP address of the client down to the JMAP server for diagnostic purpose.</p>
       </subsection>
+
+      <subsection name="Authentication">
+          <p>By default, the <code>jwt.enable</code> setting is set to false, i.e. there is no
+             authentication at all, and anyone can access the WebAdmin api with no restrictions.
+             Administrators are highly encouraged to either enable JWT or disable the webadmin interface altogether,
+             to prevent abuse of the server and unrestricted access to user data.
+          </p>
+
+          <p>To configure JWT:
+              <ul>
+                  <li>Generate a pair of authentication keys, using standard algorithms such as RSA or EC.
+                      For example, to generate EC keys using openssl:
+                      <br /><code>openssl ecparam -name prime256v1 -genkey -noout -out jwt.private.pem</code>
+                      <br /><code>openssl ec -in jwt.private.pem -pubout -out jwt.public.pem</code>
+                  </li>
+                  <li>Prepare the JWT header and payload claims:
+                      <ul>
+                          <li><strong>alg</strong> (header) - the signing algorithm, which must correspond
+                              to the key type, e.g. <code>RS256</code> for RSA or <code>ES256</code> for EC.</li>
+                          <li><strong>sub</strong> - the address of the user, e.g. <code>admin@example.com</code>.</li>
+                          <li><strong>admin</strong> - must be true (boolean literal, not string) to access admin operations.</li>
+                          <li><strong>exp</strong> - the token expiration time, as the number of seconds (not milliseconds)
+                              since the epoch, a.k.a "unix time". If this claim is omitted, the token never expires.</li>
+                      </ul>
+                      For example, a token might have the header <code>{"alg":"ES256","typ":"JWT"}</code>
+                      and payload <code>{"sub":"admin@example.com","admin":true,"exp":946684800}</code>.
+                      Additional standard or James-specific claims may be supported in the future to allow finer-grained access control.
+                  </li>
+                  <li>Encode and sign the JWT data using the private key and encode the final token. There are
+                      various tools and tutorials on how to do this. Do note that if you sign it using openssl
+                      and EC, you may need to convert the signature from the ASN.1 format to the padded raw
+                      numeric values required in the JWT.
+                  </li>
+                  <li>Save the private key somewhere safe with restrictive permissions. The server does not need it
+                      to verify token signatures, but you will need it to generate new tokens in the future.</li>
+                  <li>Save the public key somewhere where the server can read it, such as in the James conf folder.</li>
+                  <li>Set <code>jwt.enable</code> to true.</li>
+                  <li>Set <code>jwt.publickeypem.url</code> to the url of the public key PEM file, e.g. <code>file://conf/jwt.public.pem</code></li>
+                  <li>set <code>https.enable</code> and configure the other related https.* options to enable HTTPS,
+                      so that the token will not be intercepted and used by an attacker.</li>
+              </ul>
+          </p>
+
+          <p>
+              To use the token, send it with every HTTP request using a standard Authorization Bearer header:
+              <br /><code>Authorization: Bearer &lt;the signed token&gt;</code>
+          </p>
+      </subsection>
   </section>
 
 </body>


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org


(james-project) 03/05: [UPGRADE] upgrade jwks-rsa to 0.22.1

Posted by bt...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

btellier pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git

commit 18a1e9795c5798b4e8f1f23764cc3633ec9743fb
Author: Amichai Rothman <am...@amichais.net>
AuthorDate: Sun Jun 15 18:31:09 2025 +0300

    [UPGRADE] upgrade jwks-rsa to 0.22.1
---
 server/protocols/jwt/pom.xml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/server/protocols/jwt/pom.xml b/server/protocols/jwt/pom.xml
index 157f6f002b..8d551fe970 100644
--- a/server/protocols/jwt/pom.xml
+++ b/server/protocols/jwt/pom.xml
@@ -40,7 +40,7 @@
         <dependency>
             <groupId>com.auth0</groupId>
             <artifactId>jwks-rsa</artifactId>
-            <version>0.22.0</version>
+            <version>0.22.1</version>
         </dependency>
         <dependency>
             <groupId>com.fasterxml.jackson.core</groupId>


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org