Elffuss BraidHub

kikocis/EDC public

feat(keys): add functionality to extract public key to KeyParsers (#4360)

* feat(keys): add functionality to extract public key to KeyParsers

* make parserregistry return Result<PublicKey>

* pr remarks
Changesetfcd94f559e2a074f53809cfb87b21c4291ee66922893cc6d8cc6d71c49f9d6dc
AuthorPaul Latzelsperger <43503240+paullatzelsperger@users.noreply.github.com> · 2024-07-12 12:26 +02:00
CommitterGitHub <noreply@github.com> · 2024-07-12 12:26 +02:00
Parentsd3972eab6f92

Browse the files at this changeset

10 files changed

modified core/common/connector-core/src/test/java/org/eclipse/edc/connector/core/LocalPublicKeyDefaultExtensionTest.java +2 −2
@@ -58,7 +58,7 @@
5858 "key1.id", "key1",
5959 "key1.value", "value");
6060
61- when(keyParserRegistry.parse("value")).thenReturn(Result.success(mock(PublicKey.class)));
61+ when(keyParserRegistry.parsePublic("value")).thenReturn(Result.success(mock(PublicKey.class)));
6262 when(context.getConfig(EDC_PUBLIC_KEYS_PREFIX)).thenReturn(ConfigFactory.fromMap(keys));
6363 var localPublicKeyService = extension.localPublicKeyService();
6464 extension.initialize(context);
@@ -75,7 +75,7 @@
7575 "key1.id", "key1",
7676 "key1.path", path.getPath());
7777
78- when(keyParserRegistry.parse(value)).thenReturn(Result.success(mock(PublicKey.class)));
78+ when(keyParserRegistry.parsePublic(value)).thenReturn(Result.success(mock(PublicKey.class)));
7979 when(context.getConfig(EDC_PUBLIC_KEYS_PREFIX)).thenReturn(ConfigFactory.fromMap(keys));
8080 var localPublicKeyService = extension.localPublicKeyService();
8181 extension.initialize(context);
modified core/common/lib/keys-lib/src/main/java/org/eclipse/edc/keys/KeyParserRegistryImpl.java +9 −0
@@ -19,6 +19,7 @@
1919 import org.eclipse.edc.spi.result.Result;
2020
2121 import java.security.Key;
22+import java.security.PublicKey;
2223 import java.util.ArrayList;
2324 import java.util.List;
2425
@@ -37,4 +38,12 @@
3738 .map(kp -> kp.parse(encoded))
3839 .orElseGet(() -> Result.failure("No parser found that can handle that format."));
3940 }
41+
42+ @Override
43+ public Result<PublicKey> parsePublic(String encoded) {
44+ return parsers.stream().filter(kp -> kp.canHandle(encoded))
45+ .findFirst()
46+ .map(kp -> kp.parsePublic(encoded).compose(k -> Result.success((PublicKey) k)))
47+ .orElseGet(() -> Result.failure("No parser found that can handle that format."));
48+ }
4049 }
modified core/common/lib/keys-lib/src/main/java/org/eclipse/edc/keys/LocalPublicKeyServiceImpl.java +5 −11
@@ -48,6 +48,10 @@
4848 .orElseGet(() -> Result.failure("No public key could be resolved for key-ID '%s'".formatted(id)));
4949 }
5050
51+ public Result<Void> addRawKey(String id, String rawKey) {
52+ return parseKey(rawKey).onSuccess((pk) -> cachedKeys.put(id, pk)).mapEmpty();
53+ }
54+
5155 private Optional<String> resolveFromVault(String id) {
5256 return Optional.ofNullable(vault.resolveSecret(id));
5357 }
@@ -57,16 +61,6 @@
5761 }
5862
5963 private Result<PublicKey> parseKey(String encodedKey) {
60- return registry.parse(encodedKey).compose(pk -> {
61- if (pk instanceof PublicKey publicKey) {
62- return Result.success(publicKey);
63- } else {
64- return Result.failure("The specified resource did not contain public key material.");
65- }
66- });
67- }
68-
69- public Result<Void> addRawKey(String id, String rawKey) {
70- return parseKey(rawKey).onSuccess((pk) -> cachedKeys.put(id, pk)).mapTo();
64+ return registry.parsePublic(encodedKey);
7165 }
7266 }
modified core/common/lib/keys-lib/src/main/java/org/eclipse/edc/keys/keyparsers/JwkParser.java +22 −1
@@ -86,8 +86,9 @@
8686 @Override
8787 public Result<Key> parse(String encoded) {
8888 try {
89- var jwk = JWK.parse(encoded);
9089
90+
91+ var jwk = JWK.parse(encoded);
9192 // OctetKeyPairs (OKP) need special handling, as they can't be easily converted to a Java PrivateKey
9293 if (jwk instanceof OctetKeyPair okp) {
9394 return parseOctetKeyPair(okp).map(key -> key);
@@ -107,6 +108,26 @@
107108 }
108109 }
109110
111+ @Override
112+ public Result<Key> parsePublic(String encoded) {
113+ try {
114+ var jwk = JWK.parse(encoded).toPublicJWK();
115+ // OctetKeyPairs (OKP) need special handling, as they can't be easily converted to a Java PrivateKey
116+ if (jwk instanceof OctetKeyPair okp) {
117+ return parseOctetKeyPair(okp.toPublicJWK()).map(key -> key);
118+ }
119+ var list = KeyConverter.toJavaKeys(List.of(jwk)); // contains an entry each for public and private key
120+
121+ return list.stream()
122+ .findFirst()
123+ .map(Result::success)
124+ .orElse(Result.failure(ERROR_NO_KEY));
125+ } catch (ParseException | NoSuchAlgorithmException | IOException | InvalidKeySpecException e) {
126+ monitor.warning("Parser error", e);
127+ return Result.failure("Parser error: " + e.getMessage());
128+ }
129+ }
130+
110131 private Result<? extends Key> parseOctetKeyPair(OctetKeyPair okp) throws NoSuchAlgorithmException, IOException, InvalidKeySpecException {
111132 var d = okp.getDecodedD();
112133 var x = okp.getDecodedX();
modified core/common/lib/keys-lib/src/main/java/org/eclipse/edc/keys/keyparsers/PemParser.java +33 −6
@@ -62,11 +62,7 @@
6262 @Override
6363 public Result<Key> parse(String encoded) {
6464
65- var matcher = PEM_FORMAT_REGEX.matcher(encoded);
66- if (!matcher.find()) {
67- return Result.failure("The given input is not valid PEM.");
68- }
69- var keypair = parseKeys(encoded);
65+ var keypair = parsePem(encoded);
7066
7167 if (keypair.succeeded()) {
7268
@@ -83,7 +79,38 @@
8379 .orElseGet(() -> Result.failure("PEM-encoded structure did not contain a private key."));
8480 }
8581
86- return keypair.mapTo();
82+ return keypair.mapEmpty();
83+ }
84+
85+ @Override
86+ public Result<Key> parsePublic(String encoded) {
87+
88+ var keypair = parsePem(encoded);
89+ if (keypair.succeeded()) {
90+
91+ var keyPairList = keypair.getContent();
92+ if (keyPairList.size() > 1) {
93+ monitor.warning("PEM expected to contain exactly 1 key(-pair), but contained %s. Will take the first one. Please consider re-structuring your PEM document.".formatted(keyPairList.size()));
94+ }
95+ return keyPairList
96+ .stream()
97+ .filter(Objects::nonNull) // PEM strings that only contain public keys would get eliminated here
98+ .map(keyPair -> (Key) keyPair.getPublic())
99+ .filter(Objects::nonNull)
100+ .findFirst()
101+ .map(Result::success)
102+ .orElseGet(() -> Result.failure("PEM-encoded structure did not contain a public key."));
103+ }
104+
105+ return keypair.mapEmpty();
106+ }
107+
108+ private Result<List<KeyPair>> parsePem(String pemEncoded) {
109+ var matcher = PEM_FORMAT_REGEX.matcher(pemEncoded);
110+ if (!matcher.find()) {
111+ return Result.failure("The given input is not valid PEM.");
112+ }
113+ return parseKeys(pemEncoded);
87114 }
88115
89116 /**
modified core/common/lib/keys-lib/src/test/java/org/eclipse/edc/keys/LocalPublicKeyServiceImplTest.java +4 −14
@@ -22,7 +22,6 @@
2222 import org.junit.jupiter.api.Test;
2323 import org.mockito.Mockito;
2424
25-import java.security.PrivateKey;
2625 import java.security.PublicKey;
2726
2827 import static org.mockito.Mockito.mock;
@@ -31,9 +30,9 @@
3130
3231 class LocalPublicKeyServiceImplTest {
3332
34- private LocalPublicKeyServiceImpl localPublicKeyService;
3533 private final Vault vault = mock();
3634 private final KeyParserRegistry keyParserRegistry = mock();
35+ private LocalPublicKeyServiceImpl localPublicKeyService;
3736
3837 @BeforeEach
3938 void setup() {
@@ -42,7 +41,7 @@
4241
4342 @Test
4443 void resolve_withCache() {
45- when(keyParserRegistry.parse("value")).thenReturn(Result.success(mock(PublicKey.class)));
44+ when(keyParserRegistry.parsePublic("value")).thenReturn(Result.success(mock(PublicKey.class)));
4645 localPublicKeyService.addRawKey("id", "value");
4746 AbstractResultAssert.assertThat(localPublicKeyService.resolveKey("id")).isSucceeded();
4847 Mockito.verifyNoInteractions(vault);
@@ -51,7 +50,7 @@
5150 @Test
5251 void resolve_withVault() {
5352 when(vault.resolveSecret("id")).thenReturn("value");
54- when(keyParserRegistry.parse("value")).thenReturn(Result.success(mock(PublicKey.class)));
53+ when(keyParserRegistry.parsePublic("value")).thenReturn(Result.success(mock(PublicKey.class)));
5554 AbstractResultAssert.assertThat(localPublicKeyService.resolveKey("id")).isSucceeded();
5655
5756 verify(vault).resolveSecret("id");
@@ -63,19 +62,10 @@
6362 verify(vault).resolveSecret("id");
6463 }
6564
66- @Test
67- void resolve_wrongKeyType() {
68- when(vault.resolveSecret("id")).thenReturn("value");
69- when(keyParserRegistry.parse("value")).thenReturn(Result.success(mock(PrivateKey.class)));
70-
71- AbstractResultAssert.assertThat(localPublicKeyService.resolveKey("id")).isFailed();
72- verify(vault).resolveSecret("id");
73- }
74-
7565 @Test
7666 void resolve_wrongKeyFormat() {
7767 when(vault.resolveSecret("id")).thenReturn("value");
78- when(keyParserRegistry.parse("value")).thenReturn(Result.failure("failure"));
68+ when(keyParserRegistry.parsePublic("value")).thenReturn(Result.failure("failure"));
7969
8070 AbstractResultAssert.assertThat(localPublicKeyService.resolveKey("id")).isFailed();
8171 verify(vault).resolveSecret("id");
modified core/common/lib/keys-lib/src/test/java/org/eclipse/edc/keys/keyparsers/JwkParserTest.java +17 −0
@@ -63,6 +63,23 @@
6363 assertThat(result).isSucceeded().isInstanceOf(PublicKey.class);
6464 }
6565
66+
67+ @ParameterizedTest
68+ @ArgumentsSource(KeyProvider.class)
69+ void parsePublic_withPublicKey(JWK jwk) {
70+ var publickey = jwk.toPublicJWK();
71+ var result = parser.parsePublic(publickey.toJSONString());
72+ assertThat(result).isSucceeded().isInstanceOf(PublicKey.class);
73+ }
74+
75+
76+ @ParameterizedTest
77+ @ArgumentsSource(KeyProvider.class)
78+ void parsePublic_withPrivateKey(JWK jwk) {
79+ var result = parser.parsePublic(jwk.toJSONString());
80+ assertThat(result).isSucceeded().isInstanceOf(PublicKey.class);
81+ }
82+
6683 private static class KeyProvider implements ArgumentsProvider {
6784 @Override
6885 public Stream<? extends Arguments> provideArguments(ExtensionContext context) {
modified core/common/lib/keys-lib/src/test/java/org/eclipse/edc/keys/keyparsers/PemParserTest.java +46 −0
@@ -17,6 +17,7 @@
1717 import org.assertj.core.api.Assertions;
1818 import org.eclipse.edc.junit.testfixtures.TestUtils;
1919 import org.junit.jupiter.api.Named;
20+import org.junit.jupiter.api.Test;
2021 import org.junit.jupiter.api.extension.ExtensionContext;
2122 import org.junit.jupiter.params.ParameterizedTest;
2223 import org.junit.jupiter.params.provider.Arguments;
@@ -74,6 +75,38 @@
7475 .isInstanceOf(PublicKey.class);
7576 }
7677
78+
79+ @ParameterizedTest
80+ @ArgumentsSource(PemConvertiblePrivateKeyProvider.class)
81+ void parsePublic_withPrivateKey(String pem) {
82+ var result = parser.parsePublic(pem);
83+ assertThat(result)
84+ .isSucceeded()
85+ .isNotNull()
86+ .isInstanceOf(PublicKey.class);
87+
88+ }
89+
90+ @Test
91+ void parsePublic_withPrivateKey_whenEd25519_shouldFail() {
92+ var pem = TestUtils.getResourceFileContentAsString("ed25519.pem");
93+ var result = parser.parsePublic(pem);
94+ assertThat(result)
95+ .isFailed()
96+ .detail().isEqualTo("PEM-encoded structure did not contain a public key.");
97+ }
98+
99+
100+ @ParameterizedTest
101+ @ArgumentsSource(PemPublicKeyProvider.class)
102+ void parsePublic_withPublicKey(String pem) {
103+
104+ assertThat(parser.parsePublic(pem))
105+ .isSucceeded()
106+ .isNotNull()
107+ .isInstanceOf(PublicKey.class);
108+ }
109+
77110 private static class PemPrivateKeyProvider implements ArgumentsProvider {
78111
79112 @Override
@@ -88,6 +121,19 @@
88121 }
89122 }
90123
124+ private static class PemConvertiblePrivateKeyProvider implements ArgumentsProvider {
125+
126+ @Override
127+ public Stream<? extends Arguments> provideArguments(ExtensionContext context) {
128+ return Stream.of(
129+ Arguments.of(Named.named("RSA PrivateKey", TestUtils.getResourceFileContentAsString("rsa_2048.pem"))),
130+ Arguments.of(Named.named("EC PrivateKey (P256)", TestUtils.getResourceFileContentAsString("ec_p256.pem"))),
131+ Arguments.of(Named.named("EC PrivateKey (P384)", TestUtils.getResourceFileContentAsString("ec_p384.pem"))),
132+ Arguments.of(Named.named("EC PrivateKey (P512)", TestUtils.getResourceFileContentAsString("ec_p512.pem")))
133+ );
134+ }
135+ }
136+
91137 private static class PemPublicKeyProvider implements ArgumentsProvider {
92138
93139 @Override
modified spi/common/keys-spi/src/main/java/org/eclipse/edc/keys/spi/KeyParser.java +16 −0
@@ -49,4 +49,20 @@
4949 * @return Either a {@link java.security.PrivateKey}, a {@link java.security.PublicKey} or a failure.
5050 */
5151 Result<Key> parse(String encoded);
52+
53+ /**
54+ * Parses the encoded key as public key. If the encoded string is invalid, or the parser can't handle the input,
55+ * it must return a {@link Result#failure(String)}, it must never throw an exception.
56+ * <p>
57+ * If the given key material contains public and private key data, the parser attempts to remove the private key data,
58+ * returning only the public part of the key as {@link java.security.PublicKey}.
59+ * If the given key material does not contain private key data, just public key data, returns a {@link java.security.PublicKey}. In all
60+ * other cases, a {@link Result#failure(String)} is returned, for example, when a private key cannot be converted into a public key.
61+ *
62+ * @param encoded serialized/encoded key material.
63+ * @return Either a {@link java.security.PublicKey} or a failure.
64+ */
65+ default Result<Key> parsePublic(String encoded) {
66+ return parse(encoded);
67+ }
5268 }
modified spi/common/keys-spi/src/main/java/org/eclipse/edc/keys/spi/KeyParserRegistry.java +12 −2
@@ -17,7 +17,7 @@
1717 import org.eclipse.edc.spi.result.Result;
1818
1919 import java.security.Key;
20-import java.security.PrivateKey;
20+import java.security.PublicKey;
2121
2222 /**
2323 * Registry that holds multiple {@link KeyParser} instances that are used to deserialize a private key from their
@@ -30,11 +30,21 @@
3030 void register(KeyParser parser);
3131
3232 /**
33- * Attempts to parse the String representation of a private key into a {@link PrivateKey}. If no parser can handle
33+ * Attempts to parse the String representation of a private key into a {@link Key}. If no parser can handle
3434 * the encoded format, or it is corrupt etc. then a failure is returned.
3535 *
3636 * @param encoded The private key in encoded format (PEM, OpenSSH, JWK, PKCS8,...)
3737 * @return a success result containing the private key, a failure if the encoded private key could not be deserialized.
3838 */
3939 Result<Key> parse(String encoded);
40+
41+ /**
42+ * Attempts to parse the String representation of a public or private key into a {@link Key}. If no parser can handle
43+ * the encoded format, if the encoded format contains a private key that cannot be converted to a public key,
44+ * or if the input is corrupt etc. then a failure is returned.
45+ *
46+ * @param encoded The private key in encoded format (PEM, OpenSSH, JWK, PKCS8,...)
47+ * @return a success result containing the public key, a failure if the encoded public key could not be deserialized.
48+ */
49+ Result<PublicKey> parsePublic(String encoded);
4050 }