oscerd commented on code in PR #28105:
URL: https://github.com/apache/camel/pull/28105#discussion_r4314490218


##########
components/camel-pqc/src/main/java/org/apache/camel/component/pqc/lifecycle/FileBasedKeyLifecycleManager.java:
##########
@@ -253,9 +254,30 @@ public void deleteKey(String keyId) throws Exception {
         LOG.info("Deleted key: {}", keyId);
     }
 
+    /**
+     * Lists the keys by scanning the key directory, not by reading the cache.
+     * <p/>
+     * The cache is only filled by this process, so returning it would hide 
any key file written after start-up - by
+     * another process, by an operator restoring a backup, or by a sidecar. 
That matters directly for
+     * {@link KeyRotationScheduler}, which drives entirely off this method and 
would otherwise stop rotating anything it
+     * had not seen at boot. The other implementations all query their backing 
store here.
+     */
     @Override
     public List<KeyMetadata> listKeys() throws Exception {
-        return new ArrayList<>(metadataCache.values());
+        List<KeyMetadata> keys = new ArrayList<>();
+        try (Stream<Path> files = Files.list(keyDirectory)) {
+            for (String keyId : files.filter(path -> 
path.toString().endsWith(METADATA_SUFFIX))
+                    .map(path -> path.getFileName().toString())
+                    .map(name -> name.substring(0, name.length() - 
METADATA_SUFFIX.length()))
+                    .sorted()
+                    .toList()) {
+                KeyMetadata metadata = getKeyMetadata(keyId);

Review Comment:
   Fixed in ffbe5415. Each file is read in its own `try`, logged at WARN with 
the path, and skipped, matching `loadExistingKeys()`.
   
   Your reasoning about the empty file was exactly right. The new test drops 
both a garbage and an empty `.metadata` next to a good key; against the 
previous commit it fails with `java.io.StreamCorruptedException: invalid stream 
header: 6E6F7420` — the legacy `ObjectInputStream` path, as you predicted.
   
   _Claude Code on behalf of @oscerd_



##########
components/camel-pqc/src/main/java/org/apache/camel/component/pqc/lifecycle/FileBasedKeyLifecycleManager.java:
##########
@@ -253,9 +254,30 @@ public void deleteKey(String keyId) throws Exception {
         LOG.info("Deleted key: {}", keyId);
     }
 
+    /**
+     * Lists the keys by scanning the key directory, not by reading the cache.

Review Comment:
   Fair, the javadoc claimed more than the code does. Reworded in ffbe5415 to 
say that the scan finds a key file written by another process, but that the 
metadata of a key this process already knows still comes from the cache, so a 
status written elsewhere for it is not seen until a restart.
   
   I kept the cache rather than reading every file on each call: 
`KeyRotationScheduler` polls this on a timer, and re-reading and re-parsing 
every key on every tick is a real cost for a store of any size. If you would 
rather have freshness than that, I am happy to drop the cache lookup here — it 
is a one-line change.
   
   _Claude Code on behalf of @oscerd_



##########
components/camel-pqc/src/test/java/org/apache/camel/component/pqc/lifecycle/KeyLifecycleParityTest.java:
##########
@@ -0,0 +1,138 @@
+/*
+ * 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.lifecycle;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.SecureRandom;
+import java.security.Security;
+import java.util.List;
+
+import org.bouncycastle.jcajce.spec.MLDSAParameterSpec;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Behaviour the five KeyLifecycleManager implementations are expected to 
share, but did not.
+ */
+class KeyLifecycleParityTest {
+
+    @TempDir
+    Path keyDirectory;
+
+    @BeforeEach
+    void addProviders() {
+        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
+            Security.addProvider(new BouncyCastleProvider());
+        }
+        if (Security.getProvider(BouncyCastlePQCProvider.PROVIDER_NAME) == 
null) {
+            Security.addProvider(new BouncyCastlePQCProvider());
+        }
+    }
+
+    private static KeyPair mldsaKeyPair() throws Exception {
+        KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-DSA", "BC");
+        kpg.initialize(MLDSAParameterSpec.ml_dsa_65, new SecureRandom());
+        return kpg.generateKeyPair();
+    }
+
+    @Test
+    void fileBasedListKeysSeesAKeyWrittenAfterStartup() throws Exception {
+        FileBasedKeyLifecycleManager writer = new 
FileBasedKeyLifecycleManager(keyDirectory.toString());
+        FileBasedKeyLifecycleManager reader = new 
FileBasedKeyLifecycleManager(keyDirectory.toString());
+
+        assertTrue(reader.listKeys().isEmpty(), "nothing stored yet");
+
+        // a second process, a restored backup or a sidecar writing into the 
same directory
+        writer.generateKeyPair("MLDSA", "late-key");
+
+        List<KeyMetadata> keys = reader.listKeys();
+        assertEquals(1, keys.size(), "listKeys must scan the directory, not an 
in-process cache");
+        assertEquals("late-key", keys.get(0).getKeyId());
+    }
+
+    @Test
+    void fileBasedListKeysIgnoresNonMetadataFiles() throws Exception {
+        FileBasedKeyLifecycleManager manager = new 
FileBasedKeyLifecycleManager(keyDirectory.toString());
+        manager.generateKeyPair("MLDSA", "a-key");
+        Files.writeString(keyDirectory.resolve("notes.txt"), "not a key");
+
+        List<KeyMetadata> keys = manager.listKeys();
+        assertEquals(1, keys.size(), "only .metadata files describe a key");
+        assertEquals("a-key", keys.get(0).getKeyId());
+    }
+
+    @Test
+    void aCombinedPemExportCanBeImportedBack() throws Exception {
+        KeyPair original = mldsaKeyPair();
+
+        byte[] pem = KeyFormatConverter.exportKeyPair(original, 
KeyLifecycleManager.KeyFormat.PEM, true);
+        String text = new String(pem, java.nio.charset.StandardCharsets.UTF_8);

Review Comment:
   Fixed in ffbe5415 — imported and used as the simple name.
   
   _Claude Code on behalf of @oscerd_



##########
components/camel-pqc/src/test/java/org/apache/camel/component/pqc/lifecycle/KeyLifecycleParityTest.java:
##########
@@ -0,0 +1,138 @@
+/*
+ * 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.lifecycle;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.SecureRandom;
+import java.security.Security;
+import java.util.List;
+
+import org.bouncycastle.jcajce.spec.MLDSAParameterSpec;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Behaviour the five KeyLifecycleManager implementations are expected to 
share, but did not.
+ */
+class KeyLifecycleParityTest {
+
+    @TempDir
+    Path keyDirectory;
+
+    @BeforeEach
+    void addProviders() {
+        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
+            Security.addProvider(new BouncyCastleProvider());
+        }
+        if (Security.getProvider(BouncyCastlePQCProvider.PROVIDER_NAME) == 
null) {
+            Security.addProvider(new BouncyCastlePQCProvider());
+        }
+    }
+
+    private static KeyPair mldsaKeyPair() throws Exception {
+        KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-DSA", "BC");
+        kpg.initialize(MLDSAParameterSpec.ml_dsa_65, new SecureRandom());
+        return kpg.generateKeyPair();
+    }
+
+    @Test
+    void fileBasedListKeysSeesAKeyWrittenAfterStartup() throws Exception {
+        FileBasedKeyLifecycleManager writer = new 
FileBasedKeyLifecycleManager(keyDirectory.toString());
+        FileBasedKeyLifecycleManager reader = new 
FileBasedKeyLifecycleManager(keyDirectory.toString());
+
+        assertTrue(reader.listKeys().isEmpty(), "nothing stored yet");
+
+        // a second process, a restored backup or a sidecar writing into the 
same directory
+        writer.generateKeyPair("MLDSA", "late-key");
+
+        List<KeyMetadata> keys = reader.listKeys();
+        assertEquals(1, keys.size(), "listKeys must scan the directory, not an 
in-process cache");
+        assertEquals("late-key", keys.get(0).getKeyId());
+    }
+
+    @Test
+    void fileBasedListKeysIgnoresNonMetadataFiles() throws Exception {
+        FileBasedKeyLifecycleManager manager = new 
FileBasedKeyLifecycleManager(keyDirectory.toString());
+        manager.generateKeyPair("MLDSA", "a-key");
+        Files.writeString(keyDirectory.resolve("notes.txt"), "not a key");
+
+        List<KeyMetadata> keys = manager.listKeys();
+        assertEquals(1, keys.size(), "only .metadata files describe a key");
+        assertEquals("a-key", keys.get(0).getKeyId());
+    }
+
+    @Test
+    void aCombinedPemExportCanBeImportedBack() throws Exception {
+        KeyPair original = mldsaKeyPair();
+
+        byte[] pem = KeyFormatConverter.exportKeyPair(original, 
KeyLifecycleManager.KeyFormat.PEM, true);
+        String text = new String(pem, java.nio.charset.StandardCharsets.UTF_8);
+        assertTrue(text.contains("-----BEGIN PUBLIC KEY-----"), "the export 
must carry the public block");
+        assertTrue(text.contains("-----BEGIN PRIVATE KEY-----"), "the export 
must carry the private block");
+
+        // before the fix, stripping only the PRIVATE armour left the PUBLIC 
armour in the Base64 input
+        assertNotNull(KeyFormatConverter.importPrivateKey(pem, 
KeyLifecycleManager.KeyFormat.PEM, "ML-DSA"));
+        assertNotNull(KeyFormatConverter.importPublicKey(pem, 
KeyLifecycleManager.KeyFormat.PEM, "ML-DSA"));
+
+        assertEquals(original.getPrivate(),
+                KeyFormatConverter.importPrivateKey(pem, 
KeyLifecycleManager.KeyFormat.PEM, "ML-DSA"));
+        assertEquals(original.getPublic(),
+                KeyFormatConverter.importPublicKey(pem, 
KeyLifecycleManager.KeyFormat.PEM, "ML-DSA"));
+    }
+
+    @Test
+    void aPublicOnlyPemStillRoundTrips() throws Exception {
+        KeyPair original = mldsaKeyPair();
+
+        byte[] pem = KeyFormatConverter.exportKeyPair(original, 
KeyLifecycleManager.KeyFormat.PEM, false);
+
+        assertEquals(original.getPublic(),
+                KeyFormatConverter.importPublicKey(pem, 
KeyLifecycleManager.KeyFormat.PEM, "ML-DSA"));
+    }
+
+    @Test
+    void updatingMetadataDoesNotRewriteTheKeyFiles() throws Exception {
+        FileBasedKeyLifecycleManager manager = new 
FileBasedKeyLifecycleManager(keyDirectory.toString());
+        manager.generateKeyPair("MLDSA", "a-key");
+
+        Path privateKeyFile = Files.list(keyDirectory)

Review Comment:
   Fixed in ffbe5415 — wrapped in try-with-resources, matching the main code.
   
   _Claude Code on behalf of @oscerd_



-- 
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