crbench//

← all cases

Add AuthzClientCryptoProvider for authorization client cryptographic operations

Tier 2 medium java · local · real merged PR from keycloak/keycloak #33832

Ground-truth defects

d2 · other · low
Dead code exists where ASN1Encoder instances are created and written to, but their results are immediately discarded. The actual encoding is performed by new ASN1Encoder instances created in the subsequent return statement, rendering the earlier operations useless.
d3 · security · medium
The diff removes the fail-fast `IllegalStateException` that rejected multiple crypto providers on the classpath, replacing it with an order-based sort, a debug log and `foundProviders.get(0)`. All three real providers return the same order value, and `Stream.sorted` is stable, so a tie is resolved by ServiceLoader enumeration order: on a deployment carrying both the default and the FIPS provider, which one is selected depends on classpath ordering rather than configuration.

The change under review

diff (truncated — full diff)
diff --git a/authz/client/pom.xml b/authz/client/pom.xml
index 08b4388059..05889a0504 100644
--- a/authz/client/pom.xml
+++ b/authz/client/pom.xml
@@ -58,6 +58,17 @@
             <artifactId>jackson-annotations</artifactId>
             <scope>provided</scope>
         </dependency>
+
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.hamcrest</groupId>
+            <artifactId>hamcrest</artifactId>
+            <scope>test</scope>
+        </dependency>
     </dependencies>
 
     <build>
diff --git a/authz/client/src/main/java/org/keycloak/authorization/client/AuthzClient.java b/authz/client/src/main/java/org/keycloak/authorization/client/AuthzClient.java
index f3768ed7a6..d20c227ea0 100644
--- a/authz/client/src/main/java/org/keycloak/authorization/client/AuthzClient.java
+++ b/authz/client/src/main/java/org/keycloak/authorization/client/AuthzClient.java
@@ -30,6 +30,7 @@ import org.keycloak.authorization.client.resource.AuthorizationResource;
 import org.keycloak.authorization.client.resource.ProtectionResource;
 import org.keycloak.authorization.client.util.Http;
 import org.keycloak.authorization.client.util.TokenCallable;
+import org.keycloak.common.crypto.CryptoIntegration;
 import org.keycloak.common.util.KeycloakUriBuilder;
 import org.keycloak.representations.AccessTokenResponse;
 import org.keycloak.util.SystemPropertiesJsonParserFactory;
@@ -91,6 +92,7 @@ public class AuthzClient {
      * @return a new instance
      */
     public static AuthzClient create(Configuration configuration) {
+        CryptoIntegration.init(AuthzClient.class.getClassLoader());
         return new AuthzClient(configuration);
     }
 
diff --git a/authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java b/authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java
new file mode 100644
index 0000000000..01ea3bc419
--- /dev/null
+++ b/authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java
@@ -0,0 +1,203 @@
+/*
+ * Copyright 2024 Red Hat, Inc. and/or its affiliates
+ *  and other contributors as indicated by the @author tags.
+ *
+ *  Licensed 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.
+ *
+ */
+
+package org.keycloak.authorization.client.util.crypto;
+
+import java.io.ByteArrayInputStream;
+import java.io.EOFException;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ *
+ * @author rmartinc
+ */
+class ASN1Decoder {
+
+    private final ByteArrayInputStream is;
+    private final int limit;
+    private int count;
+
+    ASN1Decoder(byte[] bytes) {
+        is = new ByteArrayInputStream(bytes);
+        count = 0;
+        limit = bytes.length;
+    }
+
+    public static ASN1Decoder create(byte[] bytes) {
+        return new ASN1Decoder(bytes);
+    }
+
+    public List<byte[]> readSequence() throws IOException {
+        int tag = readTag();
+        int tagNo = readTagNumber(tag);
+        if (tagNo != ASN1Encoder.SEQUENCE) {
+            throw new IOException("Invalid Sequence tag " + tagNo);
+        }
+        int length = readLength();
+        List<byte[]> result = new ArrayList<>();
+        while (length > 0) {
+            byte[] bytes = readNext();
+            result.add(bytes);
+            length = length - bytes.length;
+        }
+        return result;
+    }
+
+    public BigInteger readInteger() throws IOException {
+        int tag = readTag();
+        int tagNo = readTagNumber(tag);
+        if (tagNo != ASN1Encoder.INTEGER) {
+            throw new IOException("Invalid Integer tag " + tagNo);
+        }
+        int length = readLength();
+        byte[] bytes = read(length);
+        return new BigInteger(bytes);
+    }
+
+    byte[] readNext() throws IOException {
+        mark();
+        int tag = readTag();
+        readTagNumber(tag);
+        int length = readLength();
+        length += reset();
+        return read(length);
+    }
+
+    int readTag() throws IOException {
+        int tag = read();
+        if (tag < 0) {
+            throw new EOFException("EOF found inside tag value.");
+        }
+        return tag;
+    }
+
+    int readTagNumber(int tag) throws IOException {
+        int tagNo = tag & 0x1f;
+
+        //
+        // with tagged object tag number is bottom 5 bits, or stored at the start of the content
+        //
+        if (tagNo == 0x1f) {
+            tagNo = 0;
+
+            int b = read();
+
+            // X.690-0207 8.1.2.4.2
+            // "c) bits 7 to 1 of the first subsequent octet shall not all be zero."
+            if ((b & 0x7f) == 0) // Note: -1 will pass
+            {
+                throw new IOException("corrupted stream - invalid high tag number found");
+            }
+
+            while ((b >= 0) && ((b & 0x80) != 0)) {
+                tagNo |= (b & 0x7f);
+                tagNo <<= 7;
+                b = read();
+            }
+
+            if (b < 0) {
+                throw new EOFException("EOF found inside tag value.");
+            }
+
+            tagNo |= (b & 0x7f);
+        }
+
+        return tagNo;
+    }
+
+    int readLength() throws IOException {
+        int length = read();
+        if (length < 0) {
+            throw new EOFException("EOF found when length expected");
+        }
+
+        if (length == 0x80) {
+            return -1;      // indefinite-length encoding
+        }
+
+        if (length > 127) {
+            int size = length & 0x7f;
+
+            // Note: The invalid long form "0xff" (see X.690 8.1.3.5c) will be caught here
+            if (size > 4) {
+                throw new IOException("DER length more than 4 bytes: " + size);
+            }
+
+            length = 0;
+            for (int i = 0; i < size; i++) {
+                int next = read();
+
+                if (next < 0) {
+                    throw new EOFException("EOF found reading length");
+                }
+
+                length = (length << 8) + next;
+            }
+
+            if (length < 0) {
+                throw new IOException("corrupted stream - negative length found");
+            }
+
+            if (length >= limit) // after all we must have read at least 1 byte
+            {
+                throw new IOException("corrupted stream - out of bounds length found");
+            }
+        }
+
+        return length;
+    }
+
+    byte[] read(int length) throws IOException {
+        byte[] bytes = new byte[length];
+        int totalBytesRead = 0;
+
+        while (totalBytesRead < length) {
+            int bytesRead = is.read(bytes, totalBytesRead, length - totalBytesRead);
+            if (bytesRead == -1) {
+                throw new IOException(String.format("EOF found reading %d bytes", length));
+            }
+            totalBytesRead += bytesRead;
+        }
+        count += length;
+        return bytes;
+    }
+
+    void mark() {
+        count = 0;
+        is.mark(is.available());
+    }
+
+    int reset() {
+        int tmp = count;
+        is.reset();
+        return tmp;
+    }
+
+    int read() {
+        int tmp = is.read();
+        if (tmp >= 0) {
+            count++;
+        }
+        return tmp;
+    }
+}
+
diff --git a/authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Encoder.java b/authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Encoder.java
new file mode 100644
index 0000000000..2bfda3a76b
--- /dev/null
+++ b/authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Encoder.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright 2024 Red Hat, Inc. and/or its affiliates
+ *  and other contributors as indicated by the @author tags.
+ *
+ *  Licensed 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.
+ *
+ */
+
+package org.keycloak.authorization.client.util.crypto;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.math.BigInteger;
+
+/**
+ *
+ * @author rmartinc
+ */
+class ASN1Encoder {
+
+    static final int INTEGER = 0x02;
+    static final int SEQUENCE = 0x10;
+    static final int CONSTRUCTED = 0x20;
+
+    private final ByteArrayOutputStream os;
+
+    private ASN1Encoder() {
+        this.os = new ByteArrayOutputStream();
+    }
+
+    static public ASN1Encoder create() {
+        return new ASN1Encoder();
+    }
+
+    public ASN1Encoder write(BigInteger value) throws IOException {
+        writeEncoded(INTEGER, value.toByteArray());
+        return this;
+    }
+
+    public ASN1Encoder writeDerSeq(ASN1Encoder... objects) throws IOException {
+        writeEncoded(CONSTRUCTED | SEQUENCE, concatenate(objects));
+        return this;
+    }
+
+    public byte[] toByteArray() {
+        return os.toByteArray();
+    }
+
+    void writeEncoded(int tag, byte[] bytes) throws IOException {
+        write(tag);
+        writeLength(bytes.length);
+        write(bytes);
+    }
+
+    void writeLength(int length) throws IOException {
+        if (length > 127) {
+            int size = 1;
+            int val = length;
+
+            while ((val >>>= 8) != 0) {
+                size++;
+            }
+
+            write((byte) (size | 0x80));
+
+            for (int i = (size - 1) * 8; i >= 0; i -= 8) {
+                write((byte) (length >> i));
+            }
+        } else {
+            write((byte) length);
+        }
+    }
+
+    void write(byte[] bytes) throws IOException {
+        os.write(bytes);
+    }
+
+    void write(int b) throws IOException {
+        os.write(b);
+    }
+
+    byte[] concatenate(ASN1Encoder... objects) throws IOException {
+        ByteArrayOutputStream tmp = new ByteArrayOutputStream();
+        for (ASN1Encoder object : objects) {
+            tmp.write(object.toByteArray());
+        }
+        return tmp.toByteArray();
+    }
+}
+
diff --git a/authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java b/authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java
new file mode 100644
index 0000000000..90c9c81382
--- /dev/null
+++ b/authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java
@@ -0,0 +1,226 @@
+/*
+ * Copyright 2024 Red Hat, Inc. and/or its affiliates
+ *  and other contributors as indicated by the @author tags.
+ *
+ *  Licensed 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.
+ *
+ */
+
+package org.keycloak.authorization.client.util.crypto;
+
+import java.io.IOException;
+import java.math.BigInteger;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.KeyFactory;
+import java.security.KeyPairGenerator;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.Provider;
+import java.security.Signature;
+import java.security.cert.CertPathBuilder;
+import java.security.cert.CertStore;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
+import java.security.cert.CollectionCertStoreParameters;
+import java.security.interfaces.ECPrivateKey;
+import java.security.interfaces.ECPublicKey;
+import java.security.spec.ECParameterSpec;
+import java.util.List;
+import javax.crypto.Cipher;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.SecretKeyFactory;
+import javax.net.ssl.SSLSocketFactory;
+import org.keycloak.common.crypto.CertificateUtilsProvider;
+import org.keycloak.common.crypto.CryptoProvider;
+import org.keycloak.common.crypto.ECDSACryptoProvider;
+import org.keycloak.common.crypto.PemUtilsProvider;
+import org.keycloak.common.crypto.UserIdentityExtractorProvider;
+import org.keycloak.common.util.KeystoreUtil;
+
+/**
+ * <p>Simple crypto provider to be used with the authz-client.</p>
+ *
+ * @author rmartinc
+ */
+public class AuthzClientCryptoProvider implements CryptoProvider {
+
+    @Override
+    public Provider getBouncyCastleProvider() {
+        try {
+            return KeyStore.getInstance(KeyStore.getDefaultType()).getProvider();
+        } catch (KeyStoreException e) {
+            throw new IllegalStateException(e);
+        }
+    }
+
+    @Override
+    public int order() {
+        return 100;
+    }
+
+    @Override
+    public <T> T getAlgorithmProvider(Class<T> clazz, String algorithm) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+
+    @Override
+    public CertificateUtilsProvider getCertificateUtils() {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+
+    @Override
+    public PemUtilsProvider getPemUtils() {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+
+    @Override
+    public <T> T getOCSPProver(Class<T> clazz) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+
+    @Override
+    public UserIdentityExtractorProvider getIdentityExtractorProvider() {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+
+    @Override
+    public ECDSACryptoProvider getEcdsaCryptoProvider() {
+        return new ECDSACryptoProvider() {
+            @Override
+            public byte[] concatenatedRSToASN1DER(byte[] signature, int signLength) throws IOException {
+                int len = signLength / 2;
+                int arraySize = len + 1;
+
+                byte[] r = new byte[arraySize];
+                byte[] s = new byte[arraySize];
+                System.arraycopy(signature, 0, r, 1, len);
+                System.arraycopy(signature, len, s, 1, len);
+                BigInteger rBigInteger = new BigInteger(r);
+                BigInteger sBigInteger = new BigInteger(s);
+
+                ASN1Encoder.create().write(rBigInteger);
+                ASN1Encoder.create().write(sBigInteger);
+
+                return ASN1Encoder.create()
+                        .writeDerSeq(
+                                ASN1Encoder.create().write(rBigInteger),
+                                ASN1Encoder.create().write(sBigInteger))
+                        .toByteArray();
+            }
+
+            @Override
+            public byte[] asn1derToConcatenatedRS(byte[] derEncodedSignatureValue, int signLength) throws IOException {
+                int len = signLength / 2;
+
+                List<byte[]> seq = ASN1Decoder.create(derEncodedSignatureValue).readSequence();
+                if (seq.size() != 2) {
+                    throw new IOException("Invalid sequence with size different to 2");
+                }
+
+                BigInteger rBigInteger = ASN1Decoder.create(seq.get(0)).readInteger();
+                BigInteger sBigInteger = ASN1Decoder.create(seq.get(1)).readInteger();
+
+                byte[] r = integerToBytes(rBigInteger, len);

Leaderboard for this case

medium · 4 of 9 bots fully caught it (44% solve rate) · 56% avg coverage.

#BotResultCaughtCoverageFindingsFalse alarms
1 Drape (Deep Review) solved 2/2 100.0% 2 0
2 Drape (Review) solved 2/2 100.0% 6 0
3 greptile solved 2/2 100.0% 4 0
4 Claude Code (Opus 5.5) solved 2/2 100.0% 3 1
5 Mjolnir (Opus 5.5) partial 1/2 66.7% 2 0
6 qodo partial 1/2 66.7% 5 2
7 cursor miss 0/2 0.0% 0 0
8 Mjolnir (Sonnet 5.5) miss 0/2 0.0% 0 0
9 Cubic miss 0/2 0.0% 8 1

Bot results

Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 low ✓ exact
d3 medium ✓ exact
valid · matches d3 · impact medium
invalid
`readLength()` does return -1 for 0x80, but the only production caller of `readInteger()` passes it elements built by `readNext()`. In `readNext()`, `length = -1 + count(2) = 1`, so an indefinite-length INTEGER comes back as a 1-byte element holding only the tag. `readInteger()` on that element then hits EOF in `readLength()` and throws an EOFException, which is an IOException. A top-level indefinite SEQUENCE gives an empty list, which fails the size != 2 check with an IOException. So the claimed NegativeArraySizeException can't be reached through `asn1derToConcatenatedRS`, and malformed input is still rejected with an IOException. [invalid: contradiction] [consensus 3/4: invalid=3, valid=1]
valid · matches d2 · impact low
raw comments (3)
common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:57
The old check that threw when more than one CryptoProvider was found has been removed. Now providers are only sorted by order(), but DefaultCryptoProvider, WildFlyElytronProvider and FIPS1402Provider all return 200. If two of these are on the classpath (for example keycloak-crypto-default together with keycloak-crypto-fips1402), the comparator ties and the winner depends on ServiceLoader/classpath order. The other providers are reported only at debug level. A FIPS deployment can therefore quietly end up using the non-FIPS BouncyCastle provider (or the reverse), where before it failed fast. The fail-fast behaviour should be kept when the top providers share the same order.
authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java:128
readLength() returns -1 for indefinite-length encoding (0x80), and callers don't handle it. readInteger() then calls read(-1), which throws NegativeArraySizeException (an unchecked exception) instead of IOException. readNext() computes length = -1 + count and reads the wrong number of bytes. A malformed or attacker-supplied DER signature can therefore throw an unexpected RuntimeException out of asn1derToConcatenatedRS instead of being cleanly rejected. DER does not allow indefinite length, so this case should throw IOException.
authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java:113
Leftover dead code: `ASN1Encoder.create().write(rBigInteger); ASN1Encoder.create().write(sBigInteger);` builds two encoders and throws them away before the real encoding below. It is wasted work and looks like a copy/paste mistake.
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 low ✗ —
d3 medium ✗ —
uncertain
The comparator only calls order() when more than one provider is found. Before this change, finding several providers already threw an IllegalStateException, and a lone third-party provider is never compared. So the claim that this now 'prevents startup' rests on a mixed-version classpath that is not shown. [uncertain: no evidence quoted] [consensus 2/5: valid=2, invalid=2, uncertain=1]
invalid
Returning null would make BouncyIntegration fall back to the first security provider, which is normally SUN as well, so the suggested fix yields the same PROVIDER; no distinct failure demonstrated. [invalid: contradiction] [consensus 5/5: invalid=5]
valid · impact low
A zero-length INTEGER yields an empty array and BigInteger throws NumberFormatException rather than IOException; only on malformed input. [grounded: diff] [consensus 5/5: valid=5]
valid · impact low
Only the low 5 bits are compared, so non-universal or primitive tag 16 is accepted as a SEQUENCE; lax parsing of malformed input. [grounded: diff] [consensus 5/5: valid=5]
valid · impact low
-1 flows into read(length) causing NegativeArraySizeException in readInteger, or an empty list in readSequence; it is never cleanly rejected. [grounded: diff] [consensus 5/5: valid=5]
valid · impact low
No check that a child's encoded size fits within the remaining sequence length; it reads past the sequence boundary on malformed input. [grounded: diff] [consensus 5/5: valid=5]
minor · impact low
Test coverage suggestion; it does not show the production code misbehaves. [grounded: diff] [consensus 5/5: minor=5]
minor · impact low
Unused test dependency; a cleanup/style note, not a behavioural defect. [grounded: diff] [consensus 5/5: minor=5]
raw comments (9)
common/src/main/java/org/keycloak/common/crypto/CryptoProvider.java:44
<!-- cubic:v=3634a7d5-d65b-4ef0-adf0-355fd70d96b6 --> <!-- cubic:review-run=a37d4989-19c1-5efc-a7b3-724e7d6f3843 --> <!-- metadata:{"confidence":8} --> P1: When an older or third-party `CryptoProvider` remains on the classpath, provider discovery now throws `AbstractMethodError` while sorting and prevents startup. Make this new SPI method a default returning the lowest priority so existing implementations remain loadable. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At common/src/main/java/org/keycloak/common/crypto/CryptoProvider.java, line 44: <comment>When an older or third-party `CryptoProvider` remains on the classpath, provider discovery now throws `AbstractMethodError` while sorting and prevents startup. Make this new SPI method a default returning the lowest priority so existing implementations remain loadable.</comment> <file context> @@ -36,6 +36,13 @@ public interface CryptoProvider { + * + * The higher number has preference over the lower number + */ + int order(); + /** </file context> ``` </details> ```suggestion default int order() { return 0; } ```
authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java:63
<!-- cubic:v=c3a652ab-8307-4488-ab84-d2b0936366d4 --> <!-- cubic:review-run=a37d4989-19c1-5efc-a7b3-724e7d6f3843 --> <!-- metadata:{"confidence":9} --> P2: When this fallback provider is selected, `getBouncyCastleProvider()` returns the default JKS provider rather than a Bouncy Castle provider, causing `BouncyIntegration.PROVIDER` to resolve to `SUN` (or another keystore provider) and making provider-specific crypto lookups fail. Return `null` when this client provider has no Bouncy Castle implementation so `BouncyIntegration` uses its fallback behavior. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java, line 63: <comment>When this fallback provider is selected, `getBouncyCastleProvider()` returns the default JKS provider rather than a Bouncy Castle provider, causing `BouncyIntegration.PROVIDER` to resolve to `SUN` (or another keystore provider) and making provider-specific crypto lookups fail. Return `null` when this client provider has no Bouncy Castle implementation so `BouncyIntegration` uses its fallback behavior.</comment> <file context> @@ -0,0 +1,226 @@ + @Override + public Provider getBouncyCastleProvider() { + try { + return KeyStore.getInstance(KeyStore.getDefaultType()).getProvider(); + } catch (KeyStoreException e) { + throw new IllegalStateException(e); </file context> ``` </details>
authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java:72
<!-- cubic:v=89c13a92-1905-4019-9044-80e9e972ad68 --> <!-- cubic:review-run=a37d4989-19c1-5efc-a7b3-724e7d6f3843 --> <!-- metadata:{"confidence":10} --> P2: A zero-length INTEGER throws `NumberFormatException` instead of the declared `IOException` for malformed input. Reject zero-length INTEGERs before constructing `BigInteger`. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java, line 72: <comment>A zero-length INTEGER throws `NumberFormatException` instead of the declared `IOException` for malformed input. Reject zero-length INTEGERs before constructing `BigInteger`.</comment> <file context> @@ -0,0 +1,203 @@ + throw new IOException("Invalid Integer tag " + tagNo); + } + int length = readLength(); + byte[] bytes = read(length); + return new BigInteger(bytes); + } </file context> ``` </details> ```suggestion if (length == 0) { throw new IOException("Invalid zero-length integer"); } byte[] bytes = read(length); ```
authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java:52
<!-- cubic:v=a88814ef-efe0-44fb-9b65-34fc9921e0a4 --> <!-- cubic:review-run=a37d4989-19c1-5efc-a7b3-724e7d6f3843 --> <!-- metadata:{"confidence":10} --> P2: The sequence check compares only the low five-bit tag number, so primitive or context-specific tags can be accepted as a DER SEQUENCE. Validate the complete universal constructed tag (`0x30`) instead. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java, line 52: <comment>The sequence check compares only the low five-bit tag number, so primitive or context-specific tags can be accepted as a DER SEQUENCE. Validate the complete universal constructed tag (`0x30`) instead.</comment> <file context> @@ -0,0 +1,203 @@ + public List<byte[]> readSequence() throws IOException { + int tag = readTag(); + int tagNo = readTagNumber(tag); + if (tagNo != ASN1Encoder.SEQUENCE) { + throw new IOException("Invalid Sequence tag " + tagNo); + } </file context> ``` </details> ```suggestion if (tag != (ASN1Encoder.CONSTRUCTED | ASN1Encoder.SEQUENCE)) { ```
authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java:134
<!-- cubic:v=407ff4e1-7359-405c-9f3b-8caa7edec9d3 --> <!-- cubic:review-run=a37d4989-19c1-5efc-a7b3-724e7d6f3843 --> <!-- metadata:{"confidence":10} --> P2: When input uses an indefinite length, the decoder neither handles the end-of-contents marker nor rejects the encoding. Reject indefinite lengths with `IOException` or implement complete EOC parsing. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java, line 134: <comment>When input uses an indefinite length, the decoder neither handles the end-of-contents marker nor rejects the encoding. Reject indefinite lengths with `IOException` or implement complete EOC parsing.</comment> <file context> @@ -0,0 +1,203 @@ + } + + if (length == 0x80) { + return -1; // indefinite-length encoding + } + </file context> ``` </details> ```suggestion throw new IOException("Indefinite-length encoding is not supported"); ```
authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java:60
<!-- cubic:v=00c531e7-8561-4a1e-9c93-906cd331a27e --> <!-- cubic:review-run=a37d4989-19c1-5efc-a7b3-724e7d6f3843 --> <!-- metadata:{"confidence":9} --> P2: When a child TLV exceeds the declared sequence length, this loop still accepts it after `length` becomes negative, consuming bytes outside the sequence. Reject a child whose encoded length exceeds the remaining sequence length. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java, line 60: <comment>When a child TLV exceeds the declared sequence length, this loop still accepts it after `length` becomes negative, consuming bytes outside the sequence. Reject a child whose encoded length exceeds the remaining sequence length.</comment> <file context> @@ -0,0 +1,203 @@ + while (length > 0) { + byte[] bytes = readNext(); + result.add(bytes); + length = length - bytes.length; + } + return result; </file context> ``` </details> ```suggestion if (bytes.length > length) { throw new IOException("Sequence element exceeds sequence length"); } length = length - bytes.length; ```
authz/client/src/test/java/org/keycloak/authorization/client/test/ECDSAAlgorithmTest.java:57
<!-- cubic:v=e2c9f332-e9d8-490c-88bd-c6a4f0f18991 --> <!-- cubic:review-run=a37d4989-19c1-5efc-a7b3-724e7d6f3843 --> <!-- metadata:{"confidence":7} --> P2: The final assertion only checks that the concatenated form is unchanged after a DER round-trip (rsConcat == rsConcat2). A bug that drops or corrupts bytes in asn1derToConcatenatedRS still passes: both sides apply the same lossy conversion, and concatenatedRSToASN1DER reconstructs the identical byte value, so rsConcat2 always equals rsConcat. The test never asserts the reconstructed ASN1 DER (asn1Des) equals the original signature (sign), and never verifies the converted signature against the public key and message, so an ECDSA conversion bug (e.g. integerToBytes truncating an r/s component larger than signLength/2) goes undetected. Assert that asn1Des equals sign and verify the reconstructed signature with keyPair.getPublic() and the original data. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At authz/client/src/test/java/org/keycloak/authorization/client/test/ECDSAAlgorithmTest.java, line 56: <comment>The final assertion only checks that the concatenated form is unchanged after a DER round-trip (rsConcat == rsConcat2). A bug that drops or corrupts bytes in asn1derToConcatenatedRS still passes: both sides apply the same lossy conversion, and concatenatedRSToASN1DER reconstructs the identical byte value, so rsConcat2 always equals rsConcat. The test never asserts the reconstructed ASN1 DER (asn1Des) equals the original signature (sign), and never verifies the converted signature against the public key and message, so an ECDSA conversion bug (e.g. integerToBytes truncating an r/s component larger than signLength/2) goes undetected. Assert that asn1Des equals sign and verify the reconstructed signature with keyPair.getPublic() and the original data.</comment> <file context> @@ -0,0 +1,74 @@ + byte[] rsConcat = prov.getEcdsaCryptoProvider().asn1derToConcatenatedRS(sign, algorithm.getSignatureLength()); + byte[] asn1Des = prov.getEcdsaCryptoProvider().concatenatedRSToASN1DER(rsConcat, algorithm.getSignatureLength()); + byte[] rsConcat2 = prov.getEcdsaCryptoProvider().asn1derToConcatenatedRS(asn1Des, algorithm.getSignatureLength()); + Assert.assertArrayEquals(rsConcat, rsConcat2); + } + </file context> ``` </details> ```suggestion byte[] asn1Des = prov.getEcdsaCryptoProvider().concatenatedRSToASN1DER(rsConcat, algorithm.getSignatureLength()); byte[] rsConcat2 = prov.getEcdsaCryptoProvider().asn1derToConcatenatedRS(asn1Des, algorithm.getSignatureLength()); Assert.assertArrayEquals(rsConcat, rsConcat2); Assert.assertArrayEquals(sign, asn1Des); Signature verifier = Signature.getInstance(JavaAlgorithm.getJavaAlgorithm(algorithm.name())); verifier.initVerify(keyPair.getPublic()); verifier.update(data); Assert.assertTrue(verifier.verify(asn1Des)); ```
authz/client/pom.xml:69
<!-- cubic:v=a117353e-d43f-42d8-9b12-c02faec56897 --> <!-- cubic:review-run=a37d4989-19c1-5efc-a7b3-724e7d6f3843 --> <!-- metadata:{"confidence":7} --> P3: The module's only unit test, ECDSAAlgorithmTest, imports only org.junit.Assert and org.junit.Test and uses no hamcrest matchers, so the added org.hamcrest:hamcrest dependency has no consumers in this module. Remove the dependency block to keep the test scope minimal. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At authz/client/pom.xml, line 69: <comment>The module's only unit test, ECDSAAlgorithmTest, imports only org.junit.Assert and org.junit.Test and uses no hamcrest matchers, so the added org.hamcrest:hamcrest dependency has no consumers in this module. Remove the dependency block to keep the test scope minimal.</comment> <file context> @@ -58,6 +58,17 @@ + </dependency> + <dependency> + <groupId>org.hamcrest</groupId> + <artifactId>hamcrest</artifactId> + <scope>test</scope> + </dependency> </file context> ``` </details>
PR-level
<!-- cubic:review-summary:start --> **8 issues found** across 12 files <!-- cubic:review-summary:end --> <details> <summary>Prompt for AI agents (unresolved issues)</summary> ```text Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately. <file name="common/src/main/java/org/keycloak/common/crypto/CryptoProvider.java"> <violation number="1" location="common/src/main/java/org/keycloak/common/crypto/CryptoProvider.java:44"> P1: When an older or third-party `CryptoProvider` remains on the classpath, provider discovery now throws `AbstractMethodError` while sorting and prevents startup. Make this new SPI method a default returning the lowest priority so existing implementations remain loadable.</violation> </file> <file name="authz/client/pom.xml"> <violation number="1" location="authz/client/pom.xml:69"> P3: The module's only unit test, ECDSAAlgorithmTest, imports only org.junit.Assert and org.junit.Test and uses no hamcrest matchers, so the added org.hamcrest:hamcrest dependency has no consumers in this module. Remove the dependency block to keep the test scope minimal.</violation> </file> <file name="authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java"> <violation number="1" location="authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java:63"> P2: When this fallback provider is selected, `getBouncyCastleProvider()` returns the default JKS provider rather than a Bouncy Castle provider, causing `BouncyIntegration.PROVIDER` to resolve to `SUN` (or another keystore provider) and making provider-specific crypto lookups fail. Return `null` when this client provider has no Bouncy Castle implementation so `BouncyIntegration` uses its fallback behavior.</violation> </file> <file name="authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java"> <violation number="1" location="authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java:52"> P2: The sequence check compares only the low five-bit tag number, so primitive or context-specific tags can be accepted as a DER SEQUENCE. Validate the complete universal constructed tag (`0x30`) instead.</violation> <violation number="2" location="authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java:60"> P2: When a child TLV exceeds the declared sequence length, this loop still accepts it after `length` becomes negative, consuming bytes outside the sequence. Reject a child whose encoded length exceeds the remaining sequence length.</violation> <violation number="3" location="authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java:72"> P2: A zero-length INTEGER throws `NumberFormatException` instead of the declared `IOException` for malformed input. Reject zero-length INTEGERs before constructing `BigInteger`.</violation> <violation number="4" location="authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java:134"> P2: When input uses an indefinite length, the decoder neither handles the end-of-contents marker nor rejects the encoding. Reject indefinite lengths with `IOException` or implement complete EOC parsing.</violation> </file> <file name="authz/client/src/test/java/org/keycloak/authorization/client/test/ECDSAAlgorithmTest.java"> <violation number="1" location="authz/client/src/test/java/org/keycloak/authorization/client/test/ECDSAAlgorithmTest.java:56"> P2: The final assertion only checks that the concatenated form is unchanged after a DER round-trip (rsConcat == rsConcat2). A bug that drops or corrupts bytes in asn1derToConcatenatedRS still passes: both sides apply the same lossy conversion, and concatenatedRSToASN1DER reconstructs the identical byte value, so rsConcat2 always equals rsConcat. The test never asserts the reconstructed ASN1 DER (asn1Des) equals the original signature (sign), and never verifies the converted signature against the public key and message, so an ECDSA conversion bug (e.g. integerToBytes truncating an r/s component larger than signLength/2) goes undetected. Assert that asn1Des equals sign and verify the reconstructed signature with keyPair.getPublic() and the original data.</violation> </file> ``` </details> <sub>Reply with feedback, questions, or to request a fix.<br /><br />[Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/52/ai_pr_review_github_delivery_bab67d8ae32516b298ce266b83b5e844f8f3e3f8301e9813b111abf5eade8f14?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F52)</sub> <!-- cubic:review-post:ai_pr_review_github_delivery_bab67d8ae32516b298ce266b83b5e844f8f3e3f8301e9813b111abf5eade8f14:3c4a73279dda4b85248239da992f009200a14229:a37d4989-19c1-5efc-a7b3-724e7d6f3843 -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 low ✗ —
d3 medium ✗ —
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 low ✓ exact
d3 medium ✓ exact
valid · matches d3 · impact medium
valid · matches d2 · impact low
raw comments (2)
common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:64
**Default and FIPS providers together now pass silently** Default, Elytron and FIPS all return `order()` 200, so when two are on the classpath `detectProvider` picks the first in classpath order instead of failing. A FIPS setup can quietly run on non-FIPS BouncyCastle. Keep failing when the top two providers have the same `order()`. ``` common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:57 .sorted(Comparator.comparingInt(CryptoProvider::order).reversed()) common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:58 .collect(Collectors.toList()); common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:60 if (foundProviders.isEmpty()) { common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:61 throw new IllegalStateException("Not able to load any cryptoProvider with the classLoader: " + classLoader); common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:64 if (foundProviders.size() > 1) { common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:65 StringBuilder builder = new StringBuilder("Ignored crypto providers: "); common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:66 for (int i = 1 ; i < foundProviders.size() ; i++) { common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:67 builder.append(foundProviders.get(i).getClass().getName() + ", "); common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:68 } common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:69 logger.debugf(builder.toString()); ```
authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java:114
**Unused ASN.1 encodings built on every verify** `concatenatedRSToASN1DER` encodes r and s twice. The first two `ASN1Encoder.create().write(...)` calls throw their result away, so every ECDSA signature check does extra work for nothing. Delete the two standalone `ASN1Encoder.create().write(...)` lines. ``` authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java:114 ASN1Encoder.create().write(rBigInteger); authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java:115 ASN1Encoder.create().write(sBigInteger); authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java:117 return ASN1Encoder.create() authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java:118 .writeDerSeq( authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java:119 ASN1Encoder.create().write(rBigInteger), authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java:120 ASN1Encoder.create().write(sBigInteger)) authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java:121 .toByteArray(); ```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 low ✓ exact
d3 medium ✓ exact
valid · matches d2 · impact low
valid · matches d3 · impact medium
valid · impact low
With a zero length, readLength returns 0 and read(0) returns an empty array. new BigInteger(new byte[0]) then throws NumberFormatException, an unchecked exception, where the method is declared to throw IOException. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
The loop only stops when length is no longer above 0. A child that runs past the declared length just drives length negative and is still accepted. Bytes after the sequence are never checked. The DER parsing is lax, but the impact is small. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
Values longer than qLength are cut down to their low bytes with no check that the dropped bytes are only the leading sign zero. A malformed value is therefore silently truncated instead of rejected. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
init uses AuthzClient's classloader and does nothing once a provider is set. If the full provider is not visible to that classloader, the limited provider (most methods throw UnsupportedOperationException) is kept for the whole JVM. This only happens in setups with multiple classloaders. [grounded: diff] [consensus 3/3: valid=3]
raw comments (6)
authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java:112
**Redundant ASN.1 encoding done twice** concatenatedRSToASN1DER encodes r and s into throw-away encoders, then encodes them again for the real result. The first two calls are dead work. Delete the two standalone write() lines. ``` authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java:112 BigInteger sBigInteger = new BigInteger(s); ```
common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:56
**Equal-order crypto providers silently picked arbitrarily** Default, Elytron and FIPS providers all return order 200, and `detectProvider` no longer fails on several matches. With two on the classpath, the first one the ServiceLoader lists wins and the rest are only debug-logged. Throw when the top two providers have equal order. ``` common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:56 List<CryptoProvider> foundProviders = StreamSupport.stream(ServiceLoader.load(CryptoProvider.class, classLoader).spliterator(), false) common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:57 .sorted(Comparator.comparingInt(CryptoProvider::order).reversed()) common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:58 .collect(Collectors.toList()); common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:60 if (foundProviders.isEmpty()) { common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:61 throw new IllegalStateException("Not able to load any cryptoProvider with the classLoader: " + classLoader); common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:62 } else { common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:63 logger.debugf("Detected crypto provider: %s", foundProviders.get(0).getClass().getName()); common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:64 if (foundProviders.size() > 1) { common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:65 StringBuilder builder = new StringBuilder("Ignored crypto providers: "); common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:66 for (int i = 1 ; i < foundProviders.size() ; i++) { ```
authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java:96
**Zero-length INTEGER throws NumberFormatException, not IOException** For DER like 30 04 02 00 02 00, readInteger reads a 0-byte value and new BigInteger(new byte[0]) throws NumberFormatException. Callers expecting IOException for a malformed signature don't catch it. Reject length 0 (and -1) in readInteger with an IOException. ``` authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java:50 int tag = readTag(); authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java:51 int tagNo = readTagNumber(tag); authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java:52 if (tagNo != ASN1Encoder.SEQUENCE) { authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java:53 throw new IOException("Invalid Sequence tag " + tagNo); ```
authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java:49
**Sequence length is never checked against its content** Unlike `readInteger` and `readNext`, `readSequence` never reads its declared content with `read(length)`. It loops `readNext`, so trailing bytes and children overrunning the declared length are accepted. Read the content with read(length), parse children from it, and require full consumption. ``` authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java:49 public List<byte[]> readSequence() throws IOException { authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java:50 int tag = readTag(); authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java:51 int tagNo = readTagNumber(tag); authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java:52 if (tagNo != ASN1Encoder.SEQUENCE) { ```
authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java:152
**Oversized r/s values silently truncated** integerToBytes cuts a value longer than qLength to its low bytes without checking that the dropped bytes are only sign padding. A malformed DER signature becomes a valid-looking R||S instead of being rejected. Throw an IOException if the dropped bytes are not a single leading zero. ``` authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java:152 byte[] bytes = s.toByteArray(); authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java:153 if (qLength < bytes.length) { authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java:154 byte[] tmp = new byte[qLength]; authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java:155 System.arraycopy(bytes, bytes.length - tmp.length, tmp, 0, tmp.length); ```
authz/client/src/main/java/org/keycloak/authorization/client/AuthzClient.java:95
**Limited crypto provider can stick for whole JVM** AuthzClient.create runs CryptoIntegration.init with its own classloader. If the real crypto module is not visible there, the stripped-down provider is chosen and never replaced, because init does nothing once a provider is set. Let a later init replace the authz provider. ``` authz/client/src/main/java/org/keycloak/authorization/client/AuthzClient.java:95 CryptoIntegration.init(AuthzClient.class.getClassLoader()); ```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 low ✓ off by one
d3 medium ✓ off by one
valid · impact low
The diff adds an abstract `order()` to the public CryptoProvider interface with no default. Every in-repo implementation was updated (I grepped for `implements CryptoProvider`), but third-party implementations would fail to compile, and an already-compiled one would throw AbstractMethodError when detectProvider sorts by order(). This is a real compatibility break, though it only hits out-of-tree providers. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d3 · impact medium
valid · matches d2 · impact low
minor
Accurate observation that the test skips the ServiceLoader/order/AuthzClient.create() wiring. It asks for more test coverage and does not claim the code misbehaves. [grounded: diff] [consensus 3/3: minor=3]
raw comments (5)
common/src/main/java/org/keycloak/common/crypto/CryptoProvider.java:44
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Provider SPI Compatibility Break** Adding `order()` as an abstract method breaks the public `CryptoProvider` SPI. Existing source implementations must add the method, while a previously compiled provider loaded alongside another provider will throw `AbstractMethodError` when provider detection invokes `order()`, preventing startup. Use a default priority to preserve compatibility. ```suggestion default int order() { return 0; } ```
common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:57
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Equal Priorities Select Arbitrarily** If more than one full crypto provider is present in a custom deployment, Default, FIPS, and Elytron all have priority 200. This sort therefore selects whichever provider `ServiceLoader` encounters first instead of failing fast, potentially activating the wrong crypto implementation. Assign distinct priorities or reject ties at the highest priority.
authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java:115
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> **Redundant Signature Encodings** These calls serialize `r` and `s` into encoder instances that are immediately discarded. The following expression repeats both encodings to build the actual sequence, causing unnecessary allocations on every conversion and making the dead calls look like required state. ```suggestion ``` Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
authz/client/src/test/java/org/keycloak/authorization/client/test/ECDSAAlgorithmTest.java:47
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> **Test Bypasses Provider Wiring** The test constructs `AuthzClientCryptoProvider` directly, so it can pass even when the new service descriptor, provider priority, or `AuthzClient.create()` initialization is broken. Add an integration-level assertion through `CryptoIntegration` or `AuthzClient.create()` to cover the production wiring introduced here. Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
PR-level
<h3>Greptile Summary</h3> This PR adds a lightweight authorization-client crypto provider, initializes crypto integration when creating an authorization client, implements dependency-free ECDSA signature conversion, and changes crypto-provider discovery to use priorities. - Adds ASN.1 DER encoding and decoding for ECDSA signatures. - Registers an authorization-client-specific `CryptoProvider`. - Introduces provider priorities and allows multiple providers on a classpath. - Adds ES256, ES384, and ES512 conversion tests. <h3>Confidence Score: 3/5</h3> The PR should not merge until the public SPI compatibility break and ambiguous selection among equally ranked crypto providers are addressed. The new abstract SPI method can break external provider implementations, while all existing full providers receive the same priority and can therefore be selected according to classpath order when they coexist. **Files Needing Attention:** common/src/main/java/org/keycloak/common/crypto/CryptoProvider.java, common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java <details><summary><h3>Important Files Changed</h3></summary> | Filename | Overview | |----------|----------| | common/src/main/java/org/keycloak/common/crypto/CryptoProvider.java | Adds a required provider-priority method that breaks compatibility with existing SPI implementations. | | common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java | Replaces rejection of multiple providers with priority selection, but equal built-in priorities leave selection ambiguous. | | authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java | Adds the lightweight ECDSA conversion provider; conversion behavior is sound, with two redundant encoding calls. | | authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java | Adds a minimal DER decoder sufficient for the valid ECDSA signatures exercised by the client. | | authz/client/src/test/java/org/keycloak/authorization/client/test/ECDSAAlgorithmTest.java | Covers valid ECDSA conversion for all supported sizes but bypasses the new provider-discovery integration. | </details> <details open><summary><h3>Flowchart</h3></summary> ```mermaid %%{init: {'theme': 'neutral'}}%% flowchart TD A[AuthzClient.create] --> B[CryptoIntegration.init] B --> C[ServiceLoader finds CryptoProvider implementations] C --> D[Sort by descending order] D --> E{Highest priority unique?} E -->|Yes| F[Select provider] E -->|No: equal priorities| G[Selection follows ServiceLoader order] F --> H[ECDSA operations use selected provider] G --> H ``` </details> <!-- greptile_other_comments_section --> <sub>Reviews (1): Last reviewed commit: ["Update authz/client/pom.xml and 11 more ..."](https://github.com/drape-io/crbench-greptile-2026-09/commit/4f851c5d7c79c8d4730f45a51d2251eec00f3978) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=64284581)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 low ✗ —
d3 medium ✓ exact
valid · impact medium
The diff removes the error for multiple providers and only sorts by order(). Default, Elytron and FIPS1402 all return 200, so when two of them are on the classpath the choice now depends on ServiceLoader order and the losers are only logged at debug level. Before this change, that misconfiguration failed fast at startup. [grounded: diff] [consensus 3/3: valid=3]
valid · matches d3 · impact medium
raw comments (2)
common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:57
[P2] Providers with the same order are now picked silently and in no fixed order `detectProvider` used to throw when it found more than one `CryptoProvider`. It now sorts them by `order()` and takes the first one. `DefaultCryptoProvider`, `WildFlyElytronProvider` and `FIPS1402Provider` (and `Fips1402StrictCryptoProvider`, which inherits from it) all return 200. If two of these are on the classpath, the stable sort keeps whatever order `ServiceLoader` found them in, and the other provider is only reported at debug level. The concrete risk is a FIPS deployment where `keycloak-crypto-default` ends up on the classpath by mistake: before this change startup failed with "Multiple crypto providers loaded…", and now Keycloak may quietly run with the non-FIPS BouncyCastle provider. The new ordering only needs to put the low-priority `AuthzClientCryptoProvider` (100) below the others. The error for several providers tied at the highest order should probably stay, or the server providers should get different orders.
common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:63
[P2] Same-order crypto providers are now chosen silently and arbitrarily This change removes the old `Multiple crypto providers loaded` failure without adding a tie check. `DefaultCryptoProvider`, `WildFlyElytronProvider` and `FIPS1402Provider` all return `order() == 200`. If two of them are on the classpath, for example `keycloak-crypto-default` together with `keycloak-crypto-fips1402` or elytron, the sort leaves them in ServiceLoader (classpath) order, and the first one is used. The others are only listed in a debug log. Before this change, that misconfiguration failed fast. Now, for example, a FIPS deployment that accidentally also includes the default BC provider can silently run with the non-FIPS provider. The new ordering only needs to settle the authz-client (100) vs. full-provider (200) case, so the method should still throw when the top two providers have the same `order()`.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 low ✗ —
d3 medium ✗ —
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d2 low ✗ —
d3 medium ✓ off by one
valid · matches d3 · impact medium
valid · impact low
order() is added as an abstract method with no default, and detectProvider now calls it while sorting. A third-party CryptoProvider compiled against the old interface would throw AbstractMethodError once a second provider (for example the new authz-client one) is on the classpath. This breaks binary compatibility, but it needs an unusual setup. [grounded: diff] [consensus 3/4: valid=3, invalid=1]
invalid
The CryptoProvider contract expects getKeyStore to throw for formats the provider cannot support. Before this change the standalone client had no crypto provider at all, and the BC-based default provider (order 200) still wins when it is present. BCFKS failing without BC is expected behavior, not a regression. [invalid: contradiction] [consensus 3/4: invalid=3, uncertain=1]
valid · impact low
The new ECDSA conversion copies only the first signLength bytes and never checks signature.length, so trailing bytes are ignored. ECDSASignatureVerifierContext passes the untrusted signature straight in. This copies the existing BC and Elytron providers, but the flaw is still present in this newly added code. [grounded: diff] [consensus 3/4: valid=3, invalid=1]
invalid
When a full provider is on the same classpath, its higher order (200) means it is chosen over AuthzClientCryptoProvider (100). When no full provider is present, JWE could not have worked before this change either. The claimed failure only happens in a speculative split-classloader setup. [invalid: contradiction] [consensus 3/4: invalid=3, valid=1]
raw comments (7)
common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java:57
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> 1\. Fips mode can use non-fips crypto <code>🐞 Bug</code> <code>⛨ Security</code> <pre> <b><i>detectProvider</i></b> sorts providers only by descending <b><i>order()</i></b> and returns the first result without resolving equal priorities. When the default and FIPS services are visible together, both report <b><i>200</i></b>, so classpath encounter order can select the default implementation for operations expected to use FIPS crypto. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description Default and FIPS crypto providers have equal priority, so automatic discovery can select the non-FIPS provider according to classpath encounter order. ## Fix Focus Areas - common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java[54-71] - crypto/default/src/main/java/org/keycloak/crypto/def/DefaultCryptoProvider.java[82-85] - crypto/fips1402/src/main/java/org/keycloak/crypto/fips/FIPS1402Provider.java[113-116] ## Recommended Fix Assign intentional, distinct priorities where automatic selection is valid, or reject equal highest-priority providers with an explicit configuration error rather than selecting one according to ServiceLoader order. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
common/src/main/java/org/keycloak/common/crypto/CryptoProvider.java:44
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> 2\. Existing crypto extensions stop startup <code>🐞 Bug</code> <code>≡ Correctness</code> <pre> <b><i>CryptoProvider.order()</i></b> is added as an abstract interface method, and <b><i>detectProvider</i></b> invokes it while sorting service-loaded implementations. An extension compiled against the previous interface has no implementation, so discovery with another provider reaches an <b><i>AbstractMethodError</i></b> before any provider can be selected. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description Adding an abstract method to the public crypto provider SPI breaks previously compiled service implementations when provider discovery invokes the method. ## Fix Focus Areas - common/src/main/java/org/keycloak/common/crypto/CryptoProvider.java[39-44] - common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java[54-58] ## Recommended Fix Make `order()` a default interface method returning a neutral priority such as zero, then let current providers override it with their desired precedence. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java:200
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> 3\. Fips keystores block client login <code>🐞 Bug</code> <code>≡ Correctness</code> <pre> <b><i>AuthzClientCryptoProvider.getKeyStore</i></b> requests <b><i>BCFKS</i></b> by name from the installed JCA providers even though the standalone authorization client does not install or depend on a provider implementing that format. JWT client credentials configured with the accepted <b><i>BCFKS</i></b> keystore type therefore fail while loading the signing key, preventing authorization-client token acquisition. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description The standalone authorization-client provider accepts the shared BCFKS keystore format but cannot obtain that format from its available security providers. ## Fix Focus Areas - authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java[60-67] - authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java[197-200] - authz/client/pom.xml[27-44] ## Recommended Fix Either install and use the appropriate Bouncy Castle provider for BCFKS keystores, including its required runtime dependency, or explicitly constrain and validate the standalone provider's supported formats before JWT credential initialization. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java:110
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> 4\. Signature checks accept appended data <code>🐞 Bug</code> <code>⛨ Security</code> <pre> <b><i>concatenatedRSToASN1DER</i></b> copies only the first <b><i>signLength</i></b> bytes of <b><i>signature</i></b> and never verifies that the supplied array has that exact length. <b><i>ECDSASignatureVerifierContext</i></b> passes the complete untrusted JWS signature into this conversion, so a valid fixed-length signature with arbitrary trailing bytes is verified as its valid prefix. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` Issue description `concatenatedRSToASN1DER` silently discards bytes after the expected raw ECDSA signature length, allowing non-canonical JWS signature values to verify. Fix Focus Areas - authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java[103-110] Recommended Fix Validate that `signature` is non-null and `signature.length == signLength` before copying either component. Throw `IOException` when it is not exact, so the existing verifier path rejects malformed signatures. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
authz/client/src/main/java/org/keycloak/authorization/client/AuthzClient.java:95
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> 5\. Encrypted requests fail after client startup <code>🐞 Bug</code> <code>≡ Correctness</code> <pre> <b><i>AuthzClient.create</i></b> initializes the process-wide <b><i>CryptoIntegration</i></b> singleton with <b><i>AuthzClientCryptoProvider</i></b>, although that provider throws <b><i>UnsupportedOperationException</i></b> from <b><i>getAlgorithmProvider</i></b>. When this is the first initialization in a JVM and later Keycloak-core code processes a non-direct JWE, <b><i>JWERegistry</i></b> reaches that unsupported method and the later initialization cannot replace the singleton. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` Issue description Creating an authorization client installs a partial crypto provider into the process-wide singleton, causing unrelated Keycloak crypto features that require unsupported provider methods to fail. Fix Focus Areas - authz/client/src/main/java/org/keycloak/authorization/client/AuthzClient.java[95-95] - authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java[74-77] Recommended Fix Do not initialize `CryptoIntegration` from `AuthzClient.create` unless the registered provider fully implements the `CryptoProvider` contract. If this provider must remain selectable, implement the operations that core call paths require rather than installing a provider that throws for them. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
PR-level
<h3>PR Summary by Qodo</h3> Enable standalone ECDSA crypto support in the authorization client <code>🐞 Bug fix</code> <code>✨ Enhancement</code> <code>🧪 Tests</code> <code>🕐 40+ Minutes</code> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <details> <summary>AI Description</summary> <dl> <dd> <br/> ><pre> >• Add a lightweight standalone ECDSA provider without requiring Bouncy Castle. >• Rank crypto providers so complete implementations override the authorization-client fallback. >• Initialize crypto integration and test ES256, ES384, and ES512 conversions. ></pre> </dd> </dl> </details> <details> <summary>Diagram</summary> <dl> <dd> <br/> ```mermaid graph TD A["AuthzClient"] --> B["Provider Discovery"] --> C["Order Ranking"] --> D["Selected Provider"] --> E["ECDSA Conversion"] --> F["ASN.1 Codec"] G["Authz Provider 100"] --> B H["Full Providers 200"] --> B ``` </dd> </dl> </details> <details> <summary>High-Level Assessment</summary> <dl> <dd> <br/> >The following are alternative approaches to this PR: <details> <summary><b>1. Require the default crypto provider</b></summary> <dl> <dd> - ➕ Reuses the established Bouncy Castle DER implementation. - ➕ Provides the complete CryptoProvider feature set. - ➖ Adds a substantial dependency to the standalone authorization client. - ➖ Introduces Bouncy Castle and FIPS classpath coupling for limited ECDSA needs. </dd> </dl> </details> <details> <summary><b>2. Centralize a dependency-free DER codec</b></summary> <dl> <dd> - ➕ Makes the conversion implementation reusable across crypto providers. - ➕ Keeps low-level ASN.1 parsing out of the authorization-client module. - ➖ Expands the common crypto module with a narrowly scoped internal codec. - ➖ Still requires maintaining custom security-sensitive DER parsing. </dd> </dl> </details> >**Recommendation:** The lightweight fallback provider is the best fit for preserving the authorization client&#x27;s small, standalone dependency footprint, while priority ordering correctly favors complete providers when present. Consider centralizing the codec only if another module needs dependency-free DER conversion; otherwise keep it scoped here and strengthen malformed, truncated, and oversized DER test coverage. </dd> </dl> </details> <details> <summary> Files changed (12) <code> +673 / -9 </code> </summary> <dl> <dd> <br/> <details> <summary>Enhancement (8) <code> +566 / -9 </code></summary> <dl> <dd> <details> <summary>ASN1Decoder.java<code>Add dependency-free ASN.1 DER decoder</code> <code>+203/-0</code></summary> <br/> >Add dependency-free ASN.1 DER decoder > ><pre> >• Introduces a bounded decoder for ASN.1 sequences, integers, tags, and DER lengths used when converting ECDSA signatures. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/50/files#diff-2197c5c4bae10b47ab382a240df36446404c3e4da7f28deed4abbdc815554eaf'>authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Decoder.java</a> </details> <details> <summary>ASN1Encoder.java<code>Add dependency-free ASN.1 DER encoder</code> <code>+101/-0</code></summary> <br/> >Add dependency-free ASN.1 DER encoder > ><pre> >• Introduces encoding for ASN.1 integers, constructed sequences, and short or long-form lengths needed by ECDSA signatures. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/50/files#diff-283968f77d6f71d79cbd9bd98897456359817898ee819ca39e5431fbc9c42c66'>authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/ASN1Encoder.java</a> </details> <details> <summary>AuthzClientCryptoProvider.java<code>Provide lightweight authorization-client cryptography</code> <code>+226/-0</code></summary> <br/> >Provide lightweight authorization-client cryptography > ><pre> >• Adds a fallback CryptoProvider focused on keystore access and ECDSA signature conversion. It converts concatenated R/S signatures to and from ASN.1 DER without Bouncy Castle and explicitly rejects unsupported operations. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/50/files#diff-30cd0a6b08c8c816fa6dc5f297798f5cd68b1cc17002a3f75f2df25d643aa747'>authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java</a> </details> <details> <summary>CryptoIntegration.java<code>Select crypto providers by priority</code> <code>+9/-3</code></summary> <br/> >Select crypto providers by priority > ><pre> >• Sorts ServiceLoader results by descending provider order, selects the highest-priority implementation, and logs lower-priority providers instead of rejecting multiple implementations. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/50/files#diff-3636e017b05aff2059498a9f5f11e761e0017ddf4453fa34d34eba14bceca3b5'>common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java</a> </details> <details> <summary>CryptoProvider.java<code>Add crypto provider ordering contract</code> <code>+8/-1</code></summary> <br/> >Add crypto provider ordering contract > ><pre> >• Adds an order method to CryptoProvider so multiple classpath implementations can declare deterministic precedence. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/50/files#diff-fa5777cfd047b2664b6c4a00a0224d3e923fd5568b7acc446ea73dc05f76551c'>common/src/main/java/org/keycloak/common/crypto/CryptoProvider.java</a> </details> <details> <summary>DefaultCryptoProvider.java<code>Prioritize the default crypto provider</code> <code>+5/-1</code></summary> <br/> >Prioritize the default crypto provider > ><pre> >• Assigns the complete default crypto provider order 200 so it overrides the authorization-client fallback. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/50/files#diff-3b74bc18910722710877fc6561178c22ea882996f82cc8b08b089dcb2faed6c0'>crypto/default/src/main/java/org/keycloak/crypto/def/DefaultCryptoProvider.java</a> </details> <details> <summary>WildFlyElytronProvider.java<code>Prioritize the Elytron crypto provider</code> <code>+5/-0</code></summary> <br/> >Prioritize the Elytron crypto provider > ><pre> >• Assigns the complete WildFly Elytron provider order 200 so it overrides the authorization-client fallback. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/50/files#diff-938cb3c90dce9b94ad2d53b1f2bf3227e3836cee1cc5e212d91b97f1993e58fb'>crypto/elytron/src/main/java/org/keycloak/crypto/elytron/WildFlyElytronProvider.java</a> </details> <details> <summary>FIPS1402Provider.java<code>Prioritize the FIPS crypto provider</code> <code>+9/-4</code></summary> <br/> >Prioritize the FIPS crypto provider > ><pre> >• Assigns the complete FIPS 140-2 provider order 200 so it overrides the authorization-client fallback. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/50/files#diff-cfd1657dd569b6f6d63a402ae1199f5ba1a45634edaf871961c52f15d1075e92'>crypto/fips1402/src/main/java/org/keycloak/crypto/fips/FIPS1402Provider.java</a> </details> </dd> </dl> </details> <details> <summary>Bug fix (1) <code> +2 / -0 </code></summary> <dl> <dd> <details> <summary>AuthzClient.java<code>Initialize crypto integration during client creation</code> <code>+2/-0</code></summary> <br/> >Initialize crypto integration during client creation > ><pre> >• Initializes CryptoIntegration with the authorization client&#x27;s class loader before constructing the client, ensuring a usable crypto provider is selected. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/50/files#diff-c7af1eedd27aa5e501a825e517712b1fcb87a12c57fd8deea9c40737d34138da'>authz/client/src/main/java/org/keycloak/authorization/client/AuthzClient.java</a> </details> </dd> </dl> </details> <details> <summary>Tests (1) <code> +74 / -0 </code></summary> <dl> <dd> <details> <summary>ECDSAAlgorithmTest.java<code>Test ECDSA signature format round trips</code> <code>+74/-0</code></summary> <br/> >Test ECDSA signature format round trips > ><pre> >• Generates an EC key pair and verifies DER-to-concatenated-to-DER conversion behavior for ES256, ES384, and ES512 signature lengths. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/50/files#diff-27658a61bd8b05433b5db3fc2ebe65ca202865edfaf94b2742a10942dfa6fee6'>authz/client/src/test/java/org/keycloak/authorization/client/test/ECDSAAlgorithmTest.java</a> </details> </dd> </dl> </details> <details> <summary>Other (2) <code> +31 / -0 </code></summary> <dl> <dd> <details> <summary>pom.xml<code>Add authorization-client test dependencies</code> <code>+11/-0</code></summary> <br/> >Add authorization-client test dependencies > ><pre> >• Adds JUnit and Hamcrest as test-scoped dependencies for the new ECDSA conversion tests. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/50/files#diff-758bb5c84208e1cae9d37c0a110979c20b510c593214fd4312fd9fd3f8556501'>authz/client/pom.xml</a> </details> <details> <summary>org.keycloak.common.crypto.CryptoProvider<code>Register the authorization-client crypto provider</code> <code>+20/-0</code></summary> <br/> >Register the authorization-client crypto provider > ><pre> >• Registers AuthzClientCryptoProvider for discovery through Java ServiceLoader. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/50/files#diff-0154c06e95e7d2950cfcb9fae0783aeb54161a0aac6e42995c988e0357d43648'>authz/client/src/main/resources/META-INF/services/org.keycloak.common.crypto.CryptoProvider</a> </details> </dd> </dl> </details> </dd> </dl> </details>
PR-level
<h3>Code Review by Qodo</h3> <code>🐞 Bugs (5)</code> <code>📘 Rule violations (0)</code> <code>📜 Skill insights (0)</code> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <br/> <img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> <details> <summary> 1. FIPS mode can use non-FIPS crypto <code>🐞 Bug</code> <code>⛨ Security</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>detectProvider</i></b> sorts providers only by descending <b><i>order()</i></b> and returns the first result without >resolving equal priorities. When the default and FIPS services are visible together, both report ><b><i>200</i></b>, so classpath encounter order can select the default implementation for operations expected to >use FIPS crypto. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java[57]](https://github.com/drape-io/crbench-qodo-2026-09/pull/50/files#diff-3636e017b05aff2059498a9f5f11e761e0017ddf4453fa34d34eba14bceca3b5R57-R57)</code> > >```diff >+ .sorted(Comparator.comparingInt(CryptoProvider::order).reversed()) >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >Provider discovery returns the first element after sorting solely by <b><i>order</i></b>, while the default and >FIPS implementations added by this PR both return <b><i>200</i></b>; both are registered as service >implementations, making their relative selection dependent on service discovery order whenever they >share a loader. ></pre> > > <code>[common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java[54-71]](https://github.com/drape-io/crbench-qodo-2026-09/blob/1c32f476a6003fc45d16bb34798d7b5f5038b539/common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java/#L54-L71)</code> > <code>[crypto/default/src/main/java/org/keycloak/crypto/def/DefaultCryptoProvider.java[82-85]](https://github.com/drape-io/crbench-qodo-2026-09/blob/1c32f476a6003fc45d16bb34798d7b5f5038b539/crypto/default/src/main/java/org/keycloak/crypto/def/DefaultCryptoProvider.java/#L82-L85)</code> > <code>[crypto/fips1402/src/main/java/org/keycloak/crypto/fips/FIPS1402Provider.java[113-116]](https://github.com/drape-io/crbench-qodo-2026-09/blob/1c32f476a6003fc45d16bb34798d7b5f5038b539/crypto/fips1402/src/main/java/org/keycloak/crypto/fips/FIPS1402Provider.java/#L113-L116)</code> > <code>[crypto/default/src/main/resources/META-INF/services/org.keycloak.common.crypto.CryptoProvider[18-18]](https://github.com/drape-io/crbench-qodo-2026-09/blob/1c32f476a6003fc45d16bb34798d7b5f5038b539/crypto/default/src/main/resources/META-INF/services/org.keycloak.common.crypto.CryptoProvider/#L18-L18)</code> > <code>[crypto/fips1402/src/main/resources/META-INF/services/org.keycloak.common.crypto.CryptoProvider[18-18]](https://github.com/drape-io/crbench-qodo-2026-09/blob/1c32f476a6003fc45d16bb34798d7b5f5038b539/crypto/fips1402/src/main/resources/META-INF/services/org.keycloak.common.crypto.CryptoProvider/#L18-L18)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >Default and FIPS crypto providers have equal priority, so automatic discovery can select the non-FIPS provider according to classpath encounter order. > >## Fix Focus Areas >- common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java[54-71] >- crypto/default/src/main/java/org/keycloak/crypto/def/DefaultCryptoProvider.java[82-85] >- crypto/fips1402/src/main/java/org/keycloak/crypto/fips/FIPS1402Provider.java[113-116] > >## Recommended Fix >Assign intentional, distinct priorities where automatic selection is valid, or reject equal highest-priority providers with an explicit configuration error rather than selecting one according to ServiceLoader order. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <details> <summary> 2. Existing crypto extensions stop startup <code>🐞 Bug</code> <code>≡ Correctness</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>CryptoProvider.order()</i></b> is added as an abstract interface method, and <b><i>detectProvider</i></b> invokes it >while sorting service-loaded implementations. An extension compiled against the previous interface >has no implementation, so discovery with another provider reaches an <b><i>AbstractMethodError</i></b> before >any provider can be selected. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[common/src/main/java/org/keycloak/common/crypto/CryptoProvider.java[R42-44]](https://github.com/drape-io/crbench-qodo-2026-09/pull/50/files#diff-fa5777cfd047b2664b6c4a00a0224d3e923fd5568b7acc446ea73dc05f76551cR42-R44)</code> > >```diff >+ * The higher number has preference over the lower number >+ */ >+ int order(); >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >The new method has no default body and the comparator invokes it on discovered services. Existing >evolution-prone methods in this interface and the analogous provider-factory ordering API use >defaults, demonstrating the repository&#x27;s compatible SPI pattern. ></pre> > > <code>[common/src/main/java/org/keycloak/common/crypto/CryptoProvider.java[39-44]](https://github.com/drape-io/crbench-qodo-2026-09/blob/1c32f476a6003fc45d16bb34798d7b5f5038b539/common/src/main/java/org/keycloak/common/crypto/CryptoProvider.java/#L39-L44)</code> > <code>[common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java[54-58]](https://github.com/drape-io/crbench-qodo-2026-09/blob/1c32f476a6003fc45d16bb34798d7b5f5038b539/common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java/#L54-L58)</code> > <code>[common/src/main/java/org/keycloak/common/crypto/CryptoProvider.java[101-113]](https://github.com/drape-io/crbench-qodo-2026-09/blob/1c32f476a6003fc45d16bb34798d7b5f5038b539/common/src/main/java/org/keycloak/common/crypto/CryptoProvider.java/#L101-L113)</code> > <code>[server-spi/src/main/java/org/keycloak/provider/ProviderFactory.java[56-60]](https://github.com/drape-io/crbench-qodo-2026-09/blob/1c32f476a6003fc45d16bb34798d7b5f5038b539/server-spi/src/main/java/org/keycloak/provider/ProviderFactory.java/#L56-L60)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >Adding an abstract method to the public crypto provider SPI breaks previously compiled service implementations when provider discovery invokes the method. > >## Fix Focus Areas >- common/src/main/java/org/keycloak/common/crypto/CryptoProvider.java[39-44] >- common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java[54-58] > >## Recommended Fix >Make `order()` a default interface method returning a neutral priority such as zero, then let current providers override it with their desired precedence. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <br/> <img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended"> <details> <summary> 3. FIPS keystores block client login <code>🐞 Bug</code> <code>≡ Correctness</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>AuthzClientCryptoProvider.getKeyStore</i></b> requests <b><i>BCFKS</i></b> by name from the installed JCA providers >even though the standalone authorization client does not install or depend on a provider >implementing that format. JWT client credentials configured with the accepted <b><i>BCFKS</i></b> keystore type >therefore fail while loading the signing key, preventing authorization-client token acquisition. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java[R198-200]](https://github.com/drape-io/crbench-qodo-2026-09/pull/50/files#diff-30cd0a6b08c8c816fa6dc5f297798f5cd68b1cc17002a3f75f2df25d643aa747R198-R200)</code> > >```diff >+ public KeyStore getKeyStore(KeystoreUtil.KeystoreFormat format) throws KeyStoreException, NoSuchProviderException { >+ return KeyStore.getInstance(format.name()); >+ } >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >JWT credential initialization maps <b><i>client-keystore-type</i></b> to the shared enum, which includes ><b><i>BCFKS</i></b>, and delegates loading to the selected crypto provider. The new standalone implementation >uses unqualified <b><i>KeyStore.getInstance(format.name())</i></b>, while its module has no default or FIPS >crypto-provider runtime dependency. ></pre> > > <code>[core/src/main/java/org/keycloak/protocol/oidc/client/authentication/JWTClientCredentialsProvider.java[121-142]](https://github.com/drape-io/crbench-qodo-2026-09/blob/1c32f476a6003fc45d16bb34798d7b5f5038b539/core/src/main/java/org/keycloak/protocol/oidc/client/authentication/JWTClientCredentialsProvider.java/#L121-L142)</code> > <code>[common/src/main/java/org/keycloak/common/util/KeystoreUtil.java[40-43]](https://github.com/drape-io/crbench-qodo-2026-09/blob/1c32f476a6003fc45d16bb34798d7b5f5038b539/common/src/main/java/org/keycloak/common/util/KeystoreUtil.java/#L40-L43)</code> > <code>[common/src/main/java/org/keycloak/common/util/KeystoreUtil.java[88-105]](https://github.com/drape-io/crbench-qodo-2026-09/blob/1c32f476a6003fc45d16bb34798d7b5f5038b539/common/src/main/java/org/keycloak/common/util/KeystoreUtil.java/#L88-L105)</code> > <code>[authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java[197-200]](https://github.com/drape-io/crbench-qodo-2026-09/blob/1c32f476a6003fc45d16bb34798d7b5f5038b539/authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java/#L197-L200)</code> > <code>[authz/client/pom.xml[27-44]](https://github.com/drape-io/crbench-qodo-2026-09/blob/1c32f476a6003fc45d16bb34798d7b5f5038b539/authz/client/pom.xml/#L27-L44)</code> > <code>[authz/client/src/main/java/org/keycloak/authorization/client/AuthzClient.java[94-96]](https://github.com/drape-io/crbench-qodo-2026-09/blob/1c32f476a6003fc45d16bb34798d7b5f5038b539/authz/client/src/main/java/org/keycloak/authorization/client/AuthzClient.java/#L94-L96)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >The standalone authorization-client provider accepts the shared BCFKS keystore format but cannot obtain that format from its available security providers. > >## Fix Focus Areas >- authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java[60-67] >- authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java[197-200] >- authz/client/pom.xml[27-44] > >## Recommended Fix >Either install and use the appropriate Bouncy Castle provider for BCFKS keystores, including its required runtime dependency, or explicitly constrain and validate the standalone provider's supported formats before JWT credential initialization. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <details> <summary> 4. Signature checks accept appended data <code>🐞 Bug</code> <code>⛨ Security</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>concatenatedRSToASN1DER</i></b> copies only the first <b><i>signLength</i></b> bytes of <b><i>signature</i></b> and never verifies >that the supplied array has that exact length. <b><i>ECDSASignatureVerifierContext</i></b> passes the complete >untrusted JWS signature into this conversion, so a valid fixed-length signature with arbitrary >trailing bytes is verified as its valid prefix. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java[R109-110]](https://github.com/drape-io/crbench-qodo-2026-09/pull/50/files#diff-30cd0a6b08c8c816fa6dc5f297798f5cd68b1cc17002a3f75f2df25d643aa747R109-R110)</code> > >```diff >+ System.arraycopy(signature, 0, r, 1, len); >+ System.arraycopy(signature, len, s, 1, len); >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >The new conversion reads two fixed-size components without checking the input length, while the >generic verifier directly invokes that conversion on its full signature argument. Therefore bytes >after a valid raw signature are ignored before the JCA verification step. ></pre> > > <code>[authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java[103-121]](https://github.com/drape-io/crbench-qodo-2026-09/blob/1c32f476a6003fc45d16bb34798d7b5f5038b539/authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java/#L103-L121)</code> > <code>[core/src/main/java/org/keycloak/crypto/ECDSASignatureVerifierContext.java[27-34]](https://github.com/drape-io/crbench-qodo-2026-09/blob/1c32f476a6003fc45d16bb34798d7b5f5038b539/core/src/main/java/org/keycloak/crypto/ECDSASignatureVerifierContext.java/#L27-L34)</code> > <code>[core/src/main/java/org/keycloak/crypto/ECDSAAlgorithm.java[45-47]](https://github.com/drape-io/crbench-qodo-2026-09/blob/1c32f476a6003fc45d16bb34798d7b5f5038b539/core/src/main/java/org/keycloak/crypto/ECDSAAlgorithm.java/#L45-L47)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >Issue description >`concatenatedRSToASN1DER` silently discards bytes after the expected raw ECDSA signature length, allowing non-canonical JWS signature values to verify. > >Fix Focus Areas >- authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java[103-110] > >Recommended Fix >Validate that `signature` is non-null and `signature.length == signLength` before copying either component. Throw `IOException` when it is not exact, so the existing verifier path rejects malformed signatures. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <details> <summary> 5. Encrypted requests fail after client startup <code>🐞 Bug</code> <code>≡ Correctness</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>AuthzClient.create</i></b> initializes the process-wide <b><i>CryptoIntegration</i></b> singleton with ><b><i>AuthzClientCryptoProvider</i></b>, although that provider throws <b><i>UnsupportedOperationException</i></b> from ><b><i>getAlgorithmProvider</i></b>. When this is the first initialization in a JVM and later Keycloak-core code >processes a non-direct JWE, <b><i>JWERegistry</i></b> reaches that unsupported method and the later >initialization cannot replace the singleton. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[authz/client/src/main/java/org/keycloak/authorization/client/AuthzClient.java[95]](https://github.com/drape-io/crbench-qodo-2026-09/pull/50/files#diff-c7af1eedd27aa5e501a825e517712b1fcb87a12c57fd8deea9c40737d34138daR95-R95)</code> > >```diff >+ CryptoIntegration.init(AuthzClient.class.getClassLoader()); >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >CryptoIntegration stores only the first detected provider globally. The provider added by this PR >explicitly does not implement algorithm-provider lookup, but core JWE lookup delegates non-direct >encryption algorithms to precisely that operation. ></pre> > > <code>[authz/client/src/main/java/org/keycloak/authorization/client/AuthzClient.java[94-97]](https://github.com/drape-io/crbench-qodo-2026-09/blob/1c32f476a6003fc45d16bb34798d7b5f5038b539/authz/client/src/main/java/org/keycloak/authorization/client/AuthzClient.java/#L94-L97)</code> > <code>[common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java[26-37]](https://github.com/drape-io/crbench-qodo-2026-09/blob/1c32f476a6003fc45d16bb34798d7b5f5038b539/common/src/main/java/org/keycloak/common/crypto/CryptoIntegration.java/#L26-L37)</code> > <code>[authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java[74-77]](https://github.com/drape-io/crbench-qodo-2026-09/blob/1c32f476a6003fc45d16bb34798d7b5f5038b539/authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java/#L74-L77)</code> > <code>[core/src/main/java/org/keycloak/jose/jwe/JWERegistry.java[50-56]](https://github.com/drape-io/crbench-qodo-2026-09/blob/1c32f476a6003fc45d16bb34798d7b5f5038b539/core/src/main/java/org/keycloak/jose/jwe/JWERegistry.java/#L50-L56)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >Issue description >Creating an authorization client installs a partial crypto provider into the process-wide singleton, causing unrelated Keycloak crypto features that require unsupported provider methods to fail. > >Fix Focus Areas >- authz/client/src/main/java/org/keycloak/authorization/client/AuthzClient.java[95-95] >- authz/client/src/main/java/org/keycloak/authorization/client/util/crypto/AuthzClientCryptoProvider.java[74-77] > >Recommended Fix >Do not initialize `CryptoIntegration` from `AuthzClient.create` unless the registered provider fully implements the `CryptoProvider` contract. If this provider must remain selectable, implement the operations that core call paths require rather than installing a provider that throws for them. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-context:start --> <details><summary><strong>Context sources</strong></summary> <div>Review mode: <code>🧠 Deep</code>: This introduces substantial security-sensitive cryptographic and ASN.1 logic while changing provider discovery across multiple modules, creating several independent paths where subtle defects could be missed in one pass.</div> <!-- qodo-context:end --> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-daily-tip:start --> <details> <summary><strong>Tip of the day</strong></summary> <br/> <pre>💡 Did you know, you can reply &#x27;qodo&#x27; on any finding to push back, ask questions, or dig deeper</pre> <a href="https://docs.qodo.ai/tips-and-tricks">More tips ↗</a> | <a href="https://app.qodo.ai/configurations?tab=display-preferences">Customize Qodo ↗</a> | <a href="https://docs.qodo.ai">Qodo docs ↗</a> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-daily-tip:end --> <!-- https://github.com/drape-io/crbench-qodo-2026-09/commit/1c32f476a6003fc45d16bb34798d7b5f5038b539 --> <a href="https://www.qodo.ai"><img src="https://www.qodo.ai/wp-content/uploads/2025/03/qodo-logo.svg" width="80" alt="Qodo Logo"></a>