diff --git a/.github/workflows/verify.yaml b/.github/workflows/verify.yaml index 38f4b3f69..c2e276362 100644 --- a/.github/workflows/verify.yaml +++ b/.github/workflows/verify.yaml @@ -70,7 +70,6 @@ jobs: - name: Run Checkstyle run: | ./gradlew checkstyleMain checkstyleTest - echo "Running Checkstyle is currently a placeholder" markdown-lint: runs-on: ubuntu-latest diff --git a/core/edr-cache-core/src/main/java/org/eclipse/tractusx/edc/edr/core/defaults/InMemoryEndpointDataReferenceCache.java b/core/edr-cache-core/src/main/java/org/eclipse/tractusx/edc/edr/core/defaults/InMemoryEndpointDataReferenceCache.java index d396b4170..219acfc63 100644 --- a/core/edr-cache-core/src/main/java/org/eclipse/tractusx/edc/edr/core/defaults/InMemoryEndpointDataReferenceCache.java +++ b/core/edr-cache-core/src/main/java/org/eclipse/tractusx/edc/edr/core/defaults/InMemoryEndpointDataReferenceCache.java @@ -22,7 +22,11 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; import java.util.concurrent.locks.ReentrantReadWriteLock; import static java.util.Collections.emptyList; diff --git a/core/edr-cache-core/src/test/java/org/eclipse/tractusx/edc/edr/core/defaults/InMemoryEndpointDataReferenceCacheTest.java b/core/edr-cache-core/src/test/java/org/eclipse/tractusx/edc/edr/core/defaults/InMemoryEndpointDataReferenceCacheTest.java index c2dab4afc..c2478fba9 100644 --- a/core/edr-cache-core/src/test/java/org/eclipse/tractusx/edc/edr/core/defaults/InMemoryEndpointDataReferenceCacheTest.java +++ b/core/edr-cache-core/src/test/java/org/eclipse/tractusx/edc/edr/core/defaults/InMemoryEndpointDataReferenceCacheTest.java @@ -26,13 +26,13 @@ class InMemoryEndpointDataReferenceCacheTest { private static final String ASSET_ID = "asset1"; private static final String EDR_ID = "edr1"; - private InMemoryEndpointDataReferenceCache cache = new InMemoryEndpointDataReferenceCache(); + private final InMemoryEndpointDataReferenceCache cache = new InMemoryEndpointDataReferenceCache(); @Test @SuppressWarnings("DataFlowIssue") void verify_operations() { - var edr = EndpointDataReference.Builder.newInstance(). - endpoint("http://test.com") + var edr = EndpointDataReference.Builder.newInstance() + .endpoint("http://test.com") .id(EDR_ID) .authCode("11111") .authKey("authentication").build(); diff --git a/core/edr-cache-core/src/test/java/org/eclipse/tractusx/edc/edr/core/defaults/PersistentCacheEntryTest.java b/core/edr-cache-core/src/test/java/org/eclipse/tractusx/edc/edr/core/defaults/PersistentCacheEntryTest.java index 764afb33b..b17c1e524 100644 --- a/core/edr-cache-core/src/test/java/org/eclipse/tractusx/edc/edr/core/defaults/PersistentCacheEntryTest.java +++ b/core/edr-cache-core/src/test/java/org/eclipse/tractusx/edc/edr/core/defaults/PersistentCacheEntryTest.java @@ -29,8 +29,8 @@ class PersistentCacheEntryTest { void verify_serializeDeserialize() throws JsonProcessingException { var mapper = new ObjectMapper(); - var edr = EndpointDataReference.Builder.newInstance(). - endpoint("http://test.com") + var edr = EndpointDataReference.Builder.newInstance() + .endpoint("http://test.com") .id(randomUUID().toString()) .authCode("11111") .authKey("authentication").build(); diff --git a/edc-controlplane/edc-runtime-memory/src/main/java/org/eclipse/tractusx/edc/vault/memory/VaultMemoryExtension.java b/edc-controlplane/edc-runtime-memory/src/main/java/org/eclipse/tractusx/edc/vault/memory/VaultMemoryExtension.java index c8d2cc7d2..434e7886f 100644 --- a/edc-controlplane/edc-runtime-memory/src/main/java/org/eclipse/tractusx/edc/vault/memory/VaultMemoryExtension.java +++ b/edc-controlplane/edc-runtime-memory/src/main/java/org/eclipse/tractusx/edc/vault/memory/VaultMemoryExtension.java @@ -17,7 +17,11 @@ import org.eclipse.edc.runtime.metamodel.annotation.Provider; import org.eclipse.edc.runtime.metamodel.annotation.Provides; import org.eclipse.edc.runtime.metamodel.annotation.Setting; -import org.eclipse.edc.spi.security.*; +import org.eclipse.edc.spi.security.CertificateResolver; +import org.eclipse.edc.spi.security.PrivateKeyResolver; +import org.eclipse.edc.spi.security.Vault; +import org.eclipse.edc.spi.security.VaultCertificateResolver; +import org.eclipse.edc.spi.security.VaultPrivateKeyResolver; import org.eclipse.edc.spi.system.ServiceExtension; import org.eclipse.edc.spi.system.ServiceExtensionContext; diff --git a/edc-controlplane/edc-runtime-memory/src/test/java/org/eclipse/tractusx/edc/vault/memory/VaultMemoryExtensionTest.java b/edc-controlplane/edc-runtime-memory/src/test/java/org/eclipse/tractusx/edc/vault/memory/VaultMemoryExtensionTest.java index bec589d79..7012d5285 100644 --- a/edc-controlplane/edc-runtime-memory/src/test/java/org/eclipse/tractusx/edc/vault/memory/VaultMemoryExtensionTest.java +++ b/edc-controlplane/edc-runtime-memory/src/test/java/org/eclipse/tractusx/edc/vault/memory/VaultMemoryExtensionTest.java @@ -22,7 +22,12 @@ import org.junit.jupiter.params.provider.ValueSource; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; class VaultMemoryExtensionTest { private VaultMemoryExtension extension; diff --git a/edc-dataplane/edc-dataplane-proxy-consumer-api/src/main/java/org/eclipse/tractusx/edc/dataplane/proxy/consumer/api/DataPlaneProxyConsumerApiExtension.java b/edc-dataplane/edc-dataplane-proxy-consumer-api/src/main/java/org/eclipse/tractusx/edc/dataplane/proxy/consumer/api/DataPlaneProxyConsumerApiExtension.java index 566a63b7b..048f56ead 100644 --- a/edc-dataplane/edc-dataplane-proxy-consumer-api/src/main/java/org/eclipse/tractusx/edc/dataplane/proxy/consumer/api/DataPlaneProxyConsumerApiExtension.java +++ b/edc-dataplane/edc-dataplane-proxy-consumer-api/src/main/java/org/eclipse/tractusx/edc/dataplane/proxy/consumer/api/DataPlaneProxyConsumerApiExtension.java @@ -25,8 +25,8 @@ import org.eclipse.edc.web.spi.WebService; import org.eclipse.edc.web.spi.configuration.WebServiceConfigurer; import org.eclipse.edc.web.spi.configuration.WebServiceSettings; -import org.eclipse.tractusx.edc.dataplane.proxy.consumer.api.asset.ConsumerAssetRequestController; import org.eclipse.tractusx.edc.dataplane.proxy.consumer.api.asset.ClientErrorExceptionMapper; +import org.eclipse.tractusx.edc.dataplane.proxy.consumer.api.asset.ConsumerAssetRequestController; import org.eclipse.tractusx.edc.edr.spi.EndpointDataReferenceCache; import java.util.concurrent.ExecutorService; @@ -38,21 +38,16 @@ */ @Extension(value = DataPlaneProxyConsumerApiExtension.NAME) public class DataPlaneProxyConsumerApiExtension implements ServiceExtension { + public static final int DEFAULT_THREAD_POOL = 10; static final String NAME = "Data Plane Proxy Consumer API"; - private static final int DEFAULT_PROXY_PORT = 8186; private static final String CONSUMER_API_ALIAS = "consumer.api"; private static final String CONSUMER_CONTEXT_PATH = "/proxy"; private static final String CONSUMER_CONFIG_KEY = "web.http.proxy"; - @Setting(value = "Data plane proxy API consumer port", type = "int") private static final String CONSUMER_PORT = "tx.dpf.consumer.proxy.port"; - @Setting(value = "Thread pool size for the consumer data plane proxy gateway", type = "int") private static final String THREAD_POOL_SIZE = "tx.dpf.consumer.proxy.thread.pool"; - - public static final int DEFAULT_THREAD_POOL = 10; - @Inject private WebService webService; diff --git a/edc-dataplane/edc-dataplane-proxy-consumer-api/src/main/java/org/eclipse/tractusx/edc/dataplane/proxy/consumer/api/asset/ConsumerAssetRequestController.java b/edc-dataplane/edc-dataplane-proxy-consumer-api/src/main/java/org/eclipse/tractusx/edc/dataplane/proxy/consumer/api/asset/ConsumerAssetRequestController.java index 2ceb4a393..89b715fad 100644 --- a/edc-dataplane/edc-dataplane-proxy-consumer-api/src/main/java/org/eclipse/tractusx/edc/dataplane/proxy/consumer/api/asset/ConsumerAssetRequestController.java +++ b/edc-dataplane/edc-dataplane-proxy-consumer-api/src/main/java/org/eclipse/tractusx/edc/dataplane/proxy/consumer/api/asset/ConsumerAssetRequestController.java @@ -137,6 +137,8 @@ private void handleCompletion(AsyncResponse response, StreamResult result, case GENERAL_ERROR: response.resume(status(INTERNAL_SERVER_ERROR).type(APPLICATION_JSON).build()); break; + default: + throw new IllegalStateException("Unexpected value: " + result.reason()); } } else if (throwable != null) { reportError(response, throwable); diff --git a/edc-dataplane/edc-dataplane-proxy-provider-api/src/main/java/org/eclipse/tractusx/edc/dataplane/proxy/provider/api/gateway/ProviderGatewayController.java b/edc-dataplane/edc-dataplane-proxy-provider-api/src/main/java/org/eclipse/tractusx/edc/dataplane/proxy/provider/api/gateway/ProviderGatewayController.java index 2f392fdce..51e83c363 100644 --- a/edc-dataplane/edc-dataplane-proxy-provider-api/src/main/java/org/eclipse/tractusx/edc/dataplane/proxy/provider/api/gateway/ProviderGatewayController.java +++ b/edc-dataplane/edc-dataplane-proxy-provider-api/src/main/java/org/eclipse/tractusx/edc/dataplane/proxy/provider/api/gateway/ProviderGatewayController.java @@ -51,7 +51,7 @@ * Implements the HTTP data proxy API. */ @Path("/" + ProviderGatewayController.GATEWAY_PATH) -public class ProviderGatewayController implements ProviderGatewayApi{ +public class ProviderGatewayController implements ProviderGatewayApi { protected static final String GATEWAY_PATH = "gateway"; private static final String HTTP_DATA = "HttpData"; @@ -185,6 +185,8 @@ private void handleCompletion(AsyncResponse response, StreamResult result, case GENERAL_ERROR: response.resume(status(INTERNAL_SERVER_ERROR).type(APPLICATION_JSON).build()); break; + default: + throw new IllegalStateException("Unexpected value: " + result.reason()); } } else if (throwable != null) { reportError(response, throwable); diff --git a/edc-dataplane/edc-dataplane-proxy-provider-core/src/test/java/org/eclipse/tractusx/edc/dataplane/proxy/provider/core/gateway/auth/RsaPublicKeyParserTest.java b/edc-dataplane/edc-dataplane-proxy-provider-core/src/test/java/org/eclipse/tractusx/edc/dataplane/proxy/provider/core/gateway/auth/RsaPublicKeyParserTest.java index d345ce388..b6e62ccfa 100644 --- a/edc-dataplane/edc-dataplane-proxy-provider-core/src/test/java/org/eclipse/tractusx/edc/dataplane/proxy/provider/core/gateway/auth/RsaPublicKeyParserTest.java +++ b/edc-dataplane/edc-dataplane-proxy-provider-core/src/test/java/org/eclipse/tractusx/edc/dataplane/proxy/provider/core/gateway/auth/RsaPublicKeyParserTest.java @@ -16,7 +16,7 @@ import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Verifies RSA public key parsing. diff --git a/edc-dataplane/edc-dataplane-proxy-provider-core/src/test/java/org/eclipse/tractusx/edc/dataplane/proxy/provider/core/gateway/auth/TestTokens.java b/edc-dataplane/edc-dataplane-proxy-provider-core/src/test/java/org/eclipse/tractusx/edc/dataplane/proxy/provider/core/gateway/auth/TestTokens.java index 8db44bee8..9c8091014 100644 --- a/edc-dataplane/edc-dataplane-proxy-provider-core/src/test/java/org/eclipse/tractusx/edc/dataplane/proxy/provider/core/gateway/auth/TestTokens.java +++ b/edc-dataplane/edc-dataplane-proxy-provider-core/src/test/java/org/eclipse/tractusx/edc/dataplane/proxy/provider/core/gateway/auth/TestTokens.java @@ -22,13 +22,14 @@ * Tokens for testing. */ public class TestTokens { + public static final String TEST_TOKEN = "eyJhbGciOiJSUzI1NiIsInZlcnNpb24iOnRydWV9.eyJpc3MiOiJ0ZXN0LWNvbm5lY3RvciIsInN1YiI6ImNvbnN1bWVyLWNvbm5lY3RvciIsImF1ZCI6InRlc3QtY29ubmV" + + "jdG9yIiwiaWF0IjoxNjgxOTEzNjM2LCJleHAiOjMzNDU5NzQwNzg4LCJjaWQiOiIzMmE2M2E3ZC04MGQ2LTRmMmUtOTBlNi04MGJhZjVmYzJiM2MifQ.QAuotoRxpEqfuzkTcTq2w5Tcyy3Rc3UzUjjvNc_zwgNROGLe-w" + + "O9tFET1dJ_I5BttRxkngDS37dS4R6lN5YXaGHgcH2rf_FuVcJUSFqTp_usGAcx6m7pQQwqpNdcYgmq0NJp3xP87EFPHAy4kBxB5bqpmx4J-zrj9U_gerZ2WlRqpu0SdgP0S5v5D1Gm-vYkLqgvsugrAWH3Ti7OjC5UMdj0k" + + "DFwro2NpMY8SSNryiVvBEv8hn0KZdhhebIqPdhqbEQZ9d8WKzcgoqQ3DBd4ijzkd3Fz7ADD2gy_Hxn8Hi2LcItuB514TjCxYAncTNqZC_JSFEyuxwcGFVz3LdSXgw"; private static final String DELIMITER = "-----"; private static final String HEADER = DELIMITER + "BEGIN" + " PUBLIC " + "KEY" + DELIMITER + "\n"; private static final String FOOTER = "\n" + DELIMITER + "END" + " PUBLIC " + "KEY" + DELIMITER + "\n"; - public static final String TEST_TOKEN = "eyJhbGciOiJSUzI1NiIsInZlcnNpb24iOnRydWV9.eyJpc3MiOiJ0ZXN0LWNvbm5lY3RvciIsInN1YiI6ImNvbnN1bWVyLWNvbm5lY3RvciIsImF1ZCI6InRlc3QtY29ubmVjdG9yIiwiaWF0IjoxNjgxOTEzNjM2LCJleHAiOjMzNDU5NzQwNzg4LCJjaWQiOiIzMmE2M2E3ZC04MGQ2LTRmMmUtOTBlNi04MGJhZjVmYzJiM2MifQ.QAuotoRxpEqfuzkTcTq2w5Tcyy3Rc3UzUjjvNc_zwgNROGLe-wO9tFET1dJ_I5BttRxkngDS37dS4R6lN5YXaGHgcH2rf_FuVcJUSFqTp_usGAcx6m7pQQwqpNdcYgmq0NJp3xP87EFPHAy4kBxB5bqpmx4J-zrj9U_gerZ2WlRqpu0SdgP0S5v5D1Gm-vYkLqgvsugrAWH3Ti7OjC5UMdj0kDFwro2NpMY8SSNryiVvBEv8hn0KZdhhebIqPdhqbEQZ9d8WKzcgoqQ3DBd4ijzkd3Fz7ADD2gy_Hxn8Hi2LcItuB514TjCxYAncTNqZC_JSFEyuxwcGFVz3LdSXgw"; - - public static String generatePublic() { try { var generator = KeyPairGenerator.getInstance("RSA"); diff --git a/edc-extensions/business-partner-validation/src/main/java/org/eclipse/tractusx/edc/validation/businesspartner/functions/AbstractBusinessPartnerValidation.java b/edc-extensions/business-partner-validation/src/main/java/org/eclipse/tractusx/edc/validation/businesspartner/functions/AbstractBusinessPartnerValidation.java index ecb5b81ef..cd124684b 100644 --- a/edc-extensions/business-partner-validation/src/main/java/org/eclipse/tractusx/edc/validation/businesspartner/functions/AbstractBusinessPartnerValidation.java +++ b/edc-extensions/business-partner-validation/src/main/java/org/eclipse/tractusx/edc/validation/businesspartner/functions/AbstractBusinessPartnerValidation.java @@ -55,7 +55,7 @@ public abstract class AbstractBusinessPartnerValidation { private static final String REFERRING_CONNECTOR_CLAIM = "referringConnector"; private final Monitor monitor; private final boolean logAgreementEvaluation; - + protected AbstractBusinessPartnerValidation(Monitor monitor, boolean logAgreementEvaluation) { this.monitor = Objects.requireNonNull(monitor); this.logAgreementEvaluation = logAgreementEvaluation; @@ -131,13 +131,7 @@ protected boolean evaluate( } } - /** - * @param referringConnectorClaim of the participant - * @param businessPartnerNumber object - * @return true if object is string and successfully evaluated against the claim - */ - private boolean isBusinessPartnerNumber( - String referringConnectorClaim, Object businessPartnerNumber, PolicyContext policyContext) { + private boolean isBusinessPartnerNumber(String referringConnectorClaim, Object businessPartnerNumber, PolicyContext policyContext) { if (businessPartnerNumber == null) { final String message = format(FAIL_EVALUATION_BECAUSE_RIGHT_VALUE_NOT_STRING, "null"); monitor.warning(message); diff --git a/edc-extensions/business-partner-validation/src/test/java/org/eclipse/tractusx/edc/validation/businesspartner/functions/AbstractBusinessPartnerValidationTest.java b/edc-extensions/business-partner-validation/src/test/java/org/eclipse/tractusx/edc/validation/businesspartner/functions/AbstractBusinessPartnerValidationTest.java index c6ed58e43..d7ad4db9f 100644 --- a/edc-extensions/business-partner-validation/src/test/java/org/eclipse/tractusx/edc/validation/businesspartner/functions/AbstractBusinessPartnerValidationTest.java +++ b/edc-extensions/business-partner-validation/src/test/java/org/eclipse/tractusx/edc/validation/businesspartner/functions/AbstractBusinessPartnerValidationTest.java @@ -50,7 +50,7 @@ class AbstractBusinessPartnerValidationTest { private ParticipantAgent participantAgent; @BeforeEach - void BeforeEach() { + void beforeEach() { this.monitor = Mockito.mock(Monitor.class); this.policyContext = Mockito.mock(PolicyContext.class); this.participantAgent = Mockito.mock(ParticipantAgent.class); diff --git a/edc-extensions/control-plane-adapter-callback/src/main/java/org/eclipse/tractusx/edc/cp/adapter/callback/TransferProcessLocalCallback.java b/edc-extensions/control-plane-adapter-callback/src/main/java/org/eclipse/tractusx/edc/cp/adapter/callback/TransferProcessLocalCallback.java index 6d450bfd8..04040b0fa 100644 --- a/edc-extensions/control-plane-adapter-callback/src/main/java/org/eclipse/tractusx/edc/cp/adapter/callback/TransferProcessLocalCallback.java +++ b/edc-extensions/control-plane-adapter-callback/src/main/java/org/eclipse/tractusx/edc/cp/adapter/callback/TransferProcessLocalCallback.java @@ -60,8 +60,8 @@ private Result storeEdr(EndpointDataReference edr) { var transferProcessId = transferProcessStore.processIdForDataRequestId(edr.getId()); var transferProcess = transferProcessStore.findById(transferProcessId); if (transferProcess != null) { - var cacheEntry = EndpointDataReferenceEntry.Builder.newInstance(). - transferProcessId(transferProcess.getId()) + var cacheEntry = EndpointDataReferenceEntry.Builder.newInstance() + .transferProcessId(transferProcess.getId()) .assetId(transferProcess.getDataRequest().getAssetId()) .agreementId(transferProcess.getDataRequest().getContractId()) .build(); diff --git a/edc-extensions/control-plane-adapter-callback/src/test/java/org/eclipse/tractusx/edc/cp/adapter/callback/AdapterTransferProcessServiceImplTest.java b/edc-extensions/control-plane-adapter-callback/src/test/java/org/eclipse/tractusx/edc/cp/adapter/callback/AdapterTransferProcessServiceImplTest.java index 1e95f0e1c..3bbdb0b2a 100644 --- a/edc-extensions/control-plane-adapter-callback/src/test/java/org/eclipse/tractusx/edc/cp/adapter/callback/AdapterTransferProcessServiceImplTest.java +++ b/edc-extensions/control-plane-adapter-callback/src/test/java/org/eclipse/tractusx/edc/cp/adapter/callback/AdapterTransferProcessServiceImplTest.java @@ -39,7 +39,7 @@ public class AdapterTransferProcessServiceImplTest { ContractNegotiationService contractNegotiationService = mock(ContractNegotiationService.class); @Test - void initEdrNegotiation_shouldFireAContractNegotiation_WhenUsingCallbacks() { + void initEdrNegotiation_shouldFireContractNegotiation_whenUsingCallbacks() { var transferService = new AdapterTransferProcessServiceImpl(contractNegotiationService); var captor = ArgumentCaptor.forClass(ContractRequest.class); diff --git a/edc-extensions/control-plane-adapter-callback/src/test/java/org/eclipse/tractusx/edc/cp/adapter/callback/ContractNegotiationCallbackTest.java b/edc-extensions/control-plane-adapter-callback/src/test/java/org/eclipse/tractusx/edc/cp/adapter/callback/ContractNegotiationCallbackTest.java index d24f05382..62545a8b5 100644 --- a/edc-extensions/control-plane-adapter-callback/src/test/java/org/eclipse/tractusx/edc/cp/adapter/callback/ContractNegotiationCallbackTest.java +++ b/edc-extensions/control-plane-adapter-callback/src/test/java/org/eclipse/tractusx/edc/cp/adapter/callback/ContractNegotiationCallbackTest.java @@ -67,7 +67,7 @@ void setup() { } @Test - void invoke_shouldStartATransferProcess() { + void invoke_shouldStartTransferProcess() { var captor = ArgumentCaptor.forClass(TransferRequest.class); @@ -99,8 +99,8 @@ void invoke_shouldStartATransferProcess() { } @Test - void invoke_shouldThrowException_whenATransferRequestFails() { - + void invoke_shouldThrowException_whenTransferRequestFails() { + when(transferProcessService.initiateTransfer(any())).thenReturn(ServiceResult.badRequest("test")); var event = getNegotiationFinalizedEvent(); diff --git a/edc-extensions/control-plane-adapter-callback/src/test/java/org/eclipse/tractusx/edc/cp/adapter/callback/InProcessCallbackMessageDispatcherTest.java b/edc-extensions/control-plane-adapter-callback/src/test/java/org/eclipse/tractusx/edc/cp/adapter/callback/InProcessCallbackMessageDispatcherTest.java index 27ef6565e..54e5bef21 100644 --- a/edc-extensions/control-plane-adapter-callback/src/test/java/org/eclipse/tractusx/edc/cp/adapter/callback/InProcessCallbackMessageDispatcherTest.java +++ b/edc-extensions/control-plane-adapter-callback/src/test/java/org/eclipse/tractusx/edc/cp/adapter/callback/InProcessCallbackMessageDispatcherTest.java @@ -55,7 +55,7 @@ void send_shouldInvokeRegisteredCallback() { } @Test - void send_shouldNotInvokeRegisteredCallback_whenItsNotACallbackRemoteMessage() { + void send_shouldNotInvokeRegisteredCallback_whenItsNotCallbackRemoteMessage() { assertThatThrownBy(() -> dispatcher.send(Object.class, new TestMessage()).join()) .hasCauseInstanceOf(EdcException.class); diff --git a/edc-extensions/control-plane-adapter-callback/src/test/java/org/eclipse/tractusx/edc/cp/adapter/callback/LocalCallbackExtensionTest.java b/edc-extensions/control-plane-adapter-callback/src/test/java/org/eclipse/tractusx/edc/cp/adapter/callback/LocalCallbackExtensionTest.java index 8e68c0ed1..a4313c40c 100644 --- a/edc-extensions/control-plane-adapter-callback/src/test/java/org/eclipse/tractusx/edc/cp/adapter/callback/LocalCallbackExtensionTest.java +++ b/edc-extensions/control-plane-adapter-callback/src/test/java/org/eclipse/tractusx/edc/cp/adapter/callback/LocalCallbackExtensionTest.java @@ -30,7 +30,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.tractusx.edc.cp.adapter.callback.InProcessCallbackMessageDispatcher.CALLBACK_EVENT_LOCAL; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; @ExtendWith(DependencyInjectionExtension.class) public class LocalCallbackExtensionTest { diff --git a/edc-extensions/cx-oauth2/src/main/java/org/eclipse/tractusx/edc/oauth2/CXOAuth2Extension.java b/edc-extensions/cx-oauth2/src/main/java/org/eclipse/tractusx/edc/oauth2/CxOauth2Extension.java similarity index 75% rename from edc-extensions/cx-oauth2/src/main/java/org/eclipse/tractusx/edc/oauth2/CXOAuth2Extension.java rename to edc-extensions/cx-oauth2/src/main/java/org/eclipse/tractusx/edc/oauth2/CxOauth2Extension.java index 4b5bffc74..338784ef3 100644 --- a/edc-extensions/cx-oauth2/src/main/java/org/eclipse/tractusx/edc/oauth2/CXOAuth2Extension.java +++ b/edc-extensions/cx-oauth2/src/main/java/org/eclipse/tractusx/edc/oauth2/CxOauth2Extension.java @@ -19,21 +19,21 @@ */ package org.eclipse.tractusx.edc.oauth2; -import java.util.Map; import org.eclipse.edc.iam.oauth2.spi.CredentialsRequestAdditionalParametersProvider; import org.eclipse.edc.runtime.metamodel.annotation.Provider; import org.eclipse.edc.spi.system.ServiceExtension; -public class CXOAuth2Extension implements ServiceExtension { +import java.util.Map; + +public class CxOauth2Extension implements ServiceExtension { - @Override - public String name() { - return "CX OAuth2"; - } + @Override + public String name() { + return "CX OAuth2"; + } - @Provider - public CredentialsRequestAdditionalParametersProvider - credentialsRequestAdditionalParametersProvider() { - return tokenParameters -> Map.of("resource", tokenParameters.getAudience()); - } + @Provider + public CredentialsRequestAdditionalParametersProvider credentialsRequestAdditionalParametersProvider() { + return tokenParameters -> Map.of("resource", tokenParameters.getAudience()); + } } diff --git a/edc-extensions/cx-oauth2/src/main/resources/META-INF/services/org.eclipse.edc.spi.system.ServiceExtension b/edc-extensions/cx-oauth2/src/main/resources/META-INF/services/org.eclipse.edc.spi.system.ServiceExtension index 2e60a45f0..964ae5b59 100644 --- a/edc-extensions/cx-oauth2/src/main/resources/META-INF/services/org.eclipse.edc.spi.system.ServiceExtension +++ b/edc-extensions/cx-oauth2/src/main/resources/META-INF/services/org.eclipse.edc.spi.system.ServiceExtension @@ -18,4 +18,4 @@ # SPDX-License-Identifier: Apache-2.0 # -org.eclipse.tractusx.edc.oauth2.CXOAuth2Extension +org.eclipse.tractusx.edc.oauth2.CxOauth2Extension diff --git a/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/DataEncryptionExtension.java b/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/DataEncryptionExtension.java index 8024bc276..074956eac 100644 --- a/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/DataEncryptionExtension.java +++ b/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/DataEncryptionExtension.java @@ -19,9 +19,6 @@ */ package org.eclipse.tractusx.edc.data.encryption; -import java.time.Duration; -import java.util.List; -import java.util.stream.Collectors; import org.eclipse.edc.connector.transfer.dataplane.spi.security.DataEncrypter; import org.eclipse.edc.runtime.metamodel.annotation.Provides; import org.eclipse.edc.runtime.metamodel.annotation.Requires; @@ -37,107 +34,108 @@ import org.eclipse.tractusx.edc.data.encryption.key.CryptoKeyFactoryImpl; import org.eclipse.tractusx.edc.data.encryption.provider.AesKeyProvider; +import java.time.Duration; +import java.util.List; +import java.util.stream.Collectors; + @Provides({DataEncrypter.class}) @Requires({Vault.class}) public class DataEncryptionExtension implements ServiceExtension { - public static final String EXTENSION_NAME = "Data Encryption Extension"; - - public static final String ENCRYPTION_KEY_SET = "edc.data.encryption.keys.alias"; + public static final String EXTENSION_NAME = "Data Encryption Extension"; - public static final String ENCRYPTION_ALGORITHM = "edc.data.encryption.algorithm"; - public static final String ENCRYPTION_ALGORITHM_DEFAULT = DataEncrypterFactory.AES_ALGORITHM; + public static final String ENCRYPTION_KEY_SET = "edc.data.encryption.keys.alias"; - public static final String CACHING_ENABLED = "edc.data.encryption.caching.enabled"; - public static final boolean CACHING_ENABLED_DEFAULT = false; + public static final String ENCRYPTION_ALGORITHM = "edc.data.encryption.algorithm"; + public static final String ENCRYPTION_ALGORITHM_DEFAULT = DataEncrypterFactory.AES_ALGORITHM; - public static final String CACHING_SECONDS = "edc.data.encryption.caching.seconds"; - public static final int CACHING_SECONDS_DEFAULT = 3600; + public static final String CACHING_ENABLED = "edc.data.encryption.caching.enabled"; + public static final boolean CACHING_ENABLED_DEFAULT = false; - private static final CryptoKeyFactory cryptoKeyFactory = new CryptoKeyFactoryImpl(); + public static final String CACHING_SECONDS = "edc.data.encryption.caching.seconds"; + public static final int CACHING_SECONDS_DEFAULT = 3600; - private Monitor monitor; - private Vault vault; - private ServiceExtensionContext context; + private static final CryptoKeyFactory CRYPTO_KEY_FACTORY = new CryptoKeyFactoryImpl(); - @Override - public String name() { - return EXTENSION_NAME; - } + private Monitor monitor; + private Vault vault; + private ServiceExtensionContext context; - @Override - public void start() { + private static AesDataEncrypterConfiguration createAesConfiguration( + ServiceExtensionContext context) { + final String key = context.getSetting(ENCRYPTION_KEY_SET, null); + if (key == null) { + throw new EdcException(EXTENSION_NAME + ": Missing setting " + ENCRYPTION_KEY_SET); + } - final String algorithm = context.getSetting(ENCRYPTION_ALGORITHM, ENCRYPTION_ALGORITHM_DEFAULT); + final boolean cachingEnabled = context.getSetting(CACHING_ENABLED, CACHING_ENABLED_DEFAULT); + final int cachingSeconds = context.getSetting(CACHING_SECONDS, CACHING_SECONDS_DEFAULT); - if (DataEncrypterFactory.NONE.equalsIgnoreCase(algorithm)) { - return; // no start-up checks for NONE algorithm + return new AesDataEncrypterConfiguration( + key, cachingEnabled, Duration.ofSeconds(cachingSeconds)); } - if (DataEncrypterFactory.AES_ALGORITHM.equals(algorithm)) { - - final AesDataEncrypterConfiguration configuration = createAesConfiguration(context); - final String keyAlias = configuration.getKeySetAlias(); - final String keySecret = vault.resolveSecret(keyAlias); - if (keySecret == null || keySecret.isEmpty()) { - throw new EdcException( - EXTENSION_NAME + ": No vault key secret found for alias " + keyAlias); - } - - try { - final AesKeyProvider aesKeyProvider = new AesKeyProvider(vault, keyAlias, cryptoKeyFactory); - final List keys = aesKeyProvider.getDecryptionKeySet().collect(Collectors.toList()); - monitor.debug( - String.format( - "Started " + EXTENSION_NAME + ": Found %s registered AES keys in vault.", - keys.size())); - } catch (Exception e) { - throw new EdcException( - EXTENSION_NAME + ": AES keys from vault must be comma separated and Base64 encoded.", - e); - } - } - } - - @Override - public void initialize(ServiceExtensionContext context) { - this.context = context; - this.monitor = context.getMonitor(); - this.vault = context.getService(Vault.class); - final DataEncrypterFactory factory = new DataEncrypterFactory(vault, monitor, cryptoKeyFactory); - - final DataEncrypter dataEncrypter; - final String algorithm = context.getSetting(ENCRYPTION_ALGORITHM, ENCRYPTION_ALGORITHM_DEFAULT); - if (DataEncrypterFactory.NONE.equalsIgnoreCase(algorithm)) { - dataEncrypter = factory.createNoneEncrypter(); - } else if (DataEncrypterFactory.AES_ALGORITHM.equalsIgnoreCase(algorithm)) { - final AesDataEncrypterConfiguration configuration = createAesConfiguration(context); - dataEncrypter = factory.createAesEncrypter(configuration); - } else { - final String msg = - String.format( - DataEncryptionExtension.EXTENSION_NAME - + ": Unsupported encryption algorithm '%s'. Supported algorithms are '%s', '%s'.", - algorithm, - DataEncrypterFactory.AES_ALGORITHM, - DataEncrypterFactory.NONE); - throw new EdcException(msg); + @Override + public String name() { + return EXTENSION_NAME; } - context.registerService(DataEncrypter.class, dataEncrypter); - } - - private static AesDataEncrypterConfiguration createAesConfiguration( - ServiceExtensionContext context) { - final String key = context.getSetting(ENCRYPTION_KEY_SET, null); - if (key == null) { - throw new EdcException(EXTENSION_NAME + ": Missing setting " + ENCRYPTION_KEY_SET); + @Override + public void start() { + + final String algorithm = context.getSetting(ENCRYPTION_ALGORITHM, ENCRYPTION_ALGORITHM_DEFAULT); + + if (DataEncrypterFactory.NONE.equalsIgnoreCase(algorithm)) { + return; // no start-up checks for NONE algorithm + } + + if (DataEncrypterFactory.AES_ALGORITHM.equals(algorithm)) { + + final AesDataEncrypterConfiguration configuration = createAesConfiguration(context); + final String keyAlias = configuration.getKeySetAlias(); + final String keySecret = vault.resolveSecret(keyAlias); + if (keySecret == null || keySecret.isEmpty()) { + throw new EdcException( + EXTENSION_NAME + ": No vault key secret found for alias " + keyAlias); + } + + try { + final AesKeyProvider aesKeyProvider = new AesKeyProvider(vault, keyAlias, CRYPTO_KEY_FACTORY); + final List keys = aesKeyProvider.getDecryptionKeySet().collect(Collectors.toList()); + monitor.debug( + String.format( + "Started " + EXTENSION_NAME + ": Found %s registered AES keys in vault.", + keys.size())); + } catch (Exception e) { + throw new EdcException( + EXTENSION_NAME + ": AES keys from vault must be comma separated and Base64 encoded.", + e); + } + } } - final boolean cachingEnabled = context.getSetting(CACHING_ENABLED, CACHING_ENABLED_DEFAULT); - final int cachingSeconds = context.getSetting(CACHING_SECONDS, CACHING_SECONDS_DEFAULT); - - return new AesDataEncrypterConfiguration( - key, cachingEnabled, Duration.ofSeconds(cachingSeconds)); - } + @Override + public void initialize(ServiceExtensionContext context) { + this.context = context; + this.monitor = context.getMonitor(); + this.vault = context.getService(Vault.class); + final DataEncrypterFactory factory = new DataEncrypterFactory(vault, monitor, CRYPTO_KEY_FACTORY); + + final DataEncrypter dataEncrypter; + final String algorithm = context.getSetting(ENCRYPTION_ALGORITHM, ENCRYPTION_ALGORITHM_DEFAULT); + if (DataEncrypterFactory.NONE.equalsIgnoreCase(algorithm)) { + dataEncrypter = factory.createNoneEncrypter(); + } else if (DataEncrypterFactory.AES_ALGORITHM.equalsIgnoreCase(algorithm)) { + final AesDataEncrypterConfiguration configuration = createAesConfiguration(context); + dataEncrypter = factory.createAesEncrypter(configuration); + } else { + final String msg = String.format(DataEncryptionExtension.EXTENSION_NAME + ": Unsupported encryption algorithm '%s'. Supported algorithms are '%s', '%s'.", + algorithm, + DataEncrypterFactory.AES_ALGORITHM, + DataEncrypterFactory.NONE); + throw new EdcException(msg); + } + + context.registerService(DataEncrypter.class, dataEncrypter); + } } diff --git a/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/algorithms/CryptoAlgorithm.java b/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/algorithms/CryptoAlgorithm.java index a49cce44d..d457677b9 100644 --- a/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/algorithms/CryptoAlgorithm.java +++ b/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/algorithms/CryptoAlgorithm.java @@ -19,22 +19,21 @@ */ package org.eclipse.tractusx.edc.data.encryption.algorithms; +import org.eclipse.tractusx.edc.data.encryption.data.DecryptedData; +import org.eclipse.tractusx.edc.data.encryption.data.EncryptedData; +import org.eclipse.tractusx.edc.data.encryption.key.CryptoKey; + import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; -import org.eclipse.tractusx.edc.data.encryption.data.DecryptedData; -import org.eclipse.tractusx.edc.data.encryption.data.EncryptedData; -import org.eclipse.tractusx.edc.data.encryption.key.CryptoKey; public interface CryptoAlgorithm { - EncryptedData encrypt(DecryptedData data, T key) - throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, - NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException; + EncryptedData encrypt(DecryptedData data, T key) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, + NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException; - DecryptedData decrypt(EncryptedData data, T key) - throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, - NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException; + DecryptedData decrypt(EncryptedData data, T key) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, + NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException; } diff --git a/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/data/CryptoData.java b/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/data/CryptoData.java index edb3b3620..9dc59a8b0 100644 --- a/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/data/CryptoData.java +++ b/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/data/CryptoData.java @@ -20,7 +20,7 @@ package org.eclipse.tractusx.edc.data.encryption.data; public interface CryptoData { - byte[] getBytes(); + byte[] getBytes(); - String getBase64(); + String getBase64(); } diff --git a/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/data/CryptoDataFactory.java b/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/data/CryptoDataFactory.java index a37460111..0144ad3a4 100644 --- a/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/data/CryptoDataFactory.java +++ b/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/data/CryptoDataFactory.java @@ -21,15 +21,15 @@ public interface CryptoDataFactory { - DecryptedData decryptedFromText(String text); + DecryptedData decryptedFromText(String text); - DecryptedData decryptedFromBase64(String base64); + DecryptedData decryptedFromBase64(String base64); - DecryptedData decryptedFromBytes(byte[] bytes); + DecryptedData decryptedFromBytes(byte[] bytes); - EncryptedData encryptedFromText(String text); + EncryptedData encryptedFromText(String text); - EncryptedData encryptedFromBase64(String base64); + EncryptedData encryptedFromBase64(String base64); - EncryptedData encryptedFromBytes(byte[] bytes); + EncryptedData encryptedFromBytes(byte[] bytes); } diff --git a/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/encrypter/AesDataEncrypterImpl.java b/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/encrypter/AesDataEncrypterImpl.java index d8b4add87..e638df98c 100644 --- a/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/encrypter/AesDataEncrypterImpl.java +++ b/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/encrypter/AesDataEncrypterImpl.java @@ -64,12 +64,8 @@ public String encrypt(String value) { try { EncryptedData encryptedData = algorithm.encrypt(decryptedData, key); return encryptedData.getBase64(); - } catch (IllegalBlockSizeException - | BadPaddingException - | InvalidKeyException - | InvalidAlgorithmParameterException - | NoSuchPaddingException - | NoSuchAlgorithmException e) { + } catch (IllegalBlockSizeException | BadPaddingException | InvalidKeyException | + InvalidAlgorithmParameterException | NoSuchPaddingException | NoSuchAlgorithmException e) { throw new EdcException(e); } } @@ -86,11 +82,9 @@ public String decrypt(String value) { .map(DecryptedData::getBytes) .map(String::new) .findFirst() - .orElseThrow( - () -> - new EdcException( - DataEncryptionExtension.EXTENSION_NAME - + ": Failed to decrypt data. This can happen if the key set is empty, contains invalid keys, the decryption key rotated out of the key set or because the data was encrypted by a different algorithm.")); + .orElseThrow(() -> + new EdcException(DataEncryptionExtension.EXTENSION_NAME + ": Failed to decrypt data. This can happen if the key set is empty, contains invalid keys, " + + "the decryption key rotated out of the key set or because the data was encrypted by a different algorithm.")); } private Optional decrypt(EncryptedData data, AesKey key) { @@ -98,17 +92,9 @@ private Optional decrypt(EncryptedData data, AesKey key) { return Optional.of(encryptionStrategy.decrypt(data, key)); } catch (AEADBadTagException e) { // thrown when wrong key is used for decryption return Optional.empty(); - } catch (IllegalBlockSizeException - | BadPaddingException - | InvalidKeyException - | NoSuchPaddingException - | NoSuchAlgorithmException - | InvalidAlgorithmParameterException e) { - monitor.warning( - String.format( - DataEncryptionExtension.EXTENSION_NAME - + ": Exception decrypting data using key from rotating key set. %s", - e.getMessage())); + } catch (IllegalBlockSizeException | BadPaddingException | InvalidKeyException | NoSuchPaddingException | + NoSuchAlgorithmException | InvalidAlgorithmParameterException e) { + monitor.warning(String.format(DataEncryptionExtension.EXTENSION_NAME + ": Exception decrypting data using key from rotating key set. %s", e.getMessage())); throw new EdcException(e); } } diff --git a/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/key/AesKey.java b/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/key/AesKey.java index 69ef83021..feb3260fa 100644 --- a/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/key/AesKey.java +++ b/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/key/AesKey.java @@ -20,7 +20,7 @@ package org.eclipse.tractusx.edc.data.encryption.key; public interface AesKey extends CryptoKey { - byte[] getBytes(); + byte[] getBytes(); - String getBase64(); + String getBase64(); } diff --git a/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/key/CryptoKeyFactory.java b/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/key/CryptoKeyFactory.java index 52fdb3c00..b7d47808a 100644 --- a/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/key/CryptoKeyFactory.java +++ b/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/key/CryptoKeyFactory.java @@ -20,7 +20,7 @@ package org.eclipse.tractusx.edc.data.encryption.key; public interface CryptoKeyFactory { - AesKey fromBase64(String base64); + AesKey fromBase64(String base64); - AesKey fromBytes(byte[] key); + AesKey fromBytes(byte[] key); } diff --git a/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/key/CryptoKeyFactoryImpl.java b/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/key/CryptoKeyFactoryImpl.java index 7a5b0fc15..dc8eb2083 100644 --- a/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/key/CryptoKeyFactoryImpl.java +++ b/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/key/CryptoKeyFactoryImpl.java @@ -23,37 +23,37 @@ public class CryptoKeyFactoryImpl implements CryptoKeyFactory { - public AesKey fromBase64(String base64) { - return fromBytes(Base64.decode(base64)); - } - - public AesKey fromBytes(byte[] key) { - int bitLength = key.length * Byte.SIZE; - if (!(bitLength == 128 || bitLength == 192 || bitLength == 256)) { - throw new IllegalArgumentException("Invalid AES key length: " + bitLength); + public AesKey fromBase64(String base64) { + return fromBytes(Base64.decode(base64)); } - return new AesKeyImpl(key, Base64.toBase64String(key)); - } + public AesKey fromBytes(byte[] key) { + int bitLength = key.length * Byte.SIZE; + if (!(bitLength == 128 || bitLength == 192 || bitLength == 256)) { + throw new IllegalArgumentException("Invalid AES key length: " + bitLength); + } + return new AesKeyImpl(key, Base64.toBase64String(key)); + } - private static class AesKeyImpl implements AesKey { - private final byte[] bytes; - private final String base64; - private AesKeyImpl(byte[] bytes, String base64) { - this.bytes = bytes; - this.base64 = base64; - } + private static class AesKeyImpl implements AesKey { + private final byte[] bytes; + private final String base64; - @Override - public byte[] getBytes() { - return bytes; - } + private AesKeyImpl(byte[] bytes, String base64) { + this.bytes = bytes; + this.base64 = base64; + } + + @Override + public byte[] getBytes() { + return bytes; + } - @Override - public String getBase64() { - return base64; + @Override + public String getBase64() { + return base64; + } } - } } diff --git a/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/provider/AesKeyProvider.java b/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/provider/AesKeyProvider.java index e740a6f43..586909282 100644 --- a/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/provider/AesKeyProvider.java +++ b/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/provider/AesKeyProvider.java @@ -47,11 +47,7 @@ public AesKeyProvider(Vault vault, String vaultKeyAlias, CryptoKeyFactory crypto public AesKey getEncryptionKey() { return getKeysStream() .findFirst() - .orElseThrow( - () -> - new RuntimeException( - DataEncryptionExtension.EXTENSION_NAME - + ": Vault must contain at least one key.")); + .orElseThrow(() -> new RuntimeException(DataEncryptionExtension.EXTENSION_NAME + ": Vault must contain at least one key.")); } @Override diff --git a/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/provider/KeyProvider.java b/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/provider/KeyProvider.java index 86bd2d16d..2a3f58d00 100644 --- a/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/provider/KeyProvider.java +++ b/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/provider/KeyProvider.java @@ -19,11 +19,12 @@ */ package org.eclipse.tractusx.edc.data.encryption.provider; -import java.util.stream.Stream; import org.eclipse.tractusx.edc.data.encryption.key.CryptoKey; +import java.util.stream.Stream; + public interface KeyProvider { - T getEncryptionKey(); + T getEncryptionKey(); - Stream getDecryptionKeySet(); + Stream getDecryptionKeySet(); } diff --git a/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/util/ArrayUtil.java b/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/util/ArrayUtil.java index a600f9385..63c22a39f 100644 --- a/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/util/ArrayUtil.java +++ b/edc-extensions/data-encryption/src/main/java/org/eclipse/tractusx/edc/data/encryption/util/ArrayUtil.java @@ -21,28 +21,29 @@ public class ArrayUtil { - private ArrayUtil() {} - - public static byte[] concat(byte[] a, byte[] b) { - byte[] c = new byte[a.length + b.length]; - System.arraycopy(a, 0, c, 0, a.length); - System.arraycopy(b, 0, c, a.length, b.length); - return c; - } + private ArrayUtil() { + } - public static String byteArrayToHex(byte[] a) { - StringBuilder sb = new StringBuilder(a.length * 2); - for (byte b : a) sb.append(String.format("%02x", b)); - return sb.toString(); - } + public static byte[] concat(byte[] a, byte[] b) { + byte[] c = new byte[a.length + b.length]; + System.arraycopy(a, 0, c, 0, a.length); + System.arraycopy(b, 0, c, a.length, b.length); + return c; + } - public static byte[] subArray(byte[] a, int startIndex, int length) { - if (startIndex + length > a.length) { - throw new IllegalArgumentException("Start index + length is greater than array length"); + public static String byteArrayToHex(byte[] a) { + StringBuilder sb = new StringBuilder(a.length * 2); + for (byte b : a) sb.append(String.format("%02x", b)); + return sb.toString(); } - byte[] b = new byte[length]; - System.arraycopy(a, startIndex, b, 0, length); - return b; - } + public static byte[] subArray(byte[] a, int startIndex, int length) { + if (startIndex + length > a.length) { + throw new IllegalArgumentException("Start index + length is greater than array length"); + } + + byte[] b = new byte[length]; + System.arraycopy(a, startIndex, b, 0, length); + return b; + } } diff --git a/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/DataEncryptionExtensionTest.java b/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/DataEncryptionExtensionTest.java index c1e0bbb1a..bf6a4d508 100644 --- a/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/DataEncryptionExtensionTest.java +++ b/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/DataEncryptionExtensionTest.java @@ -32,90 +32,90 @@ class DataEncryptionExtensionTest { - private DataEncryptionExtension extension; - - // mocks - private Monitor monitor; - private ServiceExtensionContext context; - private Vault vault; - - @BeforeEach - void setup() { - monitor = Mockito.mock(Monitor.class); - context = Mockito.mock(ServiceExtensionContext.class); - vault = Mockito.mock(Vault.class); - - extension = new DataEncryptionExtension(); - - Mockito.when(context.getMonitor()).thenReturn(monitor); - Mockito.when(context.getService(Vault.class)).thenReturn(vault); - - Mockito.when( - context.getSetting( - Mockito.eq(DataEncryptionExtension.CACHING_ENABLED), Mockito.anyBoolean())) - .thenAnswer((i) -> i.getArguments()[1]); - Mockito.when( - context.getSetting( - Mockito.eq(DataEncryptionExtension.ENCRYPTION_ALGORITHM), Mockito.anyString())) - .thenAnswer((i) -> i.getArguments()[1]); - Mockito.when( - context.getSetting( - Mockito.eq(DataEncryptionExtension.CACHING_SECONDS), Mockito.anyInt())) - .thenAnswer((i) -> i.getArguments()[1]); - } - - @Test - void testName() { - Assertions.assertEquals(DataEncryptionExtension.EXTENSION_NAME, extension.name()); - } - - @Test - void testExceptionOnMissingKeySetAlias() { - Mockito.when(context.getSetting(DataEncryptionExtension.ENCRYPTION_KEY_SET, null)) - .thenReturn(null); - Assertions.assertThrows(EdcException.class, () -> extension.initialize(context)); - } - - @Test - void testStartExceptionOnMissingKeySetInVault() { - final String keySetAlias = "foo"; - Mockito.when(context.getSetting(DataEncryptionExtension.ENCRYPTION_KEY_SET, null)) - .thenReturn(keySetAlias); - Mockito.when(vault.resolveSecret(keySetAlias)).thenReturn(""); - - extension.initialize(context); - - Assertions.assertThrows(EdcException.class, () -> extension.start()); - } - - @Test - void testStartExceptionOnStartWithWrongKeySetAlias() { - final String keySetAlias = "foo"; - Mockito.when( - context.getSetting( - DataEncryptionExtension.ENCRYPTION_ALGORITHM, DataEncrypterFactory.AES_ALGORITHM)) - .thenReturn(DataEncrypterFactory.AES_ALGORITHM); - Mockito.when(context.getSetting(DataEncryptionExtension.ENCRYPTION_KEY_SET, null)) - .thenReturn(keySetAlias); - Mockito.when(vault.resolveSecret(keySetAlias)).thenReturn("l8b2YHL7VpA=, invalid-key"); - - extension.initialize(context); - - Assertions.assertThrows(EdcException.class, () -> extension.start()); - } - - @Test - void testNonEncrypterRequiresNoOtherSetting() { - final String keySetAlias = "foo"; - Mockito.when( - context.getSetting( - DataEncryptionExtension.ENCRYPTION_ALGORITHM, DataEncrypterFactory.AES_ALGORITHM)) - .thenReturn(DataEncrypterFactory.NONE); - Mockito.when(context.getSetting(DataEncryptionExtension.ENCRYPTION_KEY_SET, null)) - .thenReturn(null); - Mockito.when(vault.resolveSecret(keySetAlias)).thenReturn(null); - - Assertions.assertDoesNotThrow(() -> extension.initialize(context)); - Assertions.assertDoesNotThrow(() -> extension.start()); - } + private DataEncryptionExtension extension; + + // mocks + private Monitor monitor; + private ServiceExtensionContext context; + private Vault vault; + + @BeforeEach + void setup() { + monitor = Mockito.mock(Monitor.class); + context = Mockito.mock(ServiceExtensionContext.class); + vault = Mockito.mock(Vault.class); + + extension = new DataEncryptionExtension(); + + Mockito.when(context.getMonitor()).thenReturn(monitor); + Mockito.when(context.getService(Vault.class)).thenReturn(vault); + + Mockito.when( + context.getSetting( + Mockito.eq(DataEncryptionExtension.CACHING_ENABLED), Mockito.anyBoolean())) + .thenAnswer((i) -> i.getArguments()[1]); + Mockito.when( + context.getSetting( + Mockito.eq(DataEncryptionExtension.ENCRYPTION_ALGORITHM), Mockito.anyString())) + .thenAnswer((i) -> i.getArguments()[1]); + Mockito.when( + context.getSetting( + Mockito.eq(DataEncryptionExtension.CACHING_SECONDS), Mockito.anyInt())) + .thenAnswer((i) -> i.getArguments()[1]); + } + + @Test + void testName() { + Assertions.assertEquals(DataEncryptionExtension.EXTENSION_NAME, extension.name()); + } + + @Test + void testExceptionOnMissingKeySetAlias() { + Mockito.when(context.getSetting(DataEncryptionExtension.ENCRYPTION_KEY_SET, null)) + .thenReturn(null); + Assertions.assertThrows(EdcException.class, () -> extension.initialize(context)); + } + + @Test + void testStartExceptionOnMissingKeySetInVault() { + final String keySetAlias = "foo"; + Mockito.when(context.getSetting(DataEncryptionExtension.ENCRYPTION_KEY_SET, null)) + .thenReturn(keySetAlias); + Mockito.when(vault.resolveSecret(keySetAlias)).thenReturn(""); + + extension.initialize(context); + + Assertions.assertThrows(EdcException.class, () -> extension.start()); + } + + @Test + void testStartExceptionOnStartWithWrongKeySetAlias() { + final String keySetAlias = "foo"; + Mockito.when( + context.getSetting( + DataEncryptionExtension.ENCRYPTION_ALGORITHM, DataEncrypterFactory.AES_ALGORITHM)) + .thenReturn(DataEncrypterFactory.AES_ALGORITHM); + Mockito.when(context.getSetting(DataEncryptionExtension.ENCRYPTION_KEY_SET, null)) + .thenReturn(keySetAlias); + Mockito.when(vault.resolveSecret(keySetAlias)).thenReturn("l8b2YHL7VpA=, invalid-key"); + + extension.initialize(context); + + Assertions.assertThrows(EdcException.class, () -> extension.start()); + } + + @Test + void testNonEncrypterRequiresNoOtherSetting() { + final String keySetAlias = "foo"; + Mockito.when( + context.getSetting( + DataEncryptionExtension.ENCRYPTION_ALGORITHM, DataEncrypterFactory.AES_ALGORITHM)) + .thenReturn(DataEncrypterFactory.NONE); + Mockito.when(context.getSetting(DataEncryptionExtension.ENCRYPTION_KEY_SET, null)) + .thenReturn(null); + Mockito.when(vault.resolveSecret(keySetAlias)).thenReturn(null); + + Assertions.assertDoesNotThrow(() -> extension.initialize(context)); + Assertions.assertDoesNotThrow(() -> extension.start()); + } } diff --git a/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/algorithms/aes/ByteCounterTest.java b/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/algorithms/aes/ByteCounterTest.java index 5a16343a5..b9236f189 100644 --- a/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/algorithms/aes/ByteCounterTest.java +++ b/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/algorithms/aes/ByteCounterTest.java @@ -19,7 +19,6 @@ */ package org.eclipse.tractusx.edc.data.encryption.algorithms.aes; -import java.util.stream.Stream; import org.eclipse.tractusx.edc.data.encryption.util.ArrayUtil; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -29,68 +28,70 @@ import org.junit.jupiter.params.provider.ArgumentsProvider; import org.junit.jupiter.params.provider.ArgumentsSource; +import java.util.stream.Stream; + class ByteCounterTest { - @ParameterizedTest - @ArgumentsSource(IncrementArgumentsProvider.class) - void testIncrements(byte[] counterValue, long numberOfIncrements, byte[] expected) { + @ParameterizedTest + @ArgumentsSource(IncrementArgumentsProvider.class) + void testIncrements(byte[] counterValue, long numberOfIncrements, byte[] expected) { - ByteCounter initializationVector = new ByteCounter(counterValue); + ByteCounter initializationVector = new ByteCounter(counterValue); - for (int i = 0; i < numberOfIncrements; i++) { - initializationVector.increment(); - } + for (int i = 0; i < numberOfIncrements; i++) { + initializationVector.increment(); + } - var result = initializationVector.getBytes(); - Assertions.assertEquals(ArrayUtil.byteArrayToHex(expected), ArrayUtil.byteArrayToHex(result)); - } + var result = initializationVector.getBytes(); + Assertions.assertEquals(ArrayUtil.byteArrayToHex(expected), ArrayUtil.byteArrayToHex(result)); + } - @Test - void testIsMaxed() { + @Test + void testIsMaxed() { - byte[] counterValue = new byte[] {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff}; - ByteCounter initializationVector = new ByteCounter(counterValue); + byte[] counterValue = new byte[]{(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff}; + ByteCounter initializationVector = new ByteCounter(counterValue); - Assertions.assertTrue(initializationVector.isMaxed()); - } + Assertions.assertTrue(initializationVector.isMaxed()); + } - @Test - void testOverflow() { + @Test + void testOverflow() { - byte[] counterValue = new byte[] {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff}; - ByteCounter initializationVector = new ByteCounter(counterValue); + byte[] counterValue = new byte[]{(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff}; + ByteCounter initializationVector = new ByteCounter(counterValue); - Assertions.assertThrows(IllegalStateException.class, initializationVector::increment); - } + Assertions.assertThrows(IllegalStateException.class, initializationVector::increment); + } - private static class IncrementArgumentsProvider implements ArgumentsProvider { - @Override - public Stream provideArguments(ExtensionContext context) throws Exception { - return Stream.of( - Arguments.of( - new byte[] {(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00}, - 0, - new byte[] {(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00}), - Arguments.of( - new byte[] {(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00}, - 1, - new byte[] {(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01}), - Arguments.of( - new byte[] {(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00}, - 2, - new byte[] {(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02}), - Arguments.of( - new byte[] {(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00}, - 255, - new byte[] {(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff}), - Arguments.of( - new byte[] {(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00}, - 65535, - new byte[] {(byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff}), - Arguments.of( - new byte[] {(byte) 0xef, (byte) 0xff, (byte) 0xff, (byte) 0xff}, - 1, - new byte[] {(byte) 0xf0, (byte) 0x00, (byte) 0x00, (byte) 0x00})); + private static class IncrementArgumentsProvider implements ArgumentsProvider { + @Override + public Stream provideArguments(ExtensionContext context) throws Exception { + return Stream.of( + Arguments.of( + new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00}, + 0, + new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00}), + Arguments.of( + new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00}, + 1, + new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01}), + Arguments.of( + new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00}, + 2, + new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02}), + Arguments.of( + new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00}, + 255, + new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff}), + Arguments.of( + new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00}, + 65535, + new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff}), + Arguments.of( + new byte[]{(byte) 0xef, (byte) 0xff, (byte) 0xff, (byte) 0xff}, + 1, + new byte[]{(byte) 0xf0, (byte) 0x00, (byte) 0x00, (byte) 0x00})); + } } - } } diff --git a/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/encrypter/DataEncrypterFactoryTest.java b/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/encrypter/DataEncrypterFactoryTest.java index 650fcfec5..7564931c1 100644 --- a/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/encrypter/DataEncrypterFactoryTest.java +++ b/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/encrypter/DataEncrypterFactoryTest.java @@ -19,7 +19,6 @@ */ package org.eclipse.tractusx.edc.data.encryption.encrypter; -import java.time.Duration; import org.eclipse.edc.connector.transfer.dataplane.spi.security.DataEncrypter; import org.eclipse.edc.spi.monitor.Monitor; import org.eclipse.edc.spi.security.Vault; @@ -31,52 +30,54 @@ import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; +import java.time.Duration; + @SuppressWarnings("FieldCanBeLocal") class DataEncrypterFactoryTest { - private static final String KEY_SET_ALIAS = "keySetAlias"; + private static final String KEY_SET_ALIAS = "keySetAlias"; - DataEncrypterFactory factory; + DataEncrypterFactory factory; - // mocks - private Vault vault; - private Monitor monitor; + // mocks + private Vault vault; + private Monitor monitor; - @BeforeEach - void setup() { - vault = Mockito.mock(Vault.class); - monitor = Mockito.mock(Monitor.class); + @BeforeEach + void setup() { + vault = Mockito.mock(Vault.class); + monitor = Mockito.mock(Monitor.class); - factory = new DataEncrypterFactory(vault, monitor, new CryptoKeyFactoryImpl()); - } + factory = new DataEncrypterFactory(vault, monitor, new CryptoKeyFactoryImpl()); + } - @ParameterizedTest - @ValueSource(strings = {DataEncrypterFactory.AES_ALGORITHM, DataEncrypterFactory.NONE}) - void testValidStrategies(String strategy) { - final AesDataEncrypterConfiguration configuration = newConfiguration(false); - Assertions.assertDoesNotThrow(() -> factory.createAesEncrypter(configuration)); - } + @ParameterizedTest + @ValueSource(strings = {DataEncrypterFactory.AES_ALGORITHM, DataEncrypterFactory.NONE}) + void testValidStrategies(String strategy) { + final AesDataEncrypterConfiguration configuration = newConfiguration(false); + Assertions.assertDoesNotThrow(() -> factory.createAesEncrypter(configuration)); + } - @Test - void testEncrypterWithCaching() { - Mockito.when(vault.resolveSecret(KEY_SET_ALIAS)).thenReturn("7h6sh6t6tchCmNnHjK2kFA=="); + @Test + void testEncrypterWithCaching() { + Mockito.when(vault.resolveSecret(KEY_SET_ALIAS)).thenReturn("7h6sh6t6tchCmNnHjK2kFA=="); - final AesDataEncrypterConfiguration configuration = newConfiguration(true); - final DataEncrypter dataEncrypter = factory.createAesEncrypter(configuration); + final AesDataEncrypterConfiguration configuration = newConfiguration(true); + final DataEncrypter dataEncrypter = factory.createAesEncrypter(configuration); - final String foo1 = dataEncrypter.encrypt("foo1"); - dataEncrypter.decrypt(foo1); - final String foo2 = dataEncrypter.encrypt("foo2"); - dataEncrypter.decrypt(foo2); - final String foo3 = dataEncrypter.encrypt("foo3"); - dataEncrypter.decrypt(foo3); + final String foo1 = dataEncrypter.encrypt("foo1"); + dataEncrypter.decrypt(foo1); + final String foo2 = dataEncrypter.encrypt("foo2"); + dataEncrypter.decrypt(foo2); + final String foo3 = dataEncrypter.encrypt("foo3"); + dataEncrypter.decrypt(foo3); - // one invoke to get encryption- and one to cache decryption key - Mockito.verify(vault, Mockito.times(2)).resolveSecret(KEY_SET_ALIAS); - } + // one invoke to get encryption- and one to cache decryption key + Mockito.verify(vault, Mockito.times(2)).resolveSecret(KEY_SET_ALIAS); + } - private AesDataEncrypterConfiguration newConfiguration(boolean isCachingEnabled) { - return new AesDataEncrypterConfiguration( - KEY_SET_ALIAS, isCachingEnabled, Duration.ofMinutes(1)); - } + private AesDataEncrypterConfiguration newConfiguration(boolean isCachingEnabled) { + return new AesDataEncrypterConfiguration( + KEY_SET_ALIAS, isCachingEnabled, Duration.ofMinutes(1)); + } } diff --git a/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/key/CryptoKeyFactoryImplTest.java b/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/key/CryptoKeyFactoryImplTest.java index 73354b76c..60f68e86d 100644 --- a/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/key/CryptoKeyFactoryImplTest.java +++ b/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/key/CryptoKeyFactoryImplTest.java @@ -25,20 +25,20 @@ class CryptoKeyFactoryImplTest { - @ParameterizedTest - @ValueSource(ints = {32, 64, 512, 1024, 2048, 4096}) - void throwsIllegalArgumentExceptionWhenInvalidAesKeyLength(int bitLength) { - CryptoKeyFactory cryptoKeyFactory = new CryptoKeyFactoryImpl(); - Assertions.assertThrows( - IllegalArgumentException.class, - () -> cryptoKeyFactory.fromBytes(new byte[bitLength / Byte.SIZE])); - } + @ParameterizedTest + @ValueSource(ints = {32, 64, 512, 1024, 2048, 4096}) + void throwsIllegalArgumentExceptionWhenInvalidAesKeyLength(int bitLength) { + CryptoKeyFactory cryptoKeyFactory = new CryptoKeyFactoryImpl(); + Assertions.assertThrows( + IllegalArgumentException.class, + () -> cryptoKeyFactory.fromBytes(new byte[bitLength / Byte.SIZE])); + } - @ParameterizedTest - @ValueSource(ints = {128, 192, 256}) - void throwsNotOnValidAesKeyLength(int bitLength) { - CryptoKeyFactory cryptoKeyFactory = new CryptoKeyFactoryImpl(); - Assertions.assertDoesNotThrow( - () -> cryptoKeyFactory.fromBytes(new byte[bitLength / Byte.SIZE])); - } + @ParameterizedTest + @ValueSource(ints = {128, 192, 256}) + void throwsNotOnValidAesKeyLength(int bitLength) { + CryptoKeyFactory cryptoKeyFactory = new CryptoKeyFactoryImpl(); + Assertions.assertDoesNotThrow( + () -> cryptoKeyFactory.fromBytes(new byte[bitLength / Byte.SIZE])); + } } diff --git a/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/provider/AesKeyProviderTest.java b/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/provider/AesKeyProviderTest.java index 04625fdb0..07152a95b 100644 --- a/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/provider/AesKeyProviderTest.java +++ b/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/provider/AesKeyProviderTest.java @@ -20,8 +20,6 @@ package org.eclipse.tractusx.edc.data.encryption.provider; -import java.util.List; -import java.util.stream.Collectors; import org.eclipse.edc.spi.security.Vault; import org.eclipse.tractusx.edc.data.encryption.key.AesKey; import org.eclipse.tractusx.edc.data.encryption.key.CryptoKeyFactoryImpl; @@ -30,51 +28,54 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import java.util.List; +import java.util.stream.Collectors; + class AesKeyProviderTest { - private static final String KEY_1 = "dVUjmYJzbwVcntkFZU+lNQ=="; - private static final String KEY_2 = "7h6sh6t6tchCmNnHjK2kFA=="; - private static final String KEY_3 = "uyNfJzhsnvfEe9OtQyR9Og=="; + private static final String KEY_1 = "dVUjmYJzbwVcntkFZU+lNQ=="; + private static final String KEY_2 = "7h6sh6t6tchCmNnHjK2kFA=="; + private static final String KEY_3 = "uyNfJzhsnvfEe9OtQyR9Og=="; - private static final String KEY_ALIAS = "foo"; + private static final String KEY_ALIAS = "foo"; - private AesKeyProvider keyProvider; + private AesKeyProvider keyProvider; - // mocks - private Vault vault; + // mocks + private Vault vault; - @BeforeEach - void setup() { - vault = Mockito.mock(Vault.class); - keyProvider = new AesKeyProvider(vault, KEY_ALIAS, new CryptoKeyFactoryImpl()); - } + @BeforeEach + void setup() { + vault = Mockito.mock(Vault.class); + keyProvider = new AesKeyProvider(vault, KEY_ALIAS, new CryptoKeyFactoryImpl()); + } - @Test - void testEncryptionKeyAlwaysFirstKey() { - Mockito.when(vault.resolveSecret(KEY_ALIAS)) - .thenReturn(String.format("%s,%s,%s", KEY_1, KEY_2, KEY_3)); + @Test + void testEncryptionKeyAlwaysFirstKey() { + Mockito.when(vault.resolveSecret(KEY_ALIAS)) + .thenReturn(String.format("%s,%s,%s", KEY_1, KEY_2, KEY_3)); - AesKey key = keyProvider.getEncryptionKey(); + AesKey key = keyProvider.getEncryptionKey(); - Assertions.assertEquals(KEY_1, key.getBase64()); - } + Assertions.assertEquals(KEY_1, key.getBase64()); + } - @Test - void testEncryptionThrowsOnNoKey() { - Mockito.when(vault.resolveSecret(KEY_ALIAS)).thenReturn(" "); + @Test + void testEncryptionThrowsOnNoKey() { + Mockito.when(vault.resolveSecret(KEY_ALIAS)).thenReturn(" "); - Assertions.assertThrows(RuntimeException.class, () -> keyProvider.getEncryptionKey()); - } + Assertions.assertThrows(RuntimeException.class, () -> keyProvider.getEncryptionKey()); + } - @Test - void testGetKeys() { - Mockito.when(vault.resolveSecret(KEY_ALIAS)) - .thenReturn(String.format("%s, ,,%s,%s", KEY_1, KEY_2, KEY_3)); + @Test + void testGetKeys() { + Mockito.when(vault.resolveSecret(KEY_ALIAS)) + .thenReturn(String.format("%s, ,,%s,%s", KEY_1, KEY_2, KEY_3)); - List keys = - keyProvider.getDecryptionKeySet().map(AesKey::getBase64).collect(Collectors.toList()); - List expected = List.of(KEY_1, KEY_2, KEY_3); + List keys = + keyProvider.getDecryptionKeySet().map(AesKey::getBase64).collect(Collectors.toList()); + List expected = List.of(KEY_1, KEY_2, KEY_3); - Assertions.assertEquals(expected, keys); - } + Assertions.assertEquals(expected, keys); + } } diff --git a/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/provider/CachingKeyProviderTest.java b/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/provider/CachingKeyProviderTest.java index 390b210f6..28ee89b33 100644 --- a/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/provider/CachingKeyProviderTest.java +++ b/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/provider/CachingKeyProviderTest.java @@ -19,83 +19,84 @@ */ package org.eclipse.tractusx.edc.data.encryption.provider; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.util.stream.Stream; import org.eclipse.tractusx.edc.data.encryption.key.CryptoKey; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.stream.Stream; + @SuppressWarnings("FieldCanBeLocal") class CachingKeyProviderTest { - private CachingKeyProvider cachingKeyProvider; + private CachingKeyProvider cachingKeyProvider; - private CryptoKey encryptionKey; - private CryptoKey decryptionKey; + private CryptoKey encryptionKey; + private CryptoKey decryptionKey; - // mocks - private KeyProvider decoratedProvider; - private Duration cacheExpiration; - private Clock clock; + // mocks + private KeyProvider decoratedProvider; + private Duration cacheExpiration; + private Clock clock; - @BeforeEach - void setup() { - decoratedProvider = Mockito.mock(KeyProvider.class); - cacheExpiration = Duration.ofSeconds(2); - clock = Mockito.mock(Clock.class); - encryptionKey = Mockito.mock(CryptoKey.class); - decryptionKey = Mockito.mock(CryptoKey.class); + @BeforeEach + void setup() { + decoratedProvider = Mockito.mock(KeyProvider.class); + cacheExpiration = Duration.ofSeconds(2); + clock = Mockito.mock(Clock.class); + encryptionKey = Mockito.mock(CryptoKey.class); + decryptionKey = Mockito.mock(CryptoKey.class); - cachingKeyProvider = - new CachingKeyProvider(decoratedProvider, cacheExpiration, clock); + cachingKeyProvider = + new CachingKeyProvider(decoratedProvider, cacheExpiration, clock); - Mockito.when(decoratedProvider.getEncryptionKey()).thenReturn(encryptionKey); - Mockito.when(decoratedProvider.getDecryptionKeySet()) - .thenAnswer((i) -> Stream.of(decryptionKey)); - } + Mockito.when(decoratedProvider.getEncryptionKey()).thenReturn(encryptionKey); + Mockito.when(decoratedProvider.getDecryptionKeySet()) + .thenAnswer((i) -> Stream.of(decryptionKey)); + } - @Test - void testCaching() { + @Test + void testCaching() { - Mockito.when(clock.instant()).thenAnswer((i) -> Instant.now()); + Mockito.when(clock.instant()).thenAnswer((i) -> Instant.now()); - cachingKeyProvider.getDecryptionKeySet(); - cachingKeyProvider.getEncryptionKey(); + cachingKeyProvider.getDecryptionKeySet(); + cachingKeyProvider.getEncryptionKey(); - cachingKeyProvider.getDecryptionKeySet(); - cachingKeyProvider.getEncryptionKey(); + cachingKeyProvider.getDecryptionKeySet(); + cachingKeyProvider.getEncryptionKey(); - cachingKeyProvider.getDecryptionKeySet(); - cachingKeyProvider.getEncryptionKey(); + cachingKeyProvider.getDecryptionKeySet(); + cachingKeyProvider.getEncryptionKey(); - cachingKeyProvider.getDecryptionKeySet(); - cachingKeyProvider.getEncryptionKey(); + cachingKeyProvider.getDecryptionKeySet(); + cachingKeyProvider.getEncryptionKey(); - Mockito.verify(decoratedProvider, Mockito.times(1)).getDecryptionKeySet(); - Mockito.verify(decoratedProvider, Mockito.times(1)).getEncryptionKey(); - } + Mockito.verify(decoratedProvider, Mockito.times(1)).getDecryptionKeySet(); + Mockito.verify(decoratedProvider, Mockito.times(1)).getEncryptionKey(); + } - @Test - void testCacheUpdate() { + @Test + void testCacheUpdate() { - Mockito.when(clock.instant()).thenAnswer((i) -> Instant.now()); + Mockito.when(clock.instant()).thenAnswer((i) -> Instant.now()); - cachingKeyProvider.getDecryptionKeySet(); - cachingKeyProvider.getEncryptionKey(); + cachingKeyProvider.getDecryptionKeySet(); + cachingKeyProvider.getEncryptionKey(); - cachingKeyProvider.getDecryptionKeySet(); - cachingKeyProvider.getEncryptionKey(); + cachingKeyProvider.getDecryptionKeySet(); + cachingKeyProvider.getEncryptionKey(); - Mockito.when(clock.instant()) - .thenAnswer((i) -> Instant.now().plus(cacheExpiration.plusSeconds(1))); + Mockito.when(clock.instant()) + .thenAnswer((i) -> Instant.now().plus(cacheExpiration.plusSeconds(1))); - cachingKeyProvider.getDecryptionKeySet(); - cachingKeyProvider.getEncryptionKey(); + cachingKeyProvider.getDecryptionKeySet(); + cachingKeyProvider.getEncryptionKey(); - Mockito.verify(decoratedProvider, Mockito.times(2)).getDecryptionKeySet(); - Mockito.verify(decoratedProvider, Mockito.times(2)).getEncryptionKey(); - } + Mockito.verify(decoratedProvider, Mockito.times(2)).getDecryptionKeySet(); + Mockito.verify(decoratedProvider, Mockito.times(2)).getEncryptionKey(); + } } diff --git a/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/util/ArrayUtilTest.java b/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/util/ArrayUtilTest.java index 45b604b64..2ddd5694d 100644 --- a/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/util/ArrayUtilTest.java +++ b/edc-extensions/data-encryption/src/test/java/org/eclipse/tractusx/edc/data/encryption/util/ArrayUtilTest.java @@ -19,7 +19,6 @@ */ package org.eclipse.tractusx.edc.data.encryption.util; -import java.util.stream.Stream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtensionContext; @@ -28,45 +27,47 @@ import org.junit.jupiter.params.provider.ArgumentsProvider; import org.junit.jupiter.params.provider.ArgumentsSource; +import java.util.stream.Stream; + class ArrayUtilTest { - @ParameterizedTest - @ArgumentsSource(ArrayArgumentsProvider.class) - void testConcat(byte[] a, byte[] b, byte[] expected) { - var result = ArrayUtil.concat(a, b); - Assertions.assertEquals(ArrayUtil.byteArrayToHex(expected), ArrayUtil.byteArrayToHex(result)); - } + @ParameterizedTest + @ArgumentsSource(ArrayArgumentsProvider.class) + void testConcat(byte[] a, byte[] b, byte[] expected) { + var result = ArrayUtil.concat(a, b); + Assertions.assertEquals(ArrayUtil.byteArrayToHex(expected), ArrayUtil.byteArrayToHex(result)); + } - @Test - void testSubArray() { - final byte[] expected = new byte[] {0x01, 0x02, 0x03, 0x04, 0x05}; - final byte[] array = new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}; - final byte[] subArray = ArrayUtil.subArray(array, 1, 5); + @Test + void testSubArray() { + final byte[] expected = new byte[]{0x01, 0x02, 0x03, 0x04, 0x05}; + final byte[] array = new byte[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}; + final byte[] subArray = ArrayUtil.subArray(array, 1, 5); - Assertions.assertEquals(ArrayUtil.byteArrayToHex(expected), ArrayUtil.byteArrayToHex(subArray)); - } + Assertions.assertEquals(ArrayUtil.byteArrayToHex(expected), ArrayUtil.byteArrayToHex(subArray)); + } - private static class ArrayArgumentsProvider implements ArgumentsProvider { + private static class ArrayArgumentsProvider implements ArgumentsProvider { - @Override - public Stream provideArguments(ExtensionContext context) throws Exception { - return Stream.of( - Arguments.of( - new byte[] {0x00, 0x01, 0x02, 0x03}, - new byte[] {0x04, 0x05, 0x06, 0x07}, - new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}), - Arguments.of( - new byte[] {0x00}, - new byte[] {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}, - new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}), - Arguments.of( - new byte[] {}, - new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}, - new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}), - Arguments.of( - new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}, - new byte[] {}, - new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07})); + @Override + public Stream provideArguments(ExtensionContext context) throws Exception { + return Stream.of( + Arguments.of( + new byte[]{0x00, 0x01, 0x02, 0x03}, + new byte[]{0x04, 0x05, 0x06, 0x07}, + new byte[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}), + Arguments.of( + new byte[]{0x00}, + new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}, + new byte[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}), + Arguments.of( + new byte[]{}, + new byte[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}, + new byte[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}), + Arguments.of( + new byte[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}, + new byte[]{}, + new byte[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07})); + } } - } } diff --git a/edc-extensions/dataplane-selector-configuration/src/main/java/org/eclipse/tractusx/edc/dataplane/selector/configuration/DataPlaneSelectorConfigurationServiceExtension.java b/edc-extensions/dataplane-selector-configuration/src/main/java/org/eclipse/tractusx/edc/dataplane/selector/configuration/DataPlaneSelectorConfigurationServiceExtension.java index d80fd53db..e57124464 100644 --- a/edc-extensions/dataplane-selector-configuration/src/main/java/org/eclipse/tractusx/edc/dataplane/selector/configuration/DataPlaneSelectorConfigurationServiceExtension.java +++ b/edc-extensions/dataplane-selector-configuration/src/main/java/org/eclipse/tractusx/edc/dataplane/selector/configuration/DataPlaneSelectorConfigurationServiceExtension.java @@ -23,11 +23,6 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.function.Predicate; -import java.util.stream.Collectors; import org.eclipse.edc.connector.dataplane.selector.spi.DataPlaneSelectorService; import org.eclipse.edc.connector.dataplane.selector.spi.instance.DataPlaneInstance; import org.eclipse.edc.runtime.metamodel.annotation.Requires; @@ -37,113 +32,113 @@ import org.eclipse.edc.spi.system.ServiceExtensionContext; import org.eclipse.edc.spi.system.configuration.Config; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.function.Predicate; +import java.util.stream.Collectors; + @Requires({DataPlaneSelectorService.class}) public class DataPlaneSelectorConfigurationServiceExtension implements ServiceExtension { - public static final String CONFIG_PREFIX = "edc.dataplane.selector"; - public static final String URL_SUFFIX = "url"; - public static final String DESTINATION_TYPES_SUFFIX = "destinationtypes"; - public static final String SOURCE_TYPES_SUFFIX = "sourcetypes"; - public static final String PROPERTIES_SUFFIX = "properties"; - public static final String PUBLIC_API_URL_PROPERTY = "publicApiUrl"; - - private static final String NAME = "Data Plane Selector Configuration Extension"; - private static final String COMMA = ","; - private static final String LOG_MISSING_CONFIGURATION = - NAME + ": Missing configuration for " + CONFIG_PREFIX + ".%s.%s"; - private static final String LOG_SKIP_BC_MISSING_CONFIGURATION = - NAME + ": Configuration issues. Skip registering of Data Plane Instance '%s'"; - private static final String LOG_REGISTERED = - NAME - + ": Registered Data Plane Instance. (id=%s, url=%s, sourceTypes=%s, destinationTypes=%s, properties=)"; - - private Monitor monitor; - private DataPlaneSelectorService dataPlaneSelectorService; - - @Override - public String name() { - return NAME; - } - - @Override - public void initialize(final ServiceExtensionContext serviceExtensionContext) { - this.dataPlaneSelectorService = - serviceExtensionContext.getService(DataPlaneSelectorService.class); - this.monitor = serviceExtensionContext.getMonitor(); - - final Config config = serviceExtensionContext.getConfig(CONFIG_PREFIX); - - config.partition().forEach(this::configureDataPlaneInstance); - } - - private void configureDataPlaneInstance(final Config config) { - final String id = config.currentNode(); - - final String url = config.getString(URL_SUFFIX, ""); - final List sourceTypes = - Arrays.stream(config.getString(SOURCE_TYPES_SUFFIX, "").split(COMMA)) - .map(String::trim) - .filter(Predicate.not(String::isEmpty)) - .distinct() - .collect(Collectors.toList()); - final List destinationTypes = - Arrays.stream(config.getString(DESTINATION_TYPES_SUFFIX, "").split(COMMA)) - .map(String::trim) - .filter(Predicate.not(String::isEmpty)) - .distinct() - .collect(Collectors.toList()); - final String propertiesJson = config.getString(PROPERTIES_SUFFIX, "{}"); - - if (url.isEmpty()) { - monitor.warning(String.format(LOG_MISSING_CONFIGURATION, id, URL_SUFFIX)); + public static final String CONFIG_PREFIX = "edc.dataplane.selector"; + public static final String URL_SUFFIX = "url"; + public static final String DESTINATION_TYPES_SUFFIX = "destinationtypes"; + public static final String SOURCE_TYPES_SUFFIX = "sourcetypes"; + public static final String PROPERTIES_SUFFIX = "properties"; + public static final String PUBLIC_API_URL_PROPERTY = "publicApiUrl"; + + private static final String NAME = "Data Plane Selector Configuration Extension"; + private static final String COMMA = ","; + private static final String LOG_MISSING_CONFIGURATION = NAME + ": Missing configuration for " + CONFIG_PREFIX + ".%s.%s"; + private static final String LOG_SKIP_BC_MISSING_CONFIGURATION = NAME + ": Configuration issues. Skip registering of Data Plane Instance '%s'"; + private static final String LOG_REGISTERED = NAME + ": Registered Data Plane Instance. (id=%s, url=%s, sourceTypes=%s, destinationTypes=%s, properties=)"; + + private Monitor monitor; + private DataPlaneSelectorService dataPlaneSelectorService; + + @Override + public String name() { + return NAME; } - if (sourceTypes.isEmpty()) { - monitor.warning(String.format(LOG_MISSING_CONFIGURATION, id, SOURCE_TYPES_SUFFIX)); - } + @Override + public void initialize(final ServiceExtensionContext serviceExtensionContext) { + this.dataPlaneSelectorService = + serviceExtensionContext.getService(DataPlaneSelectorService.class); + this.monitor = serviceExtensionContext.getMonitor(); - if (destinationTypes.isEmpty()) { - monitor.warning(String.format(LOG_MISSING_CONFIGURATION, id, DESTINATION_TYPES_SUFFIX)); - } - - final Map properties; - try { - ObjectMapper mapper = new ObjectMapper(); - properties = mapper.readValue(propertiesJson, new TypeReference>() {}); - } catch (JsonProcessingException e) { - throw new EdcException(e); - } + final Config config = serviceExtensionContext.getConfig(CONFIG_PREFIX); - final boolean missingPublicApiProperty = !properties.containsKey(PUBLIC_API_URL_PROPERTY); - if (missingPublicApiProperty) { - monitor.warning( - String.format(LOG_MISSING_CONFIGURATION, id, PROPERTIES_SUFFIX) - + "." - + PUBLIC_API_URL_PROPERTY); + config.partition().forEach(this::configureDataPlaneInstance); } - final boolean invalidConfiguration = - url.isEmpty() || sourceTypes.isEmpty() || destinationTypes.isEmpty(); - if (invalidConfiguration || missingPublicApiProperty) { - monitor.warning(String.format(LOG_SKIP_BC_MISSING_CONFIGURATION, id)); - return; + private void configureDataPlaneInstance(final Config config) { + final String id = config.currentNode(); + + final String url = config.getString(URL_SUFFIX, ""); + final List sourceTypes = + Arrays.stream(config.getString(SOURCE_TYPES_SUFFIX, "").split(COMMA)) + .map(String::trim) + .filter(Predicate.not(String::isEmpty)) + .distinct() + .collect(Collectors.toList()); + final List destinationTypes = + Arrays.stream(config.getString(DESTINATION_TYPES_SUFFIX, "").split(COMMA)) + .map(String::trim) + .filter(Predicate.not(String::isEmpty)) + .distinct() + .collect(Collectors.toList()); + final String propertiesJson = config.getString(PROPERTIES_SUFFIX, "{}"); + + if (url.isEmpty()) { + monitor.warning(String.format(LOG_MISSING_CONFIGURATION, id, URL_SUFFIX)); + } + + if (sourceTypes.isEmpty()) { + monitor.warning(String.format(LOG_MISSING_CONFIGURATION, id, SOURCE_TYPES_SUFFIX)); + } + + if (destinationTypes.isEmpty()) { + monitor.warning(String.format(LOG_MISSING_CONFIGURATION, id, DESTINATION_TYPES_SUFFIX)); + } + + final Map properties; + try { + ObjectMapper mapper = new ObjectMapper(); + properties = mapper.readValue(propertiesJson, new TypeReference>() { + }); + } catch (JsonProcessingException e) { + throw new EdcException(e); + } + + final boolean missingPublicApiProperty = !properties.containsKey(PUBLIC_API_URL_PROPERTY); + if (missingPublicApiProperty) { + monitor.warning(String.format(LOG_MISSING_CONFIGURATION, id, PROPERTIES_SUFFIX) + "." + PUBLIC_API_URL_PROPERTY); + } + + final boolean invalidConfiguration = + url.isEmpty() || sourceTypes.isEmpty() || destinationTypes.isEmpty(); + if (invalidConfiguration || missingPublicApiProperty) { + monitor.warning(String.format(LOG_SKIP_BC_MISSING_CONFIGURATION, id)); + return; + } + + final DataPlaneInstance.Builder builder = + DataPlaneInstance.Builder.newInstance().id(id).url(url); + + sourceTypes.forEach(builder::allowedSourceType); + destinationTypes.forEach(builder::allowedDestType); + properties.forEach(builder::property); + + dataPlaneSelectorService.addInstance(builder.build()); + + monitor.debug( + String.format( + LOG_REGISTERED, + id, + url, + String.join(", ", sourceTypes), + String.join(", ", destinationTypes))); } - - final DataPlaneInstance.Builder builder = - DataPlaneInstance.Builder.newInstance().id(id).url(url); - - sourceTypes.forEach(builder::allowedSourceType); - destinationTypes.forEach(builder::allowedDestType); - properties.forEach(builder::property); - - dataPlaneSelectorService.addInstance(builder.build()); - - monitor.debug( - String.format( - LOG_REGISTERED, - id, - url, - String.join(", ", sourceTypes), - String.join(", ", destinationTypes))); - } } diff --git a/edc-extensions/dataplane-selector-configuration/src/test/java/org/eclipse/tractusx/edc/dataplane/selector/configuration/DataPlaneSelectorConfigurationServiceExtensionEdcExtensionTest.java b/edc-extensions/dataplane-selector-configuration/src/test/java/org/eclipse/tractusx/edc/dataplane/selector/configuration/DataPlaneSelectorConfigurationServiceExtensionEdcExtensionTest.java index 278e2493e..6e1c2098c 100644 --- a/edc-extensions/dataplane-selector-configuration/src/test/java/org/eclipse/tractusx/edc/dataplane/selector/configuration/DataPlaneSelectorConfigurationServiceExtensionEdcExtensionTest.java +++ b/edc-extensions/dataplane-selector-configuration/src/test/java/org/eclipse/tractusx/edc/dataplane/selector/configuration/DataPlaneSelectorConfigurationServiceExtensionEdcExtensionTest.java @@ -39,119 +39,123 @@ @ExtendWith(EdcExtension.class) class DataPlaneSelectorConfigurationServiceExtensionEdcExtensionTest { - private static final String S3_BUCKET = "s3-bucket"; - private static final String BLOB_STORAGE = "blob-storage"; - private static final String LOCAL_FILE_SYSTEM = "local-file-system"; - - private static final String DATA_PLANE_INSTANCE_ID = "test-plane"; - private static final String DATA_PLANE_INSTANCE_URL = "http://127.0.0.1:8080/test"; - private static final String DATA_PLANE_INSTANCE_SOURCE_TYPES = - String.format("%s, %s", S3_BUCKET, BLOB_STORAGE); - private static final String DATA_PLANE_INSTANCE_DESTINATION_TYPES = LOCAL_FILE_SYSTEM; - - // mocks - private DataPlaneSelectorService dataPlaneSelectorService; - - @BeforeEach - final void beforeEach(EdcExtension extension) { - dataPlaneSelectorService = Mockito.mock(DataPlaneSelectorService.class); - - extension.registerSystemExtension(ServiceExtension.class, new TestExtension()); - extension.setConfiguration(getConfig()); - } - - private Map getConfig() { - final String urlKey = - String.format( - "%s.%s.%s", - DataPlaneSelectorConfigurationServiceExtension.CONFIG_PREFIX, - DATA_PLANE_INSTANCE_ID, - DataPlaneSelectorConfigurationServiceExtension.URL_SUFFIX); - final String sourceTypesKey = - String.format( - "%s.%s.%s", - DataPlaneSelectorConfigurationServiceExtension.CONFIG_PREFIX, - DATA_PLANE_INSTANCE_ID, - DataPlaneSelectorConfigurationServiceExtension.SOURCE_TYPES_SUFFIX); - final String destinationTypesKey = - String.format( - "%s.%s.%s", - DataPlaneSelectorConfigurationServiceExtension.CONFIG_PREFIX, - DATA_PLANE_INSTANCE_ID, - DataPlaneSelectorConfigurationServiceExtension.DESTINATION_TYPES_SUFFIX); - final String propertiesKey = - String.format( - "%s.%s.%s", - DataPlaneSelectorConfigurationServiceExtension.CONFIG_PREFIX, - DATA_PLANE_INSTANCE_ID, - DataPlaneSelectorConfigurationServiceExtension.PROPERTIES_SUFFIX); - - return new HashMap<>() { - { - put(urlKey, DATA_PLANE_INSTANCE_URL); - put(sourceTypesKey, DATA_PLANE_INSTANCE_SOURCE_TYPES); - put(destinationTypesKey, DATA_PLANE_INSTANCE_DESTINATION_TYPES); - put( - propertiesKey, - String.format( - "{ \"%s\": \"%s\" }", - DataPlaneSelectorConfigurationServiceExtension.PUBLIC_API_URL_PROPERTY, - DATA_PLANE_INSTANCE_URL)); - } - }; - } - - @Test - void registersDataPlaneInstance() { - Mockito.verify(dataPlaneSelectorService, Mockito.times(1)) - .addInstance( - Mockito.argThat( - dataPlaneInstance -> { - final DataAddress s3Source = - DataAddress.Builder.newInstance().type(S3_BUCKET).build(); - final DataAddress blobSource = - DataAddress.Builder.newInstance().type(BLOB_STORAGE).build(); - final DataAddress fsSink = - DataAddress.Builder.newInstance().type(LOCAL_FILE_SYSTEM).build(); - - final boolean matchingId = - dataPlaneInstance.getId().equals(DATA_PLANE_INSTANCE_ID); - final boolean matchingUrl = - dataPlaneInstance.getUrl().toString().equals(DATA_PLANE_INSTANCE_URL); - final boolean matchingCanHandleS3ToFileSystem = - dataPlaneInstance.canHandle(s3Source, fsSink); - final boolean matchingCanHandleBlobToFileSystem = - dataPlaneInstance.canHandle(blobSource, fsSink); - - if (!matchingId) - System.err.printf( - "Expected ID %s, but got %s%n", - DATA_PLANE_INSTANCE_ID, dataPlaneInstance.getId()); - if (!matchingUrl) - System.err.printf( - "Expected URL %s, but got %s%n", - DATA_PLANE_INSTANCE_URL, dataPlaneInstance.getUrl()); - if (!matchingCanHandleS3ToFileSystem) - System.err.printf( - "Expected Instance to be handle source %s and sink %s%n", - S3_BUCKET, LOCAL_FILE_SYSTEM); - if (!matchingCanHandleBlobToFileSystem) - System.err.printf( - "Expected Instance to be handle source %s and sink %s%n", - BLOB_STORAGE, LOCAL_FILE_SYSTEM); - - return matchingId - && matchingUrl - && matchingCanHandleS3ToFileSystem - && matchingCanHandleBlobToFileSystem; - })); - } - - @Provides({DataPlaneSelectorService.class}) - private class TestExtension implements ServiceExtension { - - public void initialize(ServiceExtensionContext context) { - context.registerService(DataPlaneSelectorService.class, dataPlaneSelectorService); + private static final String S3_BUCKET = "s3-bucket"; + private static final String BLOB_STORAGE = "blob-storage"; + private static final String LOCAL_FILE_SYSTEM = "local-file-system"; + + private static final String DATA_PLANE_INSTANCE_ID = "test-plane"; + private static final String DATA_PLANE_INSTANCE_URL = "http://127.0.0.1:8080/test"; + private static final String DATA_PLANE_INSTANCE_SOURCE_TYPES = + String.format("%s, %s", S3_BUCKET, BLOB_STORAGE); + private static final String DATA_PLANE_INSTANCE_DESTINATION_TYPES = LOCAL_FILE_SYSTEM; + + // mocks + private DataPlaneSelectorService dataPlaneSelectorService; + + @BeforeEach + final void beforeEach(EdcExtension extension) { + dataPlaneSelectorService = Mockito.mock(DataPlaneSelectorService.class); + + extension.registerSystemExtension(ServiceExtension.class, new TestExtension()); + extension.setConfiguration(getConfig()); + } + + private Map getConfig() { + final String urlKey = + String.format( + "%s.%s.%s", + DataPlaneSelectorConfigurationServiceExtension.CONFIG_PREFIX, + DATA_PLANE_INSTANCE_ID, + DataPlaneSelectorConfigurationServiceExtension.URL_SUFFIX); + final String sourceTypesKey = + String.format( + "%s.%s.%s", + DataPlaneSelectorConfigurationServiceExtension.CONFIG_PREFIX, + DATA_PLANE_INSTANCE_ID, + DataPlaneSelectorConfigurationServiceExtension.SOURCE_TYPES_SUFFIX); + final String destinationTypesKey = + String.format( + "%s.%s.%s", + DataPlaneSelectorConfigurationServiceExtension.CONFIG_PREFIX, + DATA_PLANE_INSTANCE_ID, + DataPlaneSelectorConfigurationServiceExtension.DESTINATION_TYPES_SUFFIX); + final String propertiesKey = + String.format( + "%s.%s.%s", + DataPlaneSelectorConfigurationServiceExtension.CONFIG_PREFIX, + DATA_PLANE_INSTANCE_ID, + DataPlaneSelectorConfigurationServiceExtension.PROPERTIES_SUFFIX); + + return new HashMap<>() { + { + put(urlKey, DATA_PLANE_INSTANCE_URL); + put(sourceTypesKey, DATA_PLANE_INSTANCE_SOURCE_TYPES); + put(destinationTypesKey, DATA_PLANE_INSTANCE_DESTINATION_TYPES); + put( + propertiesKey, + String.format( + "{ \"%s\": \"%s\" }", + DataPlaneSelectorConfigurationServiceExtension.PUBLIC_API_URL_PROPERTY, + DATA_PLANE_INSTANCE_URL)); + } + }; + } + + @Test + void registersDataPlaneInstance() { + Mockito.verify(dataPlaneSelectorService, Mockito.times(1)) + .addInstance( + Mockito.argThat( + dataPlaneInstance -> { + final DataAddress s3Source = + DataAddress.Builder.newInstance().type(S3_BUCKET).build(); + final DataAddress blobSource = + DataAddress.Builder.newInstance().type(BLOB_STORAGE).build(); + final DataAddress fsSink = + DataAddress.Builder.newInstance().type(LOCAL_FILE_SYSTEM).build(); + + final boolean matchingId = + dataPlaneInstance.getId().equals(DATA_PLANE_INSTANCE_ID); + final boolean matchingUrl = + dataPlaneInstance.getUrl().toString().equals(DATA_PLANE_INSTANCE_URL); + final boolean matchingCanHandleS3ToFileSystem = + dataPlaneInstance.canHandle(s3Source, fsSink); + final boolean matchingCanHandleBlobToFileSystem = + dataPlaneInstance.canHandle(blobSource, fsSink); + + if (!matchingId) { + System.err.printf( + "Expected ID %s, but got %s%n", + DATA_PLANE_INSTANCE_ID, dataPlaneInstance.getId()); + } + if (!matchingUrl) { + System.err.printf( + "Expected URL %s, but got %s%n", + DATA_PLANE_INSTANCE_URL, dataPlaneInstance.getUrl()); + } + if (!matchingCanHandleS3ToFileSystem) { + System.err.printf( + "Expected Instance to be handle source %s and sink %s%n", + S3_BUCKET, LOCAL_FILE_SYSTEM); + } + if (!matchingCanHandleBlobToFileSystem) { + System.err.printf( + "Expected Instance to be handle source %s and sink %s%n", + BLOB_STORAGE, LOCAL_FILE_SYSTEM); + } + + return matchingId && + matchingUrl && + matchingCanHandleS3ToFileSystem && + matchingCanHandleBlobToFileSystem; + })); + } + + @Provides({DataPlaneSelectorService.class}) + private class TestExtension implements ServiceExtension { + + public void initialize(ServiceExtensionContext context) { + context.registerService(DataPlaneSelectorService.class, dataPlaneSelectorService); + } } - } } diff --git a/edc-extensions/dataplane-selector-configuration/src/test/java/org/eclipse/tractusx/edc/dataplane/selector/configuration/DataPlaneSelectorConfigurationServiceExtensionTest.java b/edc-extensions/dataplane-selector-configuration/src/test/java/org/eclipse/tractusx/edc/dataplane/selector/configuration/DataPlaneSelectorConfigurationServiceExtensionTest.java index 5a9298e83..d16100b63 100644 --- a/edc-extensions/dataplane-selector-configuration/src/test/java/org/eclipse/tractusx/edc/dataplane/selector/configuration/DataPlaneSelectorConfigurationServiceExtensionTest.java +++ b/edc-extensions/dataplane-selector-configuration/src/test/java/org/eclipse/tractusx/edc/dataplane/selector/configuration/DataPlaneSelectorConfigurationServiceExtensionTest.java @@ -20,9 +20,6 @@ package org.eclipse.tractusx.edc.dataplane.selector.configuration; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Stream; import org.eclipse.edc.connector.dataplane.selector.spi.DataPlaneSelectorService; import org.eclipse.edc.spi.EdcException; import org.eclipse.edc.spi.monitor.Monitor; @@ -40,185 +37,193 @@ import org.junit.jupiter.params.provider.ArgumentsSource; import org.mockito.Mockito; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Stream; + class DataPlaneSelectorConfigurationServiceExtensionTest { - private static final String S3_BUCKET = "s3-bucket"; - private static final String BLOB_STORAGE = "blob-storage"; - private static final String LOCAL_FILE_SYSTEM = "local-file-system"; - - private static final String DATA_PLANE_INSTANCE_ID = "test-plane"; - private static final String DATA_PLANE_INSTANCE_URL = "http://127.0.0.1:8080/test"; - private static final String DATA_PLANE_INSTANCE_SOURCE_TYPES = - String.format("%s, %s", S3_BUCKET, BLOB_STORAGE); - private static final String DATA_PLANE_INSTANCE_DESTINATION_TYPES = LOCAL_FILE_SYSTEM; - - private static final String urlKey = - String.format( - "%s.%s", - DATA_PLANE_INSTANCE_ID, DataPlaneSelectorConfigurationServiceExtension.URL_SUFFIX); - private static final String sourceTypesKey = - String.format( - "%s.%s", - DATA_PLANE_INSTANCE_ID, - DataPlaneSelectorConfigurationServiceExtension.SOURCE_TYPES_SUFFIX); - private static final String destinationTypesKey = - String.format( - "%s.%s", - DATA_PLANE_INSTANCE_ID, - DataPlaneSelectorConfigurationServiceExtension.DESTINATION_TYPES_SUFFIX); - private static final String propertiesKey = - String.format( - "%s.%s", - DATA_PLANE_INSTANCE_ID, DataPlaneSelectorConfigurationServiceExtension.PROPERTIES_SUFFIX); - - private DataPlaneSelectorConfigurationServiceExtension extension; - - // mocks - private ServiceExtensionContext serviceExtensionContext; - private DataPlaneSelectorService dataPlaneSelectorService; - private Monitor monitor; - - @BeforeEach - void setup() { - extension = new DataPlaneSelectorConfigurationServiceExtension(); - - serviceExtensionContext = Mockito.mock(ServiceExtensionContext.class); - dataPlaneSelectorService = Mockito.mock(DataPlaneSelectorService.class); - monitor = Mockito.mock(Monitor.class); - - Mockito.when(serviceExtensionContext.getService(DataPlaneSelectorService.class)) - .thenReturn(dataPlaneSelectorService); - Mockito.when(serviceExtensionContext.getMonitor()).thenReturn(monitor); - } - - private Map getConfig() { - return new HashMap<>() { - { - put(urlKey, DATA_PLANE_INSTANCE_URL); - put(sourceTypesKey, DATA_PLANE_INSTANCE_SOURCE_TYPES); - put(destinationTypesKey, DATA_PLANE_INSTANCE_DESTINATION_TYPES); - put( - propertiesKey, + private static final String S3_BUCKET = "s3-bucket"; + private static final String BLOB_STORAGE = "blob-storage"; + private static final String LOCAL_FILE_SYSTEM = "local-file-system"; + + private static final String DATA_PLANE_INSTANCE_ID = "test-plane"; + private static final String DATA_PLANE_INSTANCE_URL = "http://127.0.0.1:8080/test"; + private static final String DATA_PLANE_INSTANCE_SOURCE_TYPES = + String.format("%s, %s", S3_BUCKET, BLOB_STORAGE); + private static final String DATA_PLANE_INSTANCE_DESTINATION_TYPES = LOCAL_FILE_SYSTEM; + + private static final String URL_KEY = + String.format( + "%s.%s", + DATA_PLANE_INSTANCE_ID, DataPlaneSelectorConfigurationServiceExtension.URL_SUFFIX); + private static final String SOURCE_TYPES_KEY = String.format( - "{ \"%s\": \"%s\" }", - DataPlaneSelectorConfigurationServiceExtension.PUBLIC_API_URL_PROPERTY, - DATA_PLANE_INSTANCE_URL)); - } - }; - } - - @Test - void testName() { - final DataPlaneSelectorConfigurationServiceExtension extension = - new DataPlaneSelectorConfigurationServiceExtension(); - - Assertions.assertNotNull(extension.name()); - Assertions.assertEquals("Data Plane Selector Configuration Extension", extension.name()); - } - - @Test - void testInitialize() { - - final Config config = ConfigFactory.fromMap(getConfig()); - - Mockito.when(serviceExtensionContext.getConfig("edc.dataplane.selector")).thenReturn(config); - - extension.initialize(serviceExtensionContext); - - Mockito.verify(serviceExtensionContext, Mockito.times(1)) - .getService(DataPlaneSelectorService.class); - Mockito.verify(serviceExtensionContext, Mockito.times(1)).getMonitor(); - Mockito.when( - serviceExtensionContext.getConfig( - DataPlaneSelectorConfigurationServiceExtension.CONFIG_PREFIX)) - .thenReturn(config); - - Mockito.verify(dataPlaneSelectorService, Mockito.times(1)) - .addInstance( - Mockito.argThat( - dataPlaneInstance -> { - final DataAddress s3Source = - DataAddress.Builder.newInstance().type(S3_BUCKET).build(); - final DataAddress blobSource = - DataAddress.Builder.newInstance().type(BLOB_STORAGE).build(); - final DataAddress fsSink = - DataAddress.Builder.newInstance().type(LOCAL_FILE_SYSTEM).build(); - - final boolean matchingId = - dataPlaneInstance.getId().equals(DATA_PLANE_INSTANCE_ID); - final boolean matchingUrl = - dataPlaneInstance.getUrl().toString().equals(DATA_PLANE_INSTANCE_URL); - final boolean matchingCanHandleS3ToFileSystem = - dataPlaneInstance.canHandle(s3Source, fsSink); - final boolean matchingCanHandleBlobToFileSystem = - dataPlaneInstance.canHandle(blobSource, fsSink); - - if (!matchingId) - System.err.printf( - "Expected ID %s, but got %s%n", - DATA_PLANE_INSTANCE_ID, dataPlaneInstance.getId()); - if (!matchingUrl) - System.err.printf( - "Expected URL %s, but got %s%n", - DATA_PLANE_INSTANCE_URL, dataPlaneInstance.getUrl()); - if (!matchingCanHandleS3ToFileSystem) - System.err.printf( - "Expected Instance to be handle source %s and sink %s%n", - S3_BUCKET, LOCAL_FILE_SYSTEM); - if (!matchingCanHandleBlobToFileSystem) - System.err.printf( - "Expected Instance to be handle source %s and sink %s%n", - BLOB_STORAGE, LOCAL_FILE_SYSTEM); - - return matchingId - && matchingUrl - && matchingCanHandleS3ToFileSystem - && matchingCanHandleBlobToFileSystem; - })); - } - - @ParameterizedTest - @ArgumentsSource(MissingConfigArgumentsProvider.class) - void testWarningOnPropertyMissing(String configKey, String configValue) { - Map configMap = getConfig(); - configMap.put(configKey, configValue); - - final Config config = ConfigFactory.fromMap(configMap); - - Mockito.when( - serviceExtensionContext.getConfig( - DataPlaneSelectorConfigurationServiceExtension.CONFIG_PREFIX)) - .thenReturn(config); - - extension.initialize(serviceExtensionContext); - - // one warning config missing, one warning data plane instance skipped - Mockito.verify(monitor, Mockito.times(2)).warning(Mockito.anyString()); - } - - @Test - void throwsExceptionOnPropertiesNoJson() { - Map configMap = getConfig(); - configMap.put(propertiesKey, "no json"); - - final Config config = ConfigFactory.fromMap(configMap); - - Mockito.when( - serviceExtensionContext.getConfig( - DataPlaneSelectorConfigurationServiceExtension.CONFIG_PREFIX)) - .thenReturn(config); - - Assertions.assertThrows( - EdcException.class, () -> extension.initialize(serviceExtensionContext)); - } - - private static class MissingConfigArgumentsProvider implements ArgumentsProvider { - @Override - public Stream provideArguments(ExtensionContext context) { - return Stream.of( - Arguments.of(urlKey, ""), - Arguments.of(sourceTypesKey, ""), - Arguments.of(destinationTypesKey, ""), - Arguments.of(propertiesKey, "{}")); + "%s.%s", + DATA_PLANE_INSTANCE_ID, + DataPlaneSelectorConfigurationServiceExtension.SOURCE_TYPES_SUFFIX); + private static final String DESTINATION_TYPES_KEY = + String.format( + "%s.%s", + DATA_PLANE_INSTANCE_ID, + DataPlaneSelectorConfigurationServiceExtension.DESTINATION_TYPES_SUFFIX); + private static final String PROPERTIES_KEY = + String.format( + "%s.%s", + DATA_PLANE_INSTANCE_ID, DataPlaneSelectorConfigurationServiceExtension.PROPERTIES_SUFFIX); + + private DataPlaneSelectorConfigurationServiceExtension extension; + + // mocks + private ServiceExtensionContext serviceExtensionContext; + private DataPlaneSelectorService dataPlaneSelectorService; + private Monitor monitor; + + @BeforeEach + void setup() { + extension = new DataPlaneSelectorConfigurationServiceExtension(); + + serviceExtensionContext = Mockito.mock(ServiceExtensionContext.class); + dataPlaneSelectorService = Mockito.mock(DataPlaneSelectorService.class); + monitor = Mockito.mock(Monitor.class); + + Mockito.when(serviceExtensionContext.getService(DataPlaneSelectorService.class)) + .thenReturn(dataPlaneSelectorService); + Mockito.when(serviceExtensionContext.getMonitor()).thenReturn(monitor); + } + + private Map getConfig() { + return new HashMap<>() { + { + put(URL_KEY, DATA_PLANE_INSTANCE_URL); + put(SOURCE_TYPES_KEY, DATA_PLANE_INSTANCE_SOURCE_TYPES); + put(DESTINATION_TYPES_KEY, DATA_PLANE_INSTANCE_DESTINATION_TYPES); + put( + PROPERTIES_KEY, + String.format( + "{ \"%s\": \"%s\" }", + DataPlaneSelectorConfigurationServiceExtension.PUBLIC_API_URL_PROPERTY, + DATA_PLANE_INSTANCE_URL)); + } + }; + } + + @Test + void testName() { + final DataPlaneSelectorConfigurationServiceExtension extension = + new DataPlaneSelectorConfigurationServiceExtension(); + + Assertions.assertNotNull(extension.name()); + Assertions.assertEquals("Data Plane Selector Configuration Extension", extension.name()); + } + + @Test + void testInitialize() { + + final Config config = ConfigFactory.fromMap(getConfig()); + + Mockito.when(serviceExtensionContext.getConfig("edc.dataplane.selector")).thenReturn(config); + + extension.initialize(serviceExtensionContext); + + Mockito.verify(serviceExtensionContext, Mockito.times(1)) + .getService(DataPlaneSelectorService.class); + Mockito.verify(serviceExtensionContext, Mockito.times(1)).getMonitor(); + Mockito.when( + serviceExtensionContext.getConfig( + DataPlaneSelectorConfigurationServiceExtension.CONFIG_PREFIX)) + .thenReturn(config); + + Mockito.verify(dataPlaneSelectorService, Mockito.times(1)) + .addInstance( + Mockito.argThat( + dataPlaneInstance -> { + final DataAddress s3Source = + DataAddress.Builder.newInstance().type(S3_BUCKET).build(); + final DataAddress blobSource = + DataAddress.Builder.newInstance().type(BLOB_STORAGE).build(); + final DataAddress fsSink = + DataAddress.Builder.newInstance().type(LOCAL_FILE_SYSTEM).build(); + + final boolean matchingId = + dataPlaneInstance.getId().equals(DATA_PLANE_INSTANCE_ID); + final boolean matchingUrl = + dataPlaneInstance.getUrl().toString().equals(DATA_PLANE_INSTANCE_URL); + final boolean matchingCanHandleS3ToFileSystem = + dataPlaneInstance.canHandle(s3Source, fsSink); + final boolean matchingCanHandleBlobToFileSystem = + dataPlaneInstance.canHandle(blobSource, fsSink); + + if (!matchingId) { + System.err.printf( + "Expected ID %s, but got %s%n", + DATA_PLANE_INSTANCE_ID, dataPlaneInstance.getId()); + } + if (!matchingUrl) { + System.err.printf( + "Expected URL %s, but got %s%n", + DATA_PLANE_INSTANCE_URL, dataPlaneInstance.getUrl()); + } + if (!matchingCanHandleS3ToFileSystem) { + System.err.printf( + "Expected Instance to be handle source %s and sink %s%n", + S3_BUCKET, LOCAL_FILE_SYSTEM); + } + if (!matchingCanHandleBlobToFileSystem) { + System.err.printf( + "Expected Instance to be handle source %s and sink %s%n", + BLOB_STORAGE, LOCAL_FILE_SYSTEM); + } + + return matchingId && + matchingUrl && + matchingCanHandleS3ToFileSystem && + matchingCanHandleBlobToFileSystem; + })); + } + + @ParameterizedTest + @ArgumentsSource(MissingConfigArgumentsProvider.class) + void testWarningOnPropertyMissing(String configKey, String configValue) { + Map configMap = getConfig(); + configMap.put(configKey, configValue); + + final Config config = ConfigFactory.fromMap(configMap); + + Mockito.when( + serviceExtensionContext.getConfig( + DataPlaneSelectorConfigurationServiceExtension.CONFIG_PREFIX)) + .thenReturn(config); + + extension.initialize(serviceExtensionContext); + + // one warning config missing, one warning data plane instance skipped + Mockito.verify(monitor, Mockito.times(2)).warning(Mockito.anyString()); + } + + @Test + void throwsExceptionOnPropertiesNoJson() { + Map configMap = getConfig(); + configMap.put(PROPERTIES_KEY, "no json"); + + final Config config = ConfigFactory.fromMap(configMap); + + Mockito.when( + serviceExtensionContext.getConfig( + DataPlaneSelectorConfigurationServiceExtension.CONFIG_PREFIX)) + .thenReturn(config); + + Assertions.assertThrows( + EdcException.class, () -> extension.initialize(serviceExtensionContext)); + } + + private static class MissingConfigArgumentsProvider implements ArgumentsProvider { + @Override + public Stream provideArguments(ExtensionContext context) { + return Stream.of( + Arguments.of(URL_KEY, ""), + Arguments.of(SOURCE_TYPES_KEY, ""), + Arguments.of(DESTINATION_TYPES_KEY, ""), + Arguments.of(PROPERTIES_KEY, "{}")); + } } - } } diff --git a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/AbstractHashicorpVaultExtension.java b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/AbstractHashicorpVaultExtension.java index dae92725f..d1a09da4a 100644 --- a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/AbstractHashicorpVaultExtension.java +++ b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/AbstractHashicorpVaultExtension.java @@ -20,78 +20,79 @@ package org.eclipse.tractusx.edc.hashicorpvault; -import java.time.Duration; import okhttp3.OkHttpClient; import org.eclipse.edc.spi.system.ServiceExtensionContext; +import java.time.Duration; + /** * Temporary solution as long as the Vault components needs to be loaded as dedicated vault * extension. Will be changed from EDC milestone 5. */ public class AbstractHashicorpVaultExtension { - public static final String VAULT_URL = "edc.vault.hashicorp.url"; + public static final String VAULT_URL = "edc.vault.hashicorp.url"; - public static final String VAULT_TOKEN = "edc.vault.hashicorp.token"; + public static final String VAULT_TOKEN = "edc.vault.hashicorp.token"; - public static final String VAULT_API_SECRET_PATH = "edc.vault.hashicorp.api.secret.path"; + public static final String VAULT_API_SECRET_PATH = "edc.vault.hashicorp.api.secret.path"; - public static final String VAULT_API_SECRET_PATH_DEFAULT = "/v1/secret"; + public static final String VAULT_API_SECRET_PATH_DEFAULT = "/v1/secret"; - public static final String VAULT_API_HEALTH_PATH = "edc.vault.hashicorp.api.health.check.path"; + public static final String VAULT_API_HEALTH_PATH = "edc.vault.hashicorp.api.health.check.path"; - public static final String VAULT_API_HEALTH_PATH_DEFAULT = "/v1/sys/health"; + public static final String VAULT_API_HEALTH_PATH_DEFAULT = "/v1/sys/health"; - public static final String VAULT_HEALTH_CHECK_STANDBY_OK = - "edc.vault.hashicorp.health.check.standby.ok"; + public static final String VAULT_HEALTH_CHECK_STANDBY_OK = + "edc.vault.hashicorp.health.check.standby.ok"; - public static final boolean VAULT_HEALTH_CHECK_STANDBY_OK_DEFAULT = false; + public static final boolean VAULT_HEALTH_CHECK_STANDBY_OK_DEFAULT = false; - private static final String VAULT_TIMEOUT_SECONDS = "edc.vault.hashicorp.timeout.seconds"; + private static final String VAULT_TIMEOUT_SECONDS = "edc.vault.hashicorp.timeout.seconds"; - protected OkHttpClient createOkHttpClient(HashicorpVaultClientConfig config) { - OkHttpClient.Builder builder = - new OkHttpClient.Builder() - .callTimeout(config.getTimeout()) - .readTimeout(config.getTimeout()); + protected OkHttpClient createOkHttpClient(HashicorpVaultClientConfig config) { + OkHttpClient.Builder builder = + new OkHttpClient.Builder() + .callTimeout(config.getTimeout()) + .readTimeout(config.getTimeout()); - return builder.build(); - } + return builder.build(); + } - protected HashicorpVaultClientConfig loadHashicorpVaultClientConfig( - ServiceExtensionContext context) { + protected HashicorpVaultClientConfig loadHashicorpVaultClientConfig( + ServiceExtensionContext context) { - final String vaultUrl = context.getSetting(VAULT_URL, null); - if (vaultUrl == null) { - throw new HashicorpVaultException(String.format("Vault URL (%s) must be defined", VAULT_URL)); - } + final String vaultUrl = context.getSetting(VAULT_URL, null); + if (vaultUrl == null) { + throw new HashicorpVaultException(String.format("Vault URL (%s) must be defined", VAULT_URL)); + } - final int vaultTimeoutSeconds = Math.max(0, context.getSetting(VAULT_TIMEOUT_SECONDS, 30)); - final Duration vaultTimeoutDuration = Duration.ofSeconds(vaultTimeoutSeconds); + final int vaultTimeoutSeconds = Math.max(0, context.getSetting(VAULT_TIMEOUT_SECONDS, 30)); + final Duration vaultTimeoutDuration = Duration.ofSeconds(vaultTimeoutSeconds); - final String vaultToken = context.getSetting(VAULT_TOKEN, null); + final String vaultToken = context.getSetting(VAULT_TOKEN, null); - if (vaultToken == null) { - throw new HashicorpVaultException( - String.format("For Vault authentication [%s] is required", VAULT_TOKEN)); - } + if (vaultToken == null) { + throw new HashicorpVaultException( + String.format("For Vault authentication [%s] is required", VAULT_TOKEN)); + } - final String apiSecretPath = - context.getSetting(VAULT_API_SECRET_PATH, VAULT_API_SECRET_PATH_DEFAULT); + final String apiSecretPath = + context.getSetting(VAULT_API_SECRET_PATH, VAULT_API_SECRET_PATH_DEFAULT); - final String apiHealthPath = - context.getSetting(VAULT_API_HEALTH_PATH, VAULT_API_HEALTH_PATH_DEFAULT); + final String apiHealthPath = + context.getSetting(VAULT_API_HEALTH_PATH, VAULT_API_HEALTH_PATH_DEFAULT); - final boolean isHealthStandbyOk = - context.getSetting(VAULT_HEALTH_CHECK_STANDBY_OK, VAULT_HEALTH_CHECK_STANDBY_OK_DEFAULT); + final boolean isHealthStandbyOk = + context.getSetting(VAULT_HEALTH_CHECK_STANDBY_OK, VAULT_HEALTH_CHECK_STANDBY_OK_DEFAULT); - return HashicorpVaultClientConfig.builder() - .vaultUrl(vaultUrl) - .vaultToken(vaultToken) - .vaultApiSecretPath(apiSecretPath) - .vaultApiHealthPath(apiHealthPath) - .isVaultApiHealthStandbyOk(isHealthStandbyOk) - .timeout(vaultTimeoutDuration) - .build(); - } + return HashicorpVaultClientConfig.builder() + .vaultUrl(vaultUrl) + .vaultToken(vaultToken) + .vaultApiSecretPath(apiSecretPath) + .vaultApiHealthPath(apiHealthPath) + .isVaultApiHealthStandbyOk(isHealthStandbyOk) + .timeout(vaultTimeoutDuration) + .build(); + } } diff --git a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpCertificateResolver.java b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpCertificateResolver.java index ed807cbb8..c5a33b67a 100644 --- a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpCertificateResolver.java +++ b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpCertificateResolver.java @@ -20,11 +20,6 @@ package org.eclipse.tractusx.edc.hashicorpvault; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.security.cert.X509Certificate; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.eclipse.edc.spi.EdcException; @@ -32,28 +27,38 @@ import org.eclipse.edc.spi.security.CertificateResolver; import org.eclipse.edc.spi.security.Vault; -/** Resolves an X.509 certificate in Hashicorp vault. */ +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.cert.X509Certificate; + +/** + * Resolves an X.509 certificate in Hashicorp vault. + */ @RequiredArgsConstructor public class HashicorpCertificateResolver implements CertificateResolver { - @NonNull private final Vault vault; - @NonNull private final Monitor monitor; + @NonNull + private final Vault vault; + @NonNull + private final Monitor monitor; - @Override - public X509Certificate resolveCertificate(@NonNull String id) { - String certificateRepresentation = vault.resolveSecret(id); - if (certificateRepresentation == null) { - return null; - } - try (InputStream inputStream = - new ByteArrayInputStream(certificateRepresentation.getBytes(StandardCharsets.UTF_8))) { - X509Certificate x509Certificate = PemUtil.readX509Certificate(inputStream); - if (x509Certificate == null) { - monitor.warning( - String.format("Expected PEM certificate on key %s, but value not PEM.", id)); - } - return x509Certificate; - } catch (IOException e) { - throw new EdcException(e.getMessage(), e); + @Override + public X509Certificate resolveCertificate(@NonNull String id) { + String certificateRepresentation = vault.resolveSecret(id); + if (certificateRepresentation == null) { + return null; + } + try (InputStream inputStream = + new ByteArrayInputStream(certificateRepresentation.getBytes(StandardCharsets.UTF_8))) { + X509Certificate x509Certificate = PemUtil.readX509Certificate(inputStream); + if (x509Certificate == null) { + monitor.warning( + String.format("Expected PEM certificate on key %s, but value not PEM.", id)); + } + return x509Certificate; + } catch (IOException e) { + throw new EdcException(e.getMessage(), e); + } } - } } diff --git a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVault.java b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVault.java index e8a59937a..2e0dac9c2 100644 --- a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVault.java +++ b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVault.java @@ -28,31 +28,35 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -/** Implements a vault backed by Hashicorp Vault. */ +/** + * Implements a vault backed by Hashicorp Vault. + */ @RequiredArgsConstructor class HashicorpVault implements Vault { - @NonNull private final HashicorpVaultClient hashicorpVaultClient; - @NonNull private final Monitor monitor; + @NonNull + private final HashicorpVaultClient hashicorpVaultClient; + @NonNull + private final Monitor monitor; - @Override - public @Nullable String resolveSecret(@NonNull String key) { - Result result = hashicorpVaultClient.getSecretValue(key); + @Override + public @Nullable String resolveSecret(@NonNull String key) { + Result result = hashicorpVaultClient.getSecretValue(key); - return result.succeeded() ? result.getContent() : null; - } + return result.succeeded() ? result.getContent() : null; + } - @Override - @NotNull - public Result storeSecret(@NotNull @NonNull String key, @NotNull @NonNull String value) { - Result result = - hashicorpVaultClient.setSecret(key, value); + @Override + @NotNull + public Result storeSecret(@NotNull @NonNull String key, @NotNull @NonNull String value) { + Result result = + hashicorpVaultClient.setSecret(key, value); - return result.succeeded() ? Result.success() : Result.failure(result.getFailureMessages()); - } + return result.succeeded() ? Result.success() : Result.failure(result.getFailureMessages()); + } - @Override - public Result deleteSecret(@NotNull @NonNull String key) { - return hashicorpVaultClient.destroySecret(key); - } + @Override + public Result deleteSecret(@NotNull @NonNull String key) { + return hashicorpVaultClient.destroySecret(key); + } } diff --git a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultClient.java b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultClient.java index 850c33243..004e08bc7 100644 --- a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultClient.java +++ b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultClient.java @@ -23,11 +23,6 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.Objects; import lombok.NonNull; import lombok.RequiredArgsConstructor; import okhttp3.Headers; @@ -40,164 +35,173 @@ import org.eclipse.edc.spi.result.Result; import org.jetbrains.annotations.NotNull; +import java.io.IOException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.Objects; + @RequiredArgsConstructor class HashicorpVaultClient { - static final String VAULT_DATA_ENTRY_NAME = "content"; - private static final String VAULT_TOKEN_HEADER = "X-Vault-Token"; - private static final String VAULT_REQUEST_HEADER = "X-Vault-Request"; - private static final String VAULT_SECRET_DATA_PATH = "data"; - private static final String VAULT_SECRET_METADATA_PATH = "metadata"; - private static final MediaType MEDIA_TYPE_APPLICATION_JSON = MediaType.get("application/json"); - private static final String CALL_UNSUCCESSFUL_ERROR_TEMPLATE = "Call unsuccessful: %s"; - - @NonNull private final HashicorpVaultClientConfig config; - @NonNull private final OkHttpClient okHttpClient; - @NonNull private final ObjectMapper objectMapper; - - Result getSecretValue(@NonNull String key) { - HttpUrl requestURI = getSecretUrl(key, VAULT_SECRET_DATA_PATH); - Headers headers = getHeaders(); - Request request = new Request.Builder().url(requestURI).headers(headers).get().build(); - - try (Response response = okHttpClient.newCall(request).execute()) { - - if (response.code() == 404) { - return Result.failure(String.format(CALL_UNSUCCESSFUL_ERROR_TEMPLATE, "Secret not found")); - } - - if (response.isSuccessful()) { - String responseBody = Objects.requireNonNull(response.body()).string(); - HashicorpVaultGetEntryResponsePayload payload = - objectMapper.readValue(responseBody, HashicorpVaultGetEntryResponsePayload.class); - String value = - Objects.requireNonNull(payload.getData().getData().get(VAULT_DATA_ENTRY_NAME)); - - return Result.success(value); - } else { - return Result.failure(String.format(CALL_UNSUCCESSFUL_ERROR_TEMPLATE, response.code())); - } - - } catch (IOException e) { - return Result.failure(e.getMessage()); + static final String VAULT_DATA_ENTRY_NAME = "content"; + private static final String VAULT_TOKEN_HEADER = "X-Vault-Token"; + private static final String VAULT_REQUEST_HEADER = "X-Vault-Request"; + private static final String VAULT_SECRET_DATA_PATH = "data"; + private static final String VAULT_SECRET_METADATA_PATH = "metadata"; + private static final MediaType MEDIA_TYPE_APPLICATION_JSON = MediaType.get("application/json"); + private static final String CALL_UNSUCCESSFUL_ERROR_TEMPLATE = "Call unsuccessful: %s"; + + @NonNull + private final HashicorpVaultClientConfig config; + @NonNull + private final OkHttpClient okHttpClient; + @NonNull + private final ObjectMapper objectMapper; + + Result getSecretValue(@NonNull String key) { + HttpUrl requestUri = getSecretUrl(key, VAULT_SECRET_DATA_PATH); + Headers headers = getHeaders(); + Request request = new Request.Builder().url(requestUri).headers(headers).get().build(); + + try (Response response = okHttpClient.newCall(request).execute()) { + + if (response.code() == 404) { + return Result.failure(String.format(CALL_UNSUCCESSFUL_ERROR_TEMPLATE, "Secret not found")); + } + + if (response.isSuccessful()) { + String responseBody = Objects.requireNonNull(response.body()).string(); + HashicorpVaultGetEntryResponsePayload payload = + objectMapper.readValue(responseBody, HashicorpVaultGetEntryResponsePayload.class); + String value = + Objects.requireNonNull(payload.getData().getData().get(VAULT_DATA_ENTRY_NAME)); + + return Result.success(value); + } else { + return Result.failure(String.format(CALL_UNSUCCESSFUL_ERROR_TEMPLATE, response.code())); + } + + } catch (IOException e) { + return Result.failure(e.getMessage()); + } } - } - - public HashicorpVaultHealthResponse getHealth() throws IOException { - - HashicorpVaultHealthResponse.HashicorpVaultHealthResponseBuilder healthResponseBuilder = - HashicorpVaultHealthResponse.builder(); - - HttpUrl requestURI = getHealthUrl(); - Headers headers = getHeaders(); - Request request = new Request.Builder().url(requestURI).headers(headers).get().build(); - try (Response response = okHttpClient.newCall(request).execute()) { - final int code = response.code(); - healthResponseBuilder.code(code); - - try { - String responseBody = Objects.requireNonNull(response.body()).string(); - HashicorpVaultHealthResponsePayload responsePayload = - objectMapper.readValue(responseBody, HashicorpVaultHealthResponsePayload.class); - healthResponseBuilder.payload(responsePayload); - } catch (JsonMappingException e) { - // ignore. status code not checked, so it may be possible that no payload was - // provided - } + + public HashicorpVaultHealthResponse getHealth() throws IOException { + + HashicorpVaultHealthResponse.HashicorpVaultHealthResponseBuilder healthResponseBuilder = + HashicorpVaultHealthResponse.builder(); + + HttpUrl requestUri = getHealthUrl(); + Headers headers = getHeaders(); + Request request = new Request.Builder().url(requestUri).headers(headers).get().build(); + try (Response response = okHttpClient.newCall(request).execute()) { + final int code = response.code(); + healthResponseBuilder.code(code); + + try { + String responseBody = Objects.requireNonNull(response.body()).string(); + HashicorpVaultHealthResponsePayload responsePayload = + objectMapper.readValue(responseBody, HashicorpVaultHealthResponsePayload.class); + healthResponseBuilder.payload(responsePayload); + } catch (JsonMappingException e) { + // ignore. status code not checked, so it may be possible that no payload was + // provided + } + } + + return healthResponseBuilder.build(); } - return healthResponseBuilder.build(); - } - - Result setSecret( - @NonNull String key, @NonNull String value) { - HttpUrl requestURI = getSecretUrl(key, VAULT_SECRET_DATA_PATH); - Headers headers = getHeaders(); - HashicorpVaultCreateEntryRequestPayload requestPayload = - HashicorpVaultCreateEntryRequestPayload.builder() - .data(Collections.singletonMap(VAULT_DATA_ENTRY_NAME, value)) - .build(); - Request request = - new Request.Builder() - .url(requestURI) - .headers(headers) - .post(createRequestBody(requestPayload)) - .build(); - - try (Response response = okHttpClient.newCall(request).execute()) { - if (response.isSuccessful()) { - String responseBody = Objects.requireNonNull(response.body()).string(); - HashicorpVaultCreateEntryResponsePayload responsePayload = - objectMapper.readValue(responseBody, HashicorpVaultCreateEntryResponsePayload.class); - return Result.success(responsePayload); - } else { - return Result.failure(String.format(CALL_UNSUCCESSFUL_ERROR_TEMPLATE, response.code())); - } - } catch (IOException e) { - return Result.failure(e.getMessage()); + Result setSecret( + @NonNull String key, @NonNull String value) { + HttpUrl requestUri = getSecretUrl(key, VAULT_SECRET_DATA_PATH); + Headers headers = getHeaders(); + HashicorpVaultCreateEntryRequestPayload requestPayload = + HashicorpVaultCreateEntryRequestPayload.builder() + .data(Collections.singletonMap(VAULT_DATA_ENTRY_NAME, value)) + .build(); + Request request = + new Request.Builder() + .url(requestUri) + .headers(headers) + .post(createRequestBody(requestPayload)) + .build(); + + try (Response response = okHttpClient.newCall(request).execute()) { + if (response.isSuccessful()) { + String responseBody = Objects.requireNonNull(response.body()).string(); + HashicorpVaultCreateEntryResponsePayload responsePayload = + objectMapper.readValue(responseBody, HashicorpVaultCreateEntryResponsePayload.class); + return Result.success(responsePayload); + } else { + return Result.failure(String.format(CALL_UNSUCCESSFUL_ERROR_TEMPLATE, response.code())); + } + } catch (IOException e) { + return Result.failure(e.getMessage()); + } } - } - - Result destroySecret(@NonNull String key) { - HttpUrl requestURI = getSecretUrl(key, VAULT_SECRET_METADATA_PATH); - Headers headers = getHeaders(); - Request request = new Request.Builder().url(requestURI).headers(headers).delete().build(); - - try (Response response = okHttpClient.newCall(request).execute()) { - return response.isSuccessful() || response.code() == 404 - ? Result.success() - : Result.failure(String.format(CALL_UNSUCCESSFUL_ERROR_TEMPLATE, response.code())); - } catch (IOException e) { - return Result.failure(e.getMessage()); + + Result destroySecret(@NonNull String key) { + HttpUrl requestUri = getSecretUrl(key, VAULT_SECRET_METADATA_PATH); + Headers headers = getHeaders(); + Request request = new Request.Builder().url(requestUri).headers(headers).delete().build(); + + try (Response response = okHttpClient.newCall(request).execute()) { + return response.isSuccessful() || response.code() == 404 + ? Result.success() + : Result.failure(String.format(CALL_UNSUCCESSFUL_ERROR_TEMPLATE, response.code())); + } catch (IOException e) { + return Result.failure(e.getMessage()); + } } - } - - @NotNull - private Headers getHeaders() { - return new Headers.Builder() - .add(VAULT_REQUEST_HEADER, Boolean.toString(true)) - .add(VAULT_TOKEN_HEADER, config.getVaultToken()) - .build(); - } - - private HttpUrl getSecretUrl(String key, String entryType) { - key = URLEncoder.encode(key, StandardCharsets.UTF_8); - - // restore '/' characters to allow sub-directories - key = key.replace("%2F", "/"); - - final String vaultApiPath = config.getVaultApiSecretPath(); - - return Objects.requireNonNull(HttpUrl.parse(config.getVaultUrl())) - .newBuilder() - .addPathSegments(PathUtil.trimLeadingOrEndingSlash(vaultApiPath)) - .addPathSegment(entryType) - .addPathSegments(key) - .build(); - } - - private HttpUrl getHealthUrl() { - final String vaultHealthPath = config.getVaultApiHealthPath(); - final boolean isVaultHealthStandbyOk = config.isVaultApiHealthStandbyOk(); - - // by setting 'standbyok' and/or 'perfstandbyok' the vault will return an active - // status - // code instead of the standby status codes - - return Objects.requireNonNull(HttpUrl.parse(config.getVaultUrl())) - .newBuilder() - .addPathSegments(PathUtil.trimLeadingOrEndingSlash(vaultHealthPath)) - .addQueryParameter("standbyok", isVaultHealthStandbyOk ? "true" : "false") - .addQueryParameter("perfstandbyok", isVaultHealthStandbyOk ? "true" : "false") - .build(); - } - - private RequestBody createRequestBody(Object requestPayload) { - String jsonRepresentation; - try { - jsonRepresentation = objectMapper.writeValueAsString(requestPayload); - } catch (JsonProcessingException e) { - throw new HashicorpVaultException(e.getMessage(), e); + + @NotNull + private Headers getHeaders() { + return new Headers.Builder() + .add(VAULT_REQUEST_HEADER, Boolean.toString(true)) + .add(VAULT_TOKEN_HEADER, config.getVaultToken()) + .build(); + } + + private HttpUrl getSecretUrl(String key, String entryType) { + key = URLEncoder.encode(key, StandardCharsets.UTF_8); + + // restore '/' characters to allow sub-directories + key = key.replace("%2F", "/"); + + final String vaultApiPath = config.getVaultApiSecretPath(); + + return Objects.requireNonNull(HttpUrl.parse(config.getVaultUrl())) + .newBuilder() + .addPathSegments(PathUtil.trimLeadingOrEndingSlash(vaultApiPath)) + .addPathSegment(entryType) + .addPathSegments(key) + .build(); + } + + private HttpUrl getHealthUrl() { + final String vaultHealthPath = config.getVaultApiHealthPath(); + final boolean isVaultHealthStandbyOk = config.isVaultApiHealthStandbyOk(); + + // by setting 'standbyok' and/or 'perfstandbyok' the vault will return an active + // status + // code instead of the standby status codes + + return Objects.requireNonNull(HttpUrl.parse(config.getVaultUrl())) + .newBuilder() + .addPathSegments(PathUtil.trimLeadingOrEndingSlash(vaultHealthPath)) + .addQueryParameter("standbyok", isVaultHealthStandbyOk ? "true" : "false") + .addQueryParameter("perfstandbyok", isVaultHealthStandbyOk ? "true" : "false") + .build(); + } + + private RequestBody createRequestBody(Object requestPayload) { + String jsonRepresentation; + try { + jsonRepresentation = objectMapper.writeValueAsString(requestPayload); + } catch (JsonProcessingException e) { + throw new HashicorpVaultException(e.getMessage(), e); + } + return RequestBody.create(jsonRepresentation, MEDIA_TYPE_APPLICATION_JSON); } - return RequestBody.create(jsonRepresentation, MEDIA_TYPE_APPLICATION_JSON); - } } diff --git a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultClientConfig.java b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultClientConfig.java index 495d6937c..2c070ceb2 100644 --- a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultClientConfig.java +++ b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultClientConfig.java @@ -20,21 +20,27 @@ package org.eclipse.tractusx.edc.hashicorpvault; -import java.time.Duration; import lombok.Builder; import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; +import java.time.Duration; + @Builder @Getter @RequiredArgsConstructor class HashicorpVaultClientConfig { - @NonNull private final String vaultUrl; - @NonNull private final String vaultToken; - @NonNull private final String vaultApiSecretPath; - @NonNull private final String vaultApiHealthPath; - @NonNull private final Duration timeout; + @NonNull + private final String vaultUrl; + @NonNull + private final String vaultToken; + @NonNull + private final String vaultApiSecretPath; + @NonNull + private final String vaultApiHealthPath; + @NonNull + private final Duration timeout; - private final boolean isVaultApiHealthStandbyOk; + private final boolean isVaultApiHealthStandbyOk; } diff --git a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultCreateEntryRequestPayload.java b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultCreateEntryRequestPayload.java index fa31d7149..e08066df0 100644 --- a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultCreateEntryRequestPayload.java +++ b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultCreateEntryRequestPayload.java @@ -22,12 +22,13 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; -import java.util.Map; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; +import java.util.Map; + @Builder @NoArgsConstructor @AllArgsConstructor @@ -35,19 +36,19 @@ @JsonIgnoreProperties(ignoreUnknown = true) class HashicorpVaultCreateEntryRequestPayload { - @JsonProperty("options") - private Options options; + @JsonProperty("options") + private Options options; - @JsonProperty("data") - private Map data; + @JsonProperty("data") + private Map data; - @Builder - @NoArgsConstructor - @AllArgsConstructor - @Data - @JsonIgnoreProperties(ignoreUnknown = true) - static class Options { - @JsonProperty("cas") - private Integer cas; - } + @Builder + @NoArgsConstructor + @AllArgsConstructor + @Data + @JsonIgnoreProperties(ignoreUnknown = true) + static class Options { + @JsonProperty("cas") + private Integer cas; + } } diff --git a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultCreateEntryResponsePayload.java b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultCreateEntryResponsePayload.java index 77ab76772..b010f4819 100644 --- a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultCreateEntryResponsePayload.java +++ b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultCreateEntryResponsePayload.java @@ -34,6 +34,6 @@ @JsonIgnoreProperties(ignoreUnknown = true) class HashicorpVaultCreateEntryResponsePayload { - @JsonProperty("data") - private HashicorpVaultEntryMetadata data; + @JsonProperty("data") + private HashicorpVaultEntryMetadata data; } diff --git a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultEntryMetadata.java b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultEntryMetadata.java index bd59309c9..0cbe726eb 100644 --- a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultEntryMetadata.java +++ b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultEntryMetadata.java @@ -22,12 +22,13 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; -import java.util.Map; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; +import java.util.Map; + @Builder @NoArgsConstructor @AllArgsConstructor @@ -35,12 +36,12 @@ @JsonIgnoreProperties(ignoreUnknown = true) class HashicorpVaultEntryMetadata { - @JsonProperty("custom_metadata") - private Map customMetadata; + @JsonProperty("custom_metadata") + private Map customMetadata; - @JsonProperty("destroyed") - private Boolean destroyed; + @JsonProperty("destroyed") + private Boolean destroyed; - @JsonProperty("version") - private Integer version; + @JsonProperty("version") + private Integer version; } diff --git a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultException.java b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultException.java index bd3c60549..8488cfa34 100644 --- a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultException.java +++ b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultException.java @@ -24,11 +24,11 @@ public class HashicorpVaultException extends EdcException { - public HashicorpVaultException(String message) { - super(message); - } + public HashicorpVaultException(String message) { + super(message); + } - public HashicorpVaultException(String message, Throwable cause) { - super(message, cause); - } + public HashicorpVaultException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultGetEntryResponsePayload.java b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultGetEntryResponsePayload.java index 175c73d47..780d29a8b 100644 --- a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultGetEntryResponsePayload.java +++ b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultGetEntryResponsePayload.java @@ -22,12 +22,13 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; -import java.util.Map; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; +import java.util.Map; + @Builder @NoArgsConstructor @AllArgsConstructor @@ -35,20 +36,20 @@ @JsonIgnoreProperties(ignoreUnknown = true) class HashicorpVaultGetEntryResponsePayload { - @JsonProperty("data") - private GetVaultEntryData data; + @JsonProperty("data") + private GetVaultEntryData data; - @Builder - @NoArgsConstructor - @AllArgsConstructor - @Data - @JsonIgnoreProperties(ignoreUnknown = true) - static class GetVaultEntryData { + @Builder + @NoArgsConstructor + @AllArgsConstructor + @Data + @JsonIgnoreProperties(ignoreUnknown = true) + static class GetVaultEntryData { - @JsonProperty("data") - private Map data; + @JsonProperty("data") + private Map data; - @JsonProperty("metadata") - private HashicorpVaultEntryMetadata metadata; - } + @JsonProperty("metadata") + private HashicorpVaultEntryMetadata metadata; + } } diff --git a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthCheck.java b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthCheck.java index 9834b0d03..6e918e160 100644 --- a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthCheck.java +++ b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthCheck.java @@ -14,7 +14,6 @@ package org.eclipse.tractusx.edc.hashicorpvault; -import java.io.IOException; import lombok.RequiredArgsConstructor; import org.eclipse.edc.spi.monitor.Monitor; import org.eclipse.edc.spi.system.health.HealthCheckResult; @@ -22,73 +21,75 @@ import org.eclipse.edc.spi.system.health.ReadinessProvider; import org.eclipse.edc.spi.system.health.StartupStatusProvider; +import java.io.IOException; + @RequiredArgsConstructor public class HashicorpVaultHealthCheck - implements ReadinessProvider, LivenessProvider, StartupStatusProvider { + implements ReadinessProvider, LivenessProvider, StartupStatusProvider { - private static final String HEALTH_CHECK_ERROR_TEMPLATE = - "HashiCorp Vault HealthCheck unsuccessful. %s %s"; + private static final String HEALTH_CHECK_ERROR_TEMPLATE = + "HashiCorp Vault HealthCheck unsuccessful. %s %s"; - private final HashicorpVaultClient client; - private final Monitor monitor; + private final HashicorpVaultClient client; + private final Monitor monitor; - @Override - public HealthCheckResult get() { + @Override + public HealthCheckResult get() { - try { - final HashicorpVaultHealthResponse response = client.getHealth(); + try { + final HashicorpVaultHealthResponse response = client.getHealth(); - switch (response.getCodeAsEnum()) { - case INITIALIZED_UNSEALED_AND_ACTIVE: - monitor.debug("HashiCorp Vault HealthCheck successful. " + response.getPayload()); - return HealthCheckResult.success(); - case UNSEALED_AND_STANDBY: - final String standbyMsg = - String.format( - HEALTH_CHECK_ERROR_TEMPLATE, "Vault is in standby", response.getPayload()); - monitor.warning(standbyMsg); - return HealthCheckResult.failed(standbyMsg); - case DISASTER_RECOVERY_MODE_REPLICATION_SECONDARY_AND_ACTIVE: - final String recoveryModeMsg = - String.format( - HEALTH_CHECK_ERROR_TEMPLATE, "Vault is in recovery mode", response.getPayload()); - monitor.warning(recoveryModeMsg); - return HealthCheckResult.failed(recoveryModeMsg); - case PERFORMANCE_STANDBY: - final String performanceStandbyMsg = - String.format( - HEALTH_CHECK_ERROR_TEMPLATE, - "Vault is in performance standby", - response.getPayload()); - monitor.warning(performanceStandbyMsg); - return HealthCheckResult.failed(performanceStandbyMsg); - case NOT_INITIALIZED: - final String notInitializedMsg = - String.format( - HEALTH_CHECK_ERROR_TEMPLATE, "Vault is not initialized", response.getPayload()); - monitor.warning(notInitializedMsg); - return HealthCheckResult.failed(notInitializedMsg); - case SEALED: - final String sealedMsg = - String.format(HEALTH_CHECK_ERROR_TEMPLATE, "Vault is sealed", response.getPayload()); - monitor.warning(sealedMsg); - return HealthCheckResult.failed(sealedMsg); - case UNSPECIFIED: - default: - final String unspecifiedMsg = - String.format( - HEALTH_CHECK_ERROR_TEMPLATE, - "Unspecified response from vault. Code: " + response.getCode(), - response.getPayload()); - monitor.warning(unspecifiedMsg); - return HealthCheckResult.failed(unspecifiedMsg); - } + switch (response.getCodeAsEnum()) { + case INITIALIZED_UNSEALED_AND_ACTIVE: + monitor.debug("HashiCorp Vault HealthCheck successful. " + response.getPayload()); + return HealthCheckResult.success(); + case UNSEALED_AND_STANDBY: + final String standbyMsg = + String.format( + HEALTH_CHECK_ERROR_TEMPLATE, "Vault is in standby", response.getPayload()); + monitor.warning(standbyMsg); + return HealthCheckResult.failed(standbyMsg); + case DISASTER_RECOVERY_MODE_REPLICATION_SECONDARY_AND_ACTIVE: + final String recoveryModeMsg = + String.format( + HEALTH_CHECK_ERROR_TEMPLATE, "Vault is in recovery mode", response.getPayload()); + monitor.warning(recoveryModeMsg); + return HealthCheckResult.failed(recoveryModeMsg); + case PERFORMANCE_STANDBY: + final String performanceStandbyMsg = + String.format( + HEALTH_CHECK_ERROR_TEMPLATE, + "Vault is in performance standby", + response.getPayload()); + monitor.warning(performanceStandbyMsg); + return HealthCheckResult.failed(performanceStandbyMsg); + case NOT_INITIALIZED: + final String notInitializedMsg = + String.format( + HEALTH_CHECK_ERROR_TEMPLATE, "Vault is not initialized", response.getPayload()); + monitor.warning(notInitializedMsg); + return HealthCheckResult.failed(notInitializedMsg); + case SEALED: + final String sealedMsg = + String.format(HEALTH_CHECK_ERROR_TEMPLATE, "Vault is sealed", response.getPayload()); + monitor.warning(sealedMsg); + return HealthCheckResult.failed(sealedMsg); + case UNSPECIFIED: + default: + final String unspecifiedMsg = + String.format( + HEALTH_CHECK_ERROR_TEMPLATE, + "Unspecified response from vault. Code: " + response.getCode(), + response.getPayload()); + monitor.warning(unspecifiedMsg); + return HealthCheckResult.failed(unspecifiedMsg); + } - } catch (IOException e) { - final String exceptionMsg = - String.format(HEALTH_CHECK_ERROR_TEMPLATE, "IOException: " + e.getMessage(), ""); - monitor.severe(exceptionMsg); - return HealthCheckResult.failed(exceptionMsg); + } catch (IOException e) { + final String exceptionMsg = + String.format(HEALTH_CHECK_ERROR_TEMPLATE, "IOException: " + e.getMessage(), ""); + monitor.severe(exceptionMsg); + return HealthCheckResult.failed(exceptionMsg); + } } - } } diff --git a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthExtension.java b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthExtension.java index 5b7cca1a3..f8b42242f 100644 --- a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthExtension.java +++ b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthExtension.java @@ -28,42 +28,42 @@ @Requires(HealthCheckService.class) public class HashicorpVaultHealthExtension extends AbstractHashicorpVaultExtension - implements ServiceExtension { + implements ServiceExtension { - public static final String VAULT_HEALTH_CHECK = "edc.vault.hashicorp.health.check.enabled"; + public static final String VAULT_HEALTH_CHECK = "edc.vault.hashicorp.health.check.enabled"; - public static final boolean VAULT_HEALTH_CHECK_DEFAULT = true; + public static final boolean VAULT_HEALTH_CHECK_DEFAULT = true; - @Override - public String name() { - return "Hashicorp Vault Health Check"; - } + @Override + public String name() { + return "Hashicorp Vault Health Check"; + } - @Override - public void initialize(ServiceExtensionContext context) { - final HashicorpVaultClientConfig config = loadHashicorpVaultClientConfig(context); + @Override + public void initialize(ServiceExtensionContext context) { + final HashicorpVaultClientConfig config = loadHashicorpVaultClientConfig(context); - final OkHttpClient okHttpClient = createOkHttpClient(config); + final OkHttpClient okHttpClient = createOkHttpClient(config); - final HashicorpVaultClient client = - new HashicorpVaultClient(config, okHttpClient, context.getTypeManager().getMapper()); + final HashicorpVaultClient client = + new HashicorpVaultClient(config, okHttpClient, context.getTypeManager().getMapper()); - configureHealthCheck(client, context); + configureHealthCheck(client, context); - context.getMonitor().info("HashicorpVaultExtension: health check initialization complete."); - } + context.getMonitor().info("HashicorpVaultExtension: health check initialization complete."); + } - private void configureHealthCheck(HashicorpVaultClient client, ServiceExtensionContext context) { - final boolean healthCheckEnabled = - context.getSetting(VAULT_HEALTH_CHECK, VAULT_HEALTH_CHECK_DEFAULT); - if (!healthCheckEnabled) return; + private void configureHealthCheck(HashicorpVaultClient client, ServiceExtensionContext context) { + final boolean healthCheckEnabled = + context.getSetting(VAULT_HEALTH_CHECK, VAULT_HEALTH_CHECK_DEFAULT); + if (!healthCheckEnabled) return; - final HashicorpVaultHealthCheck healthCheck = - new HashicorpVaultHealthCheck(client, context.getMonitor()); + final HashicorpVaultHealthCheck healthCheck = + new HashicorpVaultHealthCheck(client, context.getMonitor()); - final HealthCheckService healthCheckService = context.getService(HealthCheckService.class); - healthCheckService.addLivenessProvider(healthCheck); - healthCheckService.addReadinessProvider(healthCheck); - healthCheckService.addStartupStatusProvider(healthCheck); - } + final HealthCheckService healthCheckService = context.getService(HealthCheckService.class); + healthCheckService.addLivenessProvider(healthCheck); + healthCheckService.addReadinessProvider(healthCheck); + healthCheckService.addStartupStatusProvider(healthCheck); + } } diff --git a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthResponse.java b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthResponse.java index bbf991684..7e23a1ff2 100644 --- a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthResponse.java +++ b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthResponse.java @@ -22,38 +22,39 @@ @Getter public class HashicorpVaultHealthResponse { - @Nullable private HashicorpVaultHealthResponsePayload payload; + @Nullable + private HashicorpVaultHealthResponsePayload payload; - private int code; + private int code; - public HashiCorpVaultHealthResponseCode getCodeAsEnum() { - switch (code) { - case 200: - return HashicorpVaultHealthResponse.HashiCorpVaultHealthResponseCode - .INITIALIZED_UNSEALED_AND_ACTIVE; - case 429: - return HashicorpVaultHealthResponse.HashiCorpVaultHealthResponseCode.UNSEALED_AND_STANDBY; - case 472: - return HashicorpVaultHealthResponse.HashiCorpVaultHealthResponseCode - .DISASTER_RECOVERY_MODE_REPLICATION_SECONDARY_AND_ACTIVE; - case 473: - return HashicorpVaultHealthResponse.HashiCorpVaultHealthResponseCode.PERFORMANCE_STANDBY; - case 501: - return HashicorpVaultHealthResponse.HashiCorpVaultHealthResponseCode.NOT_INITIALIZED; - case 503: - return HashicorpVaultHealthResponse.HashiCorpVaultHealthResponseCode.SEALED; - default: - return HashicorpVaultHealthResponse.HashiCorpVaultHealthResponseCode.UNSPECIFIED; + public HashiCorpVaultHealthResponseCode getCodeAsEnum() { + switch (code) { + case 200: + return HashicorpVaultHealthResponse.HashiCorpVaultHealthResponseCode + .INITIALIZED_UNSEALED_AND_ACTIVE; + case 429: + return HashicorpVaultHealthResponse.HashiCorpVaultHealthResponseCode.UNSEALED_AND_STANDBY; + case 472: + return HashicorpVaultHealthResponse.HashiCorpVaultHealthResponseCode + .DISASTER_RECOVERY_MODE_REPLICATION_SECONDARY_AND_ACTIVE; + case 473: + return HashicorpVaultHealthResponse.HashiCorpVaultHealthResponseCode.PERFORMANCE_STANDBY; + case 501: + return HashicorpVaultHealthResponse.HashiCorpVaultHealthResponseCode.NOT_INITIALIZED; + case 503: + return HashicorpVaultHealthResponse.HashiCorpVaultHealthResponseCode.SEALED; + default: + return HashicorpVaultHealthResponse.HashiCorpVaultHealthResponseCode.UNSPECIFIED; + } } - } - public enum HashiCorpVaultHealthResponseCode { - UNSPECIFIED, // undefined status codes - INITIALIZED_UNSEALED_AND_ACTIVE, // status code 200 - UNSEALED_AND_STANDBY, // status code 429 - DISASTER_RECOVERY_MODE_REPLICATION_SECONDARY_AND_ACTIVE, // status code 472 - PERFORMANCE_STANDBY, // status code 473 - NOT_INITIALIZED, // status code 501 - SEALED // status code 503 - } + public enum HashiCorpVaultHealthResponseCode { + UNSPECIFIED, // undefined status codes + INITIALIZED_UNSEALED_AND_ACTIVE, // status code 200 + UNSEALED_AND_STANDBY, // status code 429 + DISASTER_RECOVERY_MODE_REPLICATION_SECONDARY_AND_ACTIVE, // status code 472 + PERFORMANCE_STANDBY, // status code 473 + NOT_INITIALIZED, // status code 501 + SEALED // status code 503 + } } diff --git a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthResponsePayload.java b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthResponsePayload.java index 67ef6533c..e34dde31d 100644 --- a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthResponsePayload.java +++ b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthResponsePayload.java @@ -29,33 +29,33 @@ @ToString @JsonIgnoreProperties(ignoreUnknown = true) public class HashicorpVaultHealthResponsePayload { - @JsonProperty("initialized") - private boolean isInitialized; + @JsonProperty("initialized") + private boolean isInitialized; - @JsonProperty("sealed") - private boolean isSealed; + @JsonProperty("sealed") + private boolean isSealed; - @JsonProperty("standby") - private boolean isStandby; + @JsonProperty("standby") + private boolean isStandby; - @JsonProperty("performance_standby") - private boolean isPerformanceStandby; + @JsonProperty("performance_standby") + private boolean isPerformanceStandby; - @JsonProperty("replication_performance_mode") - private String replicationPerformanceMode; + @JsonProperty("replication_performance_mode") + private String replicationPerformanceMode; - @JsonProperty("replication_dr_mode") - private String replicationDrMode; + @JsonProperty("replication_dr_mode") + private String replicationDrMode; - @JsonProperty("server_time_utc") - private long serverTimeUtc; + @JsonProperty("server_time_utc") + private long serverTimeUtc; - @JsonProperty("version") - private String version; + @JsonProperty("version") + private String version; - @JsonProperty("cluster_name") - private String clusterName; + @JsonProperty("cluster_name") + private String clusterName; - @JsonProperty("cluster_id") - private String clusterId; + @JsonProperty("cluster_id") + private String clusterId; } diff --git a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultVaultExtension.java b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultVaultExtension.java index d8b41b2c1..d9fdd0b75 100644 --- a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultVaultExtension.java +++ b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultVaultExtension.java @@ -31,31 +31,31 @@ @Provides({Vault.class, CertificateResolver.class, PrivateKeyResolver.class}) public class HashicorpVaultVaultExtension extends AbstractHashicorpVaultExtension - implements ServiceExtension { + implements ServiceExtension { - @Override - public String name() { - return "Hashicorp Vault"; - } + @Override + public String name() { + return "Hashicorp Vault"; + } - @Override - public void initialize(ServiceExtensionContext context) { - final HashicorpVaultClientConfig config = loadHashicorpVaultClientConfig(context); + @Override + public void initialize(ServiceExtensionContext context) { + final HashicorpVaultClientConfig config = loadHashicorpVaultClientConfig(context); - final OkHttpClient okHttpClient = createOkHttpClient(config); + final OkHttpClient okHttpClient = createOkHttpClient(config); - final HashicorpVaultClient client = - new HashicorpVaultClient(config, okHttpClient, context.getTypeManager().getMapper()); + final HashicorpVaultClient client = + new HashicorpVaultClient(config, okHttpClient, context.getTypeManager().getMapper()); - final HashicorpVault vault = new HashicorpVault(client, context.getMonitor()); - final CertificateResolver certificateResolver = - new HashicorpCertificateResolver(vault, context.getMonitor()); - final VaultPrivateKeyResolver privateKeyResolver = new VaultPrivateKeyResolver(vault); + final HashicorpVault vault = new HashicorpVault(client, context.getMonitor()); + final CertificateResolver certificateResolver = + new HashicorpCertificateResolver(vault, context.getMonitor()); + final VaultPrivateKeyResolver privateKeyResolver = new VaultPrivateKeyResolver(vault); - context.registerService(Vault.class, vault); - context.registerService(CertificateResolver.class, certificateResolver); - context.registerService(PrivateKeyResolver.class, privateKeyResolver); + context.registerService(Vault.class, vault); + context.registerService(CertificateResolver.class, certificateResolver); + context.registerService(PrivateKeyResolver.class, privateKeyResolver); - context.getMonitor().info("HashicorpVaultExtension: authentication/initialization complete."); - } + context.getMonitor().info("HashicorpVaultExtension: authentication/initialization complete."); + } } diff --git a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/PathUtil.java b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/PathUtil.java index f22895355..1652ab758 100644 --- a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/PathUtil.java +++ b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/PathUtil.java @@ -16,14 +16,15 @@ final class PathUtil { - private PathUtil() {} + private PathUtil() { + } - static String trimLeadingOrEndingSlash(String path) { - var fixedPath = path; + static String trimLeadingOrEndingSlash(String path) { + var fixedPath = path; - if (fixedPath.startsWith("/")) fixedPath = fixedPath.substring(1); - if (fixedPath.endsWith("/")) fixedPath = fixedPath.substring(0, fixedPath.length() - 1); + if (fixedPath.startsWith("/")) fixedPath = fixedPath.substring(1); + if (fixedPath.endsWith("/")) fixedPath = fixedPath.substring(0, fixedPath.length() - 1); - return fixedPath; - } + return fixedPath; + } } diff --git a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/PemUtil.java b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/PemUtil.java index 6596d781b..f3ba161a8 100644 --- a/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/PemUtil.java +++ b/edc-extensions/hashicorp-vault/src/main/java/org/eclipse/tractusx/edc/hashicorpvault/PemUtil.java @@ -20,12 +20,6 @@ package org.eclipse.tractusx.edc.hashicorpvault; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.security.Provider; -import java.security.cert.X509Certificate; import lombok.NonNull; import lombok.SneakyThrows; import org.bouncycastle.cert.X509CertificateHolder; @@ -34,30 +28,37 @@ import org.bouncycastle.openssl.PEMParser; import org.jetbrains.annotations.NotNull; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.security.Provider; +import java.security.cert.X509Certificate; + final class PemUtil { - private PemUtil() { - throw new IllegalStateException("Private constructor invocation disallowed"); - } + private static final Provider PROVIDER = new BouncyCastleProvider(); + private static final JcaX509CertificateConverter X509_CONVERTER = + new JcaX509CertificateConverter().setProvider(PROVIDER); - private static final Provider PROVIDER = new BouncyCastleProvider(); - private static final JcaX509CertificateConverter X509_CONVERTER = - new JcaX509CertificateConverter().setProvider(PROVIDER); + private PemUtil() { + throw new IllegalStateException("Private constructor invocation disallowed"); + } - @SneakyThrows - public static X509Certificate readX509Certificate(@NotNull @NonNull InputStream inputStream) { - X509CertificateHolder x509CertificateHolder = parsePem(inputStream); - if (x509CertificateHolder == null) { - return null; + @SneakyThrows + public static X509Certificate readX509Certificate(@NotNull @NonNull InputStream inputStream) { + X509CertificateHolder x509CertificateHolder = parsePem(inputStream); + if (x509CertificateHolder == null) { + return null; + } + return X509_CONVERTER.getCertificate(x509CertificateHolder); } - return X509_CONVERTER.getCertificate(x509CertificateHolder); - } - - @SuppressWarnings("unchecked") - private static T parsePem(@NotNull @NonNull InputStream inputStream) throws IOException { - try (Reader reader = new InputStreamReader(inputStream)) { - PEMParser pemParser = new PEMParser(reader); - return (T) pemParser.readObject(); + + @SuppressWarnings("unchecked") + private static T parsePem(@NotNull @NonNull InputStream inputStream) throws IOException { + try (Reader reader = new InputStreamReader(inputStream)) { + PEMParser pemParser = new PEMParser(reader); + return (T) pemParser.readObject(); + } } - } } diff --git a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/AbstractHashicorpIT.java b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/AbstractHashicorpIT.java deleted file mode 100644 index 084cc158a..000000000 --- a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/AbstractHashicorpIT.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (c) 2022 Mercedes-Benz Tech Innovation GmbH - * Copyright (c) 2021,2022 Contributors to the Eclipse Foundation - * - * See the NOTICE file(s) distributed with this work for additional - * information regarding copyright ownership. - * - * This program and the accompanying materials are made available under the - * terms of the Apache License, Version 2.0 which is available at - * https://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. - * - * SPDX-License-Identifier: Apache-2.0 - */ - -package org.eclipse.tractusx.edc.hashicorpvault; - -import lombok.Getter; -import org.eclipse.edc.junit.annotations.ComponentTest; -import org.eclipse.edc.junit.extensions.EdcExtension; -import org.eclipse.edc.spi.security.CertificateResolver; -import org.eclipse.edc.spi.security.Vault; -import org.eclipse.edc.spi.system.ServiceExtension; -import org.eclipse.edc.spi.system.ServiceExtensionContext; -import org.eclipse.edc.spi.system.health.HealthCheckResult; -import org.eclipse.edc.spi.system.health.HealthCheckService; -import org.eclipse.edc.spi.system.health.HealthStatus; -import org.eclipse.edc.spi.system.health.LivenessProvider; -import org.eclipse.edc.spi.system.health.ReadinessProvider; -import org.eclipse.edc.spi.system.health.StartupStatusProvider; -import org.junit.ClassRule; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.extension.ExtendWith; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; -import org.testcontainers.utility.DockerImageName; -import org.testcontainers.vault.VaultContainer; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.stream.Collectors; - -import static org.eclipse.tractusx.edc.hashicorpvault.HashicorpVaultClient.VAULT_DATA_ENTRY_NAME; -import static org.eclipse.tractusx.edc.hashicorpvault.HashicorpVaultVaultExtension.VAULT_TOKEN; -import static org.eclipse.tractusx.edc.hashicorpvault.HashicorpVaultVaultExtension.VAULT_URL; - -@ComponentTest -@Testcontainers -@ExtendWith(EdcExtension.class) -class AbstractHashicorpIT { - static final String DOCKER_IMAGE_NAME = "vault:1.9.6"; - static final String VAULT_ENTRY_KEY = "testing"; - static final String VAULT_ENTRY_VALUE = UUID.randomUUID().toString(); - static final String TOKEN = UUID.randomUUID().toString(); - - private final TestExtension testExtension = new TestExtension(); - - protected Vault getVault() { - return testExtension.getVault(); - } - - protected CertificateResolver getCertificateResolver() { - return testExtension.getCertificateResolver(); - } - - @Container @ClassRule - private static final VaultContainer vaultContainer = - new VaultContainer<>(DockerImageName.parse(DOCKER_IMAGE_NAME)) - .withVaultToken(TOKEN) - .withSecretInVault( - "secret/" + VAULT_ENTRY_KEY, - String.format("%s=%s", VAULT_DATA_ENTRY_NAME, VAULT_ENTRY_VALUE)); - - @BeforeEach - final void beforeEach(EdcExtension extension) { - extension.setConfiguration(getConfig()); - extension.registerServiceMock(HealthCheckService.class, new MyHealthCheckService()); - extension.registerSystemExtension(ServiceExtension.class, testExtension); - } - - protected Map getConfig() { - return new HashMap<>() { - { - put( - VAULT_URL, - String.format( - "http://%s:%s", vaultContainer.getHost(), vaultContainer.getFirstMappedPort())); - put(VAULT_TOKEN, TOKEN); - } - }; - } - - @Getter - private static class TestExtension implements ServiceExtension { - private Vault vault; - private CertificateResolver certificateResolver; - - @Override - public void initialize(ServiceExtensionContext context) { - vault = context.getService(Vault.class); - certificateResolver = context.getService(CertificateResolver.class); - } - } - - private static class MyHealthCheckService implements HealthCheckService { - private final List livenessProviders = new ArrayList<>(); - private final List readinessProviders = new ArrayList<>(); - private final List startupStatusProviders = new ArrayList<>(); - - @Override - public void addLivenessProvider(LivenessProvider provider) { - livenessProviders.add(provider); - } - - @Override - public void addReadinessProvider(ReadinessProvider provider) { - readinessProviders.add(provider); - } - - @Override - public void addStartupStatusProvider(StartupStatusProvider provider) { - startupStatusProviders.add(provider); - } - - @Override - public HealthStatus isLive() { - return new HealthStatus( - livenessProviders.stream() - .map( - p -> - p.get().failed() ? HealthCheckResult.failed("") : HealthCheckResult.success()) - .collect(Collectors.toList())); - } - - @Override - public HealthStatus isReady() { - return new HealthStatus( - readinessProviders.stream() - .map( - p -> - p.get().failed() ? HealthCheckResult.failed("") : HealthCheckResult.success()) - .collect(Collectors.toList())); - } - - @Override - public HealthStatus getStartupStatus() { - return new HealthStatus( - startupStatusProviders.stream() - .map( - p -> - p.get().failed() ? HealthCheckResult.failed("") : HealthCheckResult.success()) - .collect(Collectors.toList())); - } - - @Override - public void refresh() {} - } -} diff --git a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/AbstractHashicorpIt.java b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/AbstractHashicorpIt.java new file mode 100644 index 000000000..69cf65e6f --- /dev/null +++ b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/AbstractHashicorpIt.java @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2022 Mercedes-Benz Tech Innovation GmbH + * Copyright (c) 2021,2022 Contributors to the Eclipse Foundation + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.eclipse.tractusx.edc.hashicorpvault; + +import lombok.Getter; +import org.eclipse.edc.junit.annotations.ComponentTest; +import org.eclipse.edc.junit.extensions.EdcExtension; +import org.eclipse.edc.spi.security.CertificateResolver; +import org.eclipse.edc.spi.security.Vault; +import org.eclipse.edc.spi.system.ServiceExtension; +import org.eclipse.edc.spi.system.ServiceExtensionContext; +import org.eclipse.edc.spi.system.health.HealthCheckResult; +import org.eclipse.edc.spi.system.health.HealthCheckService; +import org.eclipse.edc.spi.system.health.HealthStatus; +import org.eclipse.edc.spi.system.health.LivenessProvider; +import org.eclipse.edc.spi.system.health.ReadinessProvider; +import org.eclipse.edc.spi.system.health.StartupStatusProvider; +import org.junit.ClassRule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.utility.DockerImageName; +import org.testcontainers.vault.VaultContainer; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; + +import static org.eclipse.tractusx.edc.hashicorpvault.HashicorpVaultClient.VAULT_DATA_ENTRY_NAME; +import static org.eclipse.tractusx.edc.hashicorpvault.HashicorpVaultVaultExtension.VAULT_TOKEN; +import static org.eclipse.tractusx.edc.hashicorpvault.HashicorpVaultVaultExtension.VAULT_URL; + +@ComponentTest +@Testcontainers +@ExtendWith(EdcExtension.class) +class AbstractHashicorpIt { + static final String DOCKER_IMAGE_NAME = "vault:1.9.6"; + static final String VAULT_ENTRY_KEY = "testing"; + static final String VAULT_ENTRY_VALUE = UUID.randomUUID().toString(); + static final String TOKEN = UUID.randomUUID().toString(); + @Container + @ClassRule + private static final VaultContainer VAULTCONTAINER = + new VaultContainer<>(DockerImageName.parse(DOCKER_IMAGE_NAME)) + .withVaultToken(TOKEN) + .withSecretInVault( + "secret/" + VAULT_ENTRY_KEY, + String.format("%s=%s", VAULT_DATA_ENTRY_NAME, VAULT_ENTRY_VALUE)); + private final TestExtension testExtension = new TestExtension(); + + protected Vault getVault() { + return testExtension.getVault(); + } + + protected CertificateResolver getCertificateResolver() { + return testExtension.getCertificateResolver(); + } + + @BeforeEach + final void beforeEach(EdcExtension extension) { + extension.setConfiguration(getConfig()); + extension.registerServiceMock(HealthCheckService.class, new MyHealthCheckService()); + extension.registerSystemExtension(ServiceExtension.class, testExtension); + } + + protected Map getConfig() { + return new HashMap<>() { + { + put( + VAULT_URL, + String.format( + "http://%s:%s", VAULTCONTAINER.getHost(), VAULTCONTAINER.getFirstMappedPort())); + put(VAULT_TOKEN, TOKEN); + } + }; + } + + @Getter + private static class TestExtension implements ServiceExtension { + private Vault vault; + private CertificateResolver certificateResolver; + + @Override + public void initialize(ServiceExtensionContext context) { + vault = context.getService(Vault.class); + certificateResolver = context.getService(CertificateResolver.class); + } + } + + private static class MyHealthCheckService implements HealthCheckService { + private final List livenessProviders = new ArrayList<>(); + private final List readinessProviders = new ArrayList<>(); + private final List startupStatusProviders = new ArrayList<>(); + + @Override + public void addLivenessProvider(LivenessProvider provider) { + livenessProviders.add(provider); + } + + @Override + public void addReadinessProvider(ReadinessProvider provider) { + readinessProviders.add(provider); + } + + @Override + public void addStartupStatusProvider(StartupStatusProvider provider) { + startupStatusProviders.add(provider); + } + + @Override + public HealthStatus isLive() { + return new HealthStatus( + livenessProviders.stream() + .map( + p -> + p.get().failed() ? HealthCheckResult.failed("") : HealthCheckResult.success()) + .collect(Collectors.toList())); + } + + @Override + public HealthStatus isReady() { + return new HealthStatus( + readinessProviders.stream() + .map( + p -> + p.get().failed() ? HealthCheckResult.failed("") : HealthCheckResult.success()) + .collect(Collectors.toList())); + } + + @Override + public HealthStatus getStartupStatus() { + return new HealthStatus( + startupStatusProviders.stream() + .map( + p -> + p.get().failed() ? HealthCheckResult.failed("") : HealthCheckResult.success()) + .collect(Collectors.toList())); + } + + @Override + public void refresh() { + } + } +} diff --git a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpCertificateResolverIT.java b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpCertificateResolverIt.java similarity index 50% rename from edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpCertificateResolverIT.java rename to edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpCertificateResolverIt.java index 48fc06eca..7f7a6ed55 100644 --- a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpCertificateResolverIT.java +++ b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpCertificateResolverIt.java @@ -20,41 +20,42 @@ package org.eclipse.tractusx.edc.hashicorpvault; -import java.security.cert.X509Certificate; -import java.util.UUID; import lombok.SneakyThrows; import org.eclipse.edc.spi.security.CertificateResolver; import org.eclipse.edc.spi.security.Vault; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -class HashicorpCertificateResolverIT extends AbstractHashicorpIT { - - @Test - @SneakyThrows - void resolveCertificate_success() { - String key = UUID.randomUUID().toString(); - X509Certificate certificateExpected = X509CertificateTestUtil.generateCertificate(5, "Test"); - String pem = X509CertificateTestUtil.convertToPem(certificateExpected); - - Vault vault = getVault(); - vault.storeSecret(key, pem); - CertificateResolver resolver = getCertificateResolver(); - X509Certificate certificateResult = resolver.resolveCertificate(key); - - Assertions.assertEquals(certificateExpected, certificateResult); - } - - @Test - @SneakyThrows - void resolveCertificate_malformed() { - String key = UUID.randomUUID().toString(); - String value = UUID.randomUUID().toString(); - Vault vault = getVault(); - vault.storeSecret(key, value); - - CertificateResolver resolver = getCertificateResolver(); - X509Certificate certificateResult = resolver.resolveCertificate(key); - Assertions.assertNull(certificateResult); - } +import java.security.cert.X509Certificate; +import java.util.UUID; + +class HashicorpCertificateResolverIt extends AbstractHashicorpIt { + + @Test + @SneakyThrows + void resolveCertificate_success() { + String key = UUID.randomUUID().toString(); + X509Certificate certificateExpected = X509CertificateTestUtil.generateCertificate(5, "Test"); + String pem = X509CertificateTestUtil.convertToPem(certificateExpected); + + Vault vault = getVault(); + vault.storeSecret(key, pem); + CertificateResolver resolver = getCertificateResolver(); + X509Certificate certificateResult = resolver.resolveCertificate(key); + + Assertions.assertEquals(certificateExpected, certificateResult); + } + + @Test + @SneakyThrows + void resolveCertificate_malformed() { + String key = UUID.randomUUID().toString(); + String value = UUID.randomUUID().toString(); + Vault vault = getVault(); + vault.storeSecret(key, value); + + CertificateResolver resolver = getCertificateResolver(); + X509Certificate certificateResult = resolver.resolveCertificate(key); + Assertions.assertNull(certificateResult); + } } diff --git a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpCertificateResolverTest.java b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpCertificateResolverTest.java index 754bdda28..87140d3be 100644 --- a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpCertificateResolverTest.java +++ b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpCertificateResolverTest.java @@ -20,7 +20,6 @@ package org.eclipse.tractusx.edc.hashicorpvault; -import java.security.cert.X509Certificate; import lombok.SneakyThrows; import org.eclipse.edc.spi.monitor.Monitor; import org.junit.jupiter.api.Assertions; @@ -28,45 +27,47 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import java.security.cert.X509Certificate; + class HashicorpCertificateResolverTest { - private static final String key = "key"; + private static final String KEY = "key"; - // mocks - private HashicorpCertificateResolver certificateResolver; - private HashicorpVault vault; + // mocks + private HashicorpCertificateResolver certificateResolver; + private HashicorpVault vault; - @BeforeEach - void setup() { - vault = Mockito.mock(HashicorpVault.class); - final Monitor monitor = Mockito.mock(Monitor.class); - certificateResolver = new HashicorpCertificateResolver(vault, monitor); - } + @BeforeEach + void setup() { + vault = Mockito.mock(HashicorpVault.class); + final Monitor monitor = Mockito.mock(Monitor.class); + certificateResolver = new HashicorpCertificateResolver(vault, monitor); + } - @Test - @SneakyThrows - void resolveCertificate() { - // prepare - X509Certificate certificateExpected = X509CertificateTestUtil.generateCertificate(5, "Test"); - String pem = X509CertificateTestUtil.convertToPem(certificateExpected); - Mockito.when(vault.resolveSecret(key)).thenReturn(pem); + @Test + @SneakyThrows + void resolveCertificate() { + // prepare + X509Certificate certificateExpected = X509CertificateTestUtil.generateCertificate(5, "Test"); + String pem = X509CertificateTestUtil.convertToPem(certificateExpected); + Mockito.when(vault.resolveSecret(KEY)).thenReturn(pem); - // invoke - certificateResolver.resolveCertificate(key); + // invoke + certificateResolver.resolveCertificate(KEY); - // verify - Mockito.verify(vault, Mockito.times(1)).resolveSecret(key); - } + // verify + Mockito.verify(vault, Mockito.times(1)).resolveSecret(KEY); + } - @Test - @SneakyThrows - void nullIfVaultEmpty() { - // prepare - Mockito.when(vault.resolveSecret(key)).thenReturn(null); + @Test + @SneakyThrows + void nullIfVaultEmpty() { + // prepare + Mockito.when(vault.resolveSecret(KEY)).thenReturn(null); - // invoke - final X509Certificate certificate = certificateResolver.resolveCertificate(key); + // invoke + final X509Certificate certificate = certificateResolver.resolveCertificate(KEY); - // verify - Assertions.assertNull(certificate); - } + // verify + Assertions.assertNull(certificate); + } } diff --git a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultClientTest.java b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultClientTest.java index 2bddac46e..cb8c31e9f 100644 --- a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultClientTest.java +++ b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultClientTest.java @@ -21,8 +21,6 @@ package org.eclipse.tractusx.edc.hashicorpvault; import com.fasterxml.jackson.databind.ObjectMapper; -import java.time.Duration; -import java.util.UUID; import lombok.SneakyThrows; import okhttp3.Call; import okhttp3.OkHttpClient; @@ -34,223 +32,223 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -class HashicorpVaultClientTest { - private static final String key = "key"; - private static final String customSecretPath = "v1/test/secret"; - private static final String healthPath = "sys/health"; - private static final Duration timeout = Duration.ofSeconds(30); - private static final ObjectMapper objectMapper = new ObjectMapper(); - - @Test - @SneakyThrows - void getSecretValue() { - // prepare - String vaultUrl = "https://mock.url"; - String vaultToken = UUID.randomUUID().toString(); - HashicorpVaultClientConfig hashicorpVaultClientConfig = - HashicorpVaultClientConfig.builder() - .vaultUrl(vaultUrl) - .vaultApiSecretPath(customSecretPath) - .vaultApiHealthPath(healthPath) - .isVaultApiHealthStandbyOk(false) - .vaultToken(vaultToken) - .timeout(timeout) - .build(); - - OkHttpClient okHttpClient = Mockito.mock(OkHttpClient.class); - HashicorpVaultClient vaultClient = - new HashicorpVaultClient(hashicorpVaultClientConfig, okHttpClient, objectMapper); - Call call = Mockito.mock(Call.class); - Response response = Mockito.mock(Response.class); - ResponseBody body = Mockito.mock(ResponseBody.class); - HashicorpVaultGetEntryResponsePayload payload = new HashicorpVaultGetEntryResponsePayload(); - - Mockito.when(okHttpClient.newCall(Mockito.any(Request.class))).thenReturn(call); - Mockito.when(call.execute()).thenReturn(response); - Mockito.when(response.code()).thenReturn(200); - Mockito.when(response.body()).thenReturn(body); - Mockito.when(body.string()).thenReturn(payload.toString()); - - // invoke - Result result = vaultClient.getSecretValue(key); - - // verify - Assertions.assertNotNull(result); - Mockito.verify(okHttpClient, Mockito.times(1)) - .newCall( - Mockito.argThat( - request -> - request.method().equalsIgnoreCase("GET") - && request.url().encodedPath().contains(customSecretPath + "/data") - && request.url().encodedPathSegments().contains(key))); - } - - @Test - @SneakyThrows - void setSecretValue() { - // prepare - String vaultUrl = "https://mock.url"; - String vaultToken = UUID.randomUUID().toString(); - String secretValue = UUID.randomUUID().toString(); - HashicorpVaultClientConfig hashicorpVaultClientConfig = - HashicorpVaultClientConfig.builder() - .vaultUrl(vaultUrl) - .vaultApiSecretPath(customSecretPath) - .vaultApiHealthPath(healthPath) - .isVaultApiHealthStandbyOk(false) - .vaultToken(vaultToken) - .timeout(timeout) - .build(); - - OkHttpClient okHttpClient = Mockito.mock(OkHttpClient.class); - HashicorpVaultClient vaultClient = - new HashicorpVaultClient(hashicorpVaultClientConfig, okHttpClient, objectMapper); - HashicorpVaultCreateEntryResponsePayload payload = - new HashicorpVaultCreateEntryResponsePayload(); - - Call call = Mockito.mock(Call.class); - Response response = Mockito.mock(Response.class); - ResponseBody body = Mockito.mock(ResponseBody.class); - - Mockito.when(okHttpClient.newCall(Mockito.any(Request.class))).thenReturn(call); - Mockito.when(call.execute()).thenReturn(response); - Mockito.when(response.code()).thenReturn(200); - Mockito.when(response.body()).thenReturn(body); - Mockito.when(body.string()).thenReturn(payload.toString()); - - // invoke - Result result = - vaultClient.setSecret(key, secretValue); - - // verify - Assertions.assertNotNull(result); - Mockito.verify(okHttpClient, Mockito.times(1)) - .newCall( - Mockito.argThat( - request -> - request.method().equalsIgnoreCase("POST") - && request.url().encodedPath().contains(customSecretPath + "/data") - && request.url().encodedPathSegments().contains(key))); - } - - @Test - @SneakyThrows - void getHealth() { - // prepare - String vaultUrl = "https://mock.url"; - String vaultToken = UUID.randomUUID().toString(); - String secretValue = UUID.randomUUID().toString(); - HashicorpVaultClientConfig hashicorpVaultClientConfig = - HashicorpVaultClientConfig.builder() - .vaultUrl(vaultUrl) - .vaultApiSecretPath(customSecretPath) - .vaultApiHealthPath(healthPath) - .isVaultApiHealthStandbyOk(false) - .vaultToken(vaultToken) - .timeout(timeout) - .build(); - - OkHttpClient okHttpClient = Mockito.mock(OkHttpClient.class); - HashicorpVaultClient vaultClient = - new HashicorpVaultClient(hashicorpVaultClientConfig, okHttpClient, objectMapper); - HashicorpVaultHealthResponsePayload payload = new HashicorpVaultHealthResponsePayload(); - - Call call = Mockito.mock(Call.class); - Response response = Mockito.mock(Response.class); - ResponseBody body = Mockito.mock(ResponseBody.class); - - Mockito.when(okHttpClient.newCall(Mockito.any(Request.class))).thenReturn(call); - Mockito.when(call.execute()).thenReturn(response); - Mockito.when(response.code()).thenReturn(200); - Mockito.when(response.body()).thenReturn(body); - Mockito.when(body.string()) - .thenReturn( - "{ " - + "\"initialized\": true, " - + "\"sealed\": false," - + "\"standby\": false," - + "\"performance_standby\": false," - + "\"replication_performance_mode\": \"mode\"," - + "\"replication_dr_mode\": \"mode\"," - + "\"server_time_utc\": 100," - + "\"version\": \"1.0.0\"," - + "\"cluster_name\": \"name\"," - + "\"cluster_id\": \"id\" " - + " }"); - - // invoke - HashicorpVaultHealthResponse result = vaultClient.getHealth(); - - // verify - Assertions.assertNotNull(result); - Mockito.verify(okHttpClient, Mockito.times(1)) - .newCall( - Mockito.argThat( - request -> - request.method().equalsIgnoreCase("GET") - && request.url().encodedPath().contains(healthPath) - && request.url().queryParameter("standbyok").equals("false") - && request.url().queryParameter("perfstandbyok").equals("false"))); - Assertions.assertEquals(200, result.getCode()); - Assertions.assertEquals( - HashicorpVaultHealthResponse.HashiCorpVaultHealthResponseCode - .INITIALIZED_UNSEALED_AND_ACTIVE, - result.getCodeAsEnum()); - - HashicorpVaultHealthResponsePayload resultPayload = result.getPayload(); - - Assertions.assertNotNull(resultPayload); - Assertions.assertTrue(resultPayload.isInitialized()); - Assertions.assertFalse(resultPayload.isSealed()); - Assertions.assertFalse(resultPayload.isStandby()); - Assertions.assertFalse(resultPayload.isPerformanceStandby()); - Assertions.assertEquals("mode", resultPayload.getReplicationPerformanceMode()); - Assertions.assertEquals("mode", resultPayload.getReplicationDrMode()); - Assertions.assertEquals(100, resultPayload.getServerTimeUtc()); - Assertions.assertEquals("1.0.0", resultPayload.getVersion()); - Assertions.assertEquals("id", resultPayload.getClusterId()); - Assertions.assertEquals("name", resultPayload.getClusterName()); - } - - @Test - @SneakyThrows - void destroySecretValue() { - // prepare - String vaultUrl = "https://mock.url"; - String vaultToken = UUID.randomUUID().toString(); - HashicorpVaultClientConfig hashicorpVaultClientConfig = - HashicorpVaultClientConfig.builder() - .vaultUrl(vaultUrl) - .vaultApiSecretPath(customSecretPath) - .vaultApiHealthPath(healthPath) - .isVaultApiHealthStandbyOk(false) - .vaultToken(vaultToken) - .timeout(timeout) - .build(); - - OkHttpClient okHttpClient = Mockito.mock(OkHttpClient.class); - HashicorpVaultClient vaultClient = - new HashicorpVaultClient(hashicorpVaultClientConfig, okHttpClient, objectMapper); - - Call call = Mockito.mock(Call.class); - Response response = Mockito.mock(Response.class); - ResponseBody body = Mockito.mock(ResponseBody.class); - Mockito.when(okHttpClient.newCall(Mockito.any(Request.class))).thenReturn(call); - Mockito.when(call.execute()).thenReturn(response); - Mockito.when(response.code()).thenReturn(200); - Mockito.when(response.body()).thenReturn(body); - - // invoke - Result result = vaultClient.destroySecret(key); +import java.time.Duration; +import java.util.UUID; - // verify - Assertions.assertNotNull(result); - Mockito.verify(okHttpClient, Mockito.times(1)) - .newCall( - Mockito.argThat( - request -> - request.method().equalsIgnoreCase("DELETE") - && request.url().encodedPath().contains(customSecretPath + "/metadata") - && request.url().encodedPathSegments().contains(key))); - } +class HashicorpVaultClientTest { + private static final String KEY = "key"; + private static final String CUSTOM_SECRET_PATH = "v1/test/secret"; + private static final String HEALTH_PATH = "sys/health"; + private static final Duration TIMEOUT = Duration.ofSeconds(30); + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + @Test + @SneakyThrows + void getSecretValue() { + // prepare + String vaultUrl = "https://mock.url"; + String vaultToken = UUID.randomUUID().toString(); + HashicorpVaultClientConfig hashicorpVaultClientConfig = + HashicorpVaultClientConfig.builder() + .vaultUrl(vaultUrl) + .vaultApiSecretPath(CUSTOM_SECRET_PATH) + .vaultApiHealthPath(HEALTH_PATH) + .isVaultApiHealthStandbyOk(false) + .vaultToken(vaultToken) + .timeout(TIMEOUT) + .build(); + + OkHttpClient okHttpClient = Mockito.mock(OkHttpClient.class); + HashicorpVaultClient vaultClient = + new HashicorpVaultClient(hashicorpVaultClientConfig, okHttpClient, OBJECT_MAPPER); + Call call = Mockito.mock(Call.class); + Response response = Mockito.mock(Response.class); + ResponseBody body = Mockito.mock(ResponseBody.class); + HashicorpVaultGetEntryResponsePayload payload = new HashicorpVaultGetEntryResponsePayload(); + + Mockito.when(okHttpClient.newCall(Mockito.any(Request.class))).thenReturn(call); + Mockito.when(call.execute()).thenReturn(response); + Mockito.when(response.code()).thenReturn(200); + Mockito.when(response.body()).thenReturn(body); + Mockito.when(body.string()).thenReturn(payload.toString()); + + // invoke + Result result = vaultClient.getSecretValue(KEY); + + // verify + Assertions.assertNotNull(result); + Mockito.verify(okHttpClient, Mockito.times(1)) + .newCall(Mockito.argThat(request -> request.method().equalsIgnoreCase("GET") && + request.url().encodedPath().contains(CUSTOM_SECRET_PATH + "/data") && + request.url().encodedPathSegments().contains(KEY))); + } + + @Test + @SneakyThrows + void setSecretValue() { + // prepare + String vaultUrl = "https://mock.url"; + String vaultToken = UUID.randomUUID().toString(); + String secretValue = UUID.randomUUID().toString(); + HashicorpVaultClientConfig hashicorpVaultClientConfig = + HashicorpVaultClientConfig.builder() + .vaultUrl(vaultUrl) + .vaultApiSecretPath(CUSTOM_SECRET_PATH) + .vaultApiHealthPath(HEALTH_PATH) + .isVaultApiHealthStandbyOk(false) + .vaultToken(vaultToken) + .timeout(TIMEOUT) + .build(); + + OkHttpClient okHttpClient = Mockito.mock(OkHttpClient.class); + HashicorpVaultClient vaultClient = + new HashicorpVaultClient(hashicorpVaultClientConfig, okHttpClient, OBJECT_MAPPER); + HashicorpVaultCreateEntryResponsePayload payload = + new HashicorpVaultCreateEntryResponsePayload(); + + Call call = Mockito.mock(Call.class); + Response response = Mockito.mock(Response.class); + ResponseBody body = Mockito.mock(ResponseBody.class); + + Mockito.when(okHttpClient.newCall(Mockito.any(Request.class))).thenReturn(call); + Mockito.when(call.execute()).thenReturn(response); + Mockito.when(response.code()).thenReturn(200); + Mockito.when(response.body()).thenReturn(body); + Mockito.when(body.string()).thenReturn(payload.toString()); + + // invoke + Result result = + vaultClient.setSecret(KEY, secretValue); + + // verify + Assertions.assertNotNull(result); + Mockito.verify(okHttpClient, Mockito.times(1)) + .newCall( + Mockito.argThat( + request -> + request.method().equalsIgnoreCase("POST") && + request.url().encodedPath().contains(CUSTOM_SECRET_PATH + "/data") && + request.url().encodedPathSegments().contains(KEY))); + } + + @Test + @SneakyThrows + void getHealth() { + // prepare + String vaultUrl = "https://mock.url"; + String vaultToken = UUID.randomUUID().toString(); + String secretValue = UUID.randomUUID().toString(); + HashicorpVaultClientConfig hashicorpVaultClientConfig = + HashicorpVaultClientConfig.builder() + .vaultUrl(vaultUrl) + .vaultApiSecretPath(CUSTOM_SECRET_PATH) + .vaultApiHealthPath(HEALTH_PATH) + .isVaultApiHealthStandbyOk(false) + .vaultToken(vaultToken) + .timeout(TIMEOUT) + .build(); + + OkHttpClient okHttpClient = Mockito.mock(OkHttpClient.class); + HashicorpVaultClient vaultClient = + new HashicorpVaultClient(hashicorpVaultClientConfig, okHttpClient, OBJECT_MAPPER); + HashicorpVaultHealthResponsePayload payload = new HashicorpVaultHealthResponsePayload(); + + Call call = Mockito.mock(Call.class); + Response response = Mockito.mock(Response.class); + ResponseBody body = Mockito.mock(ResponseBody.class); + + Mockito.when(okHttpClient.newCall(Mockito.any(Request.class))).thenReturn(call); + Mockito.when(call.execute()).thenReturn(response); + Mockito.when(response.code()).thenReturn(200); + Mockito.when(response.body()).thenReturn(body); + Mockito.when(body.string()) + .thenReturn( + "{ " + + "\"initialized\": true, " + + "\"sealed\": false," + + "\"standby\": false," + + "\"performance_standby\": false," + + "\"replication_performance_mode\": \"mode\"," + + "\"replication_dr_mode\": \"mode\"," + + "\"server_time_utc\": 100," + + "\"version\": \"1.0.0\"," + + "\"cluster_name\": \"name\"," + + "\"cluster_id\": \"id\" " + + " }"); + + // invoke + HashicorpVaultHealthResponse result = vaultClient.getHealth(); + + // verify + Assertions.assertNotNull(result); + Mockito.verify(okHttpClient, Mockito.times(1)) + .newCall( + Mockito.argThat( + request -> + request.method().equalsIgnoreCase("GET") && + request.url().encodedPath().contains(HEALTH_PATH) && + request.url().queryParameter("standbyok").equals("false") && + request.url().queryParameter("perfstandbyok").equals("false"))); + Assertions.assertEquals(200, result.getCode()); + Assertions.assertEquals( + HashicorpVaultHealthResponse.HashiCorpVaultHealthResponseCode + .INITIALIZED_UNSEALED_AND_ACTIVE, + result.getCodeAsEnum()); + + HashicorpVaultHealthResponsePayload resultPayload = result.getPayload(); + + Assertions.assertNotNull(resultPayload); + Assertions.assertTrue(resultPayload.isInitialized()); + Assertions.assertFalse(resultPayload.isSealed()); + Assertions.assertFalse(resultPayload.isStandby()); + Assertions.assertFalse(resultPayload.isPerformanceStandby()); + Assertions.assertEquals("mode", resultPayload.getReplicationPerformanceMode()); + Assertions.assertEquals("mode", resultPayload.getReplicationDrMode()); + Assertions.assertEquals(100, resultPayload.getServerTimeUtc()); + Assertions.assertEquals("1.0.0", resultPayload.getVersion()); + Assertions.assertEquals("id", resultPayload.getClusterId()); + Assertions.assertEquals("name", resultPayload.getClusterName()); + } + + @Test + @SneakyThrows + void destroySecretValue() { + // prepare + String vaultUrl = "https://mock.url"; + String vaultToken = UUID.randomUUID().toString(); + HashicorpVaultClientConfig hashicorpVaultClientConfig = + HashicorpVaultClientConfig.builder() + .vaultUrl(vaultUrl) + .vaultApiSecretPath(CUSTOM_SECRET_PATH) + .vaultApiHealthPath(HEALTH_PATH) + .isVaultApiHealthStandbyOk(false) + .vaultToken(vaultToken) + .timeout(TIMEOUT) + .build(); + + OkHttpClient okHttpClient = Mockito.mock(OkHttpClient.class); + HashicorpVaultClient vaultClient = + new HashicorpVaultClient(hashicorpVaultClientConfig, okHttpClient, OBJECT_MAPPER); + + Call call = Mockito.mock(Call.class); + Response response = Mockito.mock(Response.class); + ResponseBody body = Mockito.mock(ResponseBody.class); + Mockito.when(okHttpClient.newCall(Mockito.any(Request.class))).thenReturn(call); + Mockito.when(call.execute()).thenReturn(response); + Mockito.when(response.code()).thenReturn(200); + Mockito.when(response.body()).thenReturn(body); + + // invoke + Result result = vaultClient.destroySecret(KEY); + + // verify + Assertions.assertNotNull(result); + Mockito.verify(okHttpClient, Mockito.times(1)) + .newCall( + Mockito.argThat( + request -> + request.method().equalsIgnoreCase("DELETE") && + request.url().encodedPath().contains(CUSTOM_SECRET_PATH + "/metadata") && + request.url().encodedPathSegments().contains(KEY))); + } } diff --git a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultExtensionTest.java b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultExtensionTest.java index dfba9fe1c..33d3e2bd7 100644 --- a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultExtensionTest.java +++ b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultExtensionTest.java @@ -31,60 +31,60 @@ class HashicorpVaultExtensionTest { - private static final String VAULT_URL = "https://example.com"; - private static final String VAULT_TOKEN = "token"; + private static final String VAULT_URL = "https://example.com"; + private static final String VAULT_TOKEN = "token"; - private HashicorpVaultVaultExtension extension; + private HashicorpVaultVaultExtension extension; - // mocks - private ServiceExtensionContext context; - private Monitor monitor; - private HealthCheckService healthCheckService; + // mocks + private ServiceExtensionContext context; + private Monitor monitor; + private HealthCheckService healthCheckService; - @BeforeEach - void setup() { - context = Mockito.mock(ServiceExtensionContext.class); - monitor = Mockito.mock(Monitor.class); - healthCheckService = Mockito.mock(HealthCheckService.class); - extension = new HashicorpVaultVaultExtension(); + @BeforeEach + void setup() { + context = Mockito.mock(ServiceExtensionContext.class); + monitor = Mockito.mock(Monitor.class); + healthCheckService = Mockito.mock(HealthCheckService.class); + extension = new HashicorpVaultVaultExtension(); - Mockito.when(context.getService(HealthCheckService.class)).thenReturn(healthCheckService); - Mockito.when(context.getMonitor()).thenReturn(monitor); - Mockito.when(context.getTypeManager()).thenReturn(new TypeManager()); - Mockito.when(context.getSetting(HashicorpVaultVaultExtension.VAULT_URL, null)) - .thenReturn(VAULT_URL); - Mockito.when(context.getSetting(HashicorpVaultVaultExtension.VAULT_TOKEN, null)) - .thenReturn(VAULT_TOKEN); + Mockito.when(context.getService(HealthCheckService.class)).thenReturn(healthCheckService); + Mockito.when(context.getMonitor()).thenReturn(monitor); + Mockito.when(context.getTypeManager()).thenReturn(new TypeManager()); + Mockito.when(context.getSetting(HashicorpVaultVaultExtension.VAULT_URL, null)) + .thenReturn(VAULT_URL); + Mockito.when(context.getSetting(HashicorpVaultVaultExtension.VAULT_TOKEN, null)) + .thenReturn(VAULT_TOKEN); - Mockito.when( - context.getSetting( - HashicorpVaultVaultExtension.VAULT_API_SECRET_PATH, - HashicorpVaultVaultExtension.VAULT_API_SECRET_PATH_DEFAULT)) - .thenReturn(HashicorpVaultVaultExtension.VAULT_API_SECRET_PATH_DEFAULT); - Mockito.when( - context.getSetting( - HashicorpVaultVaultExtension.VAULT_API_HEALTH_PATH, - HashicorpVaultVaultExtension.VAULT_API_HEALTH_PATH_DEFAULT)) - .thenReturn(HashicorpVaultVaultExtension.VAULT_API_HEALTH_PATH_DEFAULT); - Mockito.when( - context.getSetting( - HashicorpVaultVaultExtension.VAULT_HEALTH_CHECK_STANDBY_OK, - HashicorpVaultVaultExtension.VAULT_HEALTH_CHECK_STANDBY_OK_DEFAULT)) - .thenReturn(HashicorpVaultVaultExtension.VAULT_HEALTH_CHECK_STANDBY_OK_DEFAULT); - } + Mockito.when( + context.getSetting( + HashicorpVaultVaultExtension.VAULT_API_SECRET_PATH, + HashicorpVaultVaultExtension.VAULT_API_SECRET_PATH_DEFAULT)) + .thenReturn(HashicorpVaultVaultExtension.VAULT_API_SECRET_PATH_DEFAULT); + Mockito.when( + context.getSetting( + HashicorpVaultVaultExtension.VAULT_API_HEALTH_PATH, + HashicorpVaultVaultExtension.VAULT_API_HEALTH_PATH_DEFAULT)) + .thenReturn(HashicorpVaultVaultExtension.VAULT_API_HEALTH_PATH_DEFAULT); + Mockito.when( + context.getSetting( + HashicorpVaultVaultExtension.VAULT_HEALTH_CHECK_STANDBY_OK, + HashicorpVaultVaultExtension.VAULT_HEALTH_CHECK_STANDBY_OK_DEFAULT)) + .thenReturn(HashicorpVaultVaultExtension.VAULT_HEALTH_CHECK_STANDBY_OK_DEFAULT); + } - @Test - void throwsHashicorpVaultExceptionOnVaultUrlUndefined() { - Mockito.when(context.getSetting(HashicorpVaultVaultExtension.VAULT_URL, null)).thenReturn(null); + @Test + void throwsHashicorpVaultExceptionOnVaultUrlUndefined() { + Mockito.when(context.getSetting(HashicorpVaultVaultExtension.VAULT_URL, null)).thenReturn(null); - Assertions.assertThrows(HashicorpVaultException.class, () -> extension.initialize(context)); - } + Assertions.assertThrows(HashicorpVaultException.class, () -> extension.initialize(context)); + } - @Test - void throwsHashicorpVaultExceptionOnVaultTokenUndefined() { - Mockito.when(context.getSetting(HashicorpVaultVaultExtension.VAULT_TOKEN, null)) - .thenReturn(null); + @Test + void throwsHashicorpVaultExceptionOnVaultTokenUndefined() { + Mockito.when(context.getSetting(HashicorpVaultVaultExtension.VAULT_TOKEN, null)) + .thenReturn(null); - Assertions.assertThrows(HashicorpVaultException.class, () -> extension.initialize(context)); - } + Assertions.assertThrows(HashicorpVaultException.class, () -> extension.initialize(context)); + } } diff --git a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthCheckExtensionTest.java b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthCheckExtensionTest.java index 5991f8c1e..f5f0f26b0 100644 --- a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthCheckExtensionTest.java +++ b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthCheckExtensionTest.java @@ -31,89 +31,89 @@ class HashicorpVaultHealthCheckExtensionTest { - private static final String VAULT_URL = "https://example.com"; - private static final String VAULT_TOKEN = "token"; - - private HashicorpVaultHealthExtension extension; - - // mocks - private ServiceExtensionContext context; - private Monitor monitor; - private HealthCheckService healthCheckService; - - @BeforeEach - void setup() { - context = Mockito.mock(ServiceExtensionContext.class); - monitor = Mockito.mock(Monitor.class); - healthCheckService = Mockito.mock(HealthCheckService.class); - extension = new HashicorpVaultHealthExtension(); - - Mockito.when(context.getService(HealthCheckService.class)).thenReturn(healthCheckService); - Mockito.when(context.getMonitor()).thenReturn(monitor); - Mockito.when(context.getTypeManager()).thenReturn(new TypeManager()); - Mockito.when(context.getSetting(HashicorpVaultVaultExtension.VAULT_URL, null)) - .thenReturn(VAULT_URL); - Mockito.when(context.getSetting(HashicorpVaultVaultExtension.VAULT_TOKEN, null)) - .thenReturn(VAULT_TOKEN); - - Mockito.when( - context.getSetting( - HashicorpVaultHealthExtension.VAULT_API_SECRET_PATH, - HashicorpVaultHealthExtension.VAULT_API_SECRET_PATH_DEFAULT)) - .thenReturn(HashicorpVaultHealthExtension.VAULT_API_SECRET_PATH_DEFAULT); - Mockito.when( - context.getSetting( - HashicorpVaultHealthExtension.VAULT_API_HEALTH_PATH, - HashicorpVaultHealthExtension.VAULT_API_HEALTH_PATH_DEFAULT)) - .thenReturn(HashicorpVaultHealthExtension.VAULT_API_HEALTH_PATH_DEFAULT); - Mockito.when( - context.getSetting( - HashicorpVaultHealthExtension.VAULT_HEALTH_CHECK, - HashicorpVaultHealthExtension.VAULT_HEALTH_CHECK_DEFAULT)) - .thenReturn(HashicorpVaultHealthExtension.VAULT_HEALTH_CHECK_DEFAULT); - Mockito.when( - context.getSetting( - HashicorpVaultHealthExtension.VAULT_HEALTH_CHECK_STANDBY_OK, - HashicorpVaultHealthExtension.VAULT_HEALTH_CHECK_STANDBY_OK_DEFAULT)) - .thenReturn(HashicorpVaultHealthExtension.VAULT_HEALTH_CHECK_STANDBY_OK_DEFAULT); - } - - @Test - void registersHealthCheckIfEnabled() { - Mockito.when(context.getSetting(HashicorpVaultHealthExtension.VAULT_HEALTH_CHECK, true)) - .thenReturn(true); - - extension.initialize(context); - - Mockito.verify(healthCheckService, Mockito.times(1)).addReadinessProvider(Mockito.any()); - Mockito.verify(healthCheckService, Mockito.times(1)).addLivenessProvider(Mockito.any()); - Mockito.verify(healthCheckService, Mockito.times(1)).addStartupStatusProvider(Mockito.any()); - } - - @Test - void registersNoHealthCheckIfDisabled() { - Mockito.when(context.getSetting(HashicorpVaultHealthExtension.VAULT_HEALTH_CHECK, true)) - .thenReturn(false); - - extension.initialize(context); - - Mockito.verify(healthCheckService, Mockito.times(0)).addReadinessProvider(Mockito.any()); - Mockito.verify(healthCheckService, Mockito.times(0)).addLivenessProvider(Mockito.any()); - Mockito.verify(healthCheckService, Mockito.times(0)).addStartupStatusProvider(Mockito.any()); - } - - @Test - void throwsHashicorpVaultExceptionOnVaultUrlUndefined() { - Mockito.when(context.getSetting(HashicorpVaultVaultExtension.VAULT_URL, null)).thenReturn(null); - - Assertions.assertThrows(HashicorpVaultException.class, () -> extension.initialize(context)); - } - - @Test - void throwsHashicorpVaultExceptionOnVaultTokenUndefined() { - Mockito.when(context.getSetting(HashicorpVaultVaultExtension.VAULT_TOKEN, null)) - .thenReturn(null); - - Assertions.assertThrows(HashicorpVaultException.class, () -> extension.initialize(context)); - } + private static final String VAULT_URL = "https://example.com"; + private static final String VAULT_TOKEN = "token"; + + private HashicorpVaultHealthExtension extension; + + // mocks + private ServiceExtensionContext context; + private Monitor monitor; + private HealthCheckService healthCheckService; + + @BeforeEach + void setup() { + context = Mockito.mock(ServiceExtensionContext.class); + monitor = Mockito.mock(Monitor.class); + healthCheckService = Mockito.mock(HealthCheckService.class); + extension = new HashicorpVaultHealthExtension(); + + Mockito.when(context.getService(HealthCheckService.class)).thenReturn(healthCheckService); + Mockito.when(context.getMonitor()).thenReturn(monitor); + Mockito.when(context.getTypeManager()).thenReturn(new TypeManager()); + Mockito.when(context.getSetting(HashicorpVaultVaultExtension.VAULT_URL, null)) + .thenReturn(VAULT_URL); + Mockito.when(context.getSetting(HashicorpVaultVaultExtension.VAULT_TOKEN, null)) + .thenReturn(VAULT_TOKEN); + + Mockito.when( + context.getSetting( + HashicorpVaultHealthExtension.VAULT_API_SECRET_PATH, + HashicorpVaultHealthExtension.VAULT_API_SECRET_PATH_DEFAULT)) + .thenReturn(HashicorpVaultHealthExtension.VAULT_API_SECRET_PATH_DEFAULT); + Mockito.when( + context.getSetting( + HashicorpVaultHealthExtension.VAULT_API_HEALTH_PATH, + HashicorpVaultHealthExtension.VAULT_API_HEALTH_PATH_DEFAULT)) + .thenReturn(HashicorpVaultHealthExtension.VAULT_API_HEALTH_PATH_DEFAULT); + Mockito.when( + context.getSetting( + HashicorpVaultHealthExtension.VAULT_HEALTH_CHECK, + HashicorpVaultHealthExtension.VAULT_HEALTH_CHECK_DEFAULT)) + .thenReturn(HashicorpVaultHealthExtension.VAULT_HEALTH_CHECK_DEFAULT); + Mockito.when( + context.getSetting( + HashicorpVaultHealthExtension.VAULT_HEALTH_CHECK_STANDBY_OK, + HashicorpVaultHealthExtension.VAULT_HEALTH_CHECK_STANDBY_OK_DEFAULT)) + .thenReturn(HashicorpVaultHealthExtension.VAULT_HEALTH_CHECK_STANDBY_OK_DEFAULT); + } + + @Test + void registersHealthCheckIfEnabled() { + Mockito.when(context.getSetting(HashicorpVaultHealthExtension.VAULT_HEALTH_CHECK, true)) + .thenReturn(true); + + extension.initialize(context); + + Mockito.verify(healthCheckService, Mockito.times(1)).addReadinessProvider(Mockito.any()); + Mockito.verify(healthCheckService, Mockito.times(1)).addLivenessProvider(Mockito.any()); + Mockito.verify(healthCheckService, Mockito.times(1)).addStartupStatusProvider(Mockito.any()); + } + + @Test + void registersNoHealthCheckIfDisabled() { + Mockito.when(context.getSetting(HashicorpVaultHealthExtension.VAULT_HEALTH_CHECK, true)) + .thenReturn(false); + + extension.initialize(context); + + Mockito.verify(healthCheckService, Mockito.times(0)).addReadinessProvider(Mockito.any()); + Mockito.verify(healthCheckService, Mockito.times(0)).addLivenessProvider(Mockito.any()); + Mockito.verify(healthCheckService, Mockito.times(0)).addStartupStatusProvider(Mockito.any()); + } + + @Test + void throwsHashicorpVaultExceptionOnVaultUrlUndefined() { + Mockito.when(context.getSetting(HashicorpVaultVaultExtension.VAULT_URL, null)).thenReturn(null); + + Assertions.assertThrows(HashicorpVaultException.class, () -> extension.initialize(context)); + } + + @Test + void throwsHashicorpVaultExceptionOnVaultTokenUndefined() { + Mockito.when(context.getSetting(HashicorpVaultVaultExtension.VAULT_TOKEN, null)) + .thenReturn(null); + + Assertions.assertThrows(HashicorpVaultException.class, () -> extension.initialize(context)); + } } diff --git a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthCheckTest.java b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthCheckTest.java index 3abf95289..6304a1fdf 100644 --- a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthCheckTest.java +++ b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultHealthCheckTest.java @@ -20,7 +20,6 @@ package org.eclipse.tractusx.edc.hashicorpvault; -import java.io.IOException; import org.eclipse.edc.spi.monitor.Monitor; import org.eclipse.edc.spi.system.health.HealthCheckResult; import org.junit.jupiter.api.Assertions; @@ -30,46 +29,48 @@ import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; +import java.io.IOException; + class HashicorpVaultHealthCheckTest { - private HashicorpVaultHealthCheck healthCheck; + private HashicorpVaultHealthCheck healthCheck; - // mocks - private Monitor monitor; - private HashicorpVaultClient client; + // mocks + private Monitor monitor; + private HashicorpVaultClient client; - @BeforeEach - void setup() { - monitor = Mockito.mock(Monitor.class); - client = Mockito.mock(HashicorpVaultClient.class); + @BeforeEach + void setup() { + monitor = Mockito.mock(Monitor.class); + client = Mockito.mock(HashicorpVaultClient.class); - healthCheck = new HashicorpVaultHealthCheck(client, monitor); - } + healthCheck = new HashicorpVaultHealthCheck(client, monitor); + } - @ParameterizedTest - @ValueSource(ints = {200, 409, 472, 473, 501, 503, 999}) - void testResponseFromCode(int code) throws IOException { + @ParameterizedTest + @ValueSource(ints = {200, 409, 472, 473, 501, 503, 999}) + void testResponseFromCode(int code) throws IOException { - Mockito.when(client.getHealth()) - .thenReturn( - new HashicorpVaultHealthResponse(new HashicorpVaultHealthResponsePayload(), code)); + Mockito.when(client.getHealth()) + .thenReturn( + new HashicorpVaultHealthResponse(new HashicorpVaultHealthResponsePayload(), code)); - final HealthCheckResult result = healthCheck.get(); + final HealthCheckResult result = healthCheck.get(); - if (code == 200) { - Mockito.verify(monitor, Mockito.times(1)).debug(Mockito.anyString()); - Assertions.assertTrue(result.succeeded()); - } else { - Assertions.assertTrue(result.failed()); - Mockito.verify(monitor, Mockito.times(1)).warning(Mockito.anyString()); + if (code == 200) { + Mockito.verify(monitor, Mockito.times(1)).debug(Mockito.anyString()); + Assertions.assertTrue(result.succeeded()); + } else { + Assertions.assertTrue(result.failed()); + Mockito.verify(monitor, Mockito.times(1)).warning(Mockito.anyString()); + } } - } - @Test - void testResponseFromException() throws IOException { - Mockito.when(client.getHealth()).thenThrow(new IOException()); + @Test + void testResponseFromException() throws IOException { + Mockito.when(client.getHealth()).thenThrow(new IOException()); - final HealthCheckResult result = healthCheck.get(); - Assertions.assertFalse(result.succeeded()); - } + final HealthCheckResult result = healthCheck.get(); + Assertions.assertFalse(result.succeeded()); + } } diff --git a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultIT.java b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultIT.java deleted file mode 100644 index f6cb202b8..000000000 --- a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultIT.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) 2022 Mercedes-Benz Tech Innovation GmbH - * Copyright (c) 2021,2022 Contributors to the Eclipse Foundation - * - * See the NOTICE file(s) distributed with this work for additional - * information regarding copyright ownership. - * - * This program and the accompanying materials are made available under the - * terms of the Apache License, Version 2.0 which is available at - * https://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. - * - * SPDX-License-Identifier: Apache-2.0 - */ - -package org.eclipse.tractusx.edc.hashicorpvault; - -import java.util.UUID; -import org.eclipse.edc.spi.security.Vault; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -class HashicorpVaultIT extends AbstractHashicorpIT { - - @Test - @DisplayName("Resolve a secret that exists") - void testResolveSecret_exists() { - Vault vault = getVault(); - String secretValue = vault.resolveSecret(VAULT_ENTRY_KEY); - Assertions.assertEquals(VAULT_ENTRY_VALUE, secretValue); - } - - @Test - @DisplayName("Resolve a secret from a sub directory") - void testResolveSecret_inASubDirectory() { - Vault vault = getVault(); - String key = "sub/" + VAULT_ENTRY_KEY; - String value = key + "value"; - - vault.storeSecret(key, value); - String secretValue = vault.resolveSecret(key); - Assertions.assertEquals(value, secretValue); - } - - @ParameterizedTest - @ValueSource(strings = {"foo!bar", "foo.bar", "foo[bar]", "sub/foo{bar}"}) - @DisplayName("Resolve a secret with url encoded characters") - void testResolveSecret_withUrlEncodedCharacters(String key) { - Vault vault = getVault(); - String value = key + "value"; - - vault.storeSecret(key, value); - String secretValue = vault.resolveSecret(key); - Assertions.assertEquals(value, secretValue); - } - - @Test - @DisplayName("Resolve a secret that does not exist") - void testResolveSecret_doesNotExist() { - Vault vault = getVault(); - Assertions.assertNull(vault.resolveSecret("wrong_key")); - } - - @Test - @DisplayName("Update a secret that exists") - void testSetSecret_exists() { - String key = UUID.randomUUID().toString(); - String value1 = UUID.randomUUID().toString(); - String value2 = UUID.randomUUID().toString(); - - Vault vault = getVault(); - vault.storeSecret(key, value1); - vault.storeSecret(key, value2); - String secretValue = vault.resolveSecret(key); - Assertions.assertEquals(value2, secretValue); - } - - @Test - @DisplayName("Create a secret that does not exist") - void testSetSecret_doesNotExist() { - String key = UUID.randomUUID().toString(); - String value = UUID.randomUUID().toString(); - - Vault vault = getVault(); - vault.storeSecret(key, value); - String secretValue = vault.resolveSecret(key); - Assertions.assertEquals(value, secretValue); - } - - @Test - @DisplayName("Delete a secret that exists") - void testDeleteSecret_exists() { - String key = UUID.randomUUID().toString(); - String value = UUID.randomUUID().toString(); - - Vault vault = getVault(); - vault.storeSecret(key, value); - vault.deleteSecret(key); - - Assertions.assertNull(vault.resolveSecret(key)); - } - - @Test - @DisplayName("Try to delete a secret that does not exist") - void testDeleteSecret_doesNotExist() { - String key = UUID.randomUUID().toString(); - - Vault vault = getVault(); - vault.deleteSecret(key); - - Assertions.assertNull(vault.resolveSecret(key)); - } -} diff --git a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultIt.java b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultIt.java new file mode 100644 index 000000000..fd56385d1 --- /dev/null +++ b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultIt.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2022 Mercedes-Benz Tech Innovation GmbH + * Copyright (c) 2021,2022 Contributors to the Eclipse Foundation + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.eclipse.tractusx.edc.hashicorpvault; + +import org.eclipse.edc.spi.security.Vault; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.UUID; + +class HashicorpVaultIt extends AbstractHashicorpIt { + + @Test + @DisplayName("Resolve a secret that exists") + void testResolveSecret_exists() { + Vault vault = getVault(); + String secretValue = vault.resolveSecret(VAULT_ENTRY_KEY); + Assertions.assertEquals(VAULT_ENTRY_VALUE, secretValue); + } + + @Test + @DisplayName("Resolve a secret from a sub directory") + void testResolveSecret_inSubDirectory() { + Vault vault = getVault(); + String key = "sub/" + VAULT_ENTRY_KEY; + String value = key + "value"; + + vault.storeSecret(key, value); + String secretValue = vault.resolveSecret(key); + Assertions.assertEquals(value, secretValue); + } + + @ParameterizedTest + @ValueSource(strings = {"foo!bar", "foo.bar", "foo[bar]", "sub/foo{bar}"}) + @DisplayName("Resolve a secret with url encoded characters") + void testResolveSecret_withUrlEncodedCharacters(String key) { + Vault vault = getVault(); + String value = key + "value"; + + vault.storeSecret(key, value); + String secretValue = vault.resolveSecret(key); + Assertions.assertEquals(value, secretValue); + } + + @Test + @DisplayName("Resolve a secret that does not exist") + void testResolveSecret_doesNotExist() { + Vault vault = getVault(); + Assertions.assertNull(vault.resolveSecret("wrong_key")); + } + + @Test + @DisplayName("Update a secret that exists") + void testSetSecret_exists() { + String key = UUID.randomUUID().toString(); + String value1 = UUID.randomUUID().toString(); + String value2 = UUID.randomUUID().toString(); + + Vault vault = getVault(); + vault.storeSecret(key, value1); + vault.storeSecret(key, value2); + String secretValue = vault.resolveSecret(key); + Assertions.assertEquals(value2, secretValue); + } + + @Test + @DisplayName("Create a secret that does not exist") + void testSetSecret_doesNotExist() { + String key = UUID.randomUUID().toString(); + String value = UUID.randomUUID().toString(); + + Vault vault = getVault(); + vault.storeSecret(key, value); + String secretValue = vault.resolveSecret(key); + Assertions.assertEquals(value, secretValue); + } + + @Test + @DisplayName("Delete a secret that exists") + void testDeleteSecret_exists() { + String key = UUID.randomUUID().toString(); + String value = UUID.randomUUID().toString(); + + Vault vault = getVault(); + vault.storeSecret(key, value); + vault.deleteSecret(key); + + Assertions.assertNull(vault.resolveSecret(key)); + } + + @Test + @DisplayName("Try to delete a secret that does not exist") + void testDeleteSecret_doesNotExist() { + String key = UUID.randomUUID().toString(); + + Vault vault = getVault(); + vault.deleteSecret(key); + + Assertions.assertNull(vault.resolveSecret(key)); + } +} diff --git a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultTest.java b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultTest.java index 03512f2a6..168d22562 100644 --- a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultTest.java +++ b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/HashicorpVaultTest.java @@ -20,7 +20,6 @@ package org.eclipse.tractusx.edc.hashicorpvault; -import java.util.UUID; import lombok.SneakyThrows; import org.eclipse.edc.spi.monitor.Monitor; import org.eclipse.edc.spi.result.Result; @@ -29,123 +28,125 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import java.util.UUID; + class HashicorpVaultTest { - private static final String key = "key"; - - // mocks - private HashicorpVaultClient vaultClient; - private HashicorpVault vault; - - @BeforeEach - void setup() { - vaultClient = Mockito.mock(HashicorpVaultClient.class); - final Monitor monitor = Mockito.mock(Monitor.class); - vault = new HashicorpVault(vaultClient, monitor); - } - - @Test - @SneakyThrows - void getSecretSuccess() { - // prepare - String value = UUID.randomUUID().toString(); - Result result = Mockito.mock(Result.class); - Mockito.when(vaultClient.getSecretValue(key)).thenReturn(result); - Mockito.when(result.getContent()).thenReturn(value); - Mockito.when(result.succeeded()).thenReturn(true); - Mockito.when(result.failed()).thenReturn(false); - - // invoke - String returnValue = vault.resolveSecret(key); - - // verify - Mockito.verify(vaultClient, Mockito.times(1)).getSecretValue(key); - Assertions.assertEquals(value, returnValue); - } - - @Test - @SneakyThrows - void getSecretFailure() { - // prepare - Result result = Mockito.mock(Result.class); - Mockito.when(vaultClient.getSecretValue(key)).thenReturn(result); - Mockito.when(result.succeeded()).thenReturn(false); - Mockito.when(result.failed()).thenReturn(true); - - // invoke - String returnValue = vault.resolveSecret(key); - - // verify - Mockito.verify(vaultClient, Mockito.times(1)).getSecretValue(key); - Assertions.assertNull(returnValue); - } - - @Test - @SneakyThrows - void setSecretSuccess() { - // prepare - String value = UUID.randomUUID().toString(); - Result result = Mockito.mock(Result.class); - Mockito.when(vaultClient.setSecret(key, value)).thenReturn(result); - Mockito.when(result.succeeded()).thenReturn(true); - Mockito.when(result.failed()).thenReturn(false); - - // invoke - Result returnValue = vault.storeSecret(key, value); - - // verify - Mockito.verify(vaultClient, Mockito.times(1)).setSecret(key, value); - Assertions.assertTrue(returnValue.succeeded()); - } - - @Test - @SneakyThrows - void setSecretFailure() { - // prepare - String value = UUID.randomUUID().toString(); - Result result = Mockito.mock(Result.class); - Mockito.when(vaultClient.setSecret(key, value)).thenReturn(result); - Mockito.when(result.succeeded()).thenReturn(false); - Mockito.when(result.failed()).thenReturn(true); - - // invoke - Result returnValue = vault.storeSecret(key, value); - - // verify - Mockito.verify(vaultClient, Mockito.times(1)).setSecret(key, value); - Assertions.assertTrue(returnValue.failed()); - } - - @Test - @SneakyThrows - void destroySecretSuccess() { - // prepare - Result result = Mockito.mock(Result.class); - Mockito.when(vaultClient.destroySecret(key)).thenReturn(result); - Mockito.when(result.succeeded()).thenReturn(true); - Mockito.when(result.failed()).thenReturn(false); - - // invoke - Result returnValue = vault.deleteSecret(key); - - // verify - Mockito.verify(vaultClient, Mockito.times(1)).destroySecret(key); - Assertions.assertTrue(returnValue.succeeded()); - } - - @Test - @SneakyThrows - void destroySecretFailure() { - // prepare - Result result = Mockito.mock(Result.class); - Mockito.when(vaultClient.destroySecret(key)).thenReturn(result); - Mockito.when(result.succeeded()).thenReturn(false); - Mockito.when(result.failed()).thenReturn(true); - - // invoke - Result returnValue = vault.deleteSecret(key); - - // verify - Mockito.verify(vaultClient, Mockito.times(1)).destroySecret(key); - Assertions.assertTrue(returnValue.failed()); - } + private static final String KEY = "key"; + + // mocks + private HashicorpVaultClient vaultClient; + private HashicorpVault vault; + + @BeforeEach + void setup() { + vaultClient = Mockito.mock(HashicorpVaultClient.class); + final Monitor monitor = Mockito.mock(Monitor.class); + vault = new HashicorpVault(vaultClient, monitor); + } + + @Test + @SneakyThrows + void getSecretSuccess() { + // prepare + String value = UUID.randomUUID().toString(); + Result result = Mockito.mock(Result.class); + Mockito.when(vaultClient.getSecretValue(KEY)).thenReturn(result); + Mockito.when(result.getContent()).thenReturn(value); + Mockito.when(result.succeeded()).thenReturn(true); + Mockito.when(result.failed()).thenReturn(false); + + // invoke + String returnValue = vault.resolveSecret(KEY); + + // verify + Mockito.verify(vaultClient, Mockito.times(1)).getSecretValue(KEY); + Assertions.assertEquals(value, returnValue); + } + + @Test + @SneakyThrows + void getSecretFailure() { + // prepare + Result result = Mockito.mock(Result.class); + Mockito.when(vaultClient.getSecretValue(KEY)).thenReturn(result); + Mockito.when(result.succeeded()).thenReturn(false); + Mockito.when(result.failed()).thenReturn(true); + + // invoke + String returnValue = vault.resolveSecret(KEY); + + // verify + Mockito.verify(vaultClient, Mockito.times(1)).getSecretValue(KEY); + Assertions.assertNull(returnValue); + } + + @Test + @SneakyThrows + void setSecretSuccess() { + // prepare + String value = UUID.randomUUID().toString(); + Result result = Mockito.mock(Result.class); + Mockito.when(vaultClient.setSecret(KEY, value)).thenReturn(result); + Mockito.when(result.succeeded()).thenReturn(true); + Mockito.when(result.failed()).thenReturn(false); + + // invoke + Result returnValue = vault.storeSecret(KEY, value); + + // verify + Mockito.verify(vaultClient, Mockito.times(1)).setSecret(KEY, value); + Assertions.assertTrue(returnValue.succeeded()); + } + + @Test + @SneakyThrows + void setSecretFailure() { + // prepare + String value = UUID.randomUUID().toString(); + Result result = Mockito.mock(Result.class); + Mockito.when(vaultClient.setSecret(KEY, value)).thenReturn(result); + Mockito.when(result.succeeded()).thenReturn(false); + Mockito.when(result.failed()).thenReturn(true); + + // invoke + Result returnValue = vault.storeSecret(KEY, value); + + // verify + Mockito.verify(vaultClient, Mockito.times(1)).setSecret(KEY, value); + Assertions.assertTrue(returnValue.failed()); + } + + @Test + @SneakyThrows + void destroySecretSuccess() { + // prepare + Result result = Mockito.mock(Result.class); + Mockito.when(vaultClient.destroySecret(KEY)).thenReturn(result); + Mockito.when(result.succeeded()).thenReturn(true); + Mockito.when(result.failed()).thenReturn(false); + + // invoke + Result returnValue = vault.deleteSecret(KEY); + + // verify + Mockito.verify(vaultClient, Mockito.times(1)).destroySecret(KEY); + Assertions.assertTrue(returnValue.succeeded()); + } + + @Test + @SneakyThrows + void destroySecretFailure() { + // prepare + Result result = Mockito.mock(Result.class); + Mockito.when(vaultClient.destroySecret(KEY)).thenReturn(result); + Mockito.when(result.succeeded()).thenReturn(false); + Mockito.when(result.failed()).thenReturn(true); + + // invoke + Result returnValue = vault.deleteSecret(KEY); + + // verify + Mockito.verify(vaultClient, Mockito.times(1)).destroySecret(KEY); + Assertions.assertTrue(returnValue.failed()); + } } diff --git a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/PathUtilTest.java b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/PathUtilTest.java index a5d9821dd..b79a341b2 100644 --- a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/PathUtilTest.java +++ b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/PathUtilTest.java @@ -14,27 +14,28 @@ package org.eclipse.tractusx.edc.hashicorpvault; -import java.util.stream.Stream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import java.util.stream.Stream; + class PathUtilTest { - @ParameterizedTest - @MethodSource("provideStringsForTrimsPathsCorrect") - void trimsPathsCorrect(String path, String expected) { - final String result = PathUtil.trimLeadingOrEndingSlash(path); + private static Stream provideStringsForTrimsPathsCorrect() { + return Stream.of( + Arguments.of("v1/secret/data", "v1/secret/data"), + Arguments.of("/v1/secret/data", "v1/secret/data"), + Arguments.of("/v1/secret/data/", "v1/secret/data"), + Arguments.of("v1/secret/data/", "v1/secret/data")); + } - Assertions.assertEquals(expected, result); - } + @ParameterizedTest + @MethodSource("provideStringsForTrimsPathsCorrect") + void trimsPathsCorrect(String path, String expected) { + final String result = PathUtil.trimLeadingOrEndingSlash(path); - private static Stream provideStringsForTrimsPathsCorrect() { - return Stream.of( - Arguments.of("v1/secret/data", "v1/secret/data"), - Arguments.of("/v1/secret/data", "v1/secret/data"), - Arguments.of("/v1/secret/data/", "v1/secret/data"), - Arguments.of("v1/secret/data/", "v1/secret/data")); - } + Assertions.assertEquals(expected, result); + } } diff --git a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/X509CertificateTestUtil.java b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/X509CertificateTestUtil.java index 051fe00eb..af9f8b1a2 100644 --- a/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/X509CertificateTestUtil.java +++ b/edc-extensions/hashicorp-vault/src/test/java/org/eclipse/tractusx/edc/hashicorpvault/X509CertificateTestUtil.java @@ -20,23 +20,6 @@ package org.eclipse.tractusx.edc.hashicorpvault; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.time.Duration; -import java.time.Instant; -import java.util.Date; -import java.util.Optional; import lombok.SneakyThrows; import lombok.experimental.UtilityClass; import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers; @@ -59,80 +42,98 @@ import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.testcontainers.shaded.org.bouncycastle.openssl.jcajce.JcaPEMWriter; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.time.Duration; +import java.time.Instant; +import java.util.Date; +import java.util.Optional; + @UtilityClass final class X509CertificateTestUtil { - private static final String SIGNATURE_ALGORITHM = "SHA256WithRSAEncryption"; - private static final Provider PROVIDER = new BouncyCastleProvider(); - private static final JcaX509CertificateConverter JCA_X509_CERTIFICATE_CONVERTER = - new JcaX509CertificateConverter().setProvider(PROVIDER); + private static final String SIGNATURE_ALGORITHM = "SHA256WithRSAEncryption"; + private static final Provider PROVIDER = new BouncyCastleProvider(); + private static final JcaX509CertificateConverter JCA_X509_CERTIFICATE_CONVERTER = + new JcaX509CertificateConverter().setProvider(PROVIDER); - static X509Certificate generateCertificate(int validity, String cn) - throws CertificateException, OperatorCreationException, IOException, - NoSuchAlgorithmException { + static X509Certificate generateCertificate(int validity, String cn) + throws CertificateException, OperatorCreationException, IOException, + NoSuchAlgorithmException { - KeyPair keyPair = generateKeyPair(); + KeyPair keyPair = generateKeyPair(); - Instant now = Instant.now(); - ContentSigner contentSigner = - new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).build(keyPair.getPrivate()); - X500Name issuer = - new X500Name( - String.format( - "CN=%s", - Optional.ofNullable(cn) - .map(String::trim) - .filter(s -> !s.isEmpty()) - .orElse("rootCA"))); - BigInteger serial = BigInteger.valueOf(now.toEpochMilli()); - Date notBefore = Date.from(now); - Date notAfter = Date.from(now.plus(Duration.ofDays(validity))); - PublicKey publicKey = keyPair.getPublic(); - X509v3CertificateBuilder certificateBuilder = - new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, issuer, publicKey); - certificateBuilder = - certificateBuilder.addExtension( - Extension.subjectKeyIdentifier, false, createSubjectKeyId(publicKey)); - certificateBuilder = - certificateBuilder.addExtension( - Extension.authorityKeyIdentifier, false, createAuthorityKeyId(publicKey)); - certificateBuilder = - certificateBuilder.addExtension( - Extension.basicConstraints, true, new BasicConstraints(true)); - return JCA_X509_CERTIFICATE_CONVERTER.getCertificate(certificateBuilder.build(contentSigner)); - } + Instant now = Instant.now(); + ContentSigner contentSigner = + new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).build(keyPair.getPrivate()); + X500Name issuer = + new X500Name( + String.format( + "CN=%s", + Optional.ofNullable(cn) + .map(String::trim) + .filter(s -> !s.isEmpty()) + .orElse("rootCA"))); + BigInteger serial = BigInteger.valueOf(now.toEpochMilli()); + Date notBefore = Date.from(now); + Date notAfter = Date.from(now.plus(Duration.ofDays(validity))); + PublicKey publicKey = keyPair.getPublic(); + X509v3CertificateBuilder certificateBuilder = + new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, issuer, publicKey); + certificateBuilder = + certificateBuilder.addExtension( + Extension.subjectKeyIdentifier, false, createSubjectKeyId(publicKey)); + certificateBuilder = + certificateBuilder.addExtension( + Extension.authorityKeyIdentifier, false, createAuthorityKeyId(publicKey)); + certificateBuilder = + certificateBuilder.addExtension( + Extension.basicConstraints, true, new BasicConstraints(true)); + return JCA_X509_CERTIFICATE_CONVERTER.getCertificate(certificateBuilder.build(contentSigner)); + } - private static KeyPair generateKeyPair() throws NoSuchAlgorithmException { - KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", PROVIDER); - keyPairGenerator.initialize(1024, new SecureRandom()); + private static KeyPair generateKeyPair() throws NoSuchAlgorithmException { + KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", PROVIDER); + keyPairGenerator.initialize(1024, new SecureRandom()); - return keyPairGenerator.generateKeyPair(); - } + return keyPairGenerator.generateKeyPair(); + } - private static SubjectKeyIdentifier createSubjectKeyId(PublicKey publicKey) - throws OperatorCreationException { - SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); - DigestCalculator digCalc = - new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)); - return new X509ExtensionUtils(digCalc).createSubjectKeyIdentifier(publicKeyInfo); - } + private static SubjectKeyIdentifier createSubjectKeyId(PublicKey publicKey) + throws OperatorCreationException { + SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); + DigestCalculator digCalc = + new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)); + return new X509ExtensionUtils(digCalc).createSubjectKeyIdentifier(publicKeyInfo); + } - private static AuthorityKeyIdentifier createAuthorityKeyId(PublicKey publicKey) - throws OperatorCreationException { - SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); - DigestCalculator digCalc = - new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)); - return new X509ExtensionUtils(digCalc).createAuthorityKeyIdentifier(publicKeyInfo); - } + private static AuthorityKeyIdentifier createAuthorityKeyId(PublicKey publicKey) + throws OperatorCreationException { + SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); + DigestCalculator digCalc = + new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)); + return new X509ExtensionUtils(digCalc).createAuthorityKeyIdentifier(publicKeyInfo); + } - @SneakyThrows - static String convertToPem(X509Certificate certificate) { - try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { - try (OutputStreamWriter writer = new OutputStreamWriter(stream)) { - JcaPEMWriter pemWriter = new JcaPEMWriter(writer); - pemWriter.writeObject(certificate); - pemWriter.flush(); - } - return stream.toString(StandardCharsets.UTF_8); + @SneakyThrows + static String convertToPem(X509Certificate certificate) { + try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { + try (OutputStreamWriter writer = new OutputStreamWriter(stream)) { + JcaPEMWriter pemWriter = new JcaPEMWriter(writer); + pemWriter.writeObject(certificate); + pemWriter.flush(); + } + return stream.toString(StandardCharsets.UTF_8); + } } - } } diff --git a/edc-extensions/observability-api-customization/src/main/java/org/eclipse/tractusx/edc/api/observability/TxObservabilityApiController.java b/edc-extensions/observability-api-customization/src/main/java/org/eclipse/tractusx/edc/api/observability/TxObservabilityApiController.java index 5320161f9..8d5bb33af 100644 --- a/edc-extensions/observability-api-customization/src/main/java/org/eclipse/tractusx/edc/api/observability/TxObservabilityApiController.java +++ b/edc-extensions/observability-api-customization/src/main/java/org/eclipse/tractusx/edc/api/observability/TxObservabilityApiController.java @@ -20,18 +20,17 @@ import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; -import org.eclipse.edc.spi.monitor.Monitor; import org.eclipse.edc.spi.system.health.HealthCheckService; import org.eclipse.edc.spi.system.health.HealthStatus; -import org.jetbrains.annotations.NotNull; -@Consumes({ MediaType.APPLICATION_JSON }) -@Produces({ MediaType.APPLICATION_JSON }) +@Consumes({MediaType.APPLICATION_JSON}) +@Produces({MediaType.APPLICATION_JSON}) @Path("/check") public class TxObservabilityApiController implements TxObservabilityApi { private final HealthCheckService healthCheckService; + public TxObservabilityApiController(HealthCheckService provider) { healthCheckService = provider; } diff --git a/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/AbstractPostgresqlMigrationExtension.java b/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/AbstractPostgresqlMigrationExtension.java index ab0efc62d..722518e5f 100644 --- a/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/AbstractPostgresqlMigrationExtension.java +++ b/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/AbstractPostgresqlMigrationExtension.java @@ -20,8 +20,6 @@ package org.eclipse.tractusx.edc.postgresql.migration; -import java.util.Objects; -import java.util.Properties; import org.eclipse.edc.spi.persistence.EdcPersistenceException; import org.eclipse.edc.spi.system.ServiceExtension; import org.eclipse.edc.spi.system.ServiceExtensionContext; @@ -31,80 +29,75 @@ import org.flywaydb.core.api.MigrationVersion; import org.flywaydb.core.api.output.MigrateResult; +import java.util.Objects; +import java.util.Properties; + abstract class AbstractPostgresqlMigrationExtension implements ServiceExtension { - protected abstract String getDataSourceNameConfigurationKey(); + private static final String EDC_DATASOURCE_PREFIX = "edc.datasource"; + private static final String MIGRATION_LOCATION_BASE = + String.format("classpath:%s", AbstractPostgresqlMigrationExtension.class.getPackageName().replace(".", "/")); - protected abstract String getSubsystemName(); + protected abstract String getDataSourceNameConfigurationKey(); - private static final String EDC_DATASOURCE_PREFIX = "edc.datasource"; - private static final String MIGRATION_LOCATION_BASE = - String.format( - "classpath:%s", - AbstractPostgresqlMigrationExtension.class.getPackageName().replace(".", "/")); + protected abstract String getSubsystemName(); - @Override - public void initialize(final ServiceExtensionContext context) { - final String subSystemName = Objects.requireNonNull(getSubsystemName()); + @Override + public void initialize(final ServiceExtensionContext context) { + final String subSystemName = Objects.requireNonNull(getSubsystemName()); - final String dataSourceName = - context.getConfig().getString(getDataSourceNameConfigurationKey(), null); - if (dataSourceName == null) { - return; - } + final String dataSourceName = + context.getConfig().getString(getDataSourceNameConfigurationKey(), null); + if (dataSourceName == null) { + return; + } - boolean enabled = - context - .getConfig() - .getBoolean( - String.format( - "org.eclipse.tractusx.edc.postgresql.migration.%s.enabled", subSystemName), - true); + boolean enabled = context.getConfig() + .getBoolean(String.format("org.eclipse.tractusx.edc.postgresql.migration.%s.enabled", subSystemName), true); - if (!enabled) { - return; - } + if (!enabled) { + return; + } - Config datasourceConfiguration = - context.getConfig(String.join(".", EDC_DATASOURCE_PREFIX, dataSourceName)); + Config datasourceConfiguration = context.getConfig(String.join(".", EDC_DATASOURCE_PREFIX, dataSourceName)); - final String jdbcUrl = Objects.requireNonNull(datasourceConfiguration.getString("url")); - final Properties jdbcProperties = new Properties(); - jdbcProperties.putAll(datasourceConfiguration.getRelativeEntries()); + final String jdbcUrl = Objects.requireNonNull(datasourceConfiguration.getString("url")); + final Properties jdbcProperties = new Properties(); + jdbcProperties.putAll(datasourceConfiguration.getRelativeEntries()); - final DriverManagerConnectionFactory driverManagerConnectionFactory = - new DriverManagerConnectionFactory(jdbcUrl, jdbcProperties); - final ConnectionFactoryDataSource dataSource = - new ConnectionFactoryDataSource(driverManagerConnectionFactory); + final DriverManagerConnectionFactory driverManagerConnectionFactory = + new DriverManagerConnectionFactory(jdbcUrl, jdbcProperties); + final ConnectionFactoryDataSource dataSource = + new ConnectionFactoryDataSource(driverManagerConnectionFactory); - final String schemaHistoryTableName = getSchemaHistoryTableName(subSystemName); - final String migrationsLocation = getMigrationsLocation(); + final String schemaHistoryTableName = getSchemaHistoryTableName(subSystemName); + final String migrationsLocation = getMigrationsLocation(); - final Flyway flyway = - Flyway.configure() - .baselineVersion(MigrationVersion.fromVersion("0.0.0")) - .failOnMissingLocations(true) - .dataSource(dataSource) - .table(schemaHistoryTableName) - .locations(migrationsLocation) - .load(); + final Flyway flyway = + Flyway.configure() + .baselineVersion(MigrationVersion.fromVersion("0.0.0")) + .failOnMissingLocations(true) + .dataSource(dataSource) + .table(schemaHistoryTableName) + .locations(migrationsLocation) + .load(); - flyway.baseline(); + flyway.baseline(); - final MigrateResult migrateResult = flyway.migrate(); + final MigrateResult migrateResult = flyway.migrate(); - if (!migrateResult.success) { - throw new EdcPersistenceException( - String.format( - "Migrating DataSource %s for subsystem %s failed: %s", - dataSourceName, subSystemName, String.join(", ", migrateResult.warnings))); + if (!migrateResult.success) { + throw new EdcPersistenceException( + String.format( + "Migrating DataSource %s for subsystem %s failed: %s", + dataSourceName, subSystemName, String.join(", ", migrateResult.warnings))); + } } - } - private String getMigrationsLocation() { - return String.join("/", MIGRATION_LOCATION_BASE, getSubsystemName()); - } + private String getMigrationsLocation() { + return String.join("/", MIGRATION_LOCATION_BASE, getSubsystemName()); + } - private String getSchemaHistoryTableName(final String subSystemName) { - return String.format("flyway_schema_history_%s", subSystemName); - } + private String getSchemaHistoryTableName(final String subSystemName) { + return String.format("flyway_schema_history_%s", subSystemName); + } } diff --git a/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/AssetPostgresqlMigrationExtension.java b/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/AssetPostgresqlMigrationExtension.java index d44663e2b..ab3d6489a 100644 --- a/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/AssetPostgresqlMigrationExtension.java +++ b/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/AssetPostgresqlMigrationExtension.java @@ -23,13 +23,13 @@ import org.eclipse.edc.connector.store.sql.assetindex.ConfigurationKeys; public class AssetPostgresqlMigrationExtension extends AbstractPostgresqlMigrationExtension { - private static final String NAME_SUBSYSTEM = "asset"; + private static final String NAME_SUBSYSTEM = "asset"; - protected String getDataSourceNameConfigurationKey() { - return ConfigurationKeys.DATASOURCE_SETTING_NAME; - } + protected String getDataSourceNameConfigurationKey() { + return ConfigurationKeys.DATASOURCE_SETTING_NAME; + } - protected String getSubsystemName() { - return NAME_SUBSYSTEM; - } + protected String getSubsystemName() { + return NAME_SUBSYSTEM; + } } diff --git a/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/ContractDefinitionPostgresqlMigrationExtension.java b/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/ContractDefinitionPostgresqlMigrationExtension.java index a5b65aafa..168814580 100644 --- a/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/ContractDefinitionPostgresqlMigrationExtension.java +++ b/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/ContractDefinitionPostgresqlMigrationExtension.java @@ -20,17 +20,16 @@ package org.eclipse.tractusx.edc.postgresql.migration; -public class ContractDefinitionPostgresqlMigrationExtension - extends AbstractPostgresqlMigrationExtension { - private static final String NAME_SUBSYSTEM = "contractdefinition"; +public class ContractDefinitionPostgresqlMigrationExtension extends AbstractPostgresqlMigrationExtension { + private static final String NAME_SUBSYSTEM = "contractdefinition"; - private static final String DATASOURCE_SETTING_NAME = "edc.datasource.contractdefinition.name"; + private static final String DATASOURCE_SETTING_NAME = "edc.datasource.contractdefinition.name"; - protected String getDataSourceNameConfigurationKey() { - return DATASOURCE_SETTING_NAME; - } + protected String getDataSourceNameConfigurationKey() { + return DATASOURCE_SETTING_NAME; + } - protected String getSubsystemName() { - return NAME_SUBSYSTEM; - } + protected String getSubsystemName() { + return NAME_SUBSYSTEM; + } } diff --git a/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/ContractNegotiationPostgresqlMigrationExtension.java b/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/ContractNegotiationPostgresqlMigrationExtension.java index c2da93732..760883b54 100644 --- a/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/ContractNegotiationPostgresqlMigrationExtension.java +++ b/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/ContractNegotiationPostgresqlMigrationExtension.java @@ -20,17 +20,16 @@ package org.eclipse.tractusx.edc.postgresql.migration; -public class ContractNegotiationPostgresqlMigrationExtension - extends AbstractPostgresqlMigrationExtension { - private static final String NAME_SUBSYSTEM = "contractnegotiation"; +public class ContractNegotiationPostgresqlMigrationExtension extends AbstractPostgresqlMigrationExtension { + private static final String NAME_SUBSYSTEM = "contractnegotiation"; - private static final String DATASOURCE_SETTING_NAME = "edc.datasource.contractnegotiation.name"; + private static final String DATASOURCE_SETTING_NAME = "edc.datasource.contractnegotiation.name"; - protected String getDataSourceNameConfigurationKey() { - return DATASOURCE_SETTING_NAME; - } + protected String getDataSourceNameConfigurationKey() { + return DATASOURCE_SETTING_NAME; + } - protected String getSubsystemName() { - return NAME_SUBSYSTEM; - } + protected String getSubsystemName() { + return NAME_SUBSYSTEM; + } } diff --git a/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/DriverManagerConnectionFactory.java b/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/DriverManagerConnectionFactory.java index 621bc8774..9a273cccc 100644 --- a/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/DriverManagerConnectionFactory.java +++ b/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/DriverManagerConnectionFactory.java @@ -20,28 +20,29 @@ package org.eclipse.tractusx.edc.postgresql.migration; +import org.eclipse.edc.spi.persistence.EdcPersistenceException; +import org.eclipse.edc.sql.ConnectionFactory; + import java.sql.Connection; import java.sql.DriverManager; import java.util.Objects; import java.util.Properties; -import org.eclipse.edc.spi.persistence.EdcPersistenceException; -import org.eclipse.edc.sql.ConnectionFactory; class DriverManagerConnectionFactory implements ConnectionFactory { - private final String jdbcUrl; - private final Properties properties; + private final String jdbcUrl; + private final Properties properties; - public DriverManagerConnectionFactory(final String jdbcUrl, final Properties properties) { - this.jdbcUrl = Objects.requireNonNull(jdbcUrl); - this.properties = Objects.requireNonNull(properties); - } + DriverManagerConnectionFactory(final String jdbcUrl, final Properties properties) { + this.jdbcUrl = Objects.requireNonNull(jdbcUrl); + this.properties = Objects.requireNonNull(properties); + } - @Override - public Connection create() { - try { - return DriverManager.getConnection(jdbcUrl, properties); - } catch (Exception exception) { - throw new EdcPersistenceException(exception.getMessage(), exception); + @Override + public Connection create() { + try { + return DriverManager.getConnection(jdbcUrl, properties); + } catch (Exception exception) { + throw new EdcPersistenceException(exception.getMessage(), exception); + } } - } } diff --git a/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/PolicyPostgresqlMigrationExtension.java b/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/PolicyPostgresqlMigrationExtension.java index 88f47d858..02c7a5314 100644 --- a/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/PolicyPostgresqlMigrationExtension.java +++ b/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/PolicyPostgresqlMigrationExtension.java @@ -21,15 +21,15 @@ package org.eclipse.tractusx.edc.postgresql.migration; public class PolicyPostgresqlMigrationExtension extends AbstractPostgresqlMigrationExtension { - private static final String NAME_SUBSYSTEM = "policy"; + private static final String NAME_SUBSYSTEM = "policy"; - private static final String DATASOURCE_SETTING_NAME = "edc.datasource.policy.name"; + private static final String DATASOURCE_SETTING_NAME = "edc.datasource.policy.name"; - protected String getDataSourceNameConfigurationKey() { - return DATASOURCE_SETTING_NAME; - } + protected String getDataSourceNameConfigurationKey() { + return DATASOURCE_SETTING_NAME; + } - protected String getSubsystemName() { - return NAME_SUBSYSTEM; - } + protected String getSubsystemName() { + return NAME_SUBSYSTEM; + } } diff --git a/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/TransferProcessPostgresqlMigrationExtension.java b/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/TransferProcessPostgresqlMigrationExtension.java index 1379391e7..f9d41b896 100644 --- a/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/TransferProcessPostgresqlMigrationExtension.java +++ b/edc-extensions/postgresql-migration/src/main/java/org/eclipse/tractusx/edc/postgresql/migration/TransferProcessPostgresqlMigrationExtension.java @@ -20,17 +20,16 @@ package org.eclipse.tractusx.edc.postgresql.migration; -public class TransferProcessPostgresqlMigrationExtension - extends AbstractPostgresqlMigrationExtension { - private static final String NAME_SUBSYSTEM = "transferprocess"; +public class TransferProcessPostgresqlMigrationExtension extends AbstractPostgresqlMigrationExtension { + private static final String NAME_SUBSYSTEM = "transferprocess"; - private static final String DATASOURCE_SETTING_NAME = "edc.datasource.transferprocess.name"; + private static final String DATASOURCE_SETTING_NAME = "edc.datasource.transferprocess.name"; - protected String getDataSourceNameConfigurationKey() { - return DATASOURCE_SETTING_NAME; - } + protected String getDataSourceNameConfigurationKey() { + return DATASOURCE_SETTING_NAME; + } - protected String getSubsystemName() { - return NAME_SUBSYSTEM; - } + protected String getSubsystemName() { + return NAME_SUBSYSTEM; + } } diff --git a/edc-extensions/provision-additional-headers/src/main/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersProvisionedResource.java b/edc-extensions/provision-additional-headers/src/main/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersProvisionedResource.java index b0d3534ea..29b5328ed 100644 --- a/edc-extensions/provision-additional-headers/src/main/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersProvisionedResource.java +++ b/edc-extensions/provision-additional-headers/src/main/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersProvisionedResource.java @@ -28,17 +28,17 @@ @JsonDeserialize(builder = AdditionalHeadersProvisionedResource.Builder.class) class AdditionalHeadersProvisionedResource extends ProvisionedContentResource { - @JsonPOJOBuilder(withPrefix = "") - public static class Builder - extends ProvisionedContentResource.Builder { + @JsonPOJOBuilder(withPrefix = "") + public static class Builder + extends ProvisionedContentResource.Builder { - private Builder() { - super(new AdditionalHeadersProvisionedResource()); - } + private Builder() { + super(new AdditionalHeadersProvisionedResource()); + } - @JsonCreator - public static Builder newInstance() { - return new Builder(); + @JsonCreator + public static Builder newInstance() { + return new Builder(); + } } - } } diff --git a/edc-extensions/provision-additional-headers/src/main/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersProvisioner.java b/edc-extensions/provision-additional-headers/src/main/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersProvisioner.java index b5b4085e5..f4c7ccf67 100644 --- a/edc-extensions/provision-additional-headers/src/main/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersProvisioner.java +++ b/edc-extensions/provision-additional-headers/src/main/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersProvisioner.java @@ -20,8 +20,6 @@ package org.eclipse.tractusx.edc.provision.additionalheaders; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; import org.eclipse.edc.connector.transfer.spi.provision.Provisioner; import org.eclipse.edc.connector.transfer.spi.types.DeprovisionedResource; import org.eclipse.edc.connector.transfer.spi.types.ProvisionResponse; @@ -31,48 +29,50 @@ import org.eclipse.edc.spi.response.StatusResult; import org.eclipse.edc.spi.types.domain.HttpDataAddress; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + public class AdditionalHeadersProvisioner - implements Provisioner< + implements Provisioner< AdditionalHeadersResourceDefinition, AdditionalHeadersProvisionedResource> { - @Override - public boolean canProvision(ResourceDefinition resourceDefinition) { - return resourceDefinition instanceof AdditionalHeadersResourceDefinition; - } + @Override + public boolean canProvision(ResourceDefinition resourceDefinition) { + return resourceDefinition instanceof AdditionalHeadersResourceDefinition; + } - @Override - public boolean canDeprovision(ProvisionedResource provisionedResource) { - return false; // nothing to deprovision - } + @Override + public boolean canDeprovision(ProvisionedResource provisionedResource) { + return false; // nothing to deprovision + } - @Override - public CompletableFuture> provision( - AdditionalHeadersResourceDefinition resourceDefinition, Policy policy) { + @Override + public CompletableFuture> provision(AdditionalHeadersResourceDefinition resourceDefinition, Policy policy) { - var address = - HttpDataAddress.Builder.newInstance() - .copyFrom(resourceDefinition.getDataAddress()) - .addAdditionalHeader("Edc-Contract-Agreement-Id", resourceDefinition.getContractId()) - .build(); + var address = + HttpDataAddress.Builder.newInstance() + .copyFrom(resourceDefinition.getDataAddress()) + .addAdditionalHeader("Edc-Contract-Agreement-Id", resourceDefinition.getContractId()) + .build(); - var provisioned = - AdditionalHeadersProvisionedResource.Builder.newInstance() - .id(UUID.randomUUID().toString()) - .resourceDefinitionId(resourceDefinition.getId()) - .transferProcessId(resourceDefinition.getTransferProcessId()) - .dataAddress(address) - .resourceName(UUID.randomUUID().toString()) - .hasToken(false) - .build(); + var provisioned = + AdditionalHeadersProvisionedResource.Builder.newInstance() + .id(UUID.randomUUID().toString()) + .resourceDefinitionId(resourceDefinition.getId()) + .transferProcessId(resourceDefinition.getTransferProcessId()) + .dataAddress(address) + .resourceName(UUID.randomUUID().toString()) + .hasToken(false) + .build(); - var response = ProvisionResponse.Builder.newInstance().resource(provisioned).build(); - var result = StatusResult.success(response); - return CompletableFuture.completedFuture(result); - } + var response = ProvisionResponse.Builder.newInstance().resource(provisioned).build(); + var result = StatusResult.success(response); + return CompletableFuture.completedFuture(result); + } - @Override - public CompletableFuture> deprovision( - AdditionalHeadersProvisionedResource additionalHeadersProvisionedResource, Policy policy) { - return null; // nothing to deprovision - } + @Override + public CompletableFuture> deprovision( + AdditionalHeadersProvisionedResource additionalHeadersProvisionedResource, Policy policy) { + return null; // nothing to deprovision + } } diff --git a/edc-extensions/provision-additional-headers/src/main/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersResourceDefinition.java b/edc-extensions/provision-additional-headers/src/main/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersResourceDefinition.java index e609922be..ecd3f0437 100644 --- a/edc-extensions/provision-additional-headers/src/main/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersResourceDefinition.java +++ b/edc-extensions/provision-additional-headers/src/main/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersResourceDefinition.java @@ -31,43 +31,43 @@ @JsonTypeName("dataspaceconnector:additionalheadersresourcedefinition") class AdditionalHeadersResourceDefinition extends ResourceDefinition { - private String contractId; - private DataAddress dataAddress; + private String contractId; + private DataAddress dataAddress; - @Override - public Builder toBuilder() { - return initializeBuilder(new Builder()); - } + @Override + public Builder toBuilder() { + return initializeBuilder(new Builder()); + } - public DataAddress getDataAddress() { - return dataAddress; - } + public DataAddress getDataAddress() { + return dataAddress; + } - public String getContractId() { - return contractId; - } + public String getContractId() { + return contractId; + } - @JsonPOJOBuilder(withPrefix = "") - public static class Builder - extends ResourceDefinition.Builder { + @JsonPOJOBuilder(withPrefix = "") + public static class Builder + extends ResourceDefinition.Builder { - protected Builder() { - super(new AdditionalHeadersResourceDefinition()); - } + protected Builder() { + super(new AdditionalHeadersResourceDefinition()); + } - @JsonCreator - public static Builder newInstance() { - return new Builder(); - } + @JsonCreator + public static Builder newInstance() { + return new Builder(); + } - public Builder contractId(String contractId) { - this.resourceDefinition.contractId = contractId; - return this; - } + public Builder contractId(String contractId) { + this.resourceDefinition.contractId = contractId; + return this; + } - public Builder dataAddress(DataAddress dataAddress) { - this.resourceDefinition.dataAddress = dataAddress; - return this; + public Builder dataAddress(DataAddress dataAddress) { + this.resourceDefinition.dataAddress = dataAddress; + return this; + } } - } } diff --git a/edc-extensions/provision-additional-headers/src/main/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersResourceDefinitionGenerator.java b/edc-extensions/provision-additional-headers/src/main/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersResourceDefinitionGenerator.java index 1d85bdd94..62e0d6ce9 100644 --- a/edc-extensions/provision-additional-headers/src/main/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersResourceDefinitionGenerator.java +++ b/edc-extensions/provision-additional-headers/src/main/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersResourceDefinitionGenerator.java @@ -20,7 +20,6 @@ package org.eclipse.tractusx.edc.provision.additionalheaders; -import java.util.UUID; import org.eclipse.edc.connector.transfer.spi.provision.ProviderResourceDefinitionGenerator; import org.eclipse.edc.connector.transfer.spi.types.DataRequest; import org.eclipse.edc.connector.transfer.spi.types.ResourceDefinition; @@ -28,20 +27,22 @@ import org.eclipse.edc.spi.types.domain.DataAddress; import org.jetbrains.annotations.Nullable; +import java.util.UUID; + class AdditionalHeadersResourceDefinitionGenerator implements ProviderResourceDefinitionGenerator { - @Override - public boolean canGenerate(DataRequest dataRequest, DataAddress dataAddress, Policy policy) { - return "HttpData".equals(dataAddress.getType()); - } + @Override + public boolean canGenerate(DataRequest dataRequest, DataAddress dataAddress, Policy policy) { + return "HttpData".equals(dataAddress.getType()); + } - @Override - public @Nullable ResourceDefinition generate( - DataRequest dataRequest, DataAddress dataAddress, Policy policy) { - return AdditionalHeadersResourceDefinition.Builder.newInstance() - .id(UUID.randomUUID().toString()) - .dataAddress(dataAddress) - .contractId(dataRequest.getContractId()) - .build(); - } + @Override + public @Nullable ResourceDefinition generate( + DataRequest dataRequest, DataAddress dataAddress, Policy policy) { + return AdditionalHeadersResourceDefinition.Builder.newInstance() + .id(UUID.randomUUID().toString()) + .dataAddress(dataAddress) + .contractId(dataRequest.getContractId()) + .build(); + } } diff --git a/edc-extensions/provision-additional-headers/src/main/java/org/eclipse/tractusx/edc/provision/additionalheaders/ProvisionAdditionalHeadersExtension.java b/edc-extensions/provision-additional-headers/src/main/java/org/eclipse/tractusx/edc/provision/additionalheaders/ProvisionAdditionalHeadersExtension.java index ef58cd4a2..9860fdf46 100644 --- a/edc-extensions/provision-additional-headers/src/main/java/org/eclipse/tractusx/edc/provision/additionalheaders/ProvisionAdditionalHeadersExtension.java +++ b/edc-extensions/provision-additional-headers/src/main/java/org/eclipse/tractusx/edc/provision/additionalheaders/ProvisionAdditionalHeadersExtension.java @@ -29,17 +29,19 @@ public class ProvisionAdditionalHeadersExtension implements ServiceExtension { - @Inject private ResourceManifestGenerator resourceManifestGenerator; + @Inject + private ResourceManifestGenerator resourceManifestGenerator; - @Inject private ProvisionManager provisionManager; + @Inject + private ProvisionManager provisionManager; - @Inject private TypeManager typeManager; + @Inject + private TypeManager typeManager; - @Override - public void initialize(ServiceExtensionContext context) { - typeManager.registerTypes( - AdditionalHeadersResourceDefinition.class, AdditionalHeadersProvisionedResource.class); - resourceManifestGenerator.registerGenerator(new AdditionalHeadersResourceDefinitionGenerator()); - provisionManager.register(new AdditionalHeadersProvisioner()); - } + @Override + public void initialize(ServiceExtensionContext context) { + typeManager.registerTypes(AdditionalHeadersResourceDefinition.class, AdditionalHeadersProvisionedResource.class); + resourceManifestGenerator.registerGenerator(new AdditionalHeadersResourceDefinitionGenerator()); + provisionManager.register(new AdditionalHeadersProvisioner()); + } } diff --git a/edc-extensions/provision-additional-headers/src/test/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersProvisionedResourceTest.java b/edc-extensions/provision-additional-headers/src/test/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersProvisionedResourceTest.java index dc133d060..2079393d8 100644 --- a/edc-extensions/provision-additional-headers/src/test/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersProvisionedResourceTest.java +++ b/edc-extensions/provision-additional-headers/src/test/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersProvisionedResourceTest.java @@ -20,31 +20,32 @@ package org.eclipse.tractusx.edc.provision.additionalheaders; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; - -import java.util.UUID; import org.eclipse.edc.spi.types.TypeManager; import org.eclipse.edc.spi.types.domain.DataAddress; import org.junit.jupiter.api.Test; +import java.util.UUID; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + class AdditionalHeadersProvisionedResourceTest { - @Test - void serdes() { - var typeManager = new TypeManager(); - var resource = - AdditionalHeadersProvisionedResource.Builder.newInstance() - .id(UUID.randomUUID().toString()) - .resourceDefinitionId(UUID.randomUUID().toString()) - .transferProcessId(UUID.randomUUID().toString()) - .hasToken(false) - .resourceName("name") - .dataAddress(DataAddress.Builder.newInstance().type("type").build()) - .build(); - - var json = typeManager.writeValueAsString(resource); - var deserialized = typeManager.readValue(json, AdditionalHeadersProvisionedResource.class); - - assertThat(deserialized).usingRecursiveComparison().isEqualTo(resource); - } + @Test + void serdes() { + var typeManager = new TypeManager(); + var resource = + AdditionalHeadersProvisionedResource.Builder.newInstance() + .id(UUID.randomUUID().toString()) + .resourceDefinitionId(UUID.randomUUID().toString()) + .transferProcessId(UUID.randomUUID().toString()) + .hasToken(false) + .resourceName("name") + .dataAddress(DataAddress.Builder.newInstance().type("type").build()) + .build(); + + var json = typeManager.writeValueAsString(resource); + var deserialized = typeManager.readValue(json, AdditionalHeadersProvisionedResource.class); + + assertThat(deserialized).usingRecursiveComparison().isEqualTo(resource); + } } diff --git a/edc-extensions/provision-additional-headers/src/test/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersProvisionerTest.java b/edc-extensions/provision-additional-headers/src/test/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersProvisionerTest.java index 45769a935..64c4dbc99 100644 --- a/edc-extensions/provision-additional-headers/src/test/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersProvisionerTest.java +++ b/edc-extensions/provision-additional-headers/src/test/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersProvisionerTest.java @@ -20,13 +20,6 @@ package org.eclipse.tractusx.edc.provision.additionalheaders; -import static java.util.concurrent.TimeUnit.SECONDS; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.assertj.core.api.InstanceOfAssertFactories.map; -import static org.assertj.core.api.InstanceOfAssertFactories.type; -import static org.mockito.Mockito.mock; - -import java.util.UUID; import org.eclipse.edc.connector.transfer.spi.types.ProvisionResponse; import org.eclipse.edc.connector.transfer.spi.types.ProvisionedDataAddressResource; import org.eclipse.edc.connector.transfer.spi.types.ProvisionedResource; @@ -36,46 +29,54 @@ import org.eclipse.edc.spi.types.domain.HttpDataAddress; import org.junit.jupiter.api.Test; +import java.util.UUID; + +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.InstanceOfAssertFactories.map; +import static org.assertj.core.api.InstanceOfAssertFactories.type; +import static org.mockito.Mockito.mock; + class AdditionalHeadersProvisionerTest { - private final AdditionalHeadersProvisioner provisioner = new AdditionalHeadersProvisioner(); + private final AdditionalHeadersProvisioner provisioner = new AdditionalHeadersProvisioner(); - @Test - void canProvisionAdditionalHeadersResourceDefinition() { - assertThat(provisioner.canProvision(mock(AdditionalHeadersResourceDefinition.class))).isTrue(); - assertThat(provisioner.canProvision(mock(ResourceDefinition.class))).isFalse(); - } + @Test + void canProvisionAdditionalHeadersResourceDefinition() { + assertThat(provisioner.canProvision(mock(AdditionalHeadersResourceDefinition.class))).isTrue(); + assertThat(provisioner.canProvision(mock(ResourceDefinition.class))).isFalse(); + } - @Test - void cannotDeprovisionAdditionalHeadersResourceDefinition() { - assertThat(provisioner.canDeprovision(mock(AdditionalHeadersProvisionedResource.class))) - .isFalse(); - assertThat(provisioner.canDeprovision(mock(ProvisionedResource.class))).isFalse(); - } + @Test + void cannotDeprovisionAdditionalHeadersResourceDefinition() { + assertThat(provisioner.canDeprovision(mock(AdditionalHeadersProvisionedResource.class))) + .isFalse(); + assertThat(provisioner.canDeprovision(mock(ProvisionedResource.class))).isFalse(); + } - @Test - void shouldAddContractIdAdditionalHeader() { - var address = HttpDataAddress.Builder.newInstance().baseUrl("http://any").build(); - var resourceDefinition = - AdditionalHeadersResourceDefinition.Builder.newInstance() - .id(UUID.randomUUID().toString()) - .transferProcessId(UUID.randomUUID().toString()) - .contractId("contractId") - .dataAddress(address) - .build(); + @Test + void shouldAddContractIdAdditionalHeader() { + var address = HttpDataAddress.Builder.newInstance().baseUrl("http://any").build(); + var resourceDefinition = + AdditionalHeadersResourceDefinition.Builder.newInstance() + .id(UUID.randomUUID().toString()) + .transferProcessId(UUID.randomUUID().toString()) + .contractId("contractId") + .dataAddress(address) + .build(); - var result = provisioner.provision(resourceDefinition, Policy.Builder.newInstance().build()); + var result = provisioner.provision(resourceDefinition, Policy.Builder.newInstance().build()); - assertThat(result) - .succeedsWithin(5, SECONDS) - .matches(StatusResult::succeeded) - .extracting(StatusResult::getContent) - .extracting(ProvisionResponse::getResource) - .asInstanceOf(type(AdditionalHeadersProvisionedResource.class)) - .extracting(ProvisionedDataAddressResource::getDataAddress) - .extracting(a -> HttpDataAddress.Builder.newInstance().copyFrom(a).build()) - .extracting(HttpDataAddress::getAdditionalHeaders) - .asInstanceOf(map(String.class, String.class)) - .containsEntry("Edc-Contract-Agreement-Id", "contractId"); - } + assertThat(result) + .succeedsWithin(5, SECONDS) + .matches(StatusResult::succeeded) + .extracting(StatusResult::getContent) + .extracting(ProvisionResponse::getResource) + .asInstanceOf(type(AdditionalHeadersProvisionedResource.class)) + .extracting(ProvisionedDataAddressResource::getDataAddress) + .extracting(a -> HttpDataAddress.Builder.newInstance().copyFrom(a).build()) + .extracting(HttpDataAddress::getAdditionalHeaders) + .asInstanceOf(map(String.class, String.class)) + .containsEntry("Edc-Contract-Agreement-Id", "contractId"); + } } diff --git a/edc-extensions/provision-additional-headers/src/test/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersResourceDefinitionGeneratorTest.java b/edc-extensions/provision-additional-headers/src/test/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersResourceDefinitionGeneratorTest.java index 12b9a61e6..7f7e66675 100644 --- a/edc-extensions/provision-additional-headers/src/test/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersResourceDefinitionGeneratorTest.java +++ b/edc-extensions/provision-additional-headers/src/test/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersResourceDefinitionGeneratorTest.java @@ -20,68 +20,69 @@ package org.eclipse.tractusx.edc.provision.additionalheaders; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.assertj.core.api.InstanceOfAssertFactories.type; - -import java.util.UUID; import org.eclipse.edc.connector.transfer.spi.types.DataRequest; import org.eclipse.edc.policy.model.Policy; import org.eclipse.edc.spi.types.domain.DataAddress; import org.eclipse.edc.spi.types.domain.HttpDataAddress; import org.junit.jupiter.api.Test; +import java.util.UUID; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.InstanceOfAssertFactories.type; + class AdditionalHeadersResourceDefinitionGeneratorTest { - private final AdditionalHeadersResourceDefinitionGenerator generator = - new AdditionalHeadersResourceDefinitionGenerator(); + private final AdditionalHeadersResourceDefinitionGenerator generator = + new AdditionalHeadersResourceDefinitionGenerator(); - @Test - void canGenerate_shouldReturnFalseForNotHttpDataAddresses() { - var dataAddress = DataAddress.Builder.newInstance().type("any").build(); - var dataRequest = - DataRequest.Builder.newInstance() - .id(UUID.randomUUID().toString()) - .dataDestination(dataAddress) - .build(); - var build = Policy.Builder.newInstance().build(); + @Test + void canGenerate_shouldReturnFalseForNotHttpDataAddresses() { + var dataAddress = DataAddress.Builder.newInstance().type("any").build(); + var dataRequest = + DataRequest.Builder.newInstance() + .id(UUID.randomUUID().toString()) + .dataDestination(dataAddress) + .build(); + var build = Policy.Builder.newInstance().build(); - var result = generator.canGenerate(dataRequest, dataAddress, build); + var result = generator.canGenerate(dataRequest, dataAddress, build); - assertThat(result).isFalse(); - } + assertThat(result).isFalse(); + } - @Test - void canGenerate_shouldReturnTrueForHttpDataAddresses() { - var dataAddress = DataAddress.Builder.newInstance().type("HttpData").build(); - var dataRequest = - DataRequest.Builder.newInstance() - .id(UUID.randomUUID().toString()) - .dataDestination(dataAddress) - .build(); - var build = Policy.Builder.newInstance().build(); + @Test + void canGenerate_shouldReturnTrueForHttpDataAddresses() { + var dataAddress = DataAddress.Builder.newInstance().type("HttpData").build(); + var dataRequest = + DataRequest.Builder.newInstance() + .id(UUID.randomUUID().toString()) + .dataDestination(dataAddress) + .build(); + var build = Policy.Builder.newInstance().build(); - var result = generator.canGenerate(dataRequest, dataAddress, build); + var result = generator.canGenerate(dataRequest, dataAddress, build); - assertThat(result).isTrue(); - } + assertThat(result).isTrue(); + } - @Test - void shouldCreateResourceDefinitionWithDataAddress() { - var dataAddress = HttpDataAddress.Builder.newInstance().baseUrl("http://any").build(); - var dataRequest = - DataRequest.Builder.newInstance() - .id(UUID.randomUUID().toString()) - .dataDestination(dataAddress) - .build(); - var build = Policy.Builder.newInstance().build(); + @Test + void shouldCreateResourceDefinitionWithDataAddress() { + var dataAddress = HttpDataAddress.Builder.newInstance().baseUrl("http://any").build(); + var dataRequest = + DataRequest.Builder.newInstance() + .id(UUID.randomUUID().toString()) + .dataDestination(dataAddress) + .build(); + var build = Policy.Builder.newInstance().build(); - var result = generator.generate(dataRequest, dataAddress, build); + var result = generator.generate(dataRequest, dataAddress, build); - assertThat(result) - .asInstanceOf(type(AdditionalHeadersResourceDefinition.class)) - .extracting(AdditionalHeadersResourceDefinition::getDataAddress) - .extracting(address -> HttpDataAddress.Builder.newInstance().copyFrom(address).build()) - .extracting(HttpDataAddress::getBaseUrl) - .isEqualTo("http://any"); - } + assertThat(result) + .asInstanceOf(type(AdditionalHeadersResourceDefinition.class)) + .extracting(AdditionalHeadersResourceDefinition::getDataAddress) + .extracting(address -> HttpDataAddress.Builder.newInstance().copyFrom(address).build()) + .extracting(HttpDataAddress::getBaseUrl) + .isEqualTo("http://any"); + } } diff --git a/edc-extensions/provision-additional-headers/src/test/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersResourceDefinitionTest.java b/edc-extensions/provision-additional-headers/src/test/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersResourceDefinitionTest.java index 4c69e297d..11a5173a4 100644 --- a/edc-extensions/provision-additional-headers/src/test/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersResourceDefinitionTest.java +++ b/edc-extensions/provision-additional-headers/src/test/java/org/eclipse/tractusx/edc/provision/additionalheaders/AdditionalHeadersResourceDefinitionTest.java @@ -20,29 +20,30 @@ package org.eclipse.tractusx.edc.provision.additionalheaders; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; - -import java.util.UUID; import org.eclipse.edc.spi.types.TypeManager; import org.eclipse.edc.spi.types.domain.DataAddress; import org.junit.jupiter.api.Test; +import java.util.UUID; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + class AdditionalHeadersResourceDefinitionTest { - @Test - void serdes() { - var typeManager = new TypeManager(); - var definition = - AdditionalHeadersResourceDefinition.Builder.newInstance() - .id(UUID.randomUUID().toString()) - .transferProcessId(UUID.randomUUID().toString()) - .dataAddress(DataAddress.Builder.newInstance().type("type").build()) - .contractId(UUID.randomUUID().toString()) - .build(); - - var json = typeManager.writeValueAsString(definition); - var deserialized = typeManager.readValue(json, AdditionalHeadersResourceDefinition.class); - - assertThat(deserialized).usingRecursiveComparison().isEqualTo(definition); - } + @Test + void serdes() { + var typeManager = new TypeManager(); + var definition = + AdditionalHeadersResourceDefinition.Builder.newInstance() + .id(UUID.randomUUID().toString()) + .transferProcessId(UUID.randomUUID().toString()) + .dataAddress(DataAddress.Builder.newInstance().type("type").build()) + .contractId(UUID.randomUUID().toString()) + .build(); + + var json = typeManager.writeValueAsString(definition); + var deserialized = typeManager.readValue(json, AdditionalHeadersResourceDefinition.class); + + assertThat(deserialized).usingRecursiveComparison().isEqualTo(definition); + } } diff --git a/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientConfig.java b/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientConfig.java index bf5da3a2f..72f2d00c0 100644 --- a/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientConfig.java +++ b/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientConfig.java @@ -14,33 +14,37 @@ package org.eclipse.tractusx.edc.transferprocess.sftp.client; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Collection; -import java.util.List; import lombok.Builder; import lombok.Getter; import org.apache.sshd.sftp.client.SftpClient; import org.eclipse.tractusx.edc.transferprocess.sftp.common.SftpLocation; import org.eclipse.tractusx.edc.transferprocess.sftp.common.SftpUser; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Collection; +import java.util.List; + @Builder @Getter public class SftpClientConfig { - private SftpUser sftpUser; - private SftpLocation sftpLocation; - @Builder.Default private int bufferSize = 4096; - @Builder.Default private boolean hostVerification = true; + private SftpUser sftpUser; + private SftpLocation sftpLocation; + @Builder.Default + private int bufferSize = 4096; + @Builder.Default + private boolean hostVerification = true; - @Builder.Default - private Path knownHostFile = Paths.get(System.getenv("HOME"), ".ssh/known_hosts"); + @Builder.Default + private Path knownHostFile = Paths.get(System.getenv("HOME"), ".ssh/known_hosts"); - @Builder.Default private int connectionTimeoutSeconds = 10; + @Builder.Default + private int connectionTimeoutSeconds = 10; - @Builder.Default - private Collection writeOpenModes = - List.of(SftpClient.OpenMode.Create, SftpClient.OpenMode.Write); + @Builder.Default + private Collection writeOpenModes = + List.of(SftpClient.OpenMode.Create, SftpClient.OpenMode.Write); - @Builder.Default - private Collection readOpenModes = List.of(SftpClient.OpenMode.Read); + @Builder.Default + private Collection readOpenModes = List.of(SftpClient.OpenMode.Read); } diff --git a/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientExtension.java b/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientExtension.java index 9143b3583..766300c80 100644 --- a/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientExtension.java +++ b/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientExtension.java @@ -23,16 +23,17 @@ @Provides(SftpClientWrapper.class) public class SftpClientExtension implements ServiceExtension { - @Inject PipelineService pipelineService; + @Inject + PipelineService pipelineService; - @Override - public void initialize(ServiceExtensionContext context) { - SftpDataSinkFactory sftpDataSinkFactory = new SftpDataSinkFactory(); - SftpDataSourceFactory sftpDataSourceFactory = new SftpDataSourceFactory(); - SftpClientWrapperFactory sftpClientWrapperFactory = new SftpClientWrapperFactoryImpl(); + @Override + public void initialize(ServiceExtensionContext context) { + SftpDataSinkFactory sftpDataSinkFactory = new SftpDataSinkFactory(); + SftpDataSourceFactory sftpDataSourceFactory = new SftpDataSourceFactory(); + SftpClientWrapperFactory sftpClientWrapperFactory = new SftpClientWrapperFactoryImpl(); - pipelineService.registerFactory(sftpDataSinkFactory); - pipelineService.registerFactory(sftpDataSourceFactory); - context.registerService(SftpClientWrapperFactory.class, sftpClientWrapperFactory); - } + pipelineService.registerFactory(sftpDataSinkFactory); + pipelineService.registerFactory(sftpDataSourceFactory); + context.registerService(SftpClientWrapperFactory.class, sftpClientWrapperFactory); + } } diff --git a/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientWrapper.java b/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientWrapper.java index c082106f2..6d938f2e1 100644 --- a/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientWrapper.java +++ b/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientWrapper.java @@ -18,7 +18,7 @@ import java.io.InputStream; public interface SftpClientWrapper { - void uploadFile(InputStream inputStream) throws IOException; + void uploadFile(InputStream inputStream) throws IOException; - InputStream downloadFile() throws IOException; + InputStream downloadFile() throws IOException; } diff --git a/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientWrapperFactory.java b/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientWrapperFactory.java index ba60d9c04..8d2d03783 100644 --- a/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientWrapperFactory.java +++ b/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientWrapperFactory.java @@ -15,5 +15,5 @@ package org.eclipse.tractusx.edc.transferprocess.sftp.client; public interface SftpClientWrapperFactory { - SftpClientWrapper getSftpClientWrapper(SftpClientConfig config); + SftpClientWrapper getSftpClientWrapper(SftpClientConfig config); } diff --git a/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientWrapperFactoryImpl.java b/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientWrapperFactoryImpl.java index a300ea4d0..019ec9d67 100644 --- a/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientWrapperFactoryImpl.java +++ b/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientWrapperFactoryImpl.java @@ -16,8 +16,8 @@ public class SftpClientWrapperFactoryImpl implements SftpClientWrapperFactory { - @Override - public SftpClientWrapper getSftpClientWrapper(SftpClientConfig config) { - return new SftpClientWrapperImpl(config); - } + @Override + public SftpClientWrapper getSftpClientWrapper(SftpClientConfig config) { + return new SftpClientWrapperImpl(config); + } } diff --git a/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientWrapperImpl.java b/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientWrapperImpl.java index cad0ea6e5..8368f279d 100644 --- a/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientWrapperImpl.java +++ b/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientWrapperImpl.java @@ -14,10 +14,6 @@ package org.eclipse.tractusx.edc.transferprocess.sftp.client; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.time.Duration; import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; @@ -34,127 +30,134 @@ import org.eclipse.tractusx.edc.transferprocess.sftp.common.EdcSftpException; import org.jetbrains.annotations.NotNull; +import java.io.IOException; +import java.io.InputStream; +import java.time.Duration; + public class SftpClientWrapperImpl implements SftpClientWrapper { - @Getter private final SftpClientConfig config; - private final SftpClient sftpClient; - - public SftpClientWrapperImpl(SftpClientConfig config) { - this.config = config; - try { - this.sftpClient = getSftpClient(config); - } catch (IOException e) { - throw new EdcSftpException("Unable to create SftpClient.", e); - } - } - - public SftpClientWrapperImpl(SftpClientConfig config, SftpClient sftpClient) { - this.config = config; - this.sftpClient = sftpClient; - } - - @Override - public void uploadFile(@NonNull final InputStream inputStream) throws IOException { - try (final OutputStream outputStream = - sftpClient.write( - config.getSftpLocation().getPath(), - config.getBufferSize(), - config.getWriteOpenModes())) { - inputStream.transferTo(outputStream); - } - } - - @Override - public InputStream downloadFile() throws IOException { - final InputStream delegateInputStream; - try { - delegateInputStream = - sftpClient.read( - config.getSftpLocation().getPath(), - config.getBufferSize(), - config.getReadOpenModes()); - } catch (final IOException e) { - sftpClient.close(); - throw new EdcSftpException( - String.format("Unable to download file at %s", config.getSftpLocation().toString()), e); + @Getter + private final SftpClientConfig config; + private final SftpClient sftpClient; + + public SftpClientWrapperImpl(SftpClientConfig config) { + this.config = config; + try { + this.sftpClient = getSftpClient(config); + } catch (IOException e) { + throw new EdcSftpException("Unable to create SftpClient.", e); + } } - return new SftpInputStreamWrapper(sftpClient, delegateInputStream); - } - - static SftpClient getSftpClient(SftpClientConfig config) throws IOException { - final ClientSession session = getSshClientSession(config); - final SftpClientFactory factory = SftpClientFactory.instance(); - final SftpClient sftpClient = factory.createSftpClient(session); - return sftpClient.singleSessionInstance(); - } - - private static ClientSession getSshClientSession(SftpClientConfig config) throws IOException { - final SshClient sshClient = getSshClient(config); - sshClient.start(); - final ClientSession session = - sshClient - .connect( - config.getSftpUser().getName(), - config.getSftpLocation().getHost(), - config.getSftpLocation().getPort()) - .verify() - .getSession(); - session.auth().await(Duration.ofSeconds(config.getConnectionTimeoutSeconds())); - - return session; - } - - private static SshClient getSshClient(SftpClientConfig config) { - final SshClient sshClient = ClientBuilder.builder().build(); - - if (config.getSftpUser().getKeyPair() != null) { - sshClient.setKeyIdentityProvider( - KeyIdentityProvider.wrapKeyPairs(config.getSftpUser().getKeyPair())); - } else if (config.getSftpUser().getPassword() != null) { - sshClient.setPasswordIdentityProvider( - PasswordIdentityProvider.wrapPasswords(config.getSftpUser().getPassword())); - } else { - sshClient.setPasswordIdentityProvider(PasswordIdentityProvider.EMPTY_PASSWORDS_PROVIDER); + public SftpClientWrapperImpl(SftpClientConfig config, SftpClient sftpClient) { + this.config = config; + this.sftpClient = sftpClient; } - if (config.isHostVerification()) { - final ServerKeyVerifier keyVerifier = - new KnownHostsServerKeyVerifier( - RejectAllServerKeyVerifier.INSTANCE, config.getKnownHostFile()); - sshClient.setServerKeyVerifier(keyVerifier); + static SftpClient getSftpClient(SftpClientConfig config) throws IOException { + final ClientSession session = getSshClientSession(config); + final SftpClientFactory factory = SftpClientFactory.instance(); + final SftpClient sftpClient = factory.createSftpClient(session); + return sftpClient.singleSessionInstance(); } - return sshClient; - } + private static ClientSession getSshClientSession(SftpClientConfig config) throws IOException { + final SshClient sshClient = getSshClient(config); + sshClient.start(); + final ClientSession session = + sshClient + .connect( + config.getSftpUser().getName(), + config.getSftpLocation().getHost(), + config.getSftpLocation().getPort()) + .verify() + .getSession(); + session.auth().await(Duration.ofSeconds(config.getConnectionTimeoutSeconds())); + + return session; + } - @RequiredArgsConstructor - private static class SftpInputStreamWrapper extends InputStream { - @NonNull private final SftpClient sftpClient; - @NonNull private final InputStream delegateInputStream; + private static SshClient getSshClient(SftpClientConfig config) { + final SshClient sshClient = ClientBuilder.builder().build(); + + if (config.getSftpUser().getKeyPair() != null) { + sshClient.setKeyIdentityProvider( + KeyIdentityProvider.wrapKeyPairs(config.getSftpUser().getKeyPair())); + } else if (config.getSftpUser().getPassword() != null) { + sshClient.setPasswordIdentityProvider( + PasswordIdentityProvider.wrapPasswords(config.getSftpUser().getPassword())); + } else { + sshClient.setPasswordIdentityProvider(PasswordIdentityProvider.EMPTY_PASSWORDS_PROVIDER); + } + + if (config.isHostVerification()) { + final ServerKeyVerifier keyVerifier = + new KnownHostsServerKeyVerifier( + RejectAllServerKeyVerifier.INSTANCE, config.getKnownHostFile()); + sshClient.setServerKeyVerifier(keyVerifier); + } + + return sshClient; + } @Override - public int read() throws IOException { - return delegateInputStream.read(); + public void uploadFile(@NonNull final InputStream inputStream) throws IOException { + try (var outputStream = + sftpClient.write( + config.getSftpLocation().getPath(), + config.getBufferSize(), + config.getWriteOpenModes())) { + inputStream.transferTo(outputStream); + } } @Override - public int read(byte @NotNull [] b, int off, int len) throws IOException { - return delegateInputStream.read(b, off, len); + public InputStream downloadFile() throws IOException { + final InputStream delegateInputStream; + try { + delegateInputStream = + sftpClient.read( + config.getSftpLocation().getPath(), + config.getBufferSize(), + config.getReadOpenModes()); + } catch (final IOException e) { + sftpClient.close(); + throw new EdcSftpException( + String.format("Unable to download file at %s", config.getSftpLocation().toString()), e); + } + + return new SftpInputStreamWrapper(sftpClient, delegateInputStream); } - @Override - public void close() { - try { - delegateInputStream.close(); - } catch (IOException ignored) { - // Ignored. The exception should only be thrown of the stream is already closed. - } - - try { - sftpClient.close(); - } catch (IOException ignored) { - // Ignored. The exception should only be thrown of the client is already closed. - } + @RequiredArgsConstructor + private static class SftpInputStreamWrapper extends InputStream { + @NonNull + private final SftpClient sftpClient; + @NonNull + private final InputStream delegateInputStream; + + @Override + public int read() throws IOException { + return delegateInputStream.read(); + } + + @Override + public int read(byte @NotNull [] b, int off, int len) throws IOException { + return delegateInputStream.read(b, off, len); + } + + @Override + public void close() { + try { + delegateInputStream.close(); + } catch (IOException ignored) { + // Ignored. The exception should only be thrown of the stream is already closed. + } + + try { + sftpClient.close(); + } catch (IOException ignored) { + // Ignored. The exception should only be thrown of the client is already closed. + } + } } - } } diff --git a/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpDataSinkFactory.java b/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpDataSinkFactory.java index 4edcb9dec..b42041ed3 100644 --- a/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpDataSinkFactory.java +++ b/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpDataSinkFactory.java @@ -14,7 +14,6 @@ package org.eclipse.tractusx.edc.transferprocess.sftp.client; -import java.util.List; import lombok.RequiredArgsConstructor; import org.apache.sshd.sftp.client.SftpClient; import org.eclipse.edc.connector.dataplane.spi.pipeline.DataSink; @@ -25,45 +24,47 @@ import org.eclipse.tractusx.edc.transferprocess.sftp.common.SftpDataAddress; import org.jetbrains.annotations.NotNull; +import java.util.List; + @RequiredArgsConstructor public class SftpDataSinkFactory implements DataSinkFactory { - @Override - public boolean canHandle(DataFlowRequest request) { - try { - SftpDataAddress.fromDataAddress(request.getDestinationDataAddress()); - return true; - } catch (EdcSftpException e) { - return false; + @Override + public boolean canHandle(DataFlowRequest request) { + try { + SftpDataAddress.fromDataAddress(request.getDestinationDataAddress()); + return true; + } catch (EdcSftpException e) { + return false; + } } - } - @Override - public @NotNull Result validate(DataFlowRequest request) { - if (!canHandle(request)) { - return Result.failure(String.format("Invalid DataFlowRequest: %s", request.getId())); - } + @Override + public @NotNull Result validate(DataFlowRequest request) { + if (!canHandle(request)) { + return Result.failure(String.format("Invalid DataFlowRequest: %s", request.getId())); + } - return VALID; - } - - @Override - public DataSink createSink(DataFlowRequest request) { - if (!canHandle(request)) { - return null; + return VALID; } - SftpDataAddress destination = - SftpDataAddress.fromDataAddress(request.getDestinationDataAddress()); + @Override + public DataSink createSink(DataFlowRequest request) { + if (!canHandle(request)) { + return null; + } + + SftpDataAddress destination = + SftpDataAddress.fromDataAddress(request.getDestinationDataAddress()); - SftpClientConfig sftpClientConfig = - SftpClientConfig.builder() - .writeOpenModes(List.of(SftpClient.OpenMode.Create, SftpClient.OpenMode.Append)) - .sftpUser(destination.getSftpUser()) - .sftpLocation(destination.getSftpLocation()) - .build(); + SftpClientConfig sftpClientConfig = + SftpClientConfig.builder() + .writeOpenModes(List.of(SftpClient.OpenMode.Create, SftpClient.OpenMode.Append)) + .sftpUser(destination.getSftpUser()) + .sftpLocation(destination.getSftpLocation()) + .build(); - SftpClientWrapper sftpClientWrapper = new SftpClientWrapperImpl(sftpClientConfig); + SftpClientWrapper sftpClientWrapper = new SftpClientWrapperImpl(sftpClientConfig); - return new SftpDataSink(sftpClientWrapper); - } + return new SftpDataSink(sftpClientWrapper); + } } diff --git a/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpDataSourceFactory.java b/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpDataSourceFactory.java index 076afc72d..d6bcdef6b 100644 --- a/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpDataSourceFactory.java +++ b/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpDataSourceFactory.java @@ -25,40 +25,40 @@ @RequiredArgsConstructor public class SftpDataSourceFactory implements DataSourceFactory { - @Override - public boolean canHandle(DataFlowRequest request) { - try { - SftpDataAddress.fromDataAddress(request.getSourceDataAddress()); - return true; - } catch (EdcSftpException e) { - return false; + @Override + public boolean canHandle(DataFlowRequest request) { + try { + SftpDataAddress.fromDataAddress(request.getSourceDataAddress()); + return true; + } catch (EdcSftpException e) { + return false; + } } - } - @Override - public @NotNull Result validate(DataFlowRequest request) { - if (!canHandle(request)) { - return Result.failure(String.format("Invalid DataFlowRequest: %s", request.getId())); - } - - return VALID; - } + @Override + public @NotNull Result validate(DataFlowRequest request) { + if (!canHandle(request)) { + return Result.failure(String.format("Invalid DataFlowRequest: %s", request.getId())); + } - @Override - public DataSource createSource(DataFlowRequest request) { - if (!canHandle(request)) { - return null; + return VALID; } - SftpDataAddress source = SftpDataAddress.fromDataAddress(request.getSourceDataAddress()); + @Override + public DataSource createSource(DataFlowRequest request) { + if (!canHandle(request)) { + return null; + } - SftpClientConfig sftpClientConfig = - SftpClientConfig.builder() - .sftpUser(source.getSftpUser()) - .sftpLocation(source.getSftpLocation()) - .build(); + SftpDataAddress source = SftpDataAddress.fromDataAddress(request.getSourceDataAddress()); - SftpClientWrapper sftpClientWrapper = new SftpClientWrapperImpl(sftpClientConfig); - return new SftpDataSource(sftpClientWrapper); - } + SftpClientConfig sftpClientConfig = + SftpClientConfig.builder() + .sftpUser(source.getSftpUser()) + .sftpLocation(source.getSftpLocation()) + .build(); + + SftpClientWrapper sftpClientWrapper = new SftpClientWrapperImpl(sftpClientConfig); + return new SftpDataSource(sftpClientWrapper); + } } diff --git a/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpPart.java b/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpPart.java index 2b4e9e7e3..b1c5c63a6 100644 --- a/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpPart.java +++ b/edc-extensions/transferprocess-sftp-client/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpPart.java @@ -14,24 +14,26 @@ package org.eclipse.tractusx.edc.transferprocess.sftp.client; -import java.io.InputStream; import lombok.Builder; import lombok.NonNull; import lombok.SneakyThrows; import org.eclipse.edc.connector.dataplane.spi.pipeline.DataSource; +import java.io.InputStream; + @Builder public class SftpPart implements DataSource.Part { - @NonNull private final SftpClientWrapper sftpClientWrapper; + @NonNull + private final SftpClientWrapper sftpClientWrapper; - @Override - public String name() { - return ((SftpClientWrapperImpl) sftpClientWrapper).getConfig().getSftpLocation().getPath(); - } + @Override + public String name() { + return ((SftpClientWrapperImpl) sftpClientWrapper).getConfig().getSftpLocation().getPath(); + } - @Override - @SneakyThrows - public InputStream openStream() { - return sftpClientWrapper.downloadFile(); - } + @Override + @SneakyThrows + public InputStream openStream() { + return sftpClientWrapper.downloadFile(); + } } diff --git a/edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/AbstractSftpClientWrapperIT.java b/edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/AbstractSftpClientWrapperIt.java similarity index 64% rename from edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/AbstractSftpClientWrapperIT.java rename to edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/AbstractSftpClientWrapperIt.java index d1d1c1ce5..b3ea42308 100644 --- a/edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/AbstractSftpClientWrapperIT.java +++ b/edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/AbstractSftpClientWrapperIt.java @@ -41,7 +41,6 @@ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; -import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.file.Files; import java.nio.file.Path; @@ -59,26 +58,26 @@ import static java.util.concurrent.TimeUnit.SECONDS; import static org.testcontainers.shaded.org.awaitility.Awaitility.await; -abstract class AbstractSftpClientWrapperIT { +abstract class AbstractSftpClientWrapperIt { static final String DOCKER_IMAGE_NAME = "atmoz/sftp:alpine-3.6"; - static final String sftpPathPrefix = "transfer"; + static final String SFTP_PATH_PREFIX = "transfer"; static final Map DOCKER_ENV = - Map.of("SFTP_USERS", String.format("user:password:::%s", sftpPathPrefix)); - static final Path dockerVolumeDirectory; - static final Path remotePasswordUploadDirectory; - static final Path remotePasswordDownloadDirectory; - static final Path remoteKeypairUploadDirectory; - static final Path remoteKeypairDownloadDirectory; - static final Path localUploadAndGeneratorDirectory; - static final Path keyDirectory; - static final Path publicKeyPath; - static final KeyPair keyPair; + Map.of("SFTP_USERS", String.format("user:password:::%s", SFTP_PATH_PREFIX)); + static final Path DOCKER_VOLUME_DIRECTORY; + static final Path REMOTE_PASSWORD_UPLOAD_DIRECTORY; + static final Path REMOTE_PASSWORD_DOWNLOAD_DIRECTORY; + static final Path REMOTE_KEYPAIR_UPLOAD_DIRECTORY; + static final Path REMOTE_KEYPAIR_DOWNLOAD_DIRECTORY; + static final Path LOCAL_UPLOAD_AND_GENERATOR_DIRECTORY; + static final Path KEY_DIRECTORY; + static final Path PUBLIC_KEY_PATH; + static final KeyPair KEY_PAIR; @Container @ClassRule - private static final GenericContainer sftpContainer; + private static final GenericContainer SFTP_CONTAINER; static { - keyPair = generateKeyPair(); + KEY_PAIR = generateKeyPair(); try { Set fullPermission = new HashSet(); @@ -92,23 +91,23 @@ abstract class AbstractSftpClientWrapperIT { fullPermission.add(PosixFilePermission.OTHERS_READ); fullPermission.add(PosixFilePermission.OTHERS_WRITE); - dockerVolumeDirectory = Files.createTempDirectory(SftpClientWrapperIT.class.getName()); - localUploadAndGeneratorDirectory = - Files.createTempDirectory(SftpClientWrapperIT.class.getName()); - remotePasswordUploadDirectory = - Files.createDirectory(dockerVolumeDirectory.resolve("passwordUpload")); - remotePasswordDownloadDirectory = - Files.createDirectory(dockerVolumeDirectory.resolve("passwordDownload")); - remoteKeypairUploadDirectory = - Files.createDirectory(dockerVolumeDirectory.resolve("keypairUpload")); - remoteKeypairDownloadDirectory = - Files.createDirectory(dockerVolumeDirectory.resolve("keypairDownload")); - keyDirectory = Files.createTempDirectory(SftpClientWrapperIT.class.getName()); - publicKeyPath = keyDirectory.resolve("public"); - - try (final OutputStreamWriter fileWriter = - new OutputStreamWriter(new FileOutputStream(publicKeyPath.toString()))) { - final RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); + DOCKER_VOLUME_DIRECTORY = Files.createTempDirectory(SftpClientWrapperIt.class.getName()); + LOCAL_UPLOAD_AND_GENERATOR_DIRECTORY = + Files.createTempDirectory(SftpClientWrapperIt.class.getName()); + REMOTE_PASSWORD_UPLOAD_DIRECTORY = + Files.createDirectory(DOCKER_VOLUME_DIRECTORY.resolve("passwordUpload")); + REMOTE_PASSWORD_DOWNLOAD_DIRECTORY = + Files.createDirectory(DOCKER_VOLUME_DIRECTORY.resolve("passwordDownload")); + REMOTE_KEYPAIR_UPLOAD_DIRECTORY = + Files.createDirectory(DOCKER_VOLUME_DIRECTORY.resolve("keypairUpload")); + REMOTE_KEYPAIR_DOWNLOAD_DIRECTORY = + Files.createDirectory(DOCKER_VOLUME_DIRECTORY.resolve("keypairDownload")); + KEY_DIRECTORY = Files.createTempDirectory(SftpClientWrapperIt.class.getName()); + PUBLIC_KEY_PATH = KEY_DIRECTORY.resolve("public"); + + try (var fileWriter = + new OutputStreamWriter(new FileOutputStream(PUBLIC_KEY_PATH.toString()))) { + final RSAPublicKey publicKey = (RSAPublicKey) KEY_PAIR.getPublic(); final RSAKeyParameters publicKeyParameters = new RSAKeyParameters(false, publicKey.getModulus(), publicKey.getPublicExponent()); byte[] encodedKey = OpenSSHPublicKeyUtil.encodePublicKey(publicKeyParameters); @@ -117,37 +116,37 @@ abstract class AbstractSftpClientWrapperIT { fileWriter.write(authKeysEntry); } - Files.setPosixFilePermissions(dockerVolumeDirectory, fullPermission); - Files.setPosixFilePermissions(remotePasswordUploadDirectory, fullPermission); - Files.setPosixFilePermissions(remotePasswordDownloadDirectory, fullPermission); - Files.setPosixFilePermissions(remoteKeypairUploadDirectory, fullPermission); - Files.setPosixFilePermissions(remoteKeypairDownloadDirectory, fullPermission); - Files.setPosixFilePermissions(keyDirectory, fullPermission); + Files.setPosixFilePermissions(DOCKER_VOLUME_DIRECTORY, fullPermission); + Files.setPosixFilePermissions(REMOTE_PASSWORD_UPLOAD_DIRECTORY, fullPermission); + Files.setPosixFilePermissions(REMOTE_PASSWORD_DOWNLOAD_DIRECTORY, fullPermission); + Files.setPosixFilePermissions(REMOTE_KEYPAIR_UPLOAD_DIRECTORY, fullPermission); + Files.setPosixFilePermissions(REMOTE_KEYPAIR_DOWNLOAD_DIRECTORY, fullPermission); + Files.setPosixFilePermissions(KEY_DIRECTORY, fullPermission); } catch (IOException e) { throw new RuntimeException(); } - sftpContainer = + SFTP_CONTAINER = new GenericContainer<>(DockerImageName.parse(DOCKER_IMAGE_NAME)) .withEnv(DOCKER_ENV) .withExposedPorts(22) .waitingFor(Wait.forListeningPort()) .withFileSystemBind( - dockerVolumeDirectory.toAbsolutePath().toString(), - String.format("/home/user/%s", sftpPathPrefix)) - .withFileSystemBind(keyDirectory.toAbsolutePath().toString(), "/home/user/keys"); - sftpContainer.start(); + DOCKER_VOLUME_DIRECTORY.toAbsolutePath().toString(), + String.format("/home/user/%s", SFTP_PATH_PREFIX)) + .withFileSystemBind(KEY_DIRECTORY.toAbsolutePath().toString(), "/home/user/keys"); + SFTP_CONTAINER.start(); - await().atMost(10, SECONDS).until(sftpContainer::isRunning); + await().atMost(10, SECONDS).until(SFTP_CONTAINER::isRunning); try { - sftpContainer.execInContainer("mkdir", "-p", "/home/user/.ssh"); - sftpContainer.execInContainer("chmod", "700", "/home/user/.ssh"); - sftpContainer.execInContainer("chown", "user", "/home/user/.ssh/"); - sftpContainer.execInContainer( + SFTP_CONTAINER.execInContainer("mkdir", "-p", "/home/user/.ssh"); + SFTP_CONTAINER.execInContainer("chmod", "700", "/home/user/.ssh"); + SFTP_CONTAINER.execInContainer("chown", "user", "/home/user/.ssh/"); + SFTP_CONTAINER.execInContainer( "cp", "-f", "/home/user/keys/public", "/home/user/.ssh/authorized_keys"); - sftpContainer.execInContainer("chown", "user", "/home/user/.ssh/authorized_keys"); - sftpContainer.execInContainer("chmod", "600", "/home/user/.ssh/authorized_keys"); + SFTP_CONTAINER.execInContainer("chown", "user", "/home/user/.ssh/authorized_keys"); + SFTP_CONTAINER.execInContainer("chmod", "600", "/home/user/.ssh/authorized_keys"); } catch (IOException | InterruptedException e) { throw new RuntimeException(); } @@ -156,20 +155,20 @@ abstract class AbstractSftpClientWrapperIT { @AfterAll @SneakyThrows static void tearDown() { - if (Files.exists(dockerVolumeDirectory)) { - Files.walk(dockerVolumeDirectory) + if (Files.exists(DOCKER_VOLUME_DIRECTORY)) { + Files.walk(DOCKER_VOLUME_DIRECTORY) .sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); } - if (Files.exists(localUploadAndGeneratorDirectory)) { - Files.walk(localUploadAndGeneratorDirectory) + if (Files.exists(LOCAL_UPLOAD_AND_GENERATOR_DIRECTORY)) { + Files.walk(LOCAL_UPLOAD_AND_GENERATOR_DIRECTORY) .sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); } - if (Files.exists(keyDirectory)) { - Files.walk(keyDirectory) + if (Files.exists(KEY_DIRECTORY)) { + Files.walk(KEY_DIRECTORY) .sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); @@ -188,13 +187,13 @@ protected SftpUser getPasswordUser() { } protected SftpUser getKeyPairUser() { - return SftpUser.builder().name("user").keyPair(keyPair).build(); + return SftpUser.builder().name("user").keyPair(KEY_PAIR).build(); } protected SftpLocation getSftpLocation(String path) { return SftpLocation.builder() .host("127.0.0.1") - .port(sftpContainer.getFirstMappedPort()) + .port(SFTP_CONTAINER.getFirstMappedPort()) .path(path) .build(); } @@ -216,27 +215,27 @@ protected static class FilesProvider implements ArgumentsProvider { @Override public Stream provideArguments(ExtensionContext context) { return Stream.of( - Arguments.of(get1KBFile()), Arguments.of(get1MBFile()), Arguments.of(get2MBFile())); + Arguments.of(get1KbFile()), Arguments.of(get1MbFile()), Arguments.of(get2MbFile())); } - public File get1KBFile() { + public File get1KbFile() { return generateFile(1024); } - public File get1MBFile() { + public File get1MbFile() { return generateFile(1024 * 1024); } - public File get2MBFile() { + public File get2MbFile() { return generateFile(2 * 1024 * 1024); } @SneakyThrows private File generateFile(final int byteSize) { - Path path = localUploadAndGeneratorDirectory.resolve(String.format("%s.bin", byteSize)); + Path path = LOCAL_UPLOAD_AND_GENERATOR_DIRECTORY.resolve(String.format("%s.bin", byteSize)); if (!Files.exists(path)) { Files.createFile(path); - try (final OutputStream outputStream = Files.newOutputStream(path)) { + try (var outputStream = Files.newOutputStream(path)) { int bufferSize; int remaining = byteSize; do { diff --git a/edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientWrapperIT.java b/edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientWrapperIT.java deleted file mode 100644 index 368db5bf8..000000000 --- a/edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientWrapperIT.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (c) 2022 Mercedes-Benz Tech Innovation GmbH - * - * This program and the accompanying materials are made available under the - * terms of the Apache License, Version 2.0 which is available at - * https://www.apache.org/licenses/LICENSE-2.0 - * - * SPDX-License-Identifier: Apache-2.0 - * - * Contributors: - * Mercedes-Benz Tech Innovation GmbH - Initial Test - * - */ - -package org.eclipse.tractusx.edc.transferprocess.sftp.client; - -import java.io.File; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardCopyOption; -import lombok.Cleanup; -import lombok.SneakyThrows; -import org.eclipse.edc.junit.extensions.EdcExtension; -import org.eclipse.tractusx.edc.transferprocess.sftp.common.SftpLocation; -import org.eclipse.tractusx.edc.transferprocess.sftp.common.SftpUser; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ArgumentsSource; -import org.testcontainers.junit.jupiter.Testcontainers; -import org.testcontainers.shaded.org.apache.commons.io.IOUtils; - -@Disabled("Does not work") -@Testcontainers -@ExtendWith(EdcExtension.class) -class SftpClientWrapperIT extends AbstractSftpClientWrapperIT { - - @ParameterizedTest - @SneakyThrows - @ArgumentsSource(FilesProvider.class) - void uploadFileWithPassword(File file) { - final SftpUser sftpUser = getPasswordUser(); - final SftpLocation sftpLocation = - getSftpLocation( - String.format( - "%s/%s/%s", - sftpPathPrefix, - remotePasswordUploadDirectory.getFileName().toString(), - file.getName())); - - @Cleanup final InputStream fileStream = Files.newInputStream(file.toPath()); - - getSftpClient(sftpLocation, sftpUser).uploadFile(fileStream); - - final Path uploadedFilePath = remotePasswordUploadDirectory.resolve(file.getName()); - Assertions.assertTrue(Files.exists(uploadedFilePath)); - - @Cleanup final InputStream source = Files.newInputStream(file.toPath()); - @Cleanup final InputStream target = Files.newInputStream(uploadedFilePath); - - Assertions.assertTrue( - IOUtils.contentEquals(source, target), - String.format( - "File %s should have same content as file %s", file.toPath(), uploadedFilePath)); - } - - @ParameterizedTest - @SneakyThrows - @ArgumentsSource(FilesProvider.class) - void uploadFileWithKeyPair(File file) { - final SftpUser sftpUser = getKeyPairUser(); - final SftpLocation sftpLocation = - getSftpLocation( - String.format( - "%s/%s/%s", - sftpPathPrefix, - remoteKeypairUploadDirectory.getFileName().toString(), - file.getName())); - - @Cleanup final InputStream fileStream = Files.newInputStream(file.toPath()); - - getSftpClient(sftpLocation, sftpUser).uploadFile(fileStream); - - final Path uploadedFilePath = remoteKeypairUploadDirectory.resolve(file.getName()); - Assertions.assertTrue(Files.exists(uploadedFilePath)); - - @Cleanup final InputStream source = Files.newInputStream(file.toPath()); - @Cleanup final InputStream target = Files.newInputStream(uploadedFilePath); - - Assertions.assertTrue( - IOUtils.contentEquals(source, target), - String.format( - "File %s should have same content as file %s", file.toPath(), uploadedFilePath)); - } - - @ParameterizedTest - @SneakyThrows - @ArgumentsSource(FilesProvider.class) - void downloadFileWithPassword(File file) { - final SftpUser sftpUser = getPasswordUser(); - final SftpLocation sftpLocation = - getSftpLocation( - String.format( - "%s/%s/%s", - sftpPathPrefix, - remotePasswordDownloadDirectory.getFileName().toString(), - file.getName())); - - @Cleanup final InputStream fileToUpload = Files.newInputStream(file.toPath()); - Files.copy( - fileToUpload, - remotePasswordDownloadDirectory.resolve(file.getName()), - StandardCopyOption.REPLACE_EXISTING); - - @Cleanup final InputStream source = Files.newInputStream(file.toPath()); - @Cleanup final InputStream target = getSftpClient(sftpLocation, sftpUser).downloadFile(); - - Assertions.assertTrue( - IOUtils.contentEquals(source, target), - String.format( - "File %s should have same content as file %s", file.toPath(), sftpLocation.getPath())); - } - - @ParameterizedTest - @SneakyThrows - @ArgumentsSource(FilesProvider.class) - void downloadFileWithKeyPair(File file) { - final SftpUser sftpUser = getKeyPairUser(); - final SftpLocation sftpLocation = - getSftpLocation( - String.format( - "%s/%s/%s", - sftpPathPrefix, - remoteKeypairDownloadDirectory.getFileName().toString(), - file.getName())); - - @Cleanup final InputStream fileToUpload = Files.newInputStream(file.toPath()); - Files.copy( - fileToUpload, - remoteKeypairDownloadDirectory.resolve(file.getName()), - StandardCopyOption.REPLACE_EXISTING); - - @Cleanup final InputStream source = Files.newInputStream(file.toPath()); - @Cleanup final InputStream target = getSftpClient(sftpLocation, sftpUser).downloadFile(); - - Assertions.assertTrue( - IOUtils.contentEquals(source, target), - String.format( - "File %s should have same content as file %s", file.toPath(), sftpLocation.getPath())); - } -} diff --git a/edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientWrapperTest.java b/edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientWrapperTest.java index 7fcb0196c..c5830b3b4 100644 --- a/edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientWrapperTest.java +++ b/edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpClientWrapperTest.java @@ -20,10 +20,6 @@ package org.eclipse.tractusx.edc.transferprocess.sftp.client; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.util.List; import lombok.SneakyThrows; import org.apache.sshd.sftp.client.SftpClient; import org.eclipse.tractusx.edc.transferprocess.sftp.common.SftpLocation; @@ -32,54 +28,59 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.util.List; + class SftpClientWrapperTest { - @Test - @SneakyThrows - void uploadFile() { - SftpUser userMock = Mockito.mock(SftpUser.class); - SftpLocation locationMock = Mockito.mock(SftpLocation.class); - SftpClientConfig sftpClientConfig = - SftpClientConfig.builder().sftpUser(userMock).sftpLocation(locationMock).build(); - SftpClient sftpClientMock = Mockito.mock(SftpClient.class); - SftpClientWrapperImpl sftpClientWrapper = - Mockito.spy(new SftpClientWrapperImpl(sftpClientConfig, sftpClientMock)); - byte[] content = new byte[] {0, 1, 2}; - InputStream inputStream = new ByteArrayInputStream(content); - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + @Test + @SneakyThrows + void uploadFile() { + SftpUser userMock = Mockito.mock(SftpUser.class); + SftpLocation locationMock = Mockito.mock(SftpLocation.class); + SftpClientConfig sftpClientConfig = + SftpClientConfig.builder().sftpUser(userMock).sftpLocation(locationMock).build(); + SftpClient sftpClientMock = Mockito.mock(SftpClient.class); + SftpClientWrapperImpl sftpClientWrapper = + Mockito.spy(new SftpClientWrapperImpl(sftpClientConfig, sftpClientMock)); + byte[] content = new byte[]{0, 1, 2}; + InputStream inputStream = new ByteArrayInputStream(content); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - Mockito.when(locationMock.getPath()).thenReturn("path"); - Mockito.when( - sftpClientMock.write(Mockito.anyString(), Mockito.anyInt(), Mockito.anyCollection())) - .thenReturn(outputStream); - sftpClientWrapper.uploadFile(inputStream); + Mockito.when(locationMock.getPath()).thenReturn("path"); + Mockito.when( + sftpClientMock.write(Mockito.anyString(), Mockito.anyInt(), Mockito.anyCollection())) + .thenReturn(outputStream); + sftpClientWrapper.uploadFile(inputStream); - Assertions.assertArrayEquals(content, outputStream.toByteArray()); - Mockito.verify(sftpClientMock, Mockito.times(1)) - .write("path", 4096, List.of(SftpClient.OpenMode.Create, SftpClient.OpenMode.Write)); - } + Assertions.assertArrayEquals(content, outputStream.toByteArray()); + Mockito.verify(sftpClientMock, Mockito.times(1)) + .write("path", 4096, List.of(SftpClient.OpenMode.Create, SftpClient.OpenMode.Write)); + } - @Test - @SneakyThrows - void downloadFile() { - SftpUser userMock = Mockito.mock(SftpUser.class); - SftpLocation locationMock = Mockito.mock(SftpLocation.class); - SftpClientConfig sftpClientConfig = - SftpClientConfig.builder().sftpUser(userMock).sftpLocation(locationMock).build(); - SftpClient sftpClientMock = Mockito.mock(SftpClient.class); - SftpClientWrapperImpl sftpClientWrapper = - Mockito.spy(new SftpClientWrapperImpl(sftpClientConfig, sftpClientMock)); - byte[] content = new byte[] {0, 1, 2}; - InputStream inputStream = new ByteArrayInputStream(content); + @Test + @SneakyThrows + void downloadFile() { + SftpUser userMock = Mockito.mock(SftpUser.class); + SftpLocation locationMock = Mockito.mock(SftpLocation.class); + SftpClientConfig sftpClientConfig = + SftpClientConfig.builder().sftpUser(userMock).sftpLocation(locationMock).build(); + SftpClient sftpClientMock = Mockito.mock(SftpClient.class); + SftpClientWrapperImpl sftpClientWrapper = + Mockito.spy(new SftpClientWrapperImpl(sftpClientConfig, sftpClientMock)); + byte[] content = new byte[]{0, 1, 2}; + InputStream inputStream = new ByteArrayInputStream(content); - Mockito.when(locationMock.getPath()).thenReturn("path"); - Mockito.when( - sftpClientMock.read(Mockito.anyString(), Mockito.anyInt(), Mockito.anyCollection())) - .thenReturn(inputStream); + Mockito.when(locationMock.getPath()).thenReturn("path"); + Mockito.when( + sftpClientMock.read(Mockito.anyString(), Mockito.anyInt(), Mockito.anyCollection())) + .thenReturn(inputStream); - try (InputStream resultStream = sftpClientWrapper.downloadFile()) { - Assertions.assertArrayEquals(content, resultStream.readAllBytes()); - Mockito.verify(sftpClientMock, Mockito.times(1)) - .read("path", 4096, List.of(SftpClient.OpenMode.Read)); + try (InputStream resultStream = sftpClientWrapper.downloadFile()) { + Assertions.assertArrayEquals(content, resultStream.readAllBytes()); + Mockito.verify(sftpClientMock, Mockito.times(1)) + .read("path", 4096, List.of(SftpClient.OpenMode.Read)); + } } - } } diff --git a/edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpDataSinkFactoryTest.java b/edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpDataSinkFactoryTest.java index 835c764cc..1e3240854 100644 --- a/edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpDataSinkFactoryTest.java +++ b/edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpDataSinkFactoryTest.java @@ -20,8 +20,6 @@ package org.eclipse.tractusx.edc.transferprocess.sftp.client; -import java.util.List; -import java.util.Map; import lombok.SneakyThrows; import org.apache.sshd.sftp.client.SftpClient; import org.eclipse.edc.spi.types.domain.DataAddress; @@ -34,91 +32,94 @@ import org.mockito.MockedStatic; import org.mockito.Mockito; +import java.util.List; +import java.util.Map; + class SftpDataSinkFactoryTest { - @Test - void validate__valid() { - SftpDataSinkFactory dataSinkFactory = new SftpDataSinkFactory(); - SftpUser sftpUser = SftpUser.builder().name("name").build(); - SftpLocation sftpLocation = SftpLocation.builder().host("host").port(22).path("path").build(); - - SftpDataAddress sftpDataAddress = - SftpDataAddress.builder().sftpUser(sftpUser).sftpLocation(sftpLocation).build(); - DataFlowRequest request = Mockito.mock(DataFlowRequest.class); - Mockito.when(request.getDestinationDataAddress()).thenReturn(sftpDataAddress); - - Assertions.assertTrue(dataSinkFactory.validate(request).succeeded()); - } - - @Test - void validate__invalidDataAddressType() { - SftpDataSinkFactory dataSinkFactory = new SftpDataSinkFactory(); - DataAddress dataAddress = DataAddress.Builder.newInstance().type("wrong").build(); - DataFlowRequest request = Mockito.mock(DataFlowRequest.class); - Mockito.when(request.getDestinationDataAddress()).thenReturn(dataAddress); - - Assertions.assertTrue(dataSinkFactory.validate(request).failed()); - } - - @Test - void validate__invalidDataAddressParameters() { - SftpDataSinkFactory dataSinkFactory = new SftpDataSinkFactory(); - final Map properties = - Map.of( - "type", "sftp", - "locationHost", "localhost", - "locationPort", "notANumber", - "locationPath", "path", - "userName", "name", - "userPassword", "password"); - - final DataAddress dataAddress = - DataAddress.Builder.newInstance().properties(properties).build(); - DataFlowRequest request = Mockito.mock(DataFlowRequest.class); - Mockito.when(request.getDestinationDataAddress()).thenReturn(dataAddress); - - Assertions.assertTrue(dataSinkFactory.validate(request).failed()); - } - - @Test - @SneakyThrows - void createSink__successful() { - SftpDataSinkFactory dataSinkFactory = new SftpDataSinkFactory(); - SftpUser sftpUser = SftpUser.builder().name("name").build(); - SftpLocation sftpLocation = - SftpLocation.builder().host("127.0.0.1").port(22).path("path").build(); - SftpClientConfig sftpClientConfig = - SftpClientConfig.builder() - .writeOpenModes(List.of(SftpClient.OpenMode.Create, SftpClient.OpenMode.Append)) - .sftpUser(sftpUser) - .sftpLocation(sftpLocation) - .build(); - - SftpDataAddress sftpDataAddress = - SftpDataAddress.builder().sftpUser(sftpUser).sftpLocation(sftpLocation).build(); - DataFlowRequest request = Mockito.mock(DataFlowRequest.class); - Mockito.when(request.getDestinationDataAddress()).thenReturn(sftpDataAddress); - - try (MockedStatic staticWrapper = - Mockito.mockStatic(SftpClientWrapperImpl.class)) { - staticWrapper - .when(() -> SftpClientWrapperImpl.getSftpClient(sftpClientConfig)) - .thenReturn(Mockito.mock(SftpClient.class)); - Assertions.assertNotNull(dataSinkFactory.createSink(request)); - - staticWrapper.verify( - () -> SftpClientWrapperImpl.getSftpClient(Mockito.any()), Mockito.times(1)); + @Test + void validate_valid() { + SftpDataSinkFactory dataSinkFactory = new SftpDataSinkFactory(); + SftpUser sftpUser = SftpUser.builder().name("name").build(); + SftpLocation sftpLocation = SftpLocation.builder().host("host").port(22).path("path").build(); + + SftpDataAddress sftpDataAddress = + SftpDataAddress.builder().sftpUser(sftpUser).sftpLocation(sftpLocation).build(); + DataFlowRequest request = Mockito.mock(DataFlowRequest.class); + Mockito.when(request.getDestinationDataAddress()).thenReturn(sftpDataAddress); + + Assertions.assertTrue(dataSinkFactory.validate(request).succeeded()); + } + + @Test + void validate_invalidDataAddressType() { + SftpDataSinkFactory dataSinkFactory = new SftpDataSinkFactory(); + DataAddress dataAddress = DataAddress.Builder.newInstance().type("wrong").build(); + DataFlowRequest request = Mockito.mock(DataFlowRequest.class); + Mockito.when(request.getDestinationDataAddress()).thenReturn(dataAddress); + + Assertions.assertTrue(dataSinkFactory.validate(request).failed()); + } + + @Test + void validate_invalidDataAddressParameters() { + SftpDataSinkFactory dataSinkFactory = new SftpDataSinkFactory(); + final Map properties = + Map.of( + "type", "sftp", + "locationHost", "localhost", + "locationPort", "notANumber", + "locationPath", "path", + "userName", "name", + "userPassword", "password"); + + final DataAddress dataAddress = + DataAddress.Builder.newInstance().properties(properties).build(); + DataFlowRequest request = Mockito.mock(DataFlowRequest.class); + Mockito.when(request.getDestinationDataAddress()).thenReturn(dataAddress); + + Assertions.assertTrue(dataSinkFactory.validate(request).failed()); + } + + @Test + @SneakyThrows + void createSink_successful() { + SftpDataSinkFactory dataSinkFactory = new SftpDataSinkFactory(); + SftpUser sftpUser = SftpUser.builder().name("name").build(); + SftpLocation sftpLocation = + SftpLocation.builder().host("127.0.0.1").port(22).path("path").build(); + SftpClientConfig sftpClientConfig = + SftpClientConfig.builder() + .writeOpenModes(List.of(SftpClient.OpenMode.Create, SftpClient.OpenMode.Append)) + .sftpUser(sftpUser) + .sftpLocation(sftpLocation) + .build(); + + SftpDataAddress sftpDataAddress = + SftpDataAddress.builder().sftpUser(sftpUser).sftpLocation(sftpLocation).build(); + DataFlowRequest request = Mockito.mock(DataFlowRequest.class); + Mockito.when(request.getDestinationDataAddress()).thenReturn(sftpDataAddress); + + try (MockedStatic staticWrapper = + Mockito.mockStatic(SftpClientWrapperImpl.class)) { + staticWrapper + .when(() -> SftpClientWrapperImpl.getSftpClient(sftpClientConfig)) + .thenReturn(Mockito.mock(SftpClient.class)); + Assertions.assertNotNull(dataSinkFactory.createSink(request)); + + staticWrapper.verify( + () -> SftpClientWrapperImpl.getSftpClient(Mockito.any()), Mockito.times(1)); + } + } + + @Test + @SneakyThrows + void createSink_invalidDataAddressType() { + SftpDataSinkFactory dataSinkFactory = new SftpDataSinkFactory(); + DataAddress dataAddress = DataAddress.Builder.newInstance().type("wrong").build(); + DataFlowRequest request = Mockito.mock(DataFlowRequest.class); + Mockito.when(request.getDestinationDataAddress()).thenReturn(dataAddress); + + Assertions.assertNull(dataSinkFactory.createSink(request)); } - } - - @Test - @SneakyThrows - void createSink__invalidDataAddressType() { - SftpDataSinkFactory dataSinkFactory = new SftpDataSinkFactory(); - DataAddress dataAddress = DataAddress.Builder.newInstance().type("wrong").build(); - DataFlowRequest request = Mockito.mock(DataFlowRequest.class); - Mockito.when(request.getDestinationDataAddress()).thenReturn(dataAddress); - - Assertions.assertNull(dataSinkFactory.createSink(request)); - } } diff --git a/edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpDataSinkTest.java b/edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpDataSinkTest.java index 7af9eea1f..00d2b7408 100644 --- a/edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpDataSinkTest.java +++ b/edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpDataSinkTest.java @@ -20,11 +20,6 @@ package org.eclipse.tractusx.edc.transferprocess.sftp.client; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.util.Arrays; -import java.util.List; import lombok.AllArgsConstructor; import lombok.SneakyThrows; import org.apache.sshd.sftp.client.SftpClient; @@ -35,52 +30,58 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.util.Arrays; +import java.util.List; + class SftpDataSinkTest { - @Test - @SneakyThrows - void transferParts() { - final SftpUser userMock = Mockito.mock(SftpUser.class); - final SftpLocation locationMock = Mockito.mock(SftpLocation.class); - final SftpClientConfig sftpClientConfig = - SftpClientConfig.builder() - .sftpUser(userMock) - .sftpLocation(locationMock) - .writeOpenModes(List.of(SftpClient.OpenMode.Create, SftpClient.OpenMode.Append)) - .build(); - final SftpClient sftpClientMock = Mockito.mock(SftpClient.class); - final SftpClientWrapperImpl sftpClientWrapper = - Mockito.spy(new SftpClientWrapperImpl(sftpClientConfig, sftpClientMock)); - final SftpDataSink sftpDataSink = Mockito.spy(new SftpDataSink(sftpClientWrapper)); - final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + @Test + @SneakyThrows + void transferParts() { + final SftpUser userMock = Mockito.mock(SftpUser.class); + final SftpLocation locationMock = Mockito.mock(SftpLocation.class); + final SftpClientConfig sftpClientConfig = + SftpClientConfig.builder() + .sftpUser(userMock) + .sftpLocation(locationMock) + .writeOpenModes(List.of(SftpClient.OpenMode.Create, SftpClient.OpenMode.Append)) + .build(); + final SftpClient sftpClientMock = Mockito.mock(SftpClient.class); + final SftpClientWrapperImpl sftpClientWrapper = + Mockito.spy(new SftpClientWrapperImpl(sftpClientConfig, sftpClientMock)); + final SftpDataSink sftpDataSink = Mockito.spy(new SftpDataSink(sftpClientWrapper)); + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - Mockito.when(sftpClientMock.write(Mockito.any(), Mockito.anyInt(), Mockito.anyCollection())) - .thenReturn(outputStream); - Mockito.when(locationMock.getPath()).thenReturn("path"); + Mockito.when(sftpClientMock.write(Mockito.any(), Mockito.anyInt(), Mockito.anyCollection())) + .thenReturn(outputStream); + Mockito.when(locationMock.getPath()).thenReturn("path"); - List parts = - Arrays.asList(new SftpTestPart(new byte[] {0, 1}), new SftpTestPart(new byte[] {2, 3})); - byte[] expected = {0, 1, 2, 3}; + List parts = + Arrays.asList(new SftpTestPart(new byte[]{0, 1}), new SftpTestPart(new byte[]{2, 3})); + byte[] expected = {0, 1, 2, 3}; - sftpDataSink.transferParts(parts); + sftpDataSink.transferParts(parts); - Assertions.assertArrayEquals(expected, outputStream.toByteArray()); - Mockito.verify(sftpClientMock, Mockito.times(2)) - .write("path", 4096, List.of(SftpClient.OpenMode.Create, SftpClient.OpenMode.Append)); - } + Assertions.assertArrayEquals(expected, outputStream.toByteArray()); + Mockito.verify(sftpClientMock, Mockito.times(2)) + .write("path", 4096, List.of(SftpClient.OpenMode.Create, SftpClient.OpenMode.Append)); + } - @AllArgsConstructor - private static class SftpTestPart implements DataSource.Part { + @AllArgsConstructor + private static class SftpTestPart implements DataSource.Part { - final byte[] content; + final byte[] content; - @Override - public String name() { - return null; - } + @Override + public String name() { + return null; + } - @Override - public InputStream openStream() { - return new ByteArrayInputStream(content); + @Override + public InputStream openStream() { + return new ByteArrayInputStream(content); + } } - } } diff --git a/edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpDataSourceFactoryTest.java b/edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpDataSourceFactoryTest.java index 5c8a63f4f..a13a83530 100644 --- a/edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpDataSourceFactoryTest.java +++ b/edc-extensions/transferprocess-sftp-client/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/client/SftpDataSourceFactoryTest.java @@ -20,7 +20,6 @@ package org.eclipse.tractusx.edc.transferprocess.sftp.client; -import java.util.Map; import lombok.SneakyThrows; import org.apache.sshd.sftp.client.SftpClient; import org.eclipse.edc.spi.types.domain.DataAddress; @@ -33,86 +32,88 @@ import org.mockito.MockedStatic; import org.mockito.Mockito; +import java.util.Map; + class SftpDataSourceFactoryTest { - @Test - void validate__valid() { - SftpDataSourceFactory dataSourceFactory = new SftpDataSourceFactory(); - SftpUser sftpUser = SftpUser.builder().name("name").build(); - SftpLocation sftpLocation = SftpLocation.builder().host("host").port(22).path("path").build(); - - SftpDataAddress sftpDataAddress = - SftpDataAddress.builder().sftpUser(sftpUser).sftpLocation(sftpLocation).build(); - DataFlowRequest request = Mockito.mock(DataFlowRequest.class); - Mockito.when(request.getSourceDataAddress()).thenReturn(sftpDataAddress); - - Assertions.assertTrue(dataSourceFactory.validate(request).succeeded()); - } - - @Test - void validate__invalidDataAddressType() { - SftpDataSourceFactory dataSourceFactory = new SftpDataSourceFactory(); - DataAddress dataAddress = DataAddress.Builder.newInstance().type("wrong").build(); - DataFlowRequest request = Mockito.mock(DataFlowRequest.class); - Mockito.when(request.getSourceDataAddress()).thenReturn(dataAddress); - - Assertions.assertTrue(dataSourceFactory.validate(request).failed()); - } - - @Test - void validate__invalidDataAddressParameters() { - SftpDataSourceFactory dataSourceFactory = new SftpDataSourceFactory(); - final Map properties = - Map.of( - "type", "sftp", - "locationHost", "localhost", - "locationPort", "notANumber", - "locationPath", "path", - "userName", "name", - "userPassword", "password"); - - DataAddress dataAddress = DataAddress.Builder.newInstance().properties(properties).build(); - DataFlowRequest request = Mockito.mock(DataFlowRequest.class); - Mockito.when(request.getSourceDataAddress()).thenReturn(dataAddress); - - Assertions.assertTrue(dataSourceFactory.validate(request).failed()); - } - - @Test - @SneakyThrows - void createSink__successful() { - SftpDataSourceFactory dataSourceFactory = new SftpDataSourceFactory(); - SftpUser sftpUser = SftpUser.builder().name("name").build(); - SftpLocation sftpLocation = - SftpLocation.builder().host("127.0.0.1").port(22).path("path").build(); - SftpClientConfig sftpClientConfig = - SftpClientConfig.builder().sftpUser(sftpUser).sftpLocation(sftpLocation).build(); - - SftpDataAddress sftpDataAddress = - SftpDataAddress.builder().sftpUser(sftpUser).sftpLocation(sftpLocation).build(); - DataFlowRequest request = Mockito.mock(DataFlowRequest.class); - Mockito.when(request.getSourceDataAddress()).thenReturn(sftpDataAddress); - - try (MockedStatic staticWrapper = - Mockito.mockStatic(SftpClientWrapperImpl.class)) { - staticWrapper - .when(() -> SftpClientWrapperImpl.getSftpClient(sftpClientConfig)) - .thenReturn(Mockito.mock(SftpClient.class)); - Assertions.assertNotNull(dataSourceFactory.createSource(request)); - - staticWrapper.verify( - () -> SftpClientWrapperImpl.getSftpClient(Mockito.any()), Mockito.times(1)); + @Test + void validate_valid() { + SftpDataSourceFactory dataSourceFactory = new SftpDataSourceFactory(); + SftpUser sftpUser = SftpUser.builder().name("name").build(); + SftpLocation sftpLocation = SftpLocation.builder().host("host").port(22).path("path").build(); + + SftpDataAddress sftpDataAddress = + SftpDataAddress.builder().sftpUser(sftpUser).sftpLocation(sftpLocation).build(); + DataFlowRequest request = Mockito.mock(DataFlowRequest.class); + Mockito.when(request.getSourceDataAddress()).thenReturn(sftpDataAddress); + + Assertions.assertTrue(dataSourceFactory.validate(request).succeeded()); + } + + @Test + void validate_invalidDataAddressType() { + SftpDataSourceFactory dataSourceFactory = new SftpDataSourceFactory(); + DataAddress dataAddress = DataAddress.Builder.newInstance().type("wrong").build(); + DataFlowRequest request = Mockito.mock(DataFlowRequest.class); + Mockito.when(request.getSourceDataAddress()).thenReturn(dataAddress); + + Assertions.assertTrue(dataSourceFactory.validate(request).failed()); + } + + @Test + void validate_invalidDataAddressParameters() { + SftpDataSourceFactory dataSourceFactory = new SftpDataSourceFactory(); + final Map properties = + Map.of( + "type", "sftp", + "locationHost", "localhost", + "locationPort", "notANumber", + "locationPath", "path", + "userName", "name", + "userPassword", "password"); + + DataAddress dataAddress = DataAddress.Builder.newInstance().properties(properties).build(); + DataFlowRequest request = Mockito.mock(DataFlowRequest.class); + Mockito.when(request.getSourceDataAddress()).thenReturn(dataAddress); + + Assertions.assertTrue(dataSourceFactory.validate(request).failed()); + } + + @Test + @SneakyThrows + void createSink_successful() { + SftpDataSourceFactory dataSourceFactory = new SftpDataSourceFactory(); + SftpUser sftpUser = SftpUser.builder().name("name").build(); + SftpLocation sftpLocation = + SftpLocation.builder().host("127.0.0.1").port(22).path("path").build(); + SftpClientConfig sftpClientConfig = + SftpClientConfig.builder().sftpUser(sftpUser).sftpLocation(sftpLocation).build(); + + SftpDataAddress sftpDataAddress = + SftpDataAddress.builder().sftpUser(sftpUser).sftpLocation(sftpLocation).build(); + DataFlowRequest request = Mockito.mock(DataFlowRequest.class); + Mockito.when(request.getSourceDataAddress()).thenReturn(sftpDataAddress); + + try (MockedStatic staticWrapper = + Mockito.mockStatic(SftpClientWrapperImpl.class)) { + staticWrapper + .when(() -> SftpClientWrapperImpl.getSftpClient(sftpClientConfig)) + .thenReturn(Mockito.mock(SftpClient.class)); + Assertions.assertNotNull(dataSourceFactory.createSource(request)); + + staticWrapper.verify( + () -> SftpClientWrapperImpl.getSftpClient(Mockito.any()), Mockito.times(1)); + } + } + + @Test + @SneakyThrows + void createSink_invalidDataAddressType() { + SftpDataSourceFactory dataSourceFactory = new SftpDataSourceFactory(); + DataAddress dataAddress = DataAddress.Builder.newInstance().type("wrong").build(); + DataFlowRequest request = Mockito.mock(DataFlowRequest.class); + Mockito.when(request.getSourceDataAddress()).thenReturn(dataAddress); + + Assertions.assertNull(dataSourceFactory.createSource(request)); } - } - - @Test - @SneakyThrows - void createSink__invalidDataAddressType() { - SftpDataSourceFactory dataSourceFactory = new SftpDataSourceFactory(); - DataAddress dataAddress = DataAddress.Builder.newInstance().type("wrong").build(); - DataFlowRequest request = Mockito.mock(DataFlowRequest.class); - Mockito.when(request.getSourceDataAddress()).thenReturn(dataAddress); - - Assertions.assertNull(dataSourceFactory.createSource(request)); - } } diff --git a/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/EdcSftpException.java b/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/EdcSftpException.java index aa6151eec..a830b1ea9 100644 --- a/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/EdcSftpException.java +++ b/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/EdcSftpException.java @@ -17,20 +17,20 @@ import org.eclipse.edc.spi.EdcException; public class EdcSftpException extends EdcException { - public EdcSftpException(String message) { - super(message); - } + public EdcSftpException(String message) { + super(message); + } - public EdcSftpException(String message, Throwable cause) { - super(message, cause); - } + public EdcSftpException(String message, Throwable cause) { + super(message, cause); + } - public EdcSftpException(Throwable cause) { - super(cause); - } + public EdcSftpException(Throwable cause) { + super(cause); + } - public EdcSftpException( - String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } + public EdcSftpException( + String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } } diff --git a/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpDataAddress.java b/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpDataAddress.java index 0a9b8ef03..6a634df78 100644 --- a/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpDataAddress.java +++ b/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpDataAddress.java @@ -24,56 +24,59 @@ @Builder @Getter public class SftpDataAddress extends DataAddress { - private static final String LOCATION_HOST = "locationHost"; - private static final String LOCATION_PORT = "locationPort"; - private static final String LOCATION_PATH = "locationPath"; - private static final String USER_NAME = "userName"; - private static final String USER_PASSWORD = "userPassword"; - private static final String USER_PRIVATE_KEY = "userPrivateKey"; + private static final String LOCATION_HOST = "locationHost"; + private static final String LOCATION_PORT = "locationPort"; + private static final String LOCATION_PATH = "locationPath"; + private static final String USER_NAME = "userName"; + private static final String USER_PASSWORD = "userPassword"; + private static final String USER_PRIVATE_KEY = "userPrivateKey"; - @Getter private static final String CONNECTION_TYPE = "sftp"; - @NonNull private final SftpUser sftpUser; - @NonNull private final SftpLocation sftpLocation; + @Getter + private static final String CONNECTION_TYPE = "sftp"; + @NonNull + private final SftpUser sftpUser; + @NonNull + private final SftpLocation sftpLocation; - public static SftpDataAddress fromDataAddress(DataAddress dataAddress) throws EdcSftpException { - if (dataAddress instanceof SftpDataAddress) { - return (SftpDataAddress) dataAddress; - } + public static SftpDataAddress fromDataAddress(DataAddress dataAddress) throws EdcSftpException { + if (dataAddress instanceof SftpDataAddress) { + return (SftpDataAddress) dataAddress; + } - if (!dataAddress.getType().equalsIgnoreCase("sftp")) { - throw new EdcSftpException( - String.format( - "Invalid DataAddress type: %s. Expected %s.", - dataAddress.getType(), CONNECTION_TYPE)); - } + if (!dataAddress.getType().equalsIgnoreCase("sftp")) { + throw new EdcSftpException( + String.format( + "Invalid DataAddress type: %s. Expected %s.", + dataAddress.getType(), CONNECTION_TYPE)); + } - try { - SftpUser sftpUser = - SftpUser.builder() - .name(dataAddress.getProperty(USER_NAME)) - .password(dataAddress.getProperty(USER_PASSWORD)) - .keyPair( - SftpUserKeyPairGenerator.getKeyPairFromPrivateKey( - dataAddress.getProperty(USER_PRIVATE_KEY), - dataAddress.getProperty(USER_NAME))) - .build(); + try { + SftpUser sftpUser = + SftpUser.builder() + .name(dataAddress.getProperty(USER_NAME)) + .password(dataAddress.getProperty(USER_PASSWORD)) + .keyPair( + SftpUserKeyPairGenerator.getKeyPairFromPrivateKey( + dataAddress.getProperty(USER_PRIVATE_KEY), + dataAddress.getProperty(USER_NAME))) + .build(); - SftpLocation sftpLocation = - SftpLocation.builder() - .host(dataAddress.getProperty(LOCATION_HOST)) - .port(Integer.valueOf(dataAddress.getProperty(LOCATION_PORT, "22"))) - .path(dataAddress.getProperty(LOCATION_PATH)) - .build(); + SftpLocation sftpLocation = + SftpLocation.builder() + .host(dataAddress.getProperty(LOCATION_HOST)) + .port(Integer.valueOf(dataAddress.getProperty(LOCATION_PORT, "22"))) + .path(dataAddress.getProperty(LOCATION_PATH)) + .build(); - return SftpDataAddress.builder().sftpUser(sftpUser).sftpLocation(sftpLocation).build(); - } catch (NullPointerException e) { - throw new EdcSftpException(e.getMessage(), e); - } catch (NumberFormatException e) { - throw new EdcSftpException( - String.format( - "Port for SftpLocation %s/%s not a number", - dataAddress.getProperty(LOCATION_HOST), dataAddress.getProperty(LOCATION_PATH)), - e); + return SftpDataAddress.builder().sftpUser(sftpUser).sftpLocation(sftpLocation).build(); + } catch (NullPointerException e) { + throw new EdcSftpException(e.getMessage(), e); + } catch (NumberFormatException e) { + throw new EdcSftpException( + String.format( + "Port for SftpLocation %s/%s not a number", + dataAddress.getProperty(LOCATION_HOST), dataAddress.getProperty(LOCATION_PATH)), + e); + } } - } } diff --git a/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpLocation.java b/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpLocation.java index b9af1aecb..35db25e5a 100644 --- a/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpLocation.java +++ b/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpLocation.java @@ -23,12 +23,15 @@ @Getter @EqualsAndHashCode public class SftpLocation { - @NonNull private final String host; - @NonNull private final Integer port; - @NonNull private final String path; + @NonNull + private final String host; + @NonNull + private final Integer port; + @NonNull + private final String path; - @Override - public String toString() { - return String.format("%s:%d/%s", host, port, path); - } + @Override + public String toString() { + return String.format("%s:%d/%s", host, port, path); + } } diff --git a/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpLocationFactory.java b/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpLocationFactory.java index 8c229d39f..ee5d002e3 100644 --- a/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpLocationFactory.java +++ b/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpLocationFactory.java @@ -15,5 +15,5 @@ package org.eclipse.tractusx.edc.transferprocess.sftp.common; public interface SftpLocationFactory { - SftpLocation createSftpLocation(String sftpHost, Integer sftpPort, String sftpPath); + SftpLocation createSftpLocation(String sftpHost, Integer sftpPort, String sftpPath); } diff --git a/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpProvider.java b/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpProvider.java index 4ddd29396..c5d1f7608 100644 --- a/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpProvider.java +++ b/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpProvider.java @@ -15,11 +15,11 @@ package org.eclipse.tractusx.edc.transferprocess.sftp.common; public interface SftpProvider { - void createUser(SftpUser user); + void createUser(SftpUser user); - void deleteUser(SftpUser user); + void deleteUser(SftpUser user); - void createLocation(SftpLocation location); + void createLocation(SftpLocation location); - void deleteLocation(SftpLocation location); + void deleteLocation(SftpLocation location); } diff --git a/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpUser.java b/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpUser.java index b66dfc3e0..c6deda9a9 100644 --- a/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpUser.java +++ b/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpUser.java @@ -14,19 +14,21 @@ package org.eclipse.tractusx.edc.transferprocess.sftp.common; -import java.security.KeyPair; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NonNull; import lombok.ToString; +import java.security.KeyPair; + @Builder @Getter @ToString(of = "name") @EqualsAndHashCode public class SftpUser { - @NonNull private final String name; - private final String password; - private final KeyPair keyPair; + @NonNull + private final String name; + private final String password; + private final KeyPair keyPair; } diff --git a/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpUserFactory.java b/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpUserFactory.java index ea04a125e..53a399cf9 100644 --- a/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpUserFactory.java +++ b/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpUserFactory.java @@ -15,5 +15,5 @@ package org.eclipse.tractusx.edc.transferprocess.sftp.common; public interface SftpUserFactory { - SftpUser createSftpUser(String sftpUserName, String sftpUserPassword, byte[] sftpUserKeypair); + SftpUser createSftpUser(String sftpUserName, String sftpUserPassword, byte[] sftpUserKeypair); } diff --git a/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpUserKeyPairGenerator.java b/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpUserKeyPairGenerator.java index 55d2984ce..83cd7110e 100644 --- a/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpUserKeyPairGenerator.java +++ b/edc-extensions/transferprocess-sftp-common/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpUserKeyPairGenerator.java @@ -14,6 +14,9 @@ package org.eclipse.tractusx.edc.transferprocess.sftp.common; +import lombok.AllArgsConstructor; +import lombok.NonNull; + import java.security.KeyFactory; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; @@ -24,49 +27,47 @@ import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.RSAPublicKeySpec; import java.util.Base64; -import lombok.AllArgsConstructor; -import lombok.NonNull; @AllArgsConstructor public class SftpUserKeyPairGenerator { - public static KeyPair getKeyPairFromPrivateKey( - byte[] privateKeyBytes, @NonNull String sftpUserName) { - if (privateKeyBytes == null) { - return null; - } + public static KeyPair getKeyPairFromPrivateKey( + byte[] privateKeyBytes, @NonNull String sftpUserName) { + if (privateKeyBytes == null) { + return null; + } - try { - final KeyFactory keyFactory = KeyFactory.getInstance("RSA"); - final PrivateKey privateKey = - keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes)); + try { + final KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + final PrivateKey privateKey = + keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes)); - final RSAPrivateCrtKey privateKeySpec = (RSAPrivateCrtKey) privateKey; + final RSAPrivateCrtKey privateKeySpec = (RSAPrivateCrtKey) privateKey; - final PublicKey publicKey = - keyFactory.generatePublic( - new RSAPublicKeySpec( - privateKeySpec.getModulus(), privateKeySpec.getPublicExponent())); - return new KeyPair(publicKey, privateKey); + final PublicKey publicKey = + keyFactory.generatePublic( + new RSAPublicKeySpec( + privateKeySpec.getModulus(), privateKeySpec.getPublicExponent())); + return new KeyPair(publicKey, privateKey); - } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { - throw new EdcSftpException( - String.format("Unable to parse provided keypair for Sftp user %s", sftpUserName), e); + } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { + throw new EdcSftpException( + String.format("Unable to parse provided keypair for Sftp user %s", sftpUserName), e); + } } - } - public static KeyPair getKeyPairFromPrivateKey(String privateKey, @NonNull String sftpUserName) { - if (privateKey == null) { - return null; - } + public static KeyPair getKeyPairFromPrivateKey(String privateKey, @NonNull String sftpUserName) { + if (privateKey == null) { + return null; + } - byte[] publicBytes; - try { - publicBytes = Base64.getDecoder().decode(privateKey); - } catch (IllegalArgumentException e) { - throw new EdcSftpException( - String.format("Cannot decode base64 private key for user %s", sftpUserName), e); - } + byte[] publicBytes; + try { + publicBytes = Base64.getDecoder().decode(privateKey); + } catch (IllegalArgumentException e) { + throw new EdcSftpException( + String.format("Cannot decode base64 private key for user %s", sftpUserName), e); + } - return getKeyPairFromPrivateKey(publicBytes, sftpUserName); - } + return getKeyPairFromPrivateKey(publicBytes, sftpUserName); + } } diff --git a/edc-extensions/transferprocess-sftp-common/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpDataAddressTest.java b/edc-extensions/transferprocess-sftp-common/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpDataAddressTest.java index d29cdcd0e..bda97cd98 100644 --- a/edc-extensions/transferprocess-sftp-common/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpDataAddressTest.java +++ b/edc-extensions/transferprocess-sftp-common/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/common/SftpDataAddressTest.java @@ -14,198 +14,203 @@ package org.eclipse.tractusx.edc.transferprocess.sftp.common; +import lombok.SneakyThrows; +import org.eclipse.edc.spi.types.domain.DataAddress; +import org.junit.jupiter.api.Test; + import java.security.KeyPair; import java.security.KeyPairGenerator; import java.util.Base64; import java.util.Map; -import lombok.SneakyThrows; -import org.eclipse.edc.spi.types.domain.DataAddress; -import org.junit.jupiter.api.Assertions; -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.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; class SftpDataAddressTest { - @Test - void fromDataAddress__password() { - final Map properties = - Map.of( - "type", "sftp", - "locationHost", "localhost", - "locationPort", "22", - "locationPath", "path", - "userName", "name", - "userPassword", "password"); - - final DataAddress dataAddress = - DataAddress.Builder.newInstance().properties(properties).build(); - - final SftpDataAddress sftpDataAddress = SftpDataAddress.fromDataAddress(dataAddress); - - Assertions.assertEquals("localhost", sftpDataAddress.getSftpLocation().getHost()); - Assertions.assertEquals(22, sftpDataAddress.getSftpLocation().getPort()); - Assertions.assertEquals("path", sftpDataAddress.getSftpLocation().getPath()); - Assertions.assertEquals("name", sftpDataAddress.getSftpUser().getName()); - Assertions.assertEquals("password", sftpDataAddress.getSftpUser().getPassword()); - Assertions.assertNull(sftpDataAddress.getSftpUser().getKeyPair()); - } - - @Test - @SneakyThrows - void fromDataAddress__keyPair() { - final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); - keyPairGenerator.initialize(2048); - final KeyPair keyPair = keyPairGenerator.generateKeyPair(); - final byte[] privateKeyBytes = keyPair.getPrivate().getEncoded(); - - final Map properties = - Map.of( - "type", "sftp", - "locationHost", "localhost", - "locationPort", "22", - "locationPath", "path", - "userName", "name", - "userPrivateKey", Base64.getEncoder().encodeToString(privateKeyBytes)); - - final DataAddress dataAddress = - DataAddress.Builder.newInstance().properties(properties).build(); - - final SftpDataAddress sftpDataAddress = SftpDataAddress.fromDataAddress(dataAddress); - - Assertions.assertEquals("localhost", sftpDataAddress.getSftpLocation().getHost()); - Assertions.assertEquals(22, sftpDataAddress.getSftpLocation().getPort()); - Assertions.assertEquals("path", sftpDataAddress.getSftpLocation().getPath()); - Assertions.assertEquals("name", sftpDataAddress.getSftpUser().getName()); - Assertions.assertArrayEquals( - privateKeyBytes, sftpDataAddress.getSftpUser().getKeyPair().getPrivate().getEncoded()); - Assertions.assertNull(sftpDataAddress.getSftpUser().getPassword()); - } - - @Test - @SneakyThrows - void fromDataAddress__noAuth() { - final Map properties = - Map.of( - "type", "sftp", - "locationHost", "localhost", - "locationPort", "22", - "locationPath", "path", - "userName", "name"); - - final DataAddress dataAddress = - DataAddress.Builder.newInstance().properties(properties).build(); - - final SftpDataAddress sftpDataAddress = SftpDataAddress.fromDataAddress(dataAddress); - - Assertions.assertEquals("localhost", sftpDataAddress.getSftpLocation().getHost()); - Assertions.assertEquals(22, sftpDataAddress.getSftpLocation().getPort()); - Assertions.assertEquals("path", sftpDataAddress.getSftpLocation().getPath()); - Assertions.assertEquals("name", sftpDataAddress.getSftpUser().getName()); - Assertions.assertNull(sftpDataAddress.getSftpUser().getPassword()); - } - - @Test - @SneakyThrows - void fromDataAddress__invalidKeyPairBrokenBase64() { - final Map properties = - Map.of( - "type", "sftp", - "locationHost", "localhost", - "locationPort", "22", - "locationPath", "path", - "userName", "name", - "userPrivateKey", "clearlyNotAPrivateKey"); - - final DataAddress dataAddress = - DataAddress.Builder.newInstance().properties(properties).build(); - - EdcSftpException edcSftpException = - Assertions.assertThrows( - EdcSftpException.class, () -> SftpDataAddress.fromDataAddress(dataAddress)); - Assertions.assertEquals( - "Cannot decode base64 private key for user name", edcSftpException.getMessage()); - } - - @Test - @SneakyThrows - void fromDataAddress__invalidKeyPairButCorrectBase64() { - final Map properties = - Map.of( - "type", "sftp", - "locationHost", "localhost", - "locationPort", "22", - "locationPath", "path", - "userName", "name", - "userPrivateKey", "TWFueSBoYW5kcyBtYWtlIGxpZ2h0IHdvcmsu"); - - final DataAddress dataAddress = - DataAddress.Builder.newInstance().properties(properties).build(); - - EdcSftpException edcSftpException = - Assertions.assertThrows( - EdcSftpException.class, () -> SftpDataAddress.fromDataAddress(dataAddress)); - Assertions.assertEquals( - "Unable to parse provided keypair for Sftp user name", edcSftpException.getMessage()); - } - - @Test - void fromDataAddress__portNaN() { - final Map properties = - Map.of( - "type", "sftp", - "locationHost", "localhost", - "locationPort", "notANumber", - "locationPath", "path", - "userName", "name", - "userPassword", "password"); - - final DataAddress dataAddress = - DataAddress.Builder.newInstance().properties(properties).build(); - - EdcSftpException edcSftpException = - Assertions.assertThrows( - EdcSftpException.class, () -> SftpDataAddress.fromDataAddress(dataAddress)); - Assertions.assertEquals( - "Port for SftpLocation localhost/path not a number", edcSftpException.getMessage()); - } - - @Test - void fromDataAddress__missingParameter() { - final Map properties = - Map.of( - "type", "sftp", - "locationPort", "22", - "locationPath", "path", - "userName", "name", - "userPassword", "password"); - - final DataAddress dataAddress = - DataAddress.Builder.newInstance().properties(properties).build(); - - EdcSftpException edcSftpException = - Assertions.assertThrows( - EdcSftpException.class, () -> SftpDataAddress.fromDataAddress(dataAddress)); - Assertions.assertEquals("host is marked non-null but is null", edcSftpException.getMessage()); - } - - @Test - void fromDataAddress__notSftp() { - final Map properties = - Map.of( - "type", "somethingOtherThanSftp", - "locationHost", "localhost", - "locationPort", "22", - "locationPath", "path", - "userName", "name", - "userPassword", "password"); - - final DataAddress dataAddress = - DataAddress.Builder.newInstance().properties(properties).build(); - - EdcSftpException edcSftpException = - Assertions.assertThrows( - EdcSftpException.class, () -> SftpDataAddress.fromDataAddress(dataAddress)); - Assertions.assertEquals( - "Invalid DataAddress type: somethingOtherThanSftp. Expected sftp.", - edcSftpException.getMessage()); - } + @Test + void fromDataAddress_password() { + final Map properties = + Map.of( + "type", "sftp", + "locationHost", "localhost", + "locationPort", "22", + "locationPath", "path", + "userName", "name", + "userPassword", "password"); + + final DataAddress dataAddress = + DataAddress.Builder.newInstance().properties(properties).build(); + + final SftpDataAddress sftpDataAddress = SftpDataAddress.fromDataAddress(dataAddress); + + assertEquals("localhost", sftpDataAddress.getSftpLocation().getHost()); + assertEquals(22, sftpDataAddress.getSftpLocation().getPort()); + assertEquals("path", sftpDataAddress.getSftpLocation().getPath()); + assertEquals("name", sftpDataAddress.getSftpUser().getName()); + assertEquals("password", sftpDataAddress.getSftpUser().getPassword()); + assertNull(sftpDataAddress.getSftpUser().getKeyPair()); + } + + @Test + @SneakyThrows + void fromDataAddress_keyPair() { + final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); + keyPairGenerator.initialize(2048); + final KeyPair keyPair = keyPairGenerator.generateKeyPair(); + final byte[] privateKeyBytes = keyPair.getPrivate().getEncoded(); + + final Map properties = + Map.of( + "type", "sftp", + "locationHost", "localhost", + "locationPort", "22", + "locationPath", "path", + "userName", "name", + "userPrivateKey", Base64.getEncoder().encodeToString(privateKeyBytes)); + + final DataAddress dataAddress = + DataAddress.Builder.newInstance().properties(properties).build(); + + final SftpDataAddress sftpDataAddress = SftpDataAddress.fromDataAddress(dataAddress); + + assertEquals("localhost", sftpDataAddress.getSftpLocation().getHost()); + assertEquals(22, sftpDataAddress.getSftpLocation().getPort()); + assertEquals("path", sftpDataAddress.getSftpLocation().getPath()); + assertEquals("name", sftpDataAddress.getSftpUser().getName()); + assertArrayEquals( + privateKeyBytes, sftpDataAddress.getSftpUser().getKeyPair().getPrivate().getEncoded()); + assertNull(sftpDataAddress.getSftpUser().getPassword()); + } + + @Test + @SneakyThrows + void fromDataAddress_noAuth() { + final Map properties = + Map.of( + "type", "sftp", + "locationHost", "localhost", + "locationPort", "22", + "locationPath", "path", + "userName", "name"); + + final DataAddress dataAddress = + DataAddress.Builder.newInstance().properties(properties).build(); + + final SftpDataAddress sftpDataAddress = SftpDataAddress.fromDataAddress(dataAddress); + + assertEquals("localhost", sftpDataAddress.getSftpLocation().getHost()); + assertEquals(22, sftpDataAddress.getSftpLocation().getPort()); + assertEquals("path", sftpDataAddress.getSftpLocation().getPath()); + assertEquals("name", sftpDataAddress.getSftpUser().getName()); + assertNull(sftpDataAddress.getSftpUser().getPassword()); + } + + @Test + @SneakyThrows + void fromDataAddress_invalidKeyPairBrokenBase64() { + final Map properties = + Map.of( + "type", "sftp", + "locationHost", "localhost", + "locationPort", "22", + "locationPath", "path", + "userName", "name", + "userPrivateKey", "clearlyNotAPrivateKey"); + + final DataAddress dataAddress = + DataAddress.Builder.newInstance().properties(properties).build(); + + EdcSftpException edcSftpException = + assertThrows( + EdcSftpException.class, () -> SftpDataAddress.fromDataAddress(dataAddress)); + assertEquals( + "Cannot decode base64 private key for user name", edcSftpException.getMessage()); + } + + @Test + @SneakyThrows + void fromDataAddress_invalidKeyPairButCorrectBase64() { + final Map properties = + Map.of( + "type", "sftp", + "locationHost", "localhost", + "locationPort", "22", + "locationPath", "path", + "userName", "name", + "userPrivateKey", "TWFueSBoYW5kcyBtYWtlIGxpZ2h0IHdvcmsu"); + + final DataAddress dataAddress = + DataAddress.Builder.newInstance().properties(properties).build(); + + EdcSftpException edcSftpException = + assertThrows( + EdcSftpException.class, () -> SftpDataAddress.fromDataAddress(dataAddress)); + assertEquals( + "Unable to parse provided keypair for Sftp user name", edcSftpException.getMessage()); + } + + @Test + void fromDataAddress_portNaN() { + final Map properties = + Map.of( + "type", "sftp", + "locationHost", "localhost", + "locationPort", "notANumber", + "locationPath", "path", + "userName", "name", + "userPassword", "password"); + + final DataAddress dataAddress = + DataAddress.Builder.newInstance().properties(properties).build(); + + EdcSftpException edcSftpException = + assertThrows( + EdcSftpException.class, () -> SftpDataAddress.fromDataAddress(dataAddress)); + assertEquals( + "Port for SftpLocation localhost/path not a number", edcSftpException.getMessage()); + } + + @Test + void fromDataAddress_missingParameter() { + final Map properties = + Map.of( + "type", "sftp", + "locationPort", "22", + "locationPath", "path", + "userName", "name", + "userPassword", "password"); + + final DataAddress dataAddress = + DataAddress.Builder.newInstance().properties(properties).build(); + + EdcSftpException edcSftpException = + assertThrows( + EdcSftpException.class, () -> SftpDataAddress.fromDataAddress(dataAddress)); + assertEquals("host is marked non-null but is null", edcSftpException.getMessage()); + } + + @Test + void fromDataAddress_notSftp() { + final Map properties = + Map.of( + "type", "somethingOtherThanSftp", + "locationHost", "localhost", + "locationPort", "22", + "locationPath", "path", + "userName", "name", + "userPassword", "password"); + + final DataAddress dataAddress = + DataAddress.Builder.newInstance().properties(properties).build(); + + EdcSftpException edcSftpException = + assertThrows( + EdcSftpException.class, () -> SftpDataAddress.fromDataAddress(dataAddress)); + assertEquals( + "Invalid DataAddress type: somethingOtherThanSftp. Expected sftp.", + edcSftpException.getMessage()); + } } diff --git a/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/NoOpSftpProvider.java b/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/NoOpSftpProvider.java index d12015d7d..daacc9927 100644 --- a/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/NoOpSftpProvider.java +++ b/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/NoOpSftpProvider.java @@ -20,47 +20,47 @@ public class NoOpSftpProvider implements SftpProvider { - /** - * This provisioner does not create cloud resources. The assumption is that users and locations - * already exist cloud-side. Thus, this method has no functionality. - * - * @param user The user whose credentials should be deployed. - */ - @Override - public void createUser(SftpUser user) { - // do nothing - } + /** + * This provisioner does not create cloud resources. The assumption is that users and locations + * already exist cloud-side. Thus, this method has no functionality. + * + * @param user The user whose credentials should be deployed. + */ + @Override + public void createUser(SftpUser user) { + // do nothing + } - /** - * This provisioner does not create cloud resources. The assumption is that users and locations - * already exist cloud-side. Thus, this method has no functionality. - * - * @param user The user whose credentials should be deleted. - */ - @Override - public void deleteUser(SftpUser user) { - // do nothing - } + /** + * This provisioner does not create cloud resources. The assumption is that users and locations + * already exist cloud-side. Thus, this method has no functionality. + * + * @param user The user whose credentials should be deleted. + */ + @Override + public void deleteUser(SftpUser user) { + // do nothing + } - /** - * This provisioner does not create cloud resources. The assumption is that users and locations - * already exist cloud-side. Thus, this method has no functionality. - * - * @param location The location of the cloud resource that should be made available. - */ - @Override - public void createLocation(SftpLocation location) { - // do nothing - } + /** + * This provisioner does not create cloud resources. The assumption is that users and locations + * already exist cloud-side. Thus, this method has no functionality. + * + * @param location The location of the cloud resource that should be made available. + */ + @Override + public void createLocation(SftpLocation location) { + // do nothing + } - /** - * This provisioner does not create cloud resources. The assumption is that users and locations - * already exist cloud-side. Thus, this method has no functionality. - * - * @param location The location of the cloud resource that should be made unavailable. - */ - @Override - public void deleteLocation(SftpLocation location) { - // do nothing - } + /** + * This provisioner does not create cloud resources. The assumption is that users and locations + * already exist cloud-side. Thus, this method has no functionality. + * + * @param location The location of the cloud resource that should be made unavailable. + */ + @Override + public void deleteLocation(SftpLocation location) { + // do nothing + } } diff --git a/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/NoOpSftpProvisioner.java b/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/NoOpSftpProvisioner.java index 978f4bc94..1a60f9d5d 100644 --- a/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/NoOpSftpProvisioner.java +++ b/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/NoOpSftpProvisioner.java @@ -14,7 +14,6 @@ package org.eclipse.tractusx.edc.transferprocess.sftp.provisioner; -import java.util.concurrent.CompletableFuture; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.eclipse.edc.connector.transfer.spi.provision.Provisioner; @@ -31,120 +30,125 @@ import org.eclipse.tractusx.edc.transferprocess.sftp.common.SftpLocation; import org.eclipse.tractusx.edc.transferprocess.sftp.common.SftpUser; +import java.util.concurrent.CompletableFuture; + @RequiredArgsConstructor public class NoOpSftpProvisioner - implements Provisioner { - static final String DATA_ADDRESS_TYPE = "sftp"; - static final String PROVIDER_TYPE = "NoOp"; - - @NonNull private final String policyScope; - @NonNull private final PolicyEngine policyEngine; - @NonNull private final NoOpSftpProvider sftpProvider; - - @Override - public boolean canProvision(@NonNull ResourceDefinition resourceDefinition) { - if (!(resourceDefinition instanceof SftpProviderResourceDefinition)) { - return false; + implements Provisioner { + static final String DATA_ADDRESS_TYPE = "sftp"; + static final String PROVIDER_TYPE = "NoOp"; + + @NonNull + private final String policyScope; + @NonNull + private final PolicyEngine policyEngine; + @NonNull + private final NoOpSftpProvider sftpProvider; + + @Override + public boolean canProvision(@NonNull ResourceDefinition resourceDefinition) { + if (!(resourceDefinition instanceof SftpProviderResourceDefinition)) { + return false; + } + if (!(((SftpProviderResourceDefinition) resourceDefinition) + .getProviderType() + .equals(PROVIDER_TYPE))) { + return false; + } + try { + SftpDataAddress.fromDataAddress( + ((SftpProviderResourceDefinition) resourceDefinition).getSftpDataAddress()); + } catch (EdcSftpException e) { + return false; + } + return true; } - if (!(((SftpProviderResourceDefinition) resourceDefinition) - .getProviderType() - .equals(PROVIDER_TYPE))) { - return false; - } - try { - SftpDataAddress.fromDataAddress( - ((SftpProviderResourceDefinition) resourceDefinition).getSftpDataAddress()); - } catch (EdcSftpException e) { - return false; + + @Override + public boolean canDeprovision(@NonNull ProvisionedResource provisionedResource) { + if (!(provisionedResource instanceof SftpProvisionedContentResource)) { + return false; + } + + if (!(((SftpProvisionedContentResource) provisionedResource) + .getProviderType() + .equals(PROVIDER_TYPE))) { + return false; + } + + try { + SftpDataAddress.fromDataAddress( + ((SftpProvisionedContentResource) provisionedResource).getSftpDataAddress()); + } catch (EdcSftpException e) { + return false; + } + return true; } - return true; - } - @Override - public boolean canDeprovision(@NonNull ProvisionedResource provisionedResource) { - if (!(provisionedResource instanceof SftpProvisionedContentResource)) { - return false; + @Override + public CompletableFuture> provision( + SftpProviderResourceDefinition sftpProviderResourceDefinition, Policy policy) { + + return CompletableFuture.supplyAsync( + () -> { + if (!this.canProvision(sftpProviderResourceDefinition)) { + return StatusResult.failure(ResponseStatus.FATAL_ERROR); + } + // As of the time of writing, policies don't actually do anything in this context. + // They are included here in case EDC wants to use them eventually. + Policy scopedPolicy; + scopedPolicy = policyEngine.filter(policy, policyScope); + sftpProvider.createLocation( + sftpProviderResourceDefinition.getSftpDataAddress().getSftpLocation()); + sftpProvider.createUser( + sftpProviderResourceDefinition.getSftpDataAddress().getSftpUser()); + + SftpProvisionedContentResource sftpProvisionedContentResource = + SftpProvisionedContentResource.builder() + .sftpDataAddress(sftpProviderResourceDefinition.getSftpDataAddress()) + .providerType(PROVIDER_TYPE) + .scopedPolicy(scopedPolicy) + .provisionedResourceId( + generateResourceId( + sftpProviderResourceDefinition.getSftpDataAddress().getSftpUser(), + sftpProviderResourceDefinition.getSftpDataAddress().getSftpLocation())) + .build(); + + return StatusResult.success( + ProvisionResponse.Builder.newInstance() + .resource(sftpProvisionedContentResource) + .build()); + }); } - if (!(((SftpProvisionedContentResource) provisionedResource) - .getProviderType() - .equals(PROVIDER_TYPE))) { - return false; + @Override + public CompletableFuture> deprovision( + SftpProvisionedContentResource sftpProvisionedContentResource, Policy policy) { + return CompletableFuture.supplyAsync( + () -> { + if (!this.canDeprovision(sftpProvisionedContentResource)) { + return StatusResult.failure(ResponseStatus.FATAL_ERROR); + } + // As of the time of writing, policies don't actually do anything in this context. + // They are included here in case EDC wants to use them eventually. + sftpProvider.deleteLocation( + sftpProvisionedContentResource.getSftpDataAddress().getSftpLocation()); + sftpProvider.deleteUser( + sftpProvisionedContentResource.getSftpDataAddress().getSftpUser()); + + DeprovisionedResource deprovisionedResource = + DeprovisionedResource.Builder.newInstance() + .provisionedResourceId(sftpProvisionedContentResource.getProvisionedResourceId()) + .inProcess(true) + .build(); + + return StatusResult.success(deprovisionedResource); + }); } - try { - SftpDataAddress.fromDataAddress( - ((SftpProvisionedContentResource) provisionedResource).getSftpDataAddress()); - } catch (EdcSftpException e) { - return false; + private String generateResourceId(SftpUser sftpUser, SftpLocation sftpLocation) { + return String.format( + "%s@%s:%d/%s", + sftpUser.getName(), sftpLocation.getHost(), sftpLocation.getPort(), sftpLocation.getPath()); } - return true; - } - - @Override - public CompletableFuture> provision( - SftpProviderResourceDefinition sftpProviderResourceDefinition, Policy policy) { - - return CompletableFuture.supplyAsync( - () -> { - if (!this.canProvision(sftpProviderResourceDefinition)) { - return StatusResult.failure(ResponseStatus.FATAL_ERROR); - } - // As of the time of writing, policies don't actually do anything in this context. - // They are included here in case EDC wants to use them eventually. - Policy scopedPolicy; - scopedPolicy = policyEngine.filter(policy, policyScope); - sftpProvider.createLocation( - sftpProviderResourceDefinition.getSftpDataAddress().getSftpLocation()); - sftpProvider.createUser( - sftpProviderResourceDefinition.getSftpDataAddress().getSftpUser()); - - SftpProvisionedContentResource sftpProvisionedContentResource = - SftpProvisionedContentResource.builder() - .sftpDataAddress(sftpProviderResourceDefinition.getSftpDataAddress()) - .providerType(PROVIDER_TYPE) - .scopedPolicy(scopedPolicy) - .provisionedResourceId( - generateResourceId( - sftpProviderResourceDefinition.getSftpDataAddress().getSftpUser(), - sftpProviderResourceDefinition.getSftpDataAddress().getSftpLocation())) - .build(); - - return StatusResult.success( - ProvisionResponse.Builder.newInstance() - .resource(sftpProvisionedContentResource) - .build()); - }); - } - - @Override - public CompletableFuture> deprovision( - SftpProvisionedContentResource sftpProvisionedContentResource, Policy policy) { - return CompletableFuture.supplyAsync( - () -> { - if (!this.canDeprovision(sftpProvisionedContentResource)) { - return StatusResult.failure(ResponseStatus.FATAL_ERROR); - } - // As of the time of writing, policies don't actually do anything in this context. - // They are included here in case EDC wants to use them eventually. - sftpProvider.deleteLocation( - sftpProvisionedContentResource.getSftpDataAddress().getSftpLocation()); - sftpProvider.deleteUser( - sftpProvisionedContentResource.getSftpDataAddress().getSftpUser()); - - DeprovisionedResource deprovisionedResource = - DeprovisionedResource.Builder.newInstance() - .provisionedResourceId(sftpProvisionedContentResource.getProvisionedResourceId()) - .inProcess(true) - .build(); - - return StatusResult.success(deprovisionedResource); - }); - } - - private String generateResourceId(SftpUser sftpUser, SftpLocation sftpLocation) { - return String.format( - "%s@%s:%d/%s", - sftpUser.getName(), sftpLocation.getHost(), sftpLocation.getPort(), sftpLocation.getPath()); - } } diff --git a/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpLocationFactoryImpl.java b/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpLocationFactoryImpl.java index 413c98335..a2206eb8b 100644 --- a/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpLocationFactoryImpl.java +++ b/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpLocationFactoryImpl.java @@ -20,8 +20,8 @@ @RequiredArgsConstructor public class SftpLocationFactoryImpl implements SftpLocationFactory { - @Override - public SftpLocation createSftpLocation(String sftpHost, Integer sftpPort, String sftpPath) { - return SftpLocation.builder().host(sftpHost).port(sftpPort).path(sftpPath).build(); - } + @Override + public SftpLocation createSftpLocation(String sftpHost, Integer sftpPort, String sftpPath) { + return SftpLocation.builder().host(sftpHost).port(sftpPort).path(sftpPath).build(); + } } diff --git a/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProviderResourceDefinition.java b/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProviderResourceDefinition.java index a15c97cca..4b45eafb3 100644 --- a/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProviderResourceDefinition.java +++ b/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProviderResourceDefinition.java @@ -23,11 +23,13 @@ @Getter @RequiredArgsConstructor public class SftpProviderResourceDefinition extends ResourceDefinition { - @NonNull private String providerType; - @NonNull private SftpDataAddress sftpDataAddress; + @NonNull + private String providerType; + @NonNull + private SftpDataAddress sftpDataAddress; - @Override - public > B toBuilder() { - return null; - } + @Override + public > B toBuilder() { + return null; + } } diff --git a/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProviderResourceDefinitionGenerator.java b/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProviderResourceDefinitionGenerator.java index ed9c137e5..93b1515a8 100644 --- a/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProviderResourceDefinitionGenerator.java +++ b/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProviderResourceDefinitionGenerator.java @@ -14,8 +14,6 @@ package org.eclipse.tractusx.edc.transferprocess.sftp.provisioner; -import static org.eclipse.tractusx.edc.transferprocess.sftp.provisioner.NoOpSftpProvisioner.PROVIDER_TYPE; - import lombok.RequiredArgsConstructor; import org.eclipse.edc.connector.transfer.spi.provision.ProviderResourceDefinitionGenerator; import org.eclipse.edc.connector.transfer.spi.types.DataRequest; @@ -26,29 +24,31 @@ import org.eclipse.tractusx.edc.transferprocess.sftp.common.SftpDataAddress; import org.jetbrains.annotations.Nullable; +import static org.eclipse.tractusx.edc.transferprocess.sftp.provisioner.NoOpSftpProvisioner.PROVIDER_TYPE; + @RequiredArgsConstructor public class SftpProviderResourceDefinitionGenerator - implements ProviderResourceDefinitionGenerator { + implements ProviderResourceDefinitionGenerator { - @Override - public @Nullable ResourceDefinition generate( - DataRequest dataRequest, DataAddress assetAddress, Policy policy) { - SftpDataAddress sftpDataAddress; - try { - sftpDataAddress = SftpDataAddress.fromDataAddress(assetAddress); - } catch (EdcSftpException e) { - return null; + @Override + public @Nullable ResourceDefinition generate( + DataRequest dataRequest, DataAddress assetAddress, Policy policy) { + SftpDataAddress sftpDataAddress; + try { + sftpDataAddress = SftpDataAddress.fromDataAddress(assetAddress); + } catch (EdcSftpException e) { + return null; + } + return new SftpProviderResourceDefinition(PROVIDER_TYPE, sftpDataAddress); } - return new SftpProviderResourceDefinition(PROVIDER_TYPE, sftpDataAddress); - } - @Override - public boolean canGenerate(DataRequest dataRequest, DataAddress dataAddress, Policy policy) { - try { - SftpDataAddress.fromDataAddress(dataAddress); - } catch (EdcSftpException e) { - return false; + @Override + public boolean canGenerate(DataRequest dataRequest, DataAddress dataAddress, Policy policy) { + try { + SftpDataAddress.fromDataAddress(dataAddress); + } catch (EdcSftpException e) { + return false; + } + return true; } - return true; - } } diff --git a/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProvisionedContentResource.java b/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProvisionedContentResource.java index 5f7f364ab..fa39510a3 100644 --- a/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProvisionedContentResource.java +++ b/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProvisionedContentResource.java @@ -25,8 +25,12 @@ @RequiredArgsConstructor @Builder public class SftpProvisionedContentResource extends ProvisionedContentResource { - @NonNull private String providerType; - @NonNull private Policy scopedPolicy; - @NonNull private SftpDataAddress sftpDataAddress; - @NonNull private String provisionedResourceId; + @NonNull + private String providerType; + @NonNull + private Policy scopedPolicy; + @NonNull + private SftpDataAddress sftpDataAddress; + @NonNull + private String provisionedResourceId; } diff --git a/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProvisionerConfiguration.java b/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProvisionerConfiguration.java index acf67ac29..8a58b785a 100644 --- a/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProvisionerConfiguration.java +++ b/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProvisionerConfiguration.java @@ -15,27 +15,35 @@ package org.eclipse.tractusx.edc.transferprocess.sftp.provisioner; -import java.net.URL; import lombok.Builder; import lombok.Getter; import lombok.NonNull; -/** Configuration to create a resource definition and provisioner pair for sftp data transfer. */ +import java.net.URL; + +/** + * Configuration to create a resource definition and provisioner pair for sftp data transfer. + */ @Getter @Builder public class SftpProvisionerConfiguration { - @NonNull private final String name; + @NonNull + private final String name; - @NonNull @Builder.Default - private final ProvisionerType provisionerType = ProvisionerType.PROVIDER; + @NonNull + @Builder.Default + private final ProvisionerType provisionerType = ProvisionerType.PROVIDER; - @NonNull private final String dataAddressType; - @NonNull private final String policyScope; - @NonNull private final URL endpoint; + @NonNull + private final String dataAddressType; + @NonNull + private final String policyScope; + @NonNull + private final URL endpoint; - public enum ProvisionerType { - CONSUMER, - PROVIDER - } + public enum ProvisionerType { + CONSUMER, + PROVIDER + } } diff --git a/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProvisionerExtension.java b/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProvisionerExtension.java index eb3e3f80f..fe1dcb801 100644 --- a/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProvisionerExtension.java +++ b/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProvisionerExtension.java @@ -26,31 +26,33 @@ @Provides(NoOpSftpProvisioner.class) public class SftpProvisionerExtension implements ServiceExtension { - @Inject ProvisionManager provisionManager; - @Inject Monitor monitor; - @Inject PolicyEngine policyEngine; - - private static final String POLICY_SCOPE_CONFIG_PATH = "provisioner.sftp.policy.scope"; - private static final String DEFAULT_POLICY_SCOPE = "sftp.provisioner"; - - @Override - public String name() { - return "Sftp Provisioner"; - } - - @Override - public void initialize(ServiceExtensionContext context) { - final String policyScope = - context.getConfig().getString(POLICY_SCOPE_CONFIG_PATH, DEFAULT_POLICY_SCOPE); - - final NoOpSftpProvider sftpProvider = new NoOpSftpProvider(); - final NoOpSftpProvisioner noOpSftpProvisioner = - new NoOpSftpProvisioner(policyScope, policyEngine, sftpProvider); - final SftpProviderResourceDefinitionGenerator generator = - new SftpProviderResourceDefinitionGenerator(); - provisionManager.register(noOpSftpProvisioner); - context.registerService(ProviderResourceDefinitionGenerator.class, generator); - - monitor.info("SftpProvisionerExtension: authentication/initialization complete."); - } + private static final String POLICY_SCOPE_CONFIG_PATH = "provisioner.sftp.policy.scope"; + private static final String DEFAULT_POLICY_SCOPE = "sftp.provisioner"; + @Inject + ProvisionManager provisionManager; + @Inject + Monitor monitor; + @Inject + PolicyEngine policyEngine; + + @Override + public String name() { + return "Sftp Provisioner"; + } + + @Override + public void initialize(ServiceExtensionContext context) { + final String policyScope = + context.getConfig().getString(POLICY_SCOPE_CONFIG_PATH, DEFAULT_POLICY_SCOPE); + + final NoOpSftpProvider sftpProvider = new NoOpSftpProvider(); + final NoOpSftpProvisioner noOpSftpProvisioner = + new NoOpSftpProvisioner(policyScope, policyEngine, sftpProvider); + final SftpProviderResourceDefinitionGenerator generator = + new SftpProviderResourceDefinitionGenerator(); + provisionManager.register(noOpSftpProvisioner); + context.registerService(ProviderResourceDefinitionGenerator.class, generator); + + monitor.info("SftpProvisionerExtension: authentication/initialization complete."); + } } diff --git a/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpUserFactoryImpl.java b/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpUserFactoryImpl.java index 2bb921fdf..797ad7bb0 100644 --- a/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpUserFactoryImpl.java +++ b/edc-extensions/transferprocess-sftp-provisioner/src/main/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpUserFactoryImpl.java @@ -14,25 +14,26 @@ package org.eclipse.tractusx.edc.transferprocess.sftp.provisioner; -import java.security.KeyPair; import lombok.Builder; import org.eclipse.tractusx.edc.transferprocess.sftp.common.SftpUser; import org.eclipse.tractusx.edc.transferprocess.sftp.common.SftpUserFactory; import org.eclipse.tractusx.edc.transferprocess.sftp.common.SftpUserKeyPairGenerator; +import java.security.KeyPair; + @Builder public class SftpUserFactoryImpl implements SftpUserFactory { - @Override - public SftpUser createSftpUser( - String sftpUserName, String sftpUserPassword, byte[] sftpUserPrivateKey) { - KeyPair sftpUserKeyPair = - SftpUserKeyPairGenerator.getKeyPairFromPrivateKey(sftpUserPrivateKey, sftpUserName); + @Override + public SftpUser createSftpUser( + String sftpUserName, String sftpUserPassword, byte[] sftpUserPrivateKey) { + KeyPair sftpUserKeyPair = + SftpUserKeyPairGenerator.getKeyPairFromPrivateKey(sftpUserPrivateKey, sftpUserName); - return SftpUser.builder() - .name(sftpUserName) - .password(sftpUserPassword) - .keyPair(sftpUserKeyPair) - .build(); - } + return SftpUser.builder() + .name(sftpUserName) + .password(sftpUserPassword) + .keyPair(sftpUserKeyPair) + .build(); + } } diff --git a/edc-extensions/transferprocess-sftp-provisioner/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/NoOpSftpProvisionerTest.java b/edc-extensions/transferprocess-sftp-provisioner/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/NoOpSftpProvisionerTest.java index c5657191f..8f36ee170 100644 --- a/edc-extensions/transferprocess-sftp-provisioner/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/NoOpSftpProvisionerTest.java +++ b/edc-extensions/transferprocess-sftp-provisioner/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/NoOpSftpProvisionerTest.java @@ -20,7 +20,6 @@ package org.eclipse.tractusx.edc.transferprocess.sftp.provisioner; -import java.util.concurrent.CompletableFuture; import lombok.NoArgsConstructor; import lombok.SneakyThrows; import org.eclipse.edc.connector.transfer.spi.types.DeprovisionedResource; @@ -37,170 +36,173 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import java.util.concurrent.CompletableFuture; + class NoOpSftpProvisionerTest { - private final String policyScope = "scope"; - private final PolicyEngine policyEngine = Mockito.mock(PolicyEngine.class); - private final NoOpSftpProvider sftpProvider = new NoOpSftpProvider(); - - private final NoOpSftpProvisioner provisioner = - new NoOpSftpProvisioner(policyScope, policyEngine, sftpProvider); - - @Test - void canProvision__true() { - String provisionType = "NoOp"; - SftpUser sftpUser = SftpUser.builder().name("name").password("password").build(); - SftpLocation sftpLocation = SftpLocation.builder().host("host").port(22).path("path").build(); - SftpDataAddress dataAddress = new SftpDataAddress(sftpUser, sftpLocation); - SftpProviderResourceDefinition resourceDefinition = - new SftpProviderResourceDefinition(provisionType, dataAddress); - - Assertions.assertTrue(provisioner.canProvision(resourceDefinition)); - } - - @Test - void canProvision__falseProvisionType() { - String provisionType = "AmazonS3"; - SftpUser sftpUser = SftpUser.builder().name("name").password("password").build(); - SftpLocation sftpLocation = SftpLocation.builder().host("host").port(22).path("path").build(); - SftpDataAddress dataAddress = new SftpDataAddress(sftpUser, sftpLocation); - SftpProviderResourceDefinition resourceDefinition = - new SftpProviderResourceDefinition(provisionType, dataAddress); - - Assertions.assertFalse(provisioner.canProvision(resourceDefinition)); - } - - @Test - void canProvision__falseDefinitionType() { - ResourceDefinition resourceDefinition = new WrongResourceDefinition(); - - Assertions.assertFalse(provisioner.canProvision(resourceDefinition)); - } - - @Test - void canDeprovision__true() { - String provisionType = "NoOp"; - SftpUser sftpUser = SftpUser.builder().name("name").password("password").build(); - SftpLocation sftpLocation = SftpLocation.builder().host("host").port(22).path("path").build(); - Policy scopedPolicy = Mockito.mock(Policy.class); - SftpDataAddress dataAddress = new SftpDataAddress(sftpUser, sftpLocation); - String provisionedResourceID = "resource"; - SftpProvisionedContentResource provisionedContentResource = - new SftpProvisionedContentResource( - provisionType, scopedPolicy, dataAddress, provisionedResourceID); - - Assertions.assertTrue(provisioner.canDeprovision(provisionedContentResource)); - } - - @Test - void canDeprovision__falseProvisionType() { - String provisionType = "AmazonS3"; - SftpUser sftpUser = SftpUser.builder().name("name").password("password").build(); - SftpLocation sftpLocation = SftpLocation.builder().host("host").port(22).path("path").build(); - Policy scopedPolicy = Mockito.mock(Policy.class); - SftpDataAddress dataAddress = new SftpDataAddress(sftpUser, sftpLocation); - String provisionedResourceID = "resource"; - SftpProvisionedContentResource provisionedContentResource = - new SftpProvisionedContentResource( - provisionType, scopedPolicy, dataAddress, provisionedResourceID); - - Assertions.assertFalse(provisioner.canDeprovision(provisionedContentResource)); - } - - @Test - void canDeprovision__falseDefinitionType() { - ProvisionedContentResource provisionedContentResource = new WrongProvisionedContentResource(); - - Assertions.assertFalse(provisioner.canDeprovision(provisionedContentResource)); - } - - @Test - @SneakyThrows - void provision__successful() { - String provisionType = "NoOp"; - SftpUser sftpUser = SftpUser.builder().name("name").password("password").build(); - SftpLocation sftpLocation = SftpLocation.builder().host("host").port(22).path("path").build(); - SftpDataAddress dataAddress = new SftpDataAddress(sftpUser, sftpLocation); - SftpProviderResourceDefinition resourceDefinition = - new SftpProviderResourceDefinition(provisionType, dataAddress); - Policy policy = Mockito.mock(Policy.class); - - Mockito.when(policyEngine.filter(policy, policyScope)).thenReturn(policy); - - CompletableFuture> future = - provisioner.provision(resourceDefinition, policy); - StatusResult result = future.get(); - - Assertions.assertTrue(result.succeeded()); - } - - @Test - @SneakyThrows - void provision__failedWrongProvisionType() { - String provisionType = "AmazonS3"; - SftpUser sftpUser = SftpUser.builder().name("name").password("password").build(); - SftpLocation sftpLocation = SftpLocation.builder().host("host").port(22).path("path").build(); - SftpDataAddress dataAddress = new SftpDataAddress(sftpUser, sftpLocation); - SftpProviderResourceDefinition resourceDefinition = - new SftpProviderResourceDefinition(provisionType, dataAddress); - Policy policy = Mockito.mock(Policy.class); - - Mockito.when(policyEngine.filter(policy, policyScope)).thenReturn(policy); - - CompletableFuture> future = - provisioner.provision(resourceDefinition, policy); - StatusResult result = future.get(); - - Assertions.assertTrue(result.failed()); - } - - @Test - @SneakyThrows - void deprovision__successful() { - String provisionType = "NoOp"; - SftpUser sftpUser = SftpUser.builder().name("name").password("password").build(); - SftpLocation sftpLocation = SftpLocation.builder().host("host").port(22).path("path").build(); - SftpDataAddress dataAddress = new SftpDataAddress(sftpUser, sftpLocation); - Policy policy = Mockito.mock(Policy.class); - String provisionedResourceID = "resource"; - SftpProvisionedContentResource provisionedContentResource = - new SftpProvisionedContentResource( - provisionType, policy, dataAddress, provisionedResourceID); - - CompletableFuture> future = - provisioner.deprovision(provisionedContentResource, policy); - StatusResult result = future.get(); - - Assertions.assertTrue(result.succeeded()); - } - - @Test - @SneakyThrows - void deprovision__failedWrongProvisionType() { - String provisionType = "AmazonS3"; - SftpUser sftpUser = SftpUser.builder().name("name").password("password").build(); - SftpLocation sftpLocation = SftpLocation.builder().host("host").port(22).path("path").build(); - SftpDataAddress dataAddress = new SftpDataAddress(sftpUser, sftpLocation); - Policy policy = Mockito.mock(Policy.class); - String provisionedResourceID = "resource"; - SftpProvisionedContentResource provisionedContentResource = - new SftpProvisionedContentResource( - provisionType, policy, dataAddress, provisionedResourceID); - - CompletableFuture> future = - provisioner.deprovision(provisionedContentResource, policy); - StatusResult result = future.get(); - - Assertions.assertTrue(result.failed()); - } - - @NoArgsConstructor - private static class WrongResourceDefinition extends ResourceDefinition { - @Override - public > B toBuilder() { - return null; + private final String policyScope = "scope"; + private final PolicyEngine policyEngine = Mockito.mock(PolicyEngine.class); + private final NoOpSftpProvider sftpProvider = new NoOpSftpProvider(); + + private final NoOpSftpProvisioner provisioner = + new NoOpSftpProvisioner(policyScope, policyEngine, sftpProvider); + + @Test + void canProvision_true() { + String provisionType = "NoOp"; + SftpUser sftpUser = SftpUser.builder().name("name").password("password").build(); + SftpLocation sftpLocation = SftpLocation.builder().host("host").port(22).path("path").build(); + SftpDataAddress dataAddress = new SftpDataAddress(sftpUser, sftpLocation); + SftpProviderResourceDefinition resourceDefinition = + new SftpProviderResourceDefinition(provisionType, dataAddress); + + Assertions.assertTrue(provisioner.canProvision(resourceDefinition)); + } + + @Test + void canProvision_falseProvisionType() { + String provisionType = "AmazonS3"; + SftpUser sftpUser = SftpUser.builder().name("name").password("password").build(); + SftpLocation sftpLocation = SftpLocation.builder().host("host").port(22).path("path").build(); + SftpDataAddress dataAddress = new SftpDataAddress(sftpUser, sftpLocation); + SftpProviderResourceDefinition resourceDefinition = + new SftpProviderResourceDefinition(provisionType, dataAddress); + + Assertions.assertFalse(provisioner.canProvision(resourceDefinition)); + } + + @Test + void canProvision_falseDefinitionType() { + ResourceDefinition resourceDefinition = new WrongResourceDefinition(); + + Assertions.assertFalse(provisioner.canProvision(resourceDefinition)); } - } - @NoArgsConstructor - private static class WrongProvisionedContentResource extends ProvisionedContentResource {} + @Test + void canDeprovision_true() { + String provisionType = "NoOp"; + SftpUser sftpUser = SftpUser.builder().name("name").password("password").build(); + SftpLocation sftpLocation = SftpLocation.builder().host("host").port(22).path("path").build(); + Policy scopedPolicy = Mockito.mock(Policy.class); + SftpDataAddress dataAddress = new SftpDataAddress(sftpUser, sftpLocation); + String provisionedResourceId = "resource"; + SftpProvisionedContentResource provisionedContentResource = + new SftpProvisionedContentResource( + provisionType, scopedPolicy, dataAddress, provisionedResourceId); + + Assertions.assertTrue(provisioner.canDeprovision(provisionedContentResource)); + } + + @Test + void canDeprovision_falseProvisionType() { + String provisionType = "AmazonS3"; + SftpUser sftpUser = SftpUser.builder().name("name").password("password").build(); + SftpLocation sftpLocation = SftpLocation.builder().host("host").port(22).path("path").build(); + Policy scopedPolicy = Mockito.mock(Policy.class); + SftpDataAddress dataAddress = new SftpDataAddress(sftpUser, sftpLocation); + String provisionedResourceId = "resource"; + SftpProvisionedContentResource provisionedContentResource = + new SftpProvisionedContentResource( + provisionType, scopedPolicy, dataAddress, provisionedResourceId); + + Assertions.assertFalse(provisioner.canDeprovision(provisionedContentResource)); + } + + @Test + void canDeprovision_falseDefinitionType() { + ProvisionedContentResource provisionedContentResource = new WrongProvisionedContentResource(); + + Assertions.assertFalse(provisioner.canDeprovision(provisionedContentResource)); + } + + @Test + @SneakyThrows + void provision_successful() { + String provisionType = "NoOp"; + SftpUser sftpUser = SftpUser.builder().name("name").password("password").build(); + SftpLocation sftpLocation = SftpLocation.builder().host("host").port(22).path("path").build(); + SftpDataAddress dataAddress = new SftpDataAddress(sftpUser, sftpLocation); + SftpProviderResourceDefinition resourceDefinition = + new SftpProviderResourceDefinition(provisionType, dataAddress); + Policy policy = Mockito.mock(Policy.class); + + Mockito.when(policyEngine.filter(policy, policyScope)).thenReturn(policy); + + CompletableFuture> future = + provisioner.provision(resourceDefinition, policy); + StatusResult result = future.get(); + + Assertions.assertTrue(result.succeeded()); + } + + @Test + @SneakyThrows + void provision_failedWrongProvisionType() { + String provisionType = "AmazonS3"; + SftpUser sftpUser = SftpUser.builder().name("name").password("password").build(); + SftpLocation sftpLocation = SftpLocation.builder().host("host").port(22).path("path").build(); + SftpDataAddress dataAddress = new SftpDataAddress(sftpUser, sftpLocation); + SftpProviderResourceDefinition resourceDefinition = + new SftpProviderResourceDefinition(provisionType, dataAddress); + Policy policy = Mockito.mock(Policy.class); + + Mockito.when(policyEngine.filter(policy, policyScope)).thenReturn(policy); + + CompletableFuture> future = + provisioner.provision(resourceDefinition, policy); + StatusResult result = future.get(); + + Assertions.assertTrue(result.failed()); + } + + @Test + @SneakyThrows + void deprovision_successful() { + String provisionType = "NoOp"; + SftpUser sftpUser = SftpUser.builder().name("name").password("password").build(); + SftpLocation sftpLocation = SftpLocation.builder().host("host").port(22).path("path").build(); + SftpDataAddress dataAddress = new SftpDataAddress(sftpUser, sftpLocation); + Policy policy = Mockito.mock(Policy.class); + String provisionedResourceId = "resource"; + SftpProvisionedContentResource provisionedContentResource = + new SftpProvisionedContentResource( + provisionType, policy, dataAddress, provisionedResourceId); + + CompletableFuture> future = + provisioner.deprovision(provisionedContentResource, policy); + StatusResult result = future.get(); + + Assertions.assertTrue(result.succeeded()); + } + + @Test + @SneakyThrows + void deprovision_failedWrongProvisionType() { + String provisionType = "AmazonS3"; + SftpUser sftpUser = SftpUser.builder().name("name").password("password").build(); + SftpLocation sftpLocation = SftpLocation.builder().host("host").port(22).path("path").build(); + SftpDataAddress dataAddress = new SftpDataAddress(sftpUser, sftpLocation); + Policy policy = Mockito.mock(Policy.class); + String provisionedResourceId = "resource"; + SftpProvisionedContentResource provisionedContentResource = + new SftpProvisionedContentResource( + provisionType, policy, dataAddress, provisionedResourceId); + + CompletableFuture> future = + provisioner.deprovision(provisionedContentResource, policy); + StatusResult result = future.get(); + + Assertions.assertTrue(result.failed()); + } + + @NoArgsConstructor + private static class WrongResourceDefinition extends ResourceDefinition { + @Override + public > B toBuilder() { + return null; + } + } + + @NoArgsConstructor + private static class WrongProvisionedContentResource extends ProvisionedContentResource { + } } diff --git a/edc-extensions/transferprocess-sftp-provisioner/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpLocationFactoryImplTest.java b/edc-extensions/transferprocess-sftp-provisioner/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpLocationFactoryImplTest.java index afca5d5ac..2b4a11bfe 100644 --- a/edc-extensions/transferprocess-sftp-provisioner/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpLocationFactoryImplTest.java +++ b/edc-extensions/transferprocess-sftp-provisioner/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpLocationFactoryImplTest.java @@ -25,18 +25,18 @@ import org.junit.jupiter.api.Test; class SftpLocationFactoryImplTest { - private final SftpLocationFactoryImpl sftpLocationFactoryImpl = new SftpLocationFactoryImpl(); + private final SftpLocationFactoryImpl sftpLocationFactoryImpl = new SftpLocationFactoryImpl(); - @Test - void generateSftpLocation() { - final String host = "host"; - final Integer port = 22; - final String path = "path"; + @Test + void generateSftpLocation() { + final String host = "host"; + final Integer port = 22; + final String path = "path"; - final SftpLocation location = sftpLocationFactoryImpl.createSftpLocation(host, port, path); + final SftpLocation location = sftpLocationFactoryImpl.createSftpLocation(host, port, path); - Assertions.assertEquals(host, location.getHost()); - Assertions.assertEquals(port, location.getPort()); - Assertions.assertEquals(path, location.getPath()); - } + Assertions.assertEquals(host, location.getHost()); + Assertions.assertEquals(port, location.getPort()); + Assertions.assertEquals(path, location.getPath()); + } } diff --git a/edc-extensions/transferprocess-sftp-provisioner/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProviderResourceDefinitionGeneratorTest.java b/edc-extensions/transferprocess-sftp-provisioner/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProviderResourceDefinitionGeneratorTest.java index d81252705..ea58fd98a 100644 --- a/edc-extensions/transferprocess-sftp-provisioner/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProviderResourceDefinitionGeneratorTest.java +++ b/edc-extensions/transferprocess-sftp-provisioner/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpProviderResourceDefinitionGeneratorTest.java @@ -20,11 +20,6 @@ package org.eclipse.tractusx.edc.transferprocess.sftp.provisioner; -import static org.eclipse.tractusx.edc.transferprocess.sftp.provisioner.NoOpSftpProvisioner.DATA_ADDRESS_TYPE; -import static org.eclipse.tractusx.edc.transferprocess.sftp.provisioner.NoOpSftpProvisioner.PROVIDER_TYPE; - -import java.security.KeyPair; -import java.security.KeyPairGenerator; import lombok.SneakyThrows; import org.eclipse.edc.connector.transfer.spi.types.DataRequest; import org.eclipse.edc.policy.model.Policy; @@ -35,60 +30,66 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import java.security.KeyPair; +import java.security.KeyPairGenerator; + +import static org.eclipse.tractusx.edc.transferprocess.sftp.provisioner.NoOpSftpProvisioner.DATA_ADDRESS_TYPE; +import static org.eclipse.tractusx.edc.transferprocess.sftp.provisioner.NoOpSftpProvisioner.PROVIDER_TYPE; + class SftpProviderResourceDefinitionGeneratorTest { - private final SftpProviderResourceDefinitionGenerator generator = - new SftpProviderResourceDefinitionGenerator(); + private final SftpProviderResourceDefinitionGenerator generator = + new SftpProviderResourceDefinitionGenerator(); - @Test - void generate__successful() { - final String name = "name"; - final String password = "password"; - final KeyPair keyPair = generateKeyPair(); - final String host = "host"; - final Integer port = 22; - final String path = "path"; + @SneakyThrows + static KeyPair generateKeyPair() { + final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); + keyPairGenerator.initialize(2048); + return keyPairGenerator.generateKeyPair(); + } - final DataRequest dataRequest = - DataRequest.Builder.newInstance().destinationType(DATA_ADDRESS_TYPE).build(); - final SftpUser sftpUser = - SftpUser.builder().name(name).password(password).keyPair(keyPair).build(); - final SftpLocation sftpLocation = - SftpLocation.builder().host(host).port(port).path(path).build(); - final DataAddress dataAddress = new SftpDataAddress(sftpUser, sftpLocation); - final Policy policy = Policy.Builder.newInstance().build(); + @Test + void generate_successful() { + final String name = "name"; + final String password = "password"; + final KeyPair keyPair = generateKeyPair(); + final String host = "host"; + final Integer port = 22; + final String path = "path"; - final SftpProviderResourceDefinition resourceDefinition = - (SftpProviderResourceDefinition) generator.generate(dataRequest, dataAddress, policy); + final DataRequest dataRequest = + DataRequest.Builder.newInstance().destinationType(DATA_ADDRESS_TYPE).build(); + final SftpUser sftpUser = + SftpUser.builder().name(name).password(password).keyPair(keyPair).build(); + final SftpLocation sftpLocation = + SftpLocation.builder().host(host).port(port).path(path).build(); + final DataAddress dataAddress = new SftpDataAddress(sftpUser, sftpLocation); + final Policy policy = Policy.Builder.newInstance().build(); - Assertions.assertNotNull(resourceDefinition); - final SftpDataAddress sftpDataAddress = resourceDefinition.getSftpDataAddress(); + final SftpProviderResourceDefinition resourceDefinition = + (SftpProviderResourceDefinition) generator.generate(dataRequest, dataAddress, policy); - Assertions.assertEquals(PROVIDER_TYPE, resourceDefinition.getProviderType()); - Assertions.assertEquals(host, sftpDataAddress.getSftpLocation().getHost()); - Assertions.assertEquals(port, sftpDataAddress.getSftpLocation().getPort()); - Assertions.assertEquals(path, sftpDataAddress.getSftpLocation().getPath()); - Assertions.assertEquals(name, sftpDataAddress.getSftpUser().getName()); - Assertions.assertEquals(password, sftpDataAddress.getSftpUser().getPassword()); - Assertions.assertEquals(keyPair, sftpDataAddress.getSftpUser().getKeyPair()); - } + Assertions.assertNotNull(resourceDefinition); + final SftpDataAddress sftpDataAddress = resourceDefinition.getSftpDataAddress(); - @Test - void generate__wrongDataAddressType() { - final DataRequest dataRequest = - DataRequest.Builder.newInstance().destinationType(DATA_ADDRESS_TYPE).build(); - final DataAddress dataAddress = DataAddress.Builder.newInstance().type("wrong").build(); - final Policy policy = Policy.Builder.newInstance().build(); + Assertions.assertEquals(PROVIDER_TYPE, resourceDefinition.getProviderType()); + Assertions.assertEquals(host, sftpDataAddress.getSftpLocation().getHost()); + Assertions.assertEquals(port, sftpDataAddress.getSftpLocation().getPort()); + Assertions.assertEquals(path, sftpDataAddress.getSftpLocation().getPath()); + Assertions.assertEquals(name, sftpDataAddress.getSftpUser().getName()); + Assertions.assertEquals(password, sftpDataAddress.getSftpUser().getPassword()); + Assertions.assertEquals(keyPair, sftpDataAddress.getSftpUser().getKeyPair()); + } - final SftpProviderResourceDefinition resourceDefinition = - (SftpProviderResourceDefinition) generator.generate(dataRequest, dataAddress, policy); + @Test + void generate_wrongDataAddressType() { + final DataRequest dataRequest = + DataRequest.Builder.newInstance().destinationType(DATA_ADDRESS_TYPE).build(); + final DataAddress dataAddress = DataAddress.Builder.newInstance().type("wrong").build(); + final Policy policy = Policy.Builder.newInstance().build(); - Assertions.assertNull(resourceDefinition); - } + final SftpProviderResourceDefinition resourceDefinition = + (SftpProviderResourceDefinition) generator.generate(dataRequest, dataAddress, policy); - @SneakyThrows - static KeyPair generateKeyPair() { - final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); - keyPairGenerator.initialize(2048); - return keyPairGenerator.generateKeyPair(); - } + Assertions.assertNull(resourceDefinition); + } } diff --git a/edc-extensions/transferprocess-sftp-provisioner/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpUserFactoryImplTest.java b/edc-extensions/transferprocess-sftp-provisioner/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpUserFactoryImplTest.java index 29a456176..b810903a8 100644 --- a/edc-extensions/transferprocess-sftp-provisioner/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpUserFactoryImplTest.java +++ b/edc-extensions/transferprocess-sftp-provisioner/src/test/java/org/eclipse/tractusx/edc/transferprocess/sftp/provisioner/SftpUserFactoryImplTest.java @@ -20,32 +20,33 @@ package org.eclipse.tractusx.edc.transferprocess.sftp.provisioner; -import java.security.KeyPair; -import java.security.KeyPairGenerator; import lombok.SneakyThrows; import org.eclipse.tractusx.edc.transferprocess.sftp.common.SftpUser; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import java.security.KeyPair; +import java.security.KeyPairGenerator; + class SftpUserFactoryImplTest { - private final SftpUserFactoryImpl sftpUserFactoryImpl = new SftpUserFactoryImpl(); + private final SftpUserFactoryImpl sftpUserFactoryImpl = new SftpUserFactoryImpl(); - @Test - @SneakyThrows - void generateSftpLocation() { - final String name = "name"; - final String password = "password"; + @Test + @SneakyThrows + void generateSftpLocation() { + final String name = "name"; + final String password = "password"; - final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); - keyPairGenerator.initialize(2048); - final KeyPair keyPair = keyPairGenerator.generateKeyPair(); - final byte[] privateKeyBytes = keyPair.getPrivate().getEncoded(); + final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); + keyPairGenerator.initialize(2048); + final KeyPair keyPair = keyPairGenerator.generateKeyPair(); + final byte[] privateKeyBytes = keyPair.getPrivate().getEncoded(); - final SftpUser sftpUser = sftpUserFactoryImpl.createSftpUser(name, password, privateKeyBytes); + final SftpUser sftpUser = sftpUserFactoryImpl.createSftpUser(name, password, privateKeyBytes); - Assertions.assertEquals(name, sftpUser.getName()); - Assertions.assertEquals(password, sftpUser.getPassword()); + Assertions.assertEquals(name, sftpUser.getName()); + Assertions.assertEquals(password, sftpUser.getPassword()); - Assertions.assertArrayEquals(privateKeyBytes, sftpUser.getKeyPair().getPrivate().getEncoded()); - } + Assertions.assertArrayEquals(privateKeyBytes, sftpUser.getKeyPair().getPrivate().getEncoded()); + } } diff --git a/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/helpers/ContractNegotiationHelperFunctions.java b/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/helpers/ContractNegotiationHelperFunctions.java index d11e176e7..1665173a7 100644 --- a/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/helpers/ContractNegotiationHelperFunctions.java +++ b/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/helpers/ContractNegotiationHelperFunctions.java @@ -27,7 +27,7 @@ public class ContractNegotiationHelperFunctions { - private final static JsonLd jsonLd = new TitaniumJsonLd(mock(Monitor.class)); + private static final JsonLd JSON_LD = new TitaniumJsonLd(mock(Monitor.class)); public static JsonObject createNegotiationRequest(String connectorAddress, String providerId, String offerId, String assetId, JsonObject policy) { return Json.createObjectBuilder() @@ -39,7 +39,7 @@ public static JsonObject createNegotiationRequest(String connectorAddress, Strin .add(EDC_NAMESPACE + "offer", Json.createObjectBuilder() .add(EDC_NAMESPACE + "offerId", offerId) .add(EDC_NAMESPACE + "assetId", assetId) - .add(EDC_NAMESPACE + "policy", jsonLd.compact(policy).getContent()) + .add(EDC_NAMESPACE + "policy", JSON_LD.compact(policy).getContent()) ) .build(); } diff --git a/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/helpers/EdrNegotiationHelperFunctions.java b/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/helpers/EdrNegotiationHelperFunctions.java index 7b0f85d3a..23a3931a4 100644 --- a/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/helpers/EdrNegotiationHelperFunctions.java +++ b/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/helpers/EdrNegotiationHelperFunctions.java @@ -31,7 +31,7 @@ public class EdrNegotiationHelperFunctions { - private final static JsonLd jsonLd = new TitaniumJsonLd(mock(Monitor.class)); + private static final JsonLd JSON_LD = new TitaniumJsonLd(mock(Monitor.class)); public static JsonObject createEdrNegotiationRequest(String connectorAddress, String providerId, String offerId, String assetId, JsonObject policy, JsonArray callbacks) { return Json.createObjectBuilder() @@ -43,7 +43,7 @@ public static JsonObject createEdrNegotiationRequest(String connectorAddress, St .add(EDC_NAMESPACE + "offer", Json.createObjectBuilder() .add(EDC_NAMESPACE + "offerId", offerId) .add(EDC_NAMESPACE + "assetId", assetId) - .add(EDC_NAMESPACE + "policy", jsonLd.compact(policy).getContent()) + .add(EDC_NAMESPACE + "policy", JSON_LD.compact(policy).getContent()) ) .add(EDC_NAMESPACE + "callbackAddresses", callbacks) .build(); diff --git a/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/catalog/AbstractCatalogTest.java b/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/catalog/AbstractCatalogTest.java index d60d8ce83..741e198ed 100644 --- a/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/catalog/AbstractCatalogTest.java +++ b/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/catalog/AbstractCatalogTest.java @@ -35,21 +35,21 @@ public abstract class AbstractCatalogTest { - protected static final Participant sokrates = new Participant(SOKRATES_NAME, SOKRATES_BPN, sokratesConfiguration()); - protected static final Participant plato = new Participant(PLATO_NAME, PLATO_BPN, platoConfiguration()); + protected static final Participant SOKRATES = new Participant(SOKRATES_NAME, SOKRATES_BPN, sokratesConfiguration()); + protected static final Participant PLATO = new Participant(PLATO_NAME, PLATO_BPN, platoConfiguration()); @Test void requestCatalog_fulfillsPolicy_shouldReturnOffer() { // arrange - sokrates.createAsset("test-asset"); + SOKRATES.createAsset("test-asset"); var accessPolicy = noConstraintPolicyDefinition("test-ap1"); var contractPolicy = noConstraintPolicyDefinition("test-cp1"); - sokrates.createPolicy(accessPolicy); - sokrates.createPolicy(contractPolicy); - sokrates.createContractDefinition("test-asset", "test-def", "test-ap1", "test-cp1"); + SOKRATES.createPolicy(accessPolicy); + SOKRATES.createPolicy(contractPolicy); + SOKRATES.createContractDefinition("test-asset", "test-def", "test-ap1", "test-cp1"); // act - var catalog = plato.getCatalogDatasets(sokrates); + var catalog = PLATO.getCatalogDatasets(SOKRATES); // assert assertThat(catalog).isNotEmpty() @@ -66,39 +66,39 @@ void requestCatalog_filteredByBpn_shouldReject() { var onlyPlatoId = "ap"; var onlyDiogenesId = "db"; - var onlyPlatoPolicy = businessPartnerNumberPolicy(onlyPlatoId, "BPN1", "BPN2", plato.getBpn()); + var onlyPlatoPolicy = businessPartnerNumberPolicy(onlyPlatoId, "BPN1", "BPN2", PLATO.getBpn()); var onlyDiogenesPolicy = businessPartnerNumberPolicy(onlyDiogenesId, "ARISTOTELES-BPN"); var noConstraintPolicyId = "no-constraint"; - sokrates.createPolicy(onlyPlatoPolicy); - sokrates.createPolicy(onlyDiogenesPolicy); - sokrates.createPolicy(noConstraintPolicyDefinition(noConstraintPolicyId)); + SOKRATES.createPolicy(onlyPlatoPolicy); + SOKRATES.createPolicy(onlyDiogenesPolicy); + SOKRATES.createPolicy(noConstraintPolicyDefinition(noConstraintPolicyId)); - sokrates.createAsset("test-asset1"); - sokrates.createAsset("test-asset2"); - sokrates.createAsset("test-asset3"); + SOKRATES.createAsset("test-asset1"); + SOKRATES.createAsset("test-asset2"); + SOKRATES.createAsset("test-asset3"); - sokrates.createContractDefinition("test-asset1", "def1", noConstraintPolicyId, noConstraintPolicyId); - sokrates.createContractDefinition("test-asset2", "def2", onlyPlatoId, noConstraintPolicyId); - sokrates.createContractDefinition("test-asset3", "def3", onlyDiogenesId, noConstraintPolicyId); + SOKRATES.createContractDefinition("test-asset1", "def1", noConstraintPolicyId, noConstraintPolicyId); + SOKRATES.createContractDefinition("test-asset2", "def2", onlyPlatoId, noConstraintPolicyId); + SOKRATES.createContractDefinition("test-asset3", "def3", onlyDiogenesId, noConstraintPolicyId); // act - var catalog = plato.getCatalogDatasets(sokrates); + var catalog = PLATO.getCatalogDatasets(SOKRATES); assertThat(catalog).hasSize(2); } @Test @DisplayName("Multiple ContractDefinitions exist for one Asset") void requestCatalog_multipleOffersForAsset() { - sokrates.createAsset("asset-1"); - sokrates.createPolicy(noConstraintPolicyDefinition("policy-1")); - sokrates.createPolicy(businessPartnerNumberPolicy("policy-2", plato.getBpn())); + SOKRATES.createAsset("asset-1"); + SOKRATES.createPolicy(noConstraintPolicyDefinition("policy-1")); + SOKRATES.createPolicy(businessPartnerNumberPolicy("policy-2", PLATO.getBpn())); - sokrates.createContractDefinition("asset-1", "def1", "policy-1", "policy-1"); - sokrates.createContractDefinition("asset-1", "def2", "policy-2", "policy-1"); + SOKRATES.createContractDefinition("asset-1", "def1", "policy-1", "policy-1"); + SOKRATES.createContractDefinition("asset-1", "def2", "policy-2", "policy-1"); - var catalog = plato.getCatalogDatasets(sokrates); + var catalog = PLATO.getCatalogDatasets(SOKRATES); assertThat(catalog).hasSize(1) .allSatisfy(cd -> { assertThat(getDatasetAssetId(cd)).isEqualTo("asset-1"); @@ -110,24 +110,24 @@ void requestCatalog_multipleOffersForAsset() { @DisplayName("Catalog with 1000 offers") void requestCatalog_of1000Assets_shouldContainAll() { var policyId = "policy-1"; - var policy = businessPartnerNumberPolicy(policyId, plato.getBpn()); - sokrates.createPolicy(policy); - sokrates.createPolicy(noConstraintPolicyDefinition("noconstraint")); + var policy = businessPartnerNumberPolicy(policyId, PLATO.getBpn()); + SOKRATES.createPolicy(policy); + SOKRATES.createPolicy(noConstraintPolicyDefinition("noconstraint")); range(0, 1000) .forEach(i -> { var assetId = "asset-" + i; - sokrates.createAsset(assetId); - sokrates.createContractDefinition(assetId, "def-" + i, policyId, "noconstraint"); + SOKRATES.createAsset(assetId); + SOKRATES.createContractDefinition(assetId, "def-" + i, policyId, "noconstraint"); }); // request all at once - var dataset = plato.getCatalogDatasets(sokrates, createQuery(1000, 0)); + var dataset = PLATO.getCatalogDatasets(SOKRATES, createQuery(1000, 0)); assertThat(dataset).hasSize(1000); // request in chunks - var o2 = plato.getCatalogDatasets(sokrates, createQuery(500, 0)); - var o3 = plato.getCatalogDatasets(sokrates, createQuery(500, 500)); + var o2 = PLATO.getCatalogDatasets(SOKRATES, createQuery(500, 0)); + var o3 = PLATO.getCatalogDatasets(SOKRATES, createQuery(500, 500)); assertThat(o2).doesNotContainAnyElementsOf(o3); } diff --git a/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/catalog/CatalogInMemoryTest.java b/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/catalog/CatalogInMemoryTest.java index 22ec3cbdc..7cbb8b2e4 100644 --- a/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/catalog/CatalogInMemoryTest.java +++ b/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/catalog/CatalogInMemoryTest.java @@ -29,7 +29,7 @@ public class CatalogInMemoryTest extends AbstractCatalogTest { @RegisterExtension - protected static ParticipantRuntime SOKRATES_RUNTIME = new ParticipantRuntime( + protected static final ParticipantRuntime SOKRATES_RUNTIME = new ParticipantRuntime( ":edc-tests:runtime:runtime-memory", SOKRATES_NAME, SOKRATES_BPN, @@ -37,7 +37,7 @@ public class CatalogInMemoryTest extends AbstractCatalogTest { ); @RegisterExtension - protected static ParticipantRuntime PLATO_RUNTIME = new ParticipantRuntime( + protected static final ParticipantRuntime PLATO_RUNTIME = new ParticipantRuntime( ":edc-tests:runtime:runtime-memory", PLATO_NAME, PLATO_BPN, diff --git a/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/catalog/CatalogPostgresqlTest.java b/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/catalog/CatalogPostgresqlTest.java index 413d11ea2..5af78043d 100644 --- a/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/catalog/CatalogPostgresqlTest.java +++ b/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/catalog/CatalogPostgresqlTest.java @@ -29,14 +29,14 @@ public class CatalogPostgresqlTest extends AbstractCatalogTest { @RegisterExtension - protected static PgParticipantRuntime SOKRATES_RUNTIME = new PgParticipantRuntime( + protected static final PgParticipantRuntime SOKRATES_RUNTIME = new PgParticipantRuntime( ":edc-tests:runtime:runtime-postgresql", SOKRATES_NAME, SOKRATES_BPN, sokratesPostgresqlConfiguration() ); @RegisterExtension - protected static PgParticipantRuntime PLATO_RUNTIME = new PgParticipantRuntime( + protected static final PgParticipantRuntime PLATO_RUNTIME = new PgParticipantRuntime( ":edc-tests:runtime:runtime-postgresql", PLATO_NAME, PLATO_BPN, diff --git a/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/edr/AbstractNegotiateEdrTest.java b/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/edr/AbstractNegotiateEdrTest.java index 06963b571..590dd2183 100644 --- a/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/edr/AbstractNegotiateEdrTest.java +++ b/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/edr/AbstractNegotiateEdrTest.java @@ -52,9 +52,9 @@ import static org.eclipse.tractusx.edc.lifecycle.TestRuntimeConfiguration.sokratesConfiguration; public abstract class AbstractNegotiateEdrTest { - - protected static final Participant sokrates = new Participant(SOKRATES_NAME, SOKRATES_BPN, sokratesConfiguration()); - protected static final Participant plato = new Participant(PLATO_NAME, PLATO_BPN, platoConfiguration()); + + protected static final Participant SOKRATES = new Participant(SOKRATES_NAME, SOKRATES_BPN, sokratesConfiguration()); + protected static final Participant PLATO = new Participant(PLATO_NAME, PLATO_BPN, platoConfiguration()); MockWebServer server = new MockWebServer(); @@ -83,7 +83,7 @@ void negotiateEdr_shouldInvokeCallbacks() throws IOException { var authCodeHeaderName = "test-authkey"; var authCode = "test-authcode"; - plato.createAsset(assetId, Json.createObjectBuilder().build(), Json.createObjectBuilder() + PLATO.createAsset(assetId, Json.createObjectBuilder().build(), Json.createObjectBuilder() .add(EDC_NAMESPACE + "type", "HttpData") .add(EDC_NAMESPACE + "contentType", "application/json") .add(EDC_NAMESPACE + "baseUrl", url.toString()) @@ -91,20 +91,18 @@ void negotiateEdr_shouldInvokeCallbacks() throws IOException { .add(EDC_NAMESPACE + "authCode", authCode) .build()); - plato.createPolicy(businessPartnerNumberPolicy("policy-1", sokrates.getBpn())); - plato.createPolicy(businessPartnerNumberPolicy("policy-2", sokrates.getBpn())); - plato.createContractDefinition(assetId, "def-1", "policy-1", "policy-2"); + PLATO.createPolicy(businessPartnerNumberPolicy("policy-1", SOKRATES.getBpn())); + PLATO.createPolicy(businessPartnerNumberPolicy("policy-2", SOKRATES.getBpn())); + PLATO.createContractDefinition(assetId, "def-1", "policy-1", "policy-2"); - expectedEvents.forEach(_event -> { - server.enqueue(new MockResponse()); - }); + expectedEvents.forEach(event -> server.enqueue(new MockResponse())); var callbacks = Json.createArrayBuilder() .add(createCallback(url.toString(), true, Set.of("contract.negotiation", "transfer.process"))) .build(); - sokrates.negotiateEdr(plato, assetId, callbacks); + SOKRATES.negotiateEdr(PLATO, assetId, callbacks); var events = expectedEvents.stream() .map(this::waitForEvent) diff --git a/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/edr/NegotiateEdrInMemoryTest.java b/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/edr/NegotiateEdrInMemoryTest.java index eebcc54c3..072131805 100644 --- a/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/edr/NegotiateEdrInMemoryTest.java +++ b/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/edr/NegotiateEdrInMemoryTest.java @@ -30,7 +30,7 @@ public class NegotiateEdrInMemoryTest extends AbstractNegotiateEdrTest { @RegisterExtension - protected static ParticipantRuntime SOKRATES_RUNTIME = new ParticipantRuntime( + protected static final ParticipantRuntime SOKRATES_RUNTIME = new ParticipantRuntime( ":edc-tests:runtime:runtime-memory", SOKRATES_NAME, SOKRATES_BPN, @@ -38,7 +38,7 @@ public class NegotiateEdrInMemoryTest extends AbstractNegotiateEdrTest { ); @RegisterExtension - protected static ParticipantRuntime PLATO_RUNTIME = new ParticipantRuntime( + protected static final ParticipantRuntime PLATO_RUNTIME = new ParticipantRuntime( ":edc-tests:runtime:runtime-memory", PLATO_NAME, PLATO_BPN, diff --git a/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/edr/NegotiateEdrPostgresqlTest.java b/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/edr/NegotiateEdrPostgresqlTest.java index b3a43dceb..d7db9cc31 100644 --- a/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/edr/NegotiateEdrPostgresqlTest.java +++ b/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/edr/NegotiateEdrPostgresqlTest.java @@ -29,14 +29,14 @@ public class NegotiateEdrPostgresqlTest extends AbstractNegotiateEdrTest { @RegisterExtension - protected static PgParticipantRuntime SOKRATES_RUNTIME = new PgParticipantRuntime( + protected static final PgParticipantRuntime SOKRATES_RUNTIME = new PgParticipantRuntime( ":edc-tests:runtime:runtime-postgresql", SOKRATES_NAME, SOKRATES_BPN, sokratesPostgresqlConfiguration() ); @RegisterExtension - protected static PgParticipantRuntime PLATO_RUNTIME = new PgParticipantRuntime( + protected static final PgParticipantRuntime PLATO_RUNTIME = new PgParticipantRuntime( ":edc-tests:runtime:runtime-postgresql", PLATO_NAME, PLATO_BPN, diff --git a/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/transfer/AbstractHttpConsumerPullWithProxyTest.java b/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/transfer/AbstractHttpConsumerPullWithProxyTest.java index 93b93d709..ac229c08e 100644 --- a/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/transfer/AbstractHttpConsumerPullWithProxyTest.java +++ b/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/transfer/AbstractHttpConsumerPullWithProxyTest.java @@ -46,8 +46,8 @@ public abstract class AbstractHttpConsumerPullWithProxyTest { - protected static final Participant sokrates = new Participant(SOKRATES_NAME, SOKRATES_BPN, sokratesConfiguration()); - protected static final Participant plato = new Participant(PLATO_NAME, PLATO_BPN, platoConfiguration()); + protected static final Participant SOKRATES = new Participant(SOKRATES_NAME, SOKRATES_BPN, sokratesConfiguration()); + protected static final Participant PLATO = new Participant(PLATO_NAME, PLATO_BPN, platoConfiguration()); private static final Duration ASYNC_TIMEOUT = ofSeconds(45); private static final Duration ASYNC_POLL_INTERVAL = ofSeconds(1); @@ -69,12 +69,12 @@ void transferData_privateBackend() throws IOException, InterruptedException { .add(EDC_NAMESPACE + "authCode", authCode) .build(); - plato.createAsset(assetId, Json.createObjectBuilder().build(), dataAddress); + PLATO.createAsset(assetId, Json.createObjectBuilder().build(), dataAddress); - plato.createPolicy(businessPartnerNumberPolicy("policy-1", sokrates.getBpn())); - plato.createPolicy(businessPartnerNumberPolicy("policy-2", sokrates.getBpn())); - plato.createContractDefinition(assetId, "def-1", "policy-1", "policy-2"); - var negotiationId = sokrates.negotiateContract(plato, assetId); + PLATO.createPolicy(businessPartnerNumberPolicy("policy-1", SOKRATES.getBpn())); + PLATO.createPolicy(businessPartnerNumberPolicy("policy-2", SOKRATES.getBpn())); + PLATO.createContractDefinition(assetId, "def-1", "policy-1", "policy-2"); + var negotiationId = SOKRATES.negotiateContract(PLATO, assetId); // forward declarations of our actual values var transferProcessId = new AtomicReference(); @@ -86,14 +86,14 @@ void transferData_privateBackend() throws IOException, InterruptedException { await().pollInterval(ASYNC_POLL_INTERVAL) .atMost(ASYNC_TIMEOUT) .untilAsserted(() -> { - var negotiationState = sokrates.getNegotiationState(negotiationId); + var negotiationState = SOKRATES.getNegotiationState(negotiationId); assertThat(negotiationState).isEqualTo(ContractNegotiationStates.FINALIZED.toString()); - var agreementId = sokrates.getContractAgreementId(negotiationId); + var agreementId = SOKRATES.getContractAgreementId(negotiationId); assertThat(agreementId).isNotNull(); contractAgreementId.set(agreementId); - var tpId = sokrates.requestTransfer(dataRequestId, contractAgreementId.get(), assetId, plato, createProxyRequest()); + var tpId = SOKRATES.requestTransfer(dataRequestId, contractAgreementId.get(), assetId, PLATO, createProxyRequest()); transferProcessId.set(tpId); assertThat(transferProcessId).isNotNull(); }); @@ -102,7 +102,7 @@ void transferData_privateBackend() throws IOException, InterruptedException { await().pollInterval(fibonacci()) .atMost(ASYNC_TIMEOUT) .untilAsserted(() -> { - var tpState = sokrates.getTransferProcessState(transferProcessId.get()); + var tpState = SOKRATES.getTransferProcessState(transferProcessId.get()); assertThat(tpState).isNotNull().isEqualTo(TransferProcessStates.COMPLETED.toString()); }); @@ -111,13 +111,13 @@ void transferData_privateBackend() throws IOException, InterruptedException { await().pollInterval(fibonacci()) .atMost(ASYNC_TIMEOUT) .untilAsserted(() -> { - edr.set(sokrates.getDataReference(dataRequestId)); + edr.set(SOKRATES.getDataReference(dataRequestId)); assertThat(edr).isNotNull(); }); // pull data out of provider's backend service: // Cons-DP -> Prov-DP -> Prov-backend - assertThat(sokrates.pullData(edr.get(), Map.of())).isEqualTo("test response"); + assertThat(SOKRATES.pullData(edr.get(), Map.of())).isEqualTo("test response"); var rq = server.takeRequest(); assertThat(rq.getHeader(authCodeHeaderName)).isEqualTo(authCode); assertThat(rq.getHeader("Edc-Contract-Agreement-Id")).isEqualTo(contractAgreementId.get()); diff --git a/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/transfer/HttpConsumerPullWithProxyInMemoryTest.java b/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/transfer/HttpConsumerPullWithProxyInMemoryTest.java index 6de461748..b786cebd6 100644 --- a/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/transfer/HttpConsumerPullWithProxyInMemoryTest.java +++ b/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/transfer/HttpConsumerPullWithProxyInMemoryTest.java @@ -29,7 +29,7 @@ public class HttpConsumerPullWithProxyInMemoryTest extends AbstractHttpConsumerPullWithProxyTest { @RegisterExtension - protected static ParticipantRuntime SOKRATES_RUNTIME = new ParticipantRuntime( + protected static final ParticipantRuntime SOKRATES_RUNTIME = new ParticipantRuntime( ":edc-tests:runtime:runtime-memory", SOKRATES_NAME, SOKRATES_BPN, @@ -37,7 +37,7 @@ public class HttpConsumerPullWithProxyInMemoryTest extends AbstractHttpConsumerP ); @RegisterExtension - protected static ParticipantRuntime PLATO_RUNTIME = new ParticipantRuntime( + protected static final ParticipantRuntime PLATO_RUNTIME = new ParticipantRuntime( ":edc-tests:runtime:runtime-memory", PLATO_NAME, PLATO_BPN, diff --git a/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/transfer/HttpConsumerPullWithProxyPostgresqlTest.java b/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/transfer/HttpConsumerPullWithProxyPostgresqlTest.java index 35a262992..887c7a307 100644 --- a/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/transfer/HttpConsumerPullWithProxyPostgresqlTest.java +++ b/edc-tests/e2e-tests/src/test/java/org/eclipse/tractusx/edc/tests/transfer/HttpConsumerPullWithProxyPostgresqlTest.java @@ -30,14 +30,14 @@ public class HttpConsumerPullWithProxyPostgresqlTest extends AbstractHttpConsume @RegisterExtension - protected static PgParticipantRuntime SOKRATES_RUNTIME = new PgParticipantRuntime( + protected static final PgParticipantRuntime SOKRATES_RUNTIME = new PgParticipantRuntime( ":edc-tests:runtime:runtime-postgresql", SOKRATES_NAME, SOKRATES_BPN, sokratesPostgresqlConfiguration() ); @RegisterExtension - protected static PgParticipantRuntime PLATO_RUNTIME = new PgParticipantRuntime( + protected static final PgParticipantRuntime PLATO_RUNTIME = new PgParticipantRuntime( ":edc-tests:runtime:runtime-postgresql", PLATO_NAME, PLATO_BPN, diff --git a/edc-tests/edc-dataplane-proxy-e2e/src/test/java/org/eclipse/tractusx/edc/dataplane/proxy/e2e/DpfProxyEndToEndTest.java b/edc-tests/edc-dataplane-proxy-e2e/src/test/java/org/eclipse/tractusx/edc/dataplane/proxy/e2e/DpfProxyEndToEndTest.java index c7649ea67..691aa255f 100644 --- a/edc-tests/edc-dataplane-proxy-e2e/src/test/java/org/eclipse/tractusx/edc/dataplane/proxy/e2e/DpfProxyEndToEndTest.java +++ b/edc-tests/edc-dataplane-proxy-e2e/src/test/java/org/eclipse/tractusx/edc/dataplane/proxy/e2e/DpfProxyEndToEndTest.java @@ -56,45 +56,44 @@ */ @EndToEndTest public class DpfProxyEndToEndTest { + public static final String KEYSTORE_PASS = "test123"; private static final String LAUNCHER_MODULE = ":edc-tests:edc-dataplane-proxy-e2e"; - private static final int CONSUMER_HTTP_PORT = getFreePort(); private static final int CONSUMER_PROXY_PORT = getFreePort(); private static final int PRODUCER_HTTP_PORT = getFreePort(); private static final int MOCK_ENDPOINT_PORT = getFreePort(); - private static final String PROXY_SUBPATH = "proxy/aas/request"; - private static final String SINGLE_TRANSFER_ID = "5355d524-2616-43df-9096-558afffff659"; private static final String SINGLE_ASSET_ID = "79f13b89-59a6-4278-8c8e-8540849dbab8"; private static final String MULTI_ASSET_ID = "9260f395-3d94-4b8b-bdaa-941ead596ce5"; - private static final String REQUEST_TEMPLATE_TP = "{\"transferProcessId\": \"%s\", \"endpointUrl\" : \"http://localhost:%s/api/gateway/aas/test\"}"; private static final String REQUEST_TEMPLATE_ASSET = "{\"assetId\": \"%s\", \"endpointUrl\" : \"http://localhost:%s/api/gateway/aas/test\"}"; - private static final String MOCK_ENDPOINT_200_BODY = "{\"message\":\"test\"}"; - - public static final String KEYSTORE_PASS = "test123"; - - private MockWebServer mockEndpoint; - @RegisterExtension - static EdcRuntimeExtension CONSUMER = new EdcRuntimeExtension( + static EdcRuntimeExtension consumer = new EdcRuntimeExtension( LAUNCHER_MODULE, "consumer", baseConfig(Map.of( "web.http.port", valueOf(CONSUMER_HTTP_PORT), "tx.dpf.consumer.proxy.port", valueOf(CONSUMER_PROXY_PORT) ))); - @RegisterExtension - static EdcRuntimeExtension PROVIDER = new EdcRuntimeExtension( + static EdcRuntimeExtension provider = new EdcRuntimeExtension( LAUNCHER_MODULE, "provider", baseConfig(Map.of( "web.http.port", valueOf(PRODUCER_HTTP_PORT), "tx.dpf.proxy.gateway.aas.proxied.path", "http://localhost:" + MOCK_ENDPOINT_PORT ))); + private MockWebServer mockEndpoint; + + private static Map baseConfig(Map values) { + var map = new HashMap<>(values); + map.put("edc.vault", createVaultStore()); + map.put("edc.keystore", createKeyStore(KEYSTORE_PASS)); + map.put("edc.keystore.password", KEYSTORE_PASS); + return map; + } @BeforeEach void setUp() { @@ -171,23 +170,13 @@ private RequestSpecification createSpecification(String body) { .body(body); } - private static Map baseConfig(Map values) { - var map = new HashMap<>(values); - map.put("edc.vault", createVaultStore()); - map.put("edc.keystore", createKeyStore(KEYSTORE_PASS)); - map.put("edc.keystore.password", KEYSTORE_PASS); - return map; - } - /** * Loads the EDR cache. */ private void seedEdrCache() { - var edrCache = CONSUMER.getContext().getService(EndpointDataReferenceCache.class); - createEntries().forEach(e->edrCache.save(e.getEdrEntry(), e.getEdr())); + var edrCache = consumer.getContext().getService(EndpointDataReferenceCache.class); + createEntries().forEach(e -> edrCache.save(e.getEdrEntry(), e.getEdr())); } - - } diff --git a/edc-tests/edc-dataplane-proxy-e2e/src/test/java/org/eclipse/tractusx/edc/dataplane/proxy/e2e/VaultSetup.java b/edc-tests/edc-dataplane-proxy-e2e/src/test/java/org/eclipse/tractusx/edc/dataplane/proxy/e2e/VaultSetup.java index 8bbae5f09..4c656fca2 100644 --- a/edc-tests/edc-dataplane-proxy-e2e/src/test/java/org/eclipse/tractusx/edc/dataplane/proxy/e2e/VaultSetup.java +++ b/edc-tests/edc-dataplane-proxy-e2e/src/test/java/org/eclipse/tractusx/edc/dataplane/proxy/e2e/VaultSetup.java @@ -26,7 +26,13 @@ public class VaultSetup { private static final String HEADER = DELIMITER + "BEGIN" + " PUBLIC " + "KEY" + DELIMITER; private static final String FOOTER = DELIMITER + "END" + " PUBLIC " + "KEY" + DELIMITER; - private static final String VAULT_CONTENTS = "tx.dpf.data.proxy.public.key=" + HEADER + "\\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyMkG7DSIhMjFOtqQJsr+\\nKtzfKKGGQ/7mBdjwDCEj0ijKLG/LiEYWsbPA8L/oMAIdR4xpLGaajtz6wj7NbMiA\\nrtHF1HA3mNoeKGix7SfobfQ9J7gJJmSE5DA4BxatL4sPMfoV2SJanJQQjOEAA6/i\\nI+o8SeeBc/2YE55O3yeFjdHK5JIwDi9vIkGnDRBd9poyrHYV+7dcyBB45r6BwvoW\\nG41mezzlKbOl0ZtPW1T9fqp+lOiZWIHMY5ml1daGSbTWwfJxc7XfHHa8KCNQcsPR\\nhWYx6PnxvgqQwYPjvqZF7OYAMUOQX8pg6jfYiU4HgUI1jwwGw3UpJq4b3kzD3u4T\\nDQIDAQAB\\n" + FOOTER + "\n"; + private static final String VAULT_CONTENTS = "tx.dpf.data.proxy.public.key=" + HEADER + "\\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyMkG7DSIhMjFOtqQJsr+\\nKtzfKK" + + "GGQ/7mBdjwDCEj0ijKLG/LiEYWsbPA8L/oMAIdR4xpLGaajtz6wj7NbMiA\\nrtHF1HA3mNoeKGix7SfobfQ9J7gJJmSE5DA4BxatL4sPMfoV2SJanJQQjOEAA6/i\\nI+o8SeeBc/2YE55O3yeFjdHK5JIwDi9v" + + "IkGnDRBd9poyrHYV+7dcyBB45r6BwvoW\\nG41mezzlKbOl0ZtPW1T9fqp+lOiZWIHMY5ml1daGSbTWwfJxc7XfHHa8KCNQcsPR\\nhWYx6PnxvgqQwYPjvqZF7OYAMUOQX8pg6jfYiU4HgUI1jwwGw3UpJq4b3k" + + "zD3u4T\\nDQIDAQAB\\n" + FOOTER + "\n"; + + private VaultSetup() { + } public static String createVaultStore() { try { @@ -40,7 +46,4 @@ public static String createVaultStore() { throw new AssertionError(e); } } - - private VaultSetup() { - } } diff --git a/edc-tests/runtime/extensions/src/main/java/org/eclipse/tractusx/edc/lifecycle/ConsumerEdrHandlerController.java b/edc-tests/runtime/extensions/src/main/java/org/eclipse/tractusx/edc/lifecycle/ConsumerEdrHandlerController.java index 95558d999..5f443a865 100644 --- a/edc-tests/runtime/extensions/src/main/java/org/eclipse/tractusx/edc/lifecycle/ConsumerEdrHandlerController.java +++ b/edc-tests/runtime/extensions/src/main/java/org/eclipse/tractusx/edc/lifecycle/ConsumerEdrHandlerController.java @@ -32,7 +32,7 @@ public class ConsumerEdrHandlerController { private final Monitor monitor; - private Map dataReference; + private final Map dataReference; public ConsumerEdrHandlerController(Monitor monitor) { this.monitor = monitor; @@ -51,8 +51,7 @@ public void pushDataReference(EndpointDataReference edr) { @GET @Produces({MediaType.APPLICATION_JSON}) public EndpointDataReference getDataReference(@PathParam("id") String id) { - return Optional.ofNullable(dataReference.get(id)).orElseGet(() -> - { + return Optional.ofNullable(dataReference.get(id)).orElseGet(() -> { monitor.warning("No EndpointDataReference found with id " + id); return null; }); diff --git a/resources/tx-checkstyle-config.xml b/resources/tx-checkstyle-config.xml index 099908c86..cdce34857 100644 --- a/resources/tx-checkstyle-config.xml +++ b/resources/tx-checkstyle-config.xml @@ -19,7 +19,7 @@ - + @@ -47,12 +47,12 @@ - - - - - + + + + + + diff --git a/spi/edr-cache-spi/src/main/java/org/eclipse/tractusx/edc/edr/spi/EndpointDataReferenceEntry.java b/spi/edr-cache-spi/src/main/java/org/eclipse/tractusx/edc/edr/spi/EndpointDataReferenceEntry.java index 617c856cc..979980da0 100644 --- a/spi/edr-cache-spi/src/main/java/org/eclipse/tractusx/edc/edr/spi/EndpointDataReferenceEntry.java +++ b/spi/edr-cache-spi/src/main/java/org/eclipse/tractusx/edc/edr/spi/EndpointDataReferenceEntry.java @@ -19,6 +19,8 @@ import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import org.eclipse.edc.spi.types.domain.edr.EndpointDataReference; +import java.util.Objects; + import static java.util.Objects.requireNonNull; /** @@ -55,6 +57,11 @@ public boolean equals(Object o) { return transferProcessId.equals(that.transferProcessId); } + @Override + public int hashCode() { + return Objects.hash(assetId, agreementId, transferProcessId); + } + @JsonPOJOBuilder(withPrefix = "") public static class Builder { private final EndpointDataReferenceEntry entry;