Elffuss BraidHub

kikocis/EDC public

refactor: TokenGenerationService takes key ID instead of PrivateKey (#4395)

* refactor: TokenGenerationService takes key ID instead of PrivateKey

* move JwsSignerProvider to its own SPI

* Update spi/common/jwt-signer-spi/src/main/java/org/eclipse/edc/jwt/signer/spi/JwsSignerProvider.java

Co-authored-by: Enrico Risa <enrico.risa@gmail.com>

* Update core/common/token-core/src/main/java/org/eclipse/edc/token/JwtGenerationService.java

Co-authored-by: ndr_brt <andrea.bertagnolli@gmail.com>

* pr remarks

* fix tests

---------

Co-authored-by: Enrico Risa <enrico.risa@gmail.com>
Co-authored-by: ndr_brt <andrea.bertagnolli@gmail.com>
Changeset84ffd9a22d37f1417a89f4a7ebc5aaa903f009effd18fcb966be23d81588cd00
AuthorPaul Latzelsperger <43503240+paullatzelsperger@users.noreply.github.com> · 2024-08-08 09:29 +02:00
CommitterGitHub <noreply@github.com> · 2024-08-08 09:29 +02:00
Parents49f52aca5a72

Browse the files at this changeset

29 files changed

modified core/common/token-core/build.gradle.kts +1 −0
@@ -21,6 +21,7 @@
2121 api(project(":spi:common:keys-spi"))
2222 api(project(":spi:common:token-spi"))
2323 api(project(":spi:common:jwt-spi"))
24+ api(project(":spi:common:jwt-signer-spi"))
2425
2526 implementation(project(":core:common:lib:crypto-common-lib")) // for the CryptoConverter
2627 implementation(libs.nimbus.jwt)
modified core/common/token-core/src/main/java/org/eclipse/edc/token/JwtGenerationService.java +13 −8
@@ -20,6 +20,7 @@
2020 import com.nimbusds.jose.JWSHeader;
2121 import com.nimbusds.jwt.JWTClaimsSet;
2222 import com.nimbusds.jwt.SignedJWT;
23+import org.eclipse.edc.jwt.signer.spi.JwsSignerProvider;
2324 import org.eclipse.edc.security.token.jwt.CryptoConverter;
2425 import org.eclipse.edc.spi.EdcException;
2526 import org.eclipse.edc.spi.iam.TokenParameters;
@@ -29,25 +30,29 @@
2930 import org.eclipse.edc.token.spi.TokenGenerationService;
3031 import org.jetbrains.annotations.NotNull;
3132
32-import java.security.PrivateKey;
3333 import java.text.ParseException;
3434 import java.util.ArrayList;
3535 import java.util.Arrays;
3636 import java.util.Map;
37-import java.util.function.Supplier;
3837
3938 public class JwtGenerationService implements TokenGenerationService {
4039
40+ private final JwsSignerProvider jwsGeneratorFunction;
41+
42+ public JwtGenerationService(JwsSignerProvider jwsSignerProvider) {
43+
44+ this.jwsGeneratorFunction = jwsSignerProvider;
45+ }
4146
4247 @Override
43- public Result<TokenRepresentation> generate(Supplier<PrivateKey> privateKeySupplier, @NotNull TokenDecorator... decorators) {
44-
45- var privateKey = privateKeySupplier.get();
46- if (privateKey == null) {
47- return Result.failure("PrivateKey cannot be resolved.");
48+ public Result<TokenRepresentation> generate(String privateKeyId, @NotNull TokenDecorator... decorators) {
49+
50+ var tokenSignerResult = jwsGeneratorFunction.createJwsSigner(privateKeyId);
51+ if (tokenSignerResult.failed()) {
52+ return Result.failure("JWSSigner cannot be generated for private key '%s': %s".formatted(privateKeyId, tokenSignerResult.getFailureDetail()));
4853 }
4954
50- var tokenSigner = CryptoConverter.createSignerFor(privateKey);
55+ var tokenSigner = tokenSignerResult.getContent();
5156 var jwsAlgorithm = CryptoConverter.getRecommendedAlgorithm(tokenSigner);
5257
5358 var bldr = TokenParameters.Builder.newInstance();
modified core/common/token-core/src/main/java/org/eclipse/edc/token/TokenServicesExtension.java +15 −0
@@ -14,8 +14,13 @@
1414
1515 package org.eclipse.edc.token;
1616
17+import org.eclipse.edc.jwt.signer.spi.JwsSignerProvider;
18+import org.eclipse.edc.keys.spi.PrivateKeyResolver;
1719 import org.eclipse.edc.runtime.metamodel.annotation.Extension;
20+import org.eclipse.edc.runtime.metamodel.annotation.Inject;
1821 import org.eclipse.edc.runtime.metamodel.annotation.Provider;
22+import org.eclipse.edc.security.token.jwt.CryptoConverter;
23+import org.eclipse.edc.spi.result.Result;
1924 import org.eclipse.edc.spi.system.ServiceExtension;
2025 import org.eclipse.edc.token.spi.TokenDecoratorRegistry;
2126 import org.eclipse.edc.token.spi.TokenValidationRulesRegistry;
@@ -31,6 +36,9 @@
3136 public class TokenServicesExtension implements ServiceExtension {
3237 public static final String NAME = "Token Services Extension";
3338
39+ @Inject
40+ private PrivateKeyResolver privateKeyResolver;
41+
3442 @Provider
3543 public TokenValidationRulesRegistry tokenValidationRulesRegistry() {
3644 return new TokenValidationRulesRegistryImpl();
@@ -45,4 +53,11 @@
4553 public TokenDecoratorRegistry tokenDecoratorRegistry() {
4654 return new TokenDecoratorRegistryImpl();
4755 }
56+
57+ @Provider(isDefault = true)
58+ public JwsSignerProvider defaultSignerProvider() {
59+ // default implementation: resolve the private key (from vault of config) and create a JWSSigner based on its algorithm
60+ return privateKeyId -> privateKeyResolver.resolvePrivateKey(privateKeyId)
61+ .compose(pk -> Result.ofThrowable(() -> CryptoConverter.createSignerFor(pk)));
62+ }
4863 }
modified core/common/token-core/src/test/java/org/eclipse/edc/token/JwtGenerationServiceTest.java +16 −9
@@ -23,6 +23,8 @@
2323 import com.nimbusds.jose.jwk.gen.RSAKeyGenerator;
2424 import com.nimbusds.jose.util.Base64URL;
2525 import com.nimbusds.jwt.SignedJWT;
26+import org.eclipse.edc.security.token.jwt.CryptoConverter;
27+import org.eclipse.edc.spi.result.Result;
2628 import org.eclipse.edc.token.spi.TokenDecorator;
2729 import org.junit.jupiter.api.BeforeEach;
2830 import org.junit.jupiter.api.Test;
@@ -39,26 +41,31 @@
3941
4042 class JwtGenerationServiceTest {
4143
44+ public static final String TEST_KEY_ID = "test-key-id";
4245 private RSAKey keys;
4346 private JwtGenerationService tokenGenerationService;
4447
4548 @BeforeEach
4649 void setUp() throws JOSEException {
4750 keys = testKey();
48- tokenGenerationService = new JwtGenerationService();
51+ tokenGenerationService = new JwtGenerationService(keyId -> {
52+ if (TEST_KEY_ID.equals(keyId)) {
53+ try {
54+ var pk = keys.toPrivateKey();
55+ return Result.success(CryptoConverter.createSignerFor(pk));
56+ } catch (JOSEException e) {
57+ return Result.failure(e.getMessage());
58+ }
59+ }
60+ return Result.failure("key not found");
61+ });
4962 }
5063
5164 @Test
5265 void verifyTokenGeneration() throws ParseException, JOSEException {
5366 var decorator = testDecorator();
5467
55- var result = tokenGenerationService.generate(() -> {
56- try {
57- return keys.toPrivateKey();
58- } catch (JOSEException e) {
59- throw new RuntimeException(e);
60- }
61- }, decorator);
68+ var result = tokenGenerationService.generate(TEST_KEY_ID, decorator);
6269
6370 assertThat(result.succeeded()).isTrue();
6471 var token = result.getContent().getToken();
@@ -84,7 +91,7 @@
8491 void shouldFail_whenPrivateKeyCannotBeResolved() {
8592 var decorator = testDecorator();
8693
87- var result = tokenGenerationService.generate(() -> null, decorator);
94+ var result = tokenGenerationService.generate("not-exist-key", decorator);
8895
8996 assertThat(result.failed()).isTrue();
9097 }
modified core/data-plane/data-plane-core/src/main/java/org/eclipse/edc/connector/dataplane/framework/DataPlaneDefaultIamServicesExtension.java +5 −13
@@ -18,21 +18,19 @@
1818 import org.eclipse.edc.connector.dataplane.spi.iam.DataPlaneAccessControlService;
1919 import org.eclipse.edc.connector.dataplane.spi.iam.DataPlaneAccessTokenService;
2020 import org.eclipse.edc.connector.dataplane.spi.store.AccessTokenDataStore;
21+import org.eclipse.edc.jwt.signer.spi.JwsSignerProvider;
2122 import org.eclipse.edc.keys.spi.LocalPublicKeyService;
2223 import org.eclipse.edc.keys.spi.PrivateKeyResolver;
2324 import org.eclipse.edc.runtime.metamodel.annotation.Extension;
2425 import org.eclipse.edc.runtime.metamodel.annotation.Inject;
2526 import org.eclipse.edc.runtime.metamodel.annotation.Provider;
2627 import org.eclipse.edc.runtime.metamodel.annotation.Setting;
27-import org.eclipse.edc.spi.monitor.Monitor;
2828 import org.eclipse.edc.spi.result.Result;
2929 import org.eclipse.edc.spi.system.ServiceExtension;
3030 import org.eclipse.edc.spi.system.ServiceExtensionContext;
3131 import org.eclipse.edc.token.JwtGenerationService;
3232 import org.eclipse.edc.token.spi.TokenValidationService;
33-import org.jetbrains.annotations.NotNull;
3433
35-import java.security.PrivateKey;
3634 import java.util.function.Supplier;
3735
3836
@@ -54,6 +52,8 @@
5452 private PrivateKeyResolver privateKeyResolver;
5553 @Inject
5654 private LocalPublicKeyService localPublicKeyService;
55+ @Inject
56+ private JwsSignerProvider jwsSignerProvider;
5757
5858 @Override
5959 public String name() {
@@ -71,8 +71,8 @@
7171 var tokenVerifierPublicKeyAlias = context.getConfig().getString(TOKEN_VERIFIER_PUBLIC_KEY_ALIAS);
7272 var tokenSignerPrivateKeyAlias = context.getConfig().getString(TOKEN_SIGNER_PRIVATE_KEY_ALIAS);
7373 var monitor = context.getMonitor().withPrefix("DataPlane IAM");
74- return new DefaultDataPlaneAccessTokenServiceImpl(new JwtGenerationService(),
75- accessTokenDataStore, monitor, getPrivateKeySupplier(tokenSignerPrivateKeyAlias, monitor),
74+ return new DefaultDataPlaneAccessTokenServiceImpl(new JwtGenerationService(jwsSignerProvider),
75+ accessTokenDataStore, monitor, () -> tokenSignerPrivateKeyAlias,
7676 publicKeyIdSupplier(tokenVerifierPublicKeyAlias), tokenValidationService, localPublicKeyService);
7777 }
7878
@@ -80,12 +80,4 @@
8080 return () -> tokenVerifierPublicKeyAlias;
8181 }
8282
83- @NotNull
84- private Supplier<PrivateKey> getPrivateKeySupplier(String tokenSignerPrivateKeyAlias, Monitor monitor) {
85- return () -> privateKeyResolver.resolvePrivateKey(tokenSignerPrivateKeyAlias)
86- .orElse(f -> {
87- monitor.warning("Cannot resolve private key: " + f.getFailureDetail());
88- return null;
89- });
90- }
9183 }
modified core/data-plane/data-plane-core/src/main/java/org/eclipse/edc/connector/dataplane/framework/iam/DefaultDataPlaneAccessTokenServiceImpl.java +5 −6
@@ -32,7 +32,6 @@
3232 import org.eclipse.edc.token.spi.TokenValidationRule;
3333 import org.eclipse.edc.token.spi.TokenValidationService;
3434
35-import java.security.PrivateKey;
3635 import java.util.ArrayList;
3736 import java.util.List;
3837 import java.util.Map;
@@ -56,7 +55,7 @@
5655 private final TokenGenerationService tokenGenerationService;
5756 private final AccessTokenDataStore accessTokenDataStore;
5857 private final Monitor monitor;
59- private final Supplier<PrivateKey> privateKeySupplier;
58+ private final Supplier<String> privateKeyIdSupplier;
6059 private final Supplier<String> publicKeyIdSupplier;
6160 private final TokenValidationService tokenValidationService;
6261 private final PublicKeyResolver publicKeyResolver;
@@ -64,14 +63,14 @@
6463 public DefaultDataPlaneAccessTokenServiceImpl(TokenGenerationService tokenGenerationService,
6564 AccessTokenDataStore accessTokenDataStore,
6665 Monitor monitor,
67- Supplier<PrivateKey> privateKeySupplier,
66+ Supplier<String> privateKeyIdSupplier,
6867 Supplier<String> publicKeyIdSupplier,
6968 TokenValidationService tokenValidationService,
7069 PublicKeyResolver publicKeyResolver) {
7170 this.tokenGenerationService = tokenGenerationService;
7271 this.accessTokenDataStore = accessTokenDataStore;
7372 this.monitor = monitor;
74- this.privateKeySupplier = privateKeySupplier;
73+ this.privateKeyIdSupplier = privateKeyIdSupplier;
7574 this.publicKeyIdSupplier = publicKeyIdSupplier;
7675 this.tokenValidationService = tokenValidationService;
7776 this.publicKeyResolver = publicKeyResolver;
@@ -106,9 +105,9 @@
106105 allDecorators.add(tokenIdDecorator);
107106 }
108107
109- var tokenResult = tokenGenerationService.generate(privateKeySupplier, allDecorators.toArray(new TokenDecorator[0]));
108+ var tokenResult = tokenGenerationService.generate(privateKeyIdSupplier.get(), allDecorators.toArray(new TokenDecorator[0]));
110109 if (tokenResult.failed()) {
111- return tokenResult.mapTo();
110+ return tokenResult.mapEmpty();
112111 }
113112
114113 // store a record of the token for future reference. We'll need that when we resolve the AccessTokenData later.
modified extensions/common/iam/identity-trust/identity-trust-core/src/main/java/org/eclipse/edc/iam/identitytrust/core/DcpDefaultServicesExtension.java +4 −8
@@ -25,12 +25,11 @@
2525 import org.eclipse.edc.iam.identitytrust.spi.verification.SignatureSuiteRegistry;
2626 import org.eclipse.edc.iam.identitytrust.sts.embedded.EmbeddedSecureTokenService;
2727 import org.eclipse.edc.iam.verifiablecredentials.spi.validation.TrustedIssuerRegistry;
28-import org.eclipse.edc.keys.spi.PrivateKeyResolver;
28+import org.eclipse.edc.jwt.signer.spi.JwsSignerProvider;
2929 import org.eclipse.edc.runtime.metamodel.annotation.Extension;
3030 import org.eclipse.edc.runtime.metamodel.annotation.Inject;
3131 import org.eclipse.edc.runtime.metamodel.annotation.Provider;
3232 import org.eclipse.edc.runtime.metamodel.annotation.Setting;
33-import org.eclipse.edc.spi.EdcException;
3433 import org.eclipse.edc.spi.iam.AudienceResolver;
3534 import org.eclipse.edc.spi.iam.ClaimToken;
3635 import org.eclipse.edc.spi.result.Result;
@@ -38,11 +37,9 @@
3837 import org.eclipse.edc.spi.system.ServiceExtensionContext;
3938 import org.eclipse.edc.token.JwtGenerationService;
4039
41-import java.security.PrivateKey;
4240 import java.time.Clock;
4341 import java.util.Map;
4442 import java.util.concurrent.TimeUnit;
45-import java.util.function.Supplier;
4643
4744 import static org.eclipse.edc.spi.result.Result.failure;
4845 import static org.eclipse.edc.spi.result.Result.success;
@@ -63,7 +60,7 @@
6360 @Inject
6461 private Clock clock;
6562 @Inject
66- private PrivateKeyResolver privateKeyResolver;
63+ private JwsSignerProvider externalSigner;
6764
6865 @Provider(isDefault = true)
6966 public SecureTokenService createDefaultTokenService(ServiceExtensionContext context) {
@@ -78,10 +75,9 @@
7875
7976
8077 var publicKeyId = context.getSetting(STS_PUBLIC_KEY_ID, null);
81- var privKeyAlias = context.getSetting(STS_PRIVATE_KEY_ALIAS, null);
78+ var privateKeyAlias = context.getSetting(STS_PRIVATE_KEY_ALIAS, null);
8279
83- Supplier<PrivateKey> supplier = () -> privateKeyResolver.resolvePrivateKey(privKeyAlias).orElseThrow(f -> new EdcException("This EDC instance is not operational due to the following error: %s".formatted(f.getFailureDetail())));
84- return new EmbeddedSecureTokenService(new JwtGenerationService(), supplier, () -> publicKeyId, clock, TimeUnit.MINUTES.toSeconds(tokenExpiration));
80+ return new EmbeddedSecureTokenService(new JwtGenerationService(externalSigner), () -> privateKeyAlias, () -> publicKeyId, clock, TimeUnit.MINUTES.toSeconds(tokenExpiration));
8581 }
8682
8783 @Provider(isDefault = true)
modified extensions/common/iam/identity-trust/identity-trust-sts/identity-trust-sts-core/build.gradle.kts +1 −0
@@ -14,6 +14,7 @@
1414
1515 testImplementation(testFixtures(project(":spi:common:identity-trust-sts-spi")))
1616 testImplementation(project(":core:common:lib:boot-lib"))
17+ testImplementation(project(":core:common:lib:crypto-common-lib"))
1718 testImplementation(project(":core:common:lib:keys-lib"))
1819 testImplementation(project(":core:common:junit"))
1920 testImplementation(libs.nimbus.jwt)
modified extensions/common/iam/identity-trust/identity-trust-sts/identity-trust-sts-core/src/main/java/org/eclipse/edc/iam/identitytrust/sts/defaults/StsDefaultServicesExtension.java +5 −4
@@ -16,10 +16,11 @@
1616
1717 import org.eclipse.edc.iam.identitytrust.sts.defaults.service.StsClientServiceImpl;
1818 import org.eclipse.edc.iam.identitytrust.sts.defaults.service.StsClientTokenGeneratorServiceImpl;
19+import org.eclipse.edc.iam.identitytrust.sts.spi.model.StsClient;
1920 import org.eclipse.edc.iam.identitytrust.sts.spi.service.StsClientService;
2021 import org.eclipse.edc.iam.identitytrust.sts.spi.service.StsClientTokenGeneratorService;
2122 import org.eclipse.edc.iam.identitytrust.sts.spi.store.StsClientStore;
22-import org.eclipse.edc.keys.spi.PrivateKeyResolver;
23+import org.eclipse.edc.jwt.signer.spi.JwsSignerProvider;
2324 import org.eclipse.edc.runtime.metamodel.annotation.Extension;
2425 import org.eclipse.edc.runtime.metamodel.annotation.Inject;
2526 import org.eclipse.edc.runtime.metamodel.annotation.Provider;
@@ -53,7 +54,7 @@
5354 private Vault vault;
5455
5556 @Inject
56- private PrivateKeyResolver privateKeyResolver;
57+ private JwsSignerProvider jwsSignerProvider;
5758
5859 @Inject
5960 private Clock clock;
@@ -67,8 +68,8 @@
6768 public StsClientTokenGeneratorService clientTokenService(ServiceExtensionContext context) {
6869 var tokenExpiration = context.getSetting(STS_TOKEN_EXPIRATION, DEFAULT_STS_TOKEN_EXPIRATION_MIN);
6970 return new StsClientTokenGeneratorServiceImpl(
70- (client) -> new JwtGenerationService(),
71- (client) -> privateKeyResolver.resolvePrivateKey(client.getPrivateKeyAlias()).orElse(null),
71+ (client) -> new JwtGenerationService(jwsSignerProvider),
72+ StsClient::getPrivateKeyAlias,
7273 clock,
7374 TimeUnit.MINUTES.toSeconds(tokenExpiration));
7475 }
modified extensions/common/iam/identity-trust/identity-trust-sts/identity-trust-sts-core/src/main/java/org/eclipse/edc/iam/identitytrust/sts/defaults/service/StsClientTokenGeneratorServiceImpl.java +2 −3
@@ -22,7 +22,6 @@
2222 import org.eclipse.edc.spi.iam.TokenRepresentation;
2323 import org.eclipse.edc.spi.result.ServiceResult;
2424
25-import java.security.PrivateKey;
2625 import java.time.Clock;
2726 import java.util.Collections;
2827 import java.util.HashMap;
@@ -42,10 +41,10 @@
4241
4342 private final long tokenExpiration;
4443 private final StsTokenGenerationProvider tokenGenerationProvider;
45- private final Function<StsClient, PrivateKey> keyFunction;
44+ private final Function<StsClient, String> keyFunction;
4645 private final Clock clock;
4746
48- public StsClientTokenGeneratorServiceImpl(StsTokenGenerationProvider tokenGenerationProvider, Function<StsClient, PrivateKey> keyFunction, Clock clock, long tokenExpiration) {
47+ public StsClientTokenGeneratorServiceImpl(StsTokenGenerationProvider tokenGenerationProvider, Function<StsClient, String> keyFunction, Clock clock, long tokenExpiration) {
4948 this.tokenGenerationProvider = tokenGenerationProvider;
5049 this.keyFunction = keyFunction;
5150 this.clock = clock;
modified extensions/common/iam/identity-trust/identity-trust-sts/identity-trust-sts-core/src/test/java/org/eclipse/edc/iam/identitytrust/sts/defaults/StsClientTokenIssuanceIntegrationTest.java +6 −2
@@ -20,6 +20,7 @@
2020 import org.eclipse.edc.iam.identitytrust.sts.defaults.service.StsClientServiceImpl;
2121 import org.eclipse.edc.iam.identitytrust.sts.defaults.service.StsClientTokenGeneratorServiceImpl;
2222 import org.eclipse.edc.iam.identitytrust.sts.defaults.store.InMemoryStsClientStore;
23+import org.eclipse.edc.iam.identitytrust.sts.spi.model.StsClient;
2324 import org.eclipse.edc.iam.identitytrust.sts.spi.model.StsClientTokenAdditionalParams;
2425 import org.eclipse.edc.junit.annotations.ComponentTest;
2526 import org.eclipse.edc.keys.KeyParserRegistryImpl;
@@ -28,6 +29,8 @@
2829 import org.eclipse.edc.keys.keyparsers.PemParser;
2930 import org.eclipse.edc.keys.spi.KeyParserRegistry;
3031 import org.eclipse.edc.keys.spi.PrivateKeyResolver;
32+import org.eclipse.edc.security.token.jwt.CryptoConverter;
33+import org.eclipse.edc.spi.result.Result;
3134 import org.eclipse.edc.spi.security.Vault;
3235 import org.eclipse.edc.token.JwtGenerationService;
3336 import org.eclipse.edc.transaction.spi.NoopTransactionContext;
@@ -70,8 +73,9 @@
7073 privateKeyResolver = new VaultPrivateKeyResolver(keyParserRegistry, vault, mock(), mock());
7174
7275 tokenGeneratorService = new StsClientTokenGeneratorServiceImpl(
73- client -> new JwtGenerationService(),
74- stsClient -> privateKeyResolver.resolvePrivateKey(stsClient.getPrivateKeyAlias()).orElse(null),
76+ client -> new JwtGenerationService(keyId -> privateKeyResolver.resolvePrivateKey(keyId)
77+ .compose(pk -> Result.ofThrowable(() -> CryptoConverter.createSignerFor(pk)))),
78+ StsClient::getPrivateKeyAlias,
7579 Clock.systemUTC(), 60 * 5);
7680
7781 }
modified extensions/common/iam/identity-trust/identity-trust-sts/identity-trust-sts-core/src/test/java/org/eclipse/edc/iam/identitytrust/sts/defaults/service/StsClientTokenGeneratorServiceImplTest.java +1 −1
@@ -43,7 +43,7 @@
4343
4444 @BeforeEach
4545 void setup() {
46- clientTokenService = new StsClientTokenGeneratorServiceImpl(tokenGenerationProvider, (client) -> mock(), Clock.systemUTC(), TOKEN_EXPIRATION);
46+ clientTokenService = new StsClientTokenGeneratorServiceImpl(tokenGenerationProvider, (client) -> "test-key-id", Clock.systemUTC(), TOKEN_EXPIRATION);
4747 }
4848
4949 @Test
modified extensions/common/iam/identity-trust/identity-trust-sts/identity-trust-sts-embedded/src/main/java/org/eclipse/edc/iam/identitytrust/sts/embedded/EmbeddedSecureTokenService.java +9 −10
@@ -21,7 +21,6 @@
2121 import org.eclipse.edc.token.spi.TokenGenerationService;
2222 import org.jetbrains.annotations.Nullable;
2323
24-import java.security.PrivateKey;
2524 import java.time.Clock;
2625 import java.util.HashMap;
2726 import java.util.List;
@@ -50,15 +49,15 @@
5049
5150 private static final List<String> ACCESS_TOKEN_INHERITED_CLAIMS = List.of(ISSUER);
5251 private final TokenGenerationService tokenGenerationService;
53- private final Supplier<PrivateKey> privateKeySupplier;
54- private final Supplier<String> publicKeyId;
52+ private final Supplier<String> privateKeyIdSupplier;
53+ private final Supplier<String> publicKeyIdSupplier;
5554 private final Clock clock;
5655 private final long validity;
5756
58- public EmbeddedSecureTokenService(TokenGenerationService tokenGenerationService, Supplier<PrivateKey> privateKeySupplier, Supplier<String> publicKeyId, Clock clock, long validity) {
57+ public EmbeddedSecureTokenService(TokenGenerationService tokenGenerationService, Supplier<String> privateKeyIdSupplier, Supplier<String> publicKeyIdSupplier, Clock clock, long validity) {
5958 this.tokenGenerationService = tokenGenerationService;
60- this.privateKeySupplier = privateKeySupplier;
61- this.publicKeyId = publicKeyId;
59+ this.privateKeyIdSupplier = privateKeyIdSupplier;
60+ this.publicKeyIdSupplier = publicKeyIdSupplier;
6261 this.clock = clock;
6362 this.validity = validity;
6463 }
@@ -70,8 +69,8 @@
7069 .map(scope -> createAndAcceptAccessToken(claims, scope, selfIssuedClaims::put))
7170 .orElse(success())
7271 .compose(v -> {
73- var keyIdDecorator = new KeyIdDecorator(publicKeyId.get());
74- return tokenGenerationService.generate(privateKeySupplier, keyIdDecorator, new SelfIssuedTokenDecorator(selfIssuedClaims, clock, validity));
72+ var keyIdDecorator = new KeyIdDecorator(publicKeyIdSupplier.get());
73+ return tokenGenerationService.generate(privateKeyIdSupplier.get(), keyIdDecorator, new SelfIssuedTokenDecorator(selfIssuedClaims, clock, validity));
7574 });
7675 }
7776
@@ -88,8 +87,8 @@
8887 return addClaim(claims, ISSUER, withClaim(AUDIENCE, accessTokenClaims::put))
8988 .compose(v -> addClaim(claims, AUDIENCE, withClaim(SUBJECT, accessTokenClaims::put)))
9089 .compose(v -> {
91- var keyIdDecorator = new KeyIdDecorator(publicKeyId.get());
92- return tokenGenerationService.generate(privateKeySupplier, keyIdDecorator, new SelfIssuedTokenDecorator(accessTokenClaims, clock, validity));
90+ var keyIdDecorator = new KeyIdDecorator(publicKeyIdSupplier.get());
91+ return tokenGenerationService.generate(privateKeyIdSupplier.get(), keyIdDecorator, new SelfIssuedTokenDecorator(accessTokenClaims, clock, validity));
9392 });
9493
9594 }
modified extensions/common/iam/identity-trust/identity-trust-sts/identity-trust-sts-embedded/src/test/java/org/eclipse/edc/iam/identitytrust/sts/embedded/EmbeddedSecureTokenServiceIntegrationTest.java +4 −2
@@ -17,8 +17,10 @@
1717 import com.nimbusds.jose.JOSEException;
1818 import com.nimbusds.jose.JWSHeader;
1919 import com.nimbusds.jose.JWSVerifier;
20+import com.nimbusds.jose.crypto.RSASSASigner;
2021 import com.nimbusds.jose.crypto.factories.DefaultJWSVerifierFactory;
2122 import com.nimbusds.jwt.SignedJWT;
23+import org.eclipse.edc.spi.result.Result;
2224 import org.eclipse.edc.token.JwtGenerationService;
2325 import org.junit.jupiter.api.BeforeEach;
2426 import org.junit.jupiter.api.Test;
@@ -63,8 +65,8 @@
6365 @BeforeEach
6466 void setup() throws NoSuchAlgorithmException {
6567 keyPair = generateKeyPair();
66- var tokenGenerationService = new JwtGenerationService();
67- secureTokenService = new EmbeddedSecureTokenService(tokenGenerationService, () -> keyPair.getPrivate(), () -> "test-keyid", Clock.systemUTC(), 10 * 60);
68+ var tokenGenerationService = new JwtGenerationService(s -> Result.success(new RSASSASigner(keyPair.getPrivate())));
69+ secureTokenService = new EmbeddedSecureTokenService(tokenGenerationService, () -> "test-private-keyid", () -> "test-keyid", Clock.systemUTC(), 10 * 60);
6870 }
6971
7072 @Test
modified extensions/common/iam/identity-trust/identity-trust-sts/identity-trust-sts-embedded/src/test/java/org/eclipse/edc/iam/identitytrust/sts/embedded/EmbeddedSecureTokenServiceTest.java +7 −8
@@ -21,9 +21,7 @@
2121 import org.eclipse.edc.token.spi.TokenGenerationService;
2222 import org.junit.jupiter.api.Test;
2323 import org.mockito.ArgumentCaptor;
24-import org.mockito.Mockito;
2524
26-import java.security.PrivateKey;
2725 import java.time.Clock;
2826 import java.util.Map;
2927 import java.util.function.Supplier;
@@ -40,15 +38,16 @@
4038
4139 public class EmbeddedSecureTokenServiceTest {
4240
41+ public static final String TEST_PRIVATEKEY_ID = "test-privatekey-id";
4342 private final TokenGenerationService tokenGenerationService = mock();
44- private final Supplier<PrivateKey> keySupplier = Mockito::mock;
43+ private final Supplier<String> keySupplier = () -> TEST_PRIVATEKEY_ID;
4544
4645 @Test
4746 void createToken_withoutBearerAccessScope() {
4847 var sts = new EmbeddedSecureTokenService(tokenGenerationService, keySupplier, () -> "test-key", Clock.systemUTC(), 10 * 60);
4948 var token = TokenRepresentation.Builder.newInstance().token("test").build();
5049
51- when(tokenGenerationService.generate(eq(keySupplier), any(TokenDecorator[].class))).thenReturn(Result.success(token));
50+ when(tokenGenerationService.generate(eq(TEST_PRIVATEKEY_ID), any(TokenDecorator[].class))).thenReturn(Result.success(token));
5251 var result = sts.createToken(Map.of(), null);
5352
5453 assertThat(result.succeeded()).isTrue();
@@ -71,7 +70,7 @@
7170 var sts = new EmbeddedSecureTokenService(tokenGenerationService, keySupplier, () -> "test-key", Clock.systemUTC(), 10 * 60);
7271 var token = TokenRepresentation.Builder.newInstance().token("test").build();
7372
74- when(tokenGenerationService.generate(eq(keySupplier), any(TokenDecorator[].class)))
73+ when(tokenGenerationService.generate(eq(TEST_PRIVATEKEY_ID), any(TokenDecorator[].class)))
7574 .thenReturn(Result.success(token))
7675 .thenReturn(Result.success(token));
7776
@@ -104,7 +103,7 @@
104103 var sts = new EmbeddedSecureTokenService(tokenGenerationService, keySupplier, () -> "test-key", Clock.systemUTC(), 10 * 60);
105104 var token = TokenRepresentation.Builder.newInstance().token("test").build();
106105
107- when(tokenGenerationService.generate(eq(keySupplier), any(TokenDecorator[].class)))
106+ when(tokenGenerationService.generate(eq(TEST_PRIVATEKEY_ID), any(TokenDecorator[].class)))
108107 .thenReturn(Result.failure("Failed to create access token"))
109108 .thenReturn(Result.success(token));
110109
@@ -128,7 +127,7 @@
128127 var sts = new EmbeddedSecureTokenService(tokenGenerationService, keySupplier, () -> "test-key", Clock.systemUTC(), 10 * 60);
129128 var token = TokenRepresentation.Builder.newInstance().token("test").build();
130129
131- when(tokenGenerationService.generate(eq(keySupplier), any(TokenDecorator[].class)))
130+ when(tokenGenerationService.generate(eq(TEST_PRIVATEKEY_ID), any(TokenDecorator[].class)))
132131 .thenReturn(Result.success(token))
133132 .thenReturn(Result.failure("Failed to create access token"));
134133
@@ -137,7 +136,7 @@
137136
138137 assertThat(result.failed()).isTrue();
139138
140- verify(tokenGenerationService, times(2)).generate(eq(keySupplier), any(TokenDecorator[].class));
139+ verify(tokenGenerationService, times(2)).generate(eq(TEST_PRIVATEKEY_ID), any(TokenDecorator[].class));
141140
142141 }
143142
modified extensions/common/iam/oauth2/oauth2-core/src/main/java/org/eclipse/edc/iam/oauth2/Oauth2ServiceExtension.java +5 −4
@@ -22,6 +22,7 @@
2222 import org.eclipse.edc.iam.oauth2.jwt.X509CertificateDecorator;
2323 import org.eclipse.edc.iam.oauth2.spi.Oauth2AssertionDecorator;
2424 import org.eclipse.edc.iam.oauth2.spi.client.Oauth2Client;
25+import org.eclipse.edc.jwt.signer.spi.JwsSignerProvider;
2526 import org.eclipse.edc.keys.spi.CertificateResolver;
2627 import org.eclipse.edc.keys.spi.PrivateKeyResolver;
2728 import org.eclipse.edc.runtime.metamodel.annotation.Extension;
@@ -42,7 +43,6 @@
4243 import org.eclipse.edc.token.spi.TokenValidationService;
4344 import org.jetbrains.annotations.NotNull;
4445
45-import java.security.PrivateKey;
4646 import java.time.Clock;
4747 import java.util.Optional;
4848 import java.util.concurrent.TimeUnit;
@@ -110,6 +110,8 @@
110110 private TokenValidationService tokenValidationService;
111111 @Inject
112112 private TokenDecoratorRegistry jwtDecoratorRegistry;
113+ @Inject
114+ private JwsSignerProvider jwsSignerProvider;
113115
114116 @Override
115117 public String name() {
@@ -157,12 +159,11 @@
157159 private Oauth2ServiceImpl createOauth2Service(Oauth2ServiceConfiguration configuration,
158160 TokenDecoratorRegistry jwtDecoratorRegistry,
159161 IdentityProviderKeyResolver providerKeyResolver) {
160- Supplier<PrivateKey> privateKeySupplier = () -> privateKeyResolver.resolvePrivateKey(configuration.getPrivateKeyAlias())
161- .orElseThrow(f -> new EdcException(f.getFailureDetail()));
162+ Supplier<String> privateKeySupplier = configuration::getPrivateKeyAlias;
162163
163164 return new Oauth2ServiceImpl(
164165 configuration,
165- new JwtGenerationService(),
166+ new JwtGenerationService(jwsSignerProvider),
166167 privateKeySupplier,
167168 oauth2Client,
168169 jwtDecoratorRegistry,
modified extensions/common/iam/oauth2/oauth2-core/src/main/java/org/eclipse/edc/iam/oauth2/identity/Oauth2ServiceImpl.java +4 −5
@@ -36,7 +36,6 @@
3636 import org.eclipse.edc.token.spi.TokenValidationService;
3737 import org.jetbrains.annotations.NotNull;
3838
39-import java.security.PrivateKey;
4039 import java.util.function.Supplier;
4140
4241 import static org.eclipse.edc.iam.oauth2.Oauth2ServiceExtension.OAUTH2_TOKEN_CONTEXT;
@@ -49,7 +48,7 @@
4948 private static final String GRANT_TYPE = "client_credentials";
5049
5150 private final Oauth2ServiceConfiguration configuration;
52- private final Supplier<PrivateKey> privateKeySupplier;
51+ private final Supplier<String> privateKeySupplier;
5352 private final Oauth2Client client;
5453 private final TokenDecoratorRegistry jwtDecoratorRegistry;
5554 private final TokenGenerationService tokenGenerationService;
@@ -66,11 +65,11 @@
6665 * @param jwtDecoratorRegistry Registry containing the decorator for build the JWT
6766 * @param tokenValidationService Service used for token validation
6867 */
69- public Oauth2ServiceImpl(Oauth2ServiceConfiguration configuration, TokenGenerationService tokenGenerationService, Supplier<PrivateKey> privateKeySupplier,
68+ public Oauth2ServiceImpl(Oauth2ServiceConfiguration configuration, TokenGenerationService tokenGenerationService, Supplier<String> privateKeyIdSupplier,
7069 Oauth2Client client, TokenDecoratorRegistry jwtDecoratorRegistry, TokenValidationRulesRegistry tokenValidationRuleRegistry, TokenValidationService tokenValidationService,
7170 PublicKeyResolver publicKeyResolver) {
7271 this.configuration = configuration;
73- this.privateKeySupplier = privateKeySupplier;
72+ this.privateKeySupplier = privateKeyIdSupplier;
7473 this.client = client;
7574 this.jwtDecoratorRegistry = jwtDecoratorRegistry;
7675 this.tokenValidationRuleRegistry = tokenValidationRuleRegistry;
@@ -94,7 +93,7 @@
9493 @NotNull
9594 private Result<String> generateClientAssertion() {
9695 var decorators = jwtDecoratorRegistry.getDecoratorsFor(OAUTH2_TOKEN_CONTEXT).toArray(TokenDecorator[]::new);
97- return tokenGenerationService.generate(privateKeySupplier, decorators)
96+ return tokenGenerationService.generate(privateKeySupplier.get(), decorators)
9897 .map(TokenRepresentation::getToken);
9998 }
10099
modified extensions/common/iam/oauth2/oauth2-core/src/test/java/org/eclipse/edc/iam/oauth2/identity/Oauth2ServiceImplTest.java +2 −2
@@ -75,6 +75,7 @@
7575 private static final String PROVIDER_AUDIENCE = "audience-test";
7676 private static final String ENDPOINT_AUDIENCE = "endpoint-audience-test";
7777
78+ private static final String TEST_PRIVATE_KEY_ID = "test-private-key-id";
7879 private static final VerificationContext VERIFICATION_CONTEXT = VerificationContext.Builder.newInstance()
7980 .policy(Policy.Builder.newInstance().build())
8081 .build();
@@ -90,7 +91,6 @@
9091 @BeforeEach
9192 void setUp() throws JOSEException {
9293 var testKey = testKey();
93- var privateKey = testKey.toPrivateKey();
9494
9595 jwsSigner = new RSASSASigner(testKey.toPrivateKey());
9696 var publicKeyResolverMock = mock(PublicKeyResolver.class);
@@ -114,7 +114,7 @@
114114 registry.addRule(OAUTH2_TOKEN_CONTEXT, new NotBeforeValidationRule(Clock.systemUTC(), configuration.getNotBeforeValidationLeeway()));
115115 registry.addRule(OAUTH2_TOKEN_CONTEXT, new ExpirationIssuedAtValidationRule(Clock.systemUTC(), configuration.getIssuedAtLeeway()));
116116
117- authService = new Oauth2ServiceImpl(configuration, tokenGenerationService, () -> privateKey, client, jwtDecoratorRegistry, registry,
117+ authService = new Oauth2ServiceImpl(configuration, tokenGenerationService, () -> TEST_PRIVATE_KEY_ID, client, jwtDecoratorRegistry, registry,
118118 tokenValidationService, publicKeyResolverMock);
119119
120120 }
modified extensions/control-plane/transfer/transfer-data-plane/src/main/java/org/eclipse/edc/connector/controlplane/transfer/dataplane/TransferDataPlaneCoreExtension.java +4 −13
@@ -25,6 +25,7 @@
2525 import org.eclipse.edc.connector.controlplane.transfer.spi.flow.DataFlowManager;
2626 import org.eclipse.edc.connector.dataplane.selector.spi.DataPlaneSelectorService;
2727 import org.eclipse.edc.connector.dataplane.selector.spi.client.DataPlaneClientFactory;
28+import org.eclipse.edc.jwt.signer.spi.JwsSignerProvider;
2829 import org.eclipse.edc.keys.spi.LocalPublicKeyService;
2930 import org.eclipse.edc.keys.spi.PrivateKeyResolver;
3031 import org.eclipse.edc.runtime.metamodel.annotation.Extension;
@@ -41,11 +42,8 @@
4142 import org.eclipse.edc.web.spi.WebService;
4243 import org.eclipse.edc.web.spi.configuration.ApiContext;
4344 import org.eclipse.edc.web.spi.configuration.context.ControlApiUrl;
44-import org.jetbrains.annotations.NotNull;
4545
46-import java.security.PrivateKey;
4746 import java.time.Clock;
48-import java.util.function.Supplier;
4947
5048 @Extension(value = TransferDataPlaneCoreExtension.NAME)
5149 public class TransferDataPlaneCoreExtension implements ServiceExtension {
@@ -100,6 +98,8 @@
10098
10199 @Inject
102100 private TokenValidationService tokenValidationService;
101+ @Inject
102+ private JwsSignerProvider jwsSignerProvider;
103103
104104 @Override
105105 public String name() {
@@ -117,7 +117,7 @@
117117 var controller = new ConsumerPullTransferTokenValidationApiController(tokenValidationService, dataEncrypter, typeManager, (i) -> publicKeyService.resolveKey(publicKeyAlias));
118118 webService.registerResource(ApiContext.CONTROL, controller);
119119
120- var resolver = new ConsumerPullDataPlaneProxyResolver(dataEncrypter, typeManager, new JwtGenerationService(), getPrivateKeySupplier(context, privateKeyAlias), () -> publicKeyAlias, tokenExpirationDateFunction);
120+ var resolver = new ConsumerPullDataPlaneProxyResolver(dataEncrypter, typeManager, new JwtGenerationService(jwsSignerProvider), () -> privateKeyAlias, () -> publicKeyAlias, tokenExpirationDateFunction);
121121 dataFlowManager.register(new ConsumerPullTransferDataFlowController(selectorService, resolver));
122122 } else {
123123 monitor.info("One of these settings is not configured, so the connector won't be able to provide 'consumer-pull' transfers: [%s, %s]"
@@ -130,13 +130,4 @@
130130 dataAddressValidatorRegistry.registerDestinationValidator("HttpProxy", dataAddress -> ValidationResult.success());
131131 }
132132
133- @NotNull
134- private Supplier<PrivateKey> getPrivateKeySupplier(ServiceExtensionContext context, String privateKeyAlias) {
135- return () -> privateKeyResolver.resolvePrivateKey(privateKeyAlias)
136- .orElse(f -> {
137- context.getMonitor().warning("Cannot resolve private key: " + f.getFailureDetail());
138- return null;
139- });
140- }
141-
142133 }
modified extensions/control-plane/transfer/transfer-data-plane/src/main/java/org/eclipse/edc/connector/controlplane/transfer/dataplane/proxy/ConsumerPullDataPlaneProxyResolver.java +4 −5
@@ -27,7 +27,6 @@
2727 import org.eclipse.edc.token.spi.KeyIdDecorator;
2828 import org.eclipse.edc.token.spi.TokenGenerationService;
2929
30-import java.security.PrivateKey;
3130 import java.util.Optional;
3231 import java.util.function.Supplier;
3332
@@ -42,18 +41,18 @@
4241 private final DataEncrypter dataEncrypter;
4342 private final TypeManager typeManager;
4443 private final TokenGenerationService tokenGenerationService;
45- private final Supplier<PrivateKey> keySupplier;
44+ private final Supplier<String> privateKeyIdSupplier;
4645 private final Supplier<String> publicKeyIdSupplier;
4746 private final ConsumerPullTokenExpirationDateFunction tokenExpirationDateFunction;
4847
4948 public ConsumerPullDataPlaneProxyResolver(DataEncrypter dataEncrypter, TypeManager typeManager, TokenGenerationService tokenGenerationService,
50- Supplier<PrivateKey> keySupplier, Supplier<String> publicKeyIdSupplier,
49+ Supplier<String> privateKeyIdSupplier, Supplier<String> publicKeyIdSupplier,
5150 ConsumerPullTokenExpirationDateFunction tokenExpirationDateFunction) {
5251 this.dataEncrypter = dataEncrypter;
5352 this.typeManager = typeManager;
5453 this.tokenExpirationDateFunction = tokenExpirationDateFunction;
5554 this.tokenGenerationService = tokenGenerationService;
56- this.keySupplier = keySupplier;
55+ this.privateKeyIdSupplier = privateKeyIdSupplier;
5756 this.publicKeyIdSupplier = publicKeyIdSupplier;
5857 }
5958
@@ -87,7 +86,7 @@
8786 .compose(expiration -> {
8887 var keyIdDecorator = new KeyIdDecorator(publicKeyIdSupplier.get());
8988 var dataAddressDecorator = new ConsumerPullDataPlaneProxyTokenDecorator(expiration, encryptedDataAddress);
90- return tokenGenerationService.generate(keySupplier, keyIdDecorator, dataAddressDecorator);
89+ return tokenGenerationService.generate(privateKeyIdSupplier.get(), keyIdDecorator, dataAddressDecorator);
9190 })
9291 .map(TokenRepresentation::getToken);
9392 }
modified extensions/control-plane/transfer/transfer-data-plane/src/test/java/org/eclipse/edc/connector/controlplane/transfer/dataplane/proxy/ConsumerPullDataPlaneProxyResolverTest.java +4 −4
@@ -30,7 +30,6 @@
3030 import org.eclipse.edc.token.spi.TokenGenerationService;
3131 import org.junit.jupiter.api.Test;
3232 import org.mockito.ArgumentCaptor;
33-import org.mockito.Mockito;
3433
3534 import java.sql.Date;
3635 import java.time.Instant;
@@ -41,6 +40,7 @@
4140 import static org.eclipse.edc.connector.controlplane.transfer.dataplane.spi.TransferDataPlaneConstants.DATA_ADDRESS;
4241 import static org.eclipse.edc.connector.controlplane.transfer.dataplane.spi.TransferDataPlaneConstants.HTTP_PROXY;
4342 import static org.mockito.ArgumentMatchers.any;
43+import static org.mockito.ArgumentMatchers.anyString;
4444 import static org.mockito.Mockito.mock;
4545 import static org.mockito.Mockito.when;
4646
@@ -52,7 +52,7 @@
5252 private final TokenGenerationService tokenGenerationService = mock();
5353 private final ConsumerPullTokenExpirationDateFunction tokenExpirationDateFunction = mock();
5454
55- private final ConsumerPullDataPlaneProxyResolver resolver = new ConsumerPullDataPlaneProxyResolver(dataEncrypter, TYPE_MANAGER, tokenGenerationService, Mockito::mock, () -> "test-public-key", tokenExpirationDateFunction);
55+ private final ConsumerPullDataPlaneProxyResolver resolver = new ConsumerPullDataPlaneProxyResolver(dataEncrypter, TYPE_MANAGER, tokenGenerationService, () -> "test-private-key", () -> "test-public-key", tokenExpirationDateFunction);
5656
5757 private static DataAddress dataAddress() {
5858 return DataAddress.Builder.newInstance().type(UUID.randomUUID().toString()).build();
@@ -75,7 +75,7 @@
7575 var captor = ArgumentCaptor.forClass(TokenDecorator[].class);
7676 when(dataEncrypter.encrypt(TYPE_MANAGER.writeValueAsString(address))).thenReturn(encryptedAddress);
7777 when(tokenExpirationDateFunction.expiresAt(address, transferProcess.getContractId())).thenReturn(Result.success(expiration));
78- when(tokenGenerationService.generate(any(), captor.capture()))
78+ when(tokenGenerationService.generate(anyString(), captor.capture()))
7979 .thenReturn(Result.success(TokenRepresentation.Builder.newInstance().token(token).build()));
8080
8181 var result = resolver.toDataAddress(transferProcess, address, instance);
@@ -157,7 +157,7 @@
157157
158158 when(dataEncrypter.encrypt(TYPE_MANAGER.writeValueAsString(address))).thenReturn("encryptedAddress");
159159 when(tokenExpirationDateFunction.expiresAt(address, transferProcess.getContractId())).thenReturn(Result.success(expiration));
160- when(tokenGenerationService.generate(any(), any(TokenDecorator[].class))).thenReturn(Result.failure(errorMsg));
160+ when(tokenGenerationService.generate(anyString(), any(TokenDecorator[].class))).thenReturn(Result.failure(errorMsg));
161161
162162 var result = resolver.toDataAddress(transferProcess, address, instance);
163163
modified extensions/data-plane/data-plane-http-oauth2-core/src/main/java/org/eclipse/edc/connector/dataplane/http/oauth2/DataPlaneHttpOauth2Extension.java +3 −3
@@ -17,7 +17,7 @@
1717
1818 import org.eclipse.edc.connector.dataplane.http.spi.HttpRequestParamsProvider;
1919 import org.eclipse.edc.iam.oauth2.spi.client.Oauth2Client;
20-import org.eclipse.edc.keys.spi.PrivateKeyResolver;
20+import org.eclipse.edc.jwt.signer.spi.JwsSignerProvider;
2121 import org.eclipse.edc.runtime.metamodel.annotation.Extension;
2222 import org.eclipse.edc.runtime.metamodel.annotation.Inject;
2323 import org.eclipse.edc.spi.security.Vault;
@@ -43,7 +43,7 @@
4343 private Vault vault;
4444
4545 @Inject
46- private PrivateKeyResolver privateKeyResolver;
46+ private JwsSignerProvider jwsSignerProvider;
4747
4848 @Inject
4949 private Oauth2Client oauth2Client;
@@ -55,7 +55,7 @@
5555
5656 @Override
5757 public void initialize(ServiceExtensionContext context) {
58- var requestFactory = new Oauth2CredentialsRequestFactory(privateKeyResolver, clock, vault, context.getMonitor());
58+ var requestFactory = new Oauth2CredentialsRequestFactory(jwsSignerProvider, clock, vault);
5959 var oauth2ParamsDecorator = new Oauth2HttpRequestParamsDecorator(requestFactory, oauth2Client);
6060
6161 paramsProvider.registerSourceDecorator(oauth2ParamsDecorator);
modified extensions/data-plane/data-plane-http-oauth2-core/src/main/java/org/eclipse/edc/connector/dataplane/http/oauth2/Oauth2CredentialsRequestFactory.java +6 −14
@@ -18,9 +18,8 @@
1818 import org.eclipse.edc.iam.oauth2.spi.client.Oauth2CredentialsRequest;
1919 import org.eclipse.edc.iam.oauth2.spi.client.PrivateKeyOauth2CredentialsRequest;
2020 import org.eclipse.edc.iam.oauth2.spi.client.SharedSecretOauth2CredentialsRequest;
21-import org.eclipse.edc.keys.spi.PrivateKeyResolver;
21+import org.eclipse.edc.jwt.signer.spi.JwsSignerProvider;
2222 import org.eclipse.edc.spi.iam.TokenRepresentation;
23-import org.eclipse.edc.spi.monitor.Monitor;
2423 import org.eclipse.edc.spi.result.Result;
2524 import org.eclipse.edc.spi.security.Vault;
2625 import org.eclipse.edc.spi.types.domain.DataAddress;
@@ -46,16 +45,14 @@
4645
4746 private static final long DEFAULT_TOKEN_VALIDITY = TimeUnit.MINUTES.toSeconds(5);
4847 private static final String GRANT_CLIENT_CREDENTIALS = "client_credentials";
49- private final PrivateKeyResolver privateKeyResolver;
48+ private final JwsSignerProvider jwsSignerProvider;
5049 private final Clock clock;
5150 private final Vault vault;
52- private final Monitor monitor;
5351
54- public Oauth2CredentialsRequestFactory(PrivateKeyResolver privateKeyResolver, Clock clock, Vault vault, Monitor monitor) {
55- this.privateKeyResolver = privateKeyResolver;
52+ public Oauth2CredentialsRequestFactory(JwsSignerProvider jwsSignerProvider, Clock clock, Vault vault) {
53+ this.jwsSignerProvider = jwsSignerProvider;
5654 this.clock = clock;
5755 this.vault = vault;
58- this.monitor = monitor;
5956 }
6057
6158 /**
@@ -104,18 +101,13 @@
104101
105102 @NotNull
106103 private Result<TokenRepresentation> createAssertion(String pkSecret, DataAddress dataAddress) {
107- var privateKey = privateKeyResolver.resolvePrivateKey(pkSecret);
108- if (privateKey.failed()) {
109- return Result.failure("Failed to resolve private key with alias: " + pkSecret);
110- }
111-
112104 var validity = Optional.ofNullable(dataAddress.getStringProperty(VALIDITY))
113105 .map(this::parseLong)
114106 .orElse(DEFAULT_TOKEN_VALIDITY);
115107 var decorator = new Oauth2AssertionDecorator(dataAddress.getStringProperty(TOKEN_URL), dataAddress.getStringProperty(CLIENT_ID), clock, validity);
116- var service = new JwtGenerationService();
108+ var service = new JwtGenerationService(jwsSignerProvider);
117109
118- return service.generate(privateKey::getContent, decorator);
110+ return service.generate(pkSecret, decorator);
119111 }
120112
121113 @Nullable
modified extensions/data-plane/data-plane-http-oauth2-core/src/test/java/org/eclipse/edc/connector/dataplane/http/oauth2/Oauth2CredentialsRequestFactoryTest.java +14 −13
@@ -15,16 +15,17 @@
1515 package org.eclipse.edc.connector.dataplane.http.oauth2;
1616
1717 import com.nimbusds.jose.JOSEException;
18+import com.nimbusds.jose.crypto.RSASSASigner;
1819 import com.nimbusds.jose.crypto.RSASSAVerifier;
1920 import com.nimbusds.jose.jwk.KeyUse;
2021 import com.nimbusds.jose.jwk.RSAKey;
2122 import com.nimbusds.jose.jwk.gen.RSAKeyGenerator;
2223 import com.nimbusds.jwt.SignedJWT;
24+import org.assertj.core.api.AssertionsForClassTypes;
2325 import org.eclipse.edc.connector.dataplane.http.spi.HttpDataAddress;
2426 import org.eclipse.edc.iam.oauth2.spi.client.PrivateKeyOauth2CredentialsRequest;
2527 import org.eclipse.edc.iam.oauth2.spi.client.SharedSecretOauth2CredentialsRequest;
26-import org.eclipse.edc.keys.spi.PrivateKeyResolver;
27-import org.eclipse.edc.spi.monitor.Monitor;
28+import org.eclipse.edc.jwt.signer.spi.JwsSignerProvider;
2829 import org.eclipse.edc.spi.result.Result;
2930 import org.eclipse.edc.spi.security.Vault;
3031 import org.junit.jupiter.api.Test;
@@ -45,6 +46,7 @@
4546 import static org.eclipse.edc.iam.oauth2.spi.Oauth2DataAddressSchema.SCOPE;
4647 import static org.eclipse.edc.iam.oauth2.spi.Oauth2DataAddressSchema.TOKEN_URL;
4748 import static org.eclipse.edc.iam.oauth2.spi.Oauth2DataAddressSchema.VALIDITY;
49+import static org.eclipse.edc.junit.assertions.AbstractResultAssert.assertThat;
4850 import static org.mockito.Mockito.mock;
4951 import static org.mockito.Mockito.verifyNoInteractions;
5052 import static org.mockito.Mockito.when;
@@ -53,10 +55,9 @@
5355
5456 private final Instant now = Instant.now();
5557 private final Clock clock = Clock.fixed(now, UTC);
56- private final PrivateKeyResolver privateKeyResolver = mock(PrivateKeyResolver.class);
57- private final Vault vault = mock(Vault.class);
58- private final Monitor monitor = mock(Monitor.class);
59- private final Oauth2CredentialsRequestFactory factory = new Oauth2CredentialsRequestFactory(privateKeyResolver, clock, vault, monitor);
58+ private final JwsSignerProvider privateKeyResolver = mock();
59+ private final Vault vault = mock();
60+ private final Oauth2CredentialsRequestFactory factory = new Oauth2CredentialsRequestFactory(privateKeyResolver, clock, vault);
6061
6162 @Test
6263 void shouldCreateSharedSecretRequestWithKey_whenPrivateKeyNameIsAbsent() {
@@ -68,7 +69,7 @@
6869
6970 var result = factory.create(address);
7071
71- assertThat(result).matches(Result::succeeded).extracting(Result::getContent)
72+ AssertionsForClassTypes.assertThat(result).matches(Result::succeeded).extracting(Result::getContent)
7273 .asInstanceOf(type(SharedSecretOauth2CredentialsRequest.class))
7374 .satisfies(request -> {
7475 assertThat(request.getGrantType()).isEqualTo("client_credentials");
@@ -90,13 +91,13 @@
9091
9192 var result = factory.create(address);
9293
93- assertThat(result).matches(Result::failed);
94+ AssertionsForClassTypes.assertThat(result).matches(Result::failed);
9495 }
9596
9697 @Test
9798 void shouldCreatePrivateKeyRequest_whenPrivateKeyNameIsPresent() throws JOSEException {
9899 var keyPair = generateKeyPair();
99- when(privateKeyResolver.resolvePrivateKey("pk-test")).thenReturn(Result.success(keyPair.toPrivateKey()));
100+ when(privateKeyResolver.createJwsSigner("pk-test")).thenReturn(Result.success(new RSASSASigner(keyPair.toPrivateKey())));
100101
101102 var address = defaultAddress()
102103 .property(PRIVATE_KEY_NAME, "pk-test")
@@ -105,7 +106,7 @@
105106
106107 var result = factory.create(address);
107108
108- assertThat(result).matches(Result::succeeded).extracting(Result::getContent)
109+ AssertionsForClassTypes.assertThat(result).matches(Result::succeeded).extracting(Result::getContent)
109110 .asInstanceOf(type(PrivateKeyOauth2CredentialsRequest.class))
110111 .satisfies(request -> {
111112 assertThat(request.getGrantType()).isEqualTo("client_credentials");
@@ -130,7 +131,7 @@
130131
131132 @Test
132133 void shouldFailIfPrivateKeySecretNotFound() {
133- when(privateKeyResolver.resolvePrivateKey("pk-test")).thenReturn(Result.failure("not found"));
134+ when(privateKeyResolver.createJwsSigner("pk-test")).thenReturn(Result.failure("foo bar"));
134135
135136 var address = defaultAddress()
136137 .property(PRIVATE_KEY_NAME, "pk-test")
@@ -139,8 +140,8 @@
139140
140141 var result = factory.create(address);
141142
142- assertThat(result).matches(Result::failed)
143- .extracting(Result::getFailureDetail).asString().contains("pk-test");
143+ assertThat(result).isFailed()
144+ .detail().contains("foo bar");
144145 }
145146
146147 private HttpDataAddress.Builder defaultAddress() {
modified settings.gradle.kts +1 −0
@@ -234,6 +234,7 @@
234234 include(":spi:common:identity-did-spi")
235235 include(":spi:common:json-ld-spi")
236236 include(":spi:common:jwt-spi")
237+include(":spi:common:jwt-signer-spi")
237238 include(":spi:common:token-spi")
238239 include(":spi:common:oauth2-spi")
239240 include(":spi:common:policy-engine-spi")
added spi/common/jwt-signer-spi/build.gradle.kts +26 −0
@@ -0,0 +1,26 @@
1+/*
2+ * Copyright (c) 2022 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
3+ *
4+ * This program and the accompanying materials are made available under the
5+ * terms of the Apache License, Version 2.0 which is available at
6+ * https://www.apache.org/licenses/LICENSE-2.0
7+ *
8+ * SPDX-License-Identifier: Apache-2.0
9+ *
10+ * Contributors:
11+ * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation
12+ *
13+ */
14+
15+plugins {
16+ `java-library`
17+ `maven-publish`
18+}
19+
20+dependencies {
21+ api(libs.nimbus.jwt)
22+ api(project(":spi:common:boot-spi")) //Result
23+ implementation(libs.edc.runtime.metamodel)
24+}
25+
26+
added spi/common/jwt-signer-spi/src/main/java/org/eclipse/edc/jwt/signer/spi/JwsSignerProvider.java +28 −0
@@ -0,0 +1,28 @@
1+/*
2+ * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
3+ *
4+ * This program and the accompanying materials are made available under the
5+ * terms of the Apache License, Version 2.0 which is available at
6+ * https://www.apache.org/licenses/LICENSE-2.0
7+ *
8+ * SPDX-License-Identifier: Apache-2.0
9+ *
10+ * Contributors:
11+ * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation
12+ *
13+ */
14+
15+package org.eclipse.edc.jwt.signer.spi;
16+
17+import com.nimbusds.jose.JWSSigner;
18+import org.eclipse.edc.runtime.metamodel.annotation.ExtensionPoint;
19+import org.eclipse.edc.spi.result.Result;
20+
21+/**
22+ * A JwsSignerProvider provides a {@link JWSSigner} for a given private key ID.
23+ */
24+@ExtensionPoint
25+@FunctionalInterface
26+public interface JwsSignerProvider {
27+ Result<JWSSigner> createJwsSigner(String privateKeyId);
28+}
added spi/common/jwt-signer-spi/src/main/java/org/eclipse/edc/jwt/signer/spi/package-info.java +18 −0
@@ -0,0 +1,18 @@
1+/*
2+ * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
3+ *
4+ * This program and the accompanying materials are made available under the
5+ * terms of the Apache License, Version 2.0 which is available at
6+ * https://www.apache.org/licenses/LICENSE-2.0
7+ *
8+ * SPDX-License-Identifier: Apache-2.0
9+ *
10+ * Contributors:
11+ * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation
12+ *
13+ */
14+@Spi(value = "Implementation SPI that is used to contribute custom JWSSigners to the JwtGenerationService")
15+
16+package org.eclipse.edc.jwt.signer.spi;
17+
18+import org.eclipse.edc.runtime.metamodel.annotation.Spi;
No newline at the end of the file
modified spi/common/token-spi/src/main/java/org/eclipse/edc/token/spi/TokenGenerationService.java +3 −7
@@ -17,9 +17,6 @@
1717 import org.eclipse.edc.spi.iam.TokenRepresentation;
1818 import org.eclipse.edc.spi.result.Result;
1919
20-import java.security.PrivateKey;
21-import java.util.function.Supplier;
22-
2320 /**
2421 * Interface for generating token based on a set of claims and header.
2522 */
@@ -28,9 +25,8 @@
2825 /**
2926 * Generate a signed token based on the request.
3027 *
31- * @param privateKeySupplier A {@link Supplier} that provides the private on-demand.
32- * Be advised that holding the private key in memory poses a considerable security risk and should be avoided.
33- * @param decorators an optional list of {@code JwtDecorator} objects to determine the shape of the token, i.e. headers and claims
28+ * @param privateKeyId A String that identifies the private key, e.g. a secret alias in a {@link org.eclipse.edc.spi.security.Vault}
29+ * @param decorators an optional list of {@code JwtDecorator} objects to determine the shape of the token, i.e. headers and claims
3430 */
35- Result<TokenRepresentation> generate(Supplier<PrivateKey> privateKeySupplier, TokenDecorator... decorators);
31+ Result<TokenRepresentation> generate(String privateKeyId, TokenDecorator... decorators);
3632 }