gnodet-bot commented on code in PR #31032:
URL: https://github.com/apache/camel/pull/31032#discussion_r4723154229


##########
components/camel-pqc/src/test/java/org/apache/camel/component/pqc/dataformat/PQCDataFormatWireFormatTest.java:
##########
@@ -0,0 +1,423 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.pqc.dataformat;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.SecureRandom;
+import java.security.Security;
+
+import javax.crypto.Cipher;
+import javax.crypto.KeyGenerator;
+import javax.crypto.spec.GCMParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.component.pqc.PQCAlgorithmId;
+import org.apache.camel.component.pqc.PQCKeyEncapsulationAlgorithms;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.bouncycastle.jcajce.SecretKeyWithEncapsulation;
+import org.bouncycastle.jcajce.spec.KEMGenerateSpec;
+import org.bouncycastle.jcajce.spec.MLKEMParameterSpec;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Tests that {@link PQCDataFormat}:
+ * <ul>
+ * <li>writes wire format v2 on marshal (8-byte self-describing header)</li>
+ * <li>reads wire format v2 on unmarshal (round-trip)</li>
+ * <li>reads legacy wire format v1 on unmarshal (backward compatibility)</li>
+ * <li>rejects truncated, wrong-version, and wrong-format-type headers</li>
+ * <li>rejects algorithm mismatches between header and configuration (KEM and 
symmetric)</li>
+ * </ul>
+ */
+public class PQCDataFormatWireFormatTest extends CamelTestSupport {
+
+    private static final String PAYLOAD = "CAMEL-27548 wire format v2 test 
payload";
+
+    private static KeyPair keyPair;
+
+    @BeforeAll
+    static void startup() throws Exception {
+        Security.addProvider(new BouncyCastleProvider());
+        Security.addProvider(new BouncyCastlePQCProvider());
+
+        KeyPairGenerator kpg = KeyPairGenerator.getInstance(
+                PQCKeyEncapsulationAlgorithms.MLKEM.getAlgorithm(),
+                PQCKeyEncapsulationAlgorithms.MLKEM.getBcProvider());
+        kpg.initialize(MLKEMParameterSpec.ml_kem_512, new SecureRandom());
+        keyPair = kpg.generateKeyPair();
+    }
+
+    // 
-------------------------------------------------------------------------
+    // Helper: build a PQCDataFormat with the shared key pair
+    // 
-------------------------------------------------------------------------
+
+    private PQCDataFormat newFormat() {
+        PQCDataFormat fmt = new PQCDataFormat();
+        fmt.setKeyEncapsulationAlgorithm("MLKEM");
+        fmt.setSymmetricKeyAlgorithm("AES");
+        fmt.setKeyPair(keyPair);
+        return fmt;
+    }
+
+    // 
-------------------------------------------------------------------------
+    // Test: marshal writes v2 header
+    // 
-------------------------------------------------------------------------
+
+    @Test
+    void marshalWritesV2Header() throws Exception {
+        PQCDataFormat fmt = newFormat();
+        fmt.start();
+        try {
+            Exchange exchange = new DefaultExchange(context());
+            ByteArrayOutputStream out = new ByteArrayOutputStream();
+            fmt.marshal(exchange, PAYLOAD.getBytes(StandardCharsets.UTF_8), 
out);
+
+            byte[] ciphertext = out.toByteArray();
+            assertNotNull(ciphertext);
+
+            // First two bytes must be magic bytes 0x50, 0x51
+            assertEquals(PQCDataFormat.MAGIC_BYTE_0, ciphertext[0],
+                    "Expected magic byte 0 (0x50) but got 0x" + 
Integer.toHexString(ciphertext[0] & 0xFF));
+            assertEquals(PQCDataFormat.MAGIC_BYTE_1, ciphertext[1],
+                    "Expected magic byte 1 (0x51) but got 0x" + 
Integer.toHexString(ciphertext[1] & 0xFF));
+
+            // Byte 2: version
+            assertEquals(PQCDataFormat.WIRE_VERSION, ciphertext[2], "Expected 
wire format version 0x02");
+
+            // Byte 3: format type
+            assertEquals(PQCDataFormat.FORMAT_TYPE_KEM, ciphertext[3], 
"Expected format type 0x03 (KEM)");
+
+            // Bytes 4-5: KEM algorithm ID — should resolve to ML_KEM (0x0401)
+            int kemAlgId = ((ciphertext[4] & 0xFF) << 8) | (ciphertext[5] & 
0xFF);
+            assertEquals(PQCAlgorithmId.ML_KEM.getId(), kemAlgId,
+                    "Expected KEM alg ID for ML-KEM (0x" + 
Integer.toHexString(PQCAlgorithmId.ML_KEM.getId()) + ")"
+                                                                  + " but got 
0x" + Integer.toHexString(kemAlgId));
+
+            // Bytes 6-7: symmetric algorithm ID — should resolve to AES 
(0x0501)
+            int symAlgId = ((ciphertext[6] & 0xFF) << 8) | (ciphertext[7] & 
0xFF);
+            assertEquals(PQCAlgorithmId.AES.getId(), symAlgId,
+                    "Expected sym alg ID for AES (0x" + 
Integer.toHexString(PQCAlgorithmId.AES.getId()) + ")"
+                                                               + " but got 0x" 
+ Integer.toHexString(symAlgId));
+        } finally {
+            fmt.stop();
+        }
+    }
+
+    // 
-------------------------------------------------------------------------
+    // Test: marshal/unmarshal round-trip using v2 format
+    // 
-------------------------------------------------------------------------
+
+    @Test
+    void v2RoundTrip() throws Exception {
+        PQCDataFormat fmt = newFormat();
+        fmt.start();
+        try {
+            Exchange exchange = new DefaultExchange(context());
+            byte[] original = PAYLOAD.getBytes(StandardCharsets.UTF_8);
+
+            // Marshal
+            ByteArrayOutputStream out = new ByteArrayOutputStream();
+            fmt.marshal(exchange, original, out);
+
+            // Unmarshal
+            byte[] decrypted = (byte[]) fmt.unmarshal(exchange, new 
ByteArrayInputStream(out.toByteArray()));
+            assertArrayEquals(original, decrypted, "Decrypted bytes must match 
original");
+        } finally {
+            fmt.stop();
+        }
+    }
+
+    // 
-------------------------------------------------------------------------
+    // Test: unmarshal reads legacy v1 format (backward compatibility)
+    // 
-------------------------------------------------------------------------
+
+    @Test
+    void v1BackwardCompatibility() throws Exception {
+        PQCDataFormat fmt = newFormat();
+        fmt.start();
+        try {
+            byte[] original = PAYLOAD.getBytes(StandardCharsets.UTF_8);
+
+            // Build a v1 message manually:
+            // [4B encap len][encap][12B nonce][ciphertext+tag]
+            byte[] v1Bytes = buildV1Message(original, keyPair);
+
+            // The first two bytes of a v1 message must NOT be 0x50 0x51
+            assertEquals(0x00, v1Bytes[0] & 0xFF,
+                    "v1 test message must not start with 0x50 (would be 
mis-detected as v2)");
+
+            // Unmarshal must succeed and return the original plaintext
+            Exchange exchange = new DefaultExchange(context());
+            byte[] decrypted = (byte[]) fmt.unmarshal(exchange, new 
ByteArrayInputStream(v1Bytes));
+            assertArrayEquals(original, decrypted, "v1 backward-compat: 
decrypted bytes must match original");
+        } finally {
+            fmt.stop();
+        }
+    }
+
+    // 
-------------------------------------------------------------------------
+    // Test: tampered header is rejected (AAD binding)
+    // 
-------------------------------------------------------------------------
+
+    @Test
+    void tamperedHeaderIsRejected() throws Exception {
+        PQCDataFormat fmt = newFormat();
+        fmt.start();
+        try {
+            Exchange exchange = new DefaultExchange(context());
+            byte[] original = PAYLOAD.getBytes(StandardCharsets.UTF_8);
+
+            ByteArrayOutputStream out = new ByteArrayOutputStream();
+            fmt.marshal(exchange, original, out);
+            byte[] ciphertext = out.toByteArray();
+
+            // Flip a bit in the KEM algorithm ID field (byte 4) — this is 
part of the AAD-bound header
+            ciphertext[4] ^= 0x01;

Review Comment:
   The flip targets byte 4 (the KEM algorithm ID), which changes kemAlgId from 
ML-KEM (0x0401) to 0x0501 (AES). This triggers the **algorithm ID mismatch 
check** in `unmarshalV2` *before* `decryptPayload` is ever called — the AEAD 
tag is never verified. If `cipher.updateAAD(headerBytes)` were accidentally 
removed, this test would still pass.
   
   To cover the AAD defense layer independently, add a test that tampers a byte 
that bypasses the structural validation. The simplest approach: flip a byte in 
the header where the configured algorithm does **not** have a known ID (so the 
mismatch check skips it), leaving the AEAD tag as the only defense. For example:
   
   ```java
   @Test
   void tamperedHeaderAadIsEnforced() throws Exception {
       PQCDataFormat fmt = newFormat();
       fmt.start();
       try {
           Exchange exchange = new DefaultExchange(context());
           ByteArrayOutputStream out = new ByteArrayOutputStream();
           fmt.marshal(exchange, PAYLOAD.getBytes(StandardCharsets.UTF_8), out);
           byte[] ciphertext = out.toByteArray();
   
           // Flip a bit in the magic bytes area that passes all structural 
checks
           // but invalidates the AAD — here, change magic byte 1 to something 
that
           // still matches MAGIC_BYTE_1 XOR 0 to demonstrate an alternative 
approach:
           // tamper symAlgId (byte 7) while ensuring fromJcaName(symAlg) 
returns UNKNOWN
           // so the mismatch guard is skipped, leaving only the AEAD tag to 
catch it.
           // Simplest: use a symmetric algo not in PQCAlgorithmId registry, or 
call decryptPayload
           // directly via reflection with a modified headerBytes array.
           // The key assertion: AEADBadTagException is thrown.
       } finally {
           fmt.stop();
       }
   }
   ```
   
   Alternatively, call `decryptPayload` via reflection with a correct 
ciphertext but incorrect `headerBytes` (one byte flipped) and assert the AEAD 
tag fails.



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

To unsubscribe, e-mail: [email protected]

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

Reply via email to