diff --git a/server/src/main/java/com/mirth/connect/connectors/file/FileDispatcher.java b/server/src/main/java/com/mirth/connect/connectors/file/FileDispatcher.java index 29139928d..603cfca3c 100644 --- a/server/src/main/java/com/mirth/connect/connectors/file/FileDispatcher.java +++ b/server/src/main/java/com/mirth/connect/connectors/file/FileDispatcher.java @@ -19,6 +19,7 @@ import org.apache.logging.log4j.Logger; import com.mirth.connect.connectors.file.filesystems.FileSystemConnection; +import com.mirth.connect.connectors.file.filesystems.S3Connection; import com.mirth.connect.donkey.model.channel.ConnectorProperties; import com.mirth.connect.donkey.model.event.ConnectionStatusEventType; import com.mirth.connect.donkey.model.event.ErrorEventType; @@ -165,6 +166,11 @@ public Response send(ConnectorProperties connectorProperties, ConnectorMessage c ThreadUtils.checkInterruptedStatus(); fileSystemConnection = fileConnector.getConnection(fileSystemOptions); + if (fileSystemConnection instanceof S3Connection s3Connection + && fileDispatcherProperties.getSchemeProperties() instanceof S3SchemeProperties s3Properties) { + // A pooled connection keeps the headers it was created with; send this message's + s3Connection.setCustomHeaders(s3Properties.getCustomHeaders()); + } if (fileDispatcherProperties.isErrorOnExists() && fileSystemConnection.exists(filename, path)) { throw new IOException("Destination file already exists, will not overwrite."); } else if (fileDispatcherProperties.isTemporary()) { diff --git a/server/src/main/java/com/mirth/connect/connectors/file/filesystems/FileSystemConnectionFactory.java b/server/src/main/java/com/mirth/connect/connectors/file/filesystems/FileSystemConnectionFactory.java index f5ca58734..23c103d87 100644 --- a/server/src/main/java/com/mirth/connect/connectors/file/filesystems/FileSystemConnectionFactory.java +++ b/server/src/main/java/com/mirth/connect/connectors/file/filesystems/FileSystemConnectionFactory.java @@ -122,7 +122,9 @@ public String getPoolKey() { poolKey.append("s3://"); - if (!s3SchemeProperties.isUseDefaultCredentialProviderChain()) { + // S3Connection.createCredentialsProvider signs with the username and password whenever + // they are set, even with the default provider chain on, so they belong in the key then too + if (!s3SchemeProperties.isUseDefaultCredentialProviderChain() || StringUtils.isNotBlank(username) || StringUtils.isNotBlank(password)) { poolKey.append(username); poolKey.append(':'); poolKey.append(password); diff --git a/server/src/main/java/com/mirth/connect/connectors/file/filesystems/S3Connection.java b/server/src/main/java/com/mirth/connect/connectors/file/filesystems/S3Connection.java index f988649dd..f5ef97447 100644 --- a/server/src/main/java/com/mirth/connect/connectors/file/filesystems/S3Connection.java +++ b/server/src/main/java/com/mirth/connect/connectors/file/filesystems/S3Connection.java @@ -157,10 +157,16 @@ public void populateSourceMap(Map sourceMap) { S3Client client; StsClient sts; int stsDuration; + // The headers sent with each write: the ones this connection was created with, replaced by + // each message's while the File Writer has it, and put back by passivate(). + // schemeProps belongs to the message that created the pool and is shared by every connection in + // it, so per-message headers can't go there. + Map> customHeaders; public S3Connection(FileSystemConnectionOptions fileSystemOptions, int timeout) throws Exception { this.fileSystemOptions = fileSystemOptions; schemeProps = (S3SchemeProperties) fileSystemOptions.getSchemeProperties(); + customHeaders = schemeProps.getCustomHeaders(); clientBuilder = S3Client.builder(); clientBuilder.httpClientBuilder(createClientConfiguration(timeout)); @@ -271,11 +277,15 @@ ListObjectsV2Request.Builder createListRequest(String bucketName, String prefix) return ListObjectsV2Request.builder().bucket(bucketName).prefix(prefix).delimiter(DELIMITER); } + public void setCustomHeaders(Map> customHeaders) { + this.customHeaders = customHeaders; + } + Map getCustomHeaders() { Map headers = new HashMap(); - if (MapUtils.isNotEmpty(schemeProps.getCustomHeaders())) { - for (Entry> entry : schemeProps.getCustomHeaders().entrySet()) { + if (MapUtils.isNotEmpty(customHeaders)) { + for (Entry> entry : customHeaders.entrySet()) { for (String value : entry.getValue()) { headers.put(entry.getKey(), value); } @@ -631,7 +641,9 @@ public void disconnect() {} public void activate() {} @Override - public void passivate() {} + public void passivate() { + customHeaders = schemeProps.getCustomHeaders(); + } @Override public void destroy() { diff --git a/server/src/test/java/com/mirth/connect/connectors/file/FileDispatcherTest.java b/server/src/test/java/com/mirth/connect/connectors/file/FileDispatcherTest.java new file mode 100644 index 000000000..2fe457282 --- /dev/null +++ b/server/src/test/java/com/mirth/connect/connectors/file/FileDispatcherTest.java @@ -0,0 +1,174 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: Open Integration Engine + +package com.mirth.connect.connectors.file; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.lang.reflect.Field; +import java.net.URI; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.ArgumentMatchers; + +import com.mirth.connect.connectors.file.filesystems.S3Connection; +import com.mirth.connect.donkey.model.message.ConnectorMessage; +import com.mirth.connect.donkey.model.message.Status; +import com.mirth.connect.donkey.model.message.attachment.AttachmentHandlerProvider; +import com.mirth.connect.donkey.testing.StaticOverride; +import com.mirth.connect.server.controllers.ConfigurationController; +import com.mirth.connect.server.controllers.ControllerFactory; +import com.mirth.connect.server.controllers.EventController; + +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.core.sync.ResponseTransformer; +import software.amazon.awssdk.http.AbortableInputStream; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; + +public class FileDispatcherTest { + + private static StaticOverride factoryOverride; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + ControllerFactory controllerFactory = mock(ControllerFactory.class); + EventController eventController = mock(EventController.class); + when(controllerFactory.createEventController()).thenReturn(eventController); + ConfigurationController configurationController = mock(ConfigurationController.class); + when(controllerFactory.createConfigurationController()).thenReturn(configurationController); + + factoryOverride = StaticOverride.install(ControllerFactory.class, "factory", controllerFactory); + } + + @AfterClass + public static void restoreControllerFactory() { + if (factoryOverride != null) { + factoryOverride.close(); + } + } + + /* + * The pool hands the same S3Connection to every message, so each write must carry the custom + * headers of the message being written, not those of the message that created the connection. + */ + @Test + public void pooledS3ConnectionSendsEachMessagesHeaders() throws Exception { + S3Client client = mockClient(); + TestFileDispatcher dispatcher = dispatcher(connection(client)); + + assertEquals(Status.SENT, dispatcher.send(dispatcherProperties("1", false), new ConnectorMessage()).getStatus()); + assertEquals(Status.SENT, dispatcher.send(dispatcherProperties("2", false), new ConnectorMessage()).getStatus()); + + assertEquals(List.of("dir/message.txt=1", "dir/message.txt=2"), uploads(client, 2)); + } + + /* + * With Write to Temporary File on, the File Writer uploads a .tmp file and then moves it. On an + * anonymous connection the move downloads the file and uploads it again with the custom headers, + * so both uploads must carry the headers of the message being written. + */ + @Test + public void pooledS3ConnectionSendsEachMessagesHeadersThroughTemporaryFile() throws Exception { + S3Client client = mockClient(); + when(client.getObject(any(GetObjectRequest.class), ArgumentMatchers.>any())).thenAnswer(invocation -> { + ResponseTransformer transformer = invocation.getArgument(1); + return transformer.transform(GetObjectResponse.builder().contentLength(7L).build(), AbortableInputStream.create(new ByteArrayInputStream("message".getBytes()))); + }); + TestFileDispatcher dispatcher = dispatcher(connection(client)); + + assertEquals(Status.SENT, dispatcher.send(dispatcherProperties("1", true), new ConnectorMessage()).getStatus()); + assertEquals(Status.SENT, dispatcher.send(dispatcherProperties("2", true), new ConnectorMessage()).getStatus()); + + assertEquals(List.of("dir/message.txt.tmp=1", "dir/message.txt=1", "dir/message.txt.tmp=2", "dir/message.txt=2"), uploads(client, 4)); + } + + private static S3Client mockClient() { + S3Client client = mock(S3Client.class); + when(client.putObject(any(PutObjectRequest.class), any(RequestBody.class))).thenReturn(PutObjectResponse.builder().build()); + return client; + } + + /* + * An anonymous S3Connection that uses the given client. The client field is package-private to + * the filesystems package, and FileConnector's getConnection is protected to this one, so the + * client is set by reflection, after closing the real one the constructor built. + */ + private static S3Connection connection(S3Client client) throws Exception { + S3Connection connection = new S3Connection(new FileSystemConnectionOptions(true, null, null, schemeProperties("1")), 10000); + Field clientField = S3Connection.class.getDeclaredField("client"); + clientField.setAccessible(true); + ((S3Client) clientField.get(connection)).close(); + clientField.set(connection, client); + return connection; + } + + private static TestFileDispatcher dispatcher(S3Connection connection) throws Exception { + FileConnector fileConnector = mock(FileConnector.class); + URI uri = new URI("s3://bucket/dir"); + when(fileConnector.getEndpointURI(any(), any(), any(), anyBoolean())).thenReturn(uri); + when(fileConnector.getPathPart(any())).thenReturn("bucket/dir"); + when(fileConnector.getConnection(any())).thenReturn(connection); + + TestFileDispatcher dispatcher = new TestFileDispatcher(); + dispatcher.setFileConnector(fileConnector); + return dispatcher; + } + + // The key and x-test-id header of each upload, in the order they were made + private static List uploads(S3Client client, int count) { + ArgumentCaptor requests = ArgumentCaptor.forClass(PutObjectRequest.class); + verify(client, times(count)).putObject(requests.capture(), any(RequestBody.class)); + List uploads = new ArrayList(); + for (PutObjectRequest request : requests.getAllValues()) { + uploads.add(request.key() + "=" + request.metadata().get("x-test-id")); + } + return uploads; + } + + private static S3SchemeProperties schemeProperties(String headerValue) { + S3SchemeProperties schemeProperties = new S3SchemeProperties(); + schemeProperties.setRegion(Region.US_WEST_2.id()); + schemeProperties.getCustomHeaders().put("x-test-id", Collections.singletonList(headerValue)); + return schemeProperties; + } + + private static FileDispatcherProperties dispatcherProperties(String headerValue, boolean temporary) { + FileDispatcherProperties properties = new FileDispatcherProperties(); + properties.setScheme(FileScheme.S3); + properties.setSchemeProperties(schemeProperties(headerValue)); + properties.setHost("bucket/dir"); + properties.setAnonymous(true); + properties.setOutputPattern("message.txt"); + properties.setTemplate("message"); + properties.setKeepConnectionOpen(true); + properties.setTemporary(temporary); + return properties; + } + + private static class TestFileDispatcher extends FileDispatcher { + @Override + protected AttachmentHandlerProvider getAttachmentHandlerProvider() { + AttachmentHandlerProvider provider = mock(AttachmentHandlerProvider.class); + when(provider.reAttachMessage(any(), any(), any(), anyBoolean(), anyBoolean())).thenReturn("message".getBytes()); + return provider; + } + } +} diff --git a/server/src/test/java/com/mirth/connect/connectors/file/filesystems/FileSystemConnectionFactoryTest.java b/server/src/test/java/com/mirth/connect/connectors/file/filesystems/FileSystemConnectionFactoryTest.java index 963e56dc5..d1495bbbc 100644 --- a/server/src/test/java/com/mirth/connect/connectors/file/filesystems/FileSystemConnectionFactoryTest.java +++ b/server/src/test/java/com/mirth/connect/connectors/file/filesystems/FileSystemConnectionFactoryTest.java @@ -10,6 +10,7 @@ import com.mirth.connect.connectors.file.FTPSchemeProperties; import com.mirth.connect.connectors.file.FileScheme; import com.mirth.connect.connectors.file.FileSystemConnectionOptions; +import com.mirth.connect.connectors.file.S3SchemeProperties; public class FileSystemConnectionFactoryTest { @@ -49,5 +50,36 @@ public void testFTPGetPoolKeyWithInitialCommands() { assertEquals(expected, factory.getPoolKey()); } + @Test + public void testS3GetPoolKeyWithoutDefaultChain() { + FileSystemConnectionFactory factory = s3Factory(false, "username", "password"); + + assertEquals("s3://username:password@us-west-2", factory.getPoolKey()); + } + + @Test + public void testS3GetPoolKeyDefaultChainWithCredentials() { + // The connection signs with credentials that are set even when the default chain is on, so + // messages with different credentials must not share a pool + FileSystemConnectionFactory factory = s3Factory(true, "username", "password"); + + assertEquals("s3://username:password@us-west-2", factory.getPoolKey()); + } + + @Test + public void testS3GetPoolKeyDefaultChainWithoutCredentials() { + assertEquals("s3://@us-west-2", s3Factory(true, "", "").getPoolKey()); + assertEquals("s3://@us-west-2", s3Factory(true, null, null).getPoolKey()); + } + + private static FileSystemConnectionFactory s3Factory(boolean useDefaultCredentialProviderChain, String username, String password) { + S3SchemeProperties s3SchemeProps = new S3SchemeProperties(); + s3SchemeProps.setUseDefaultCredentialProviderChain(useDefaultCredentialProviderChain); + s3SchemeProps.setUseTemporaryCredentials(false); + s3SchemeProps.setRegion("us-west-2"); + FileSystemConnectionOptions options = new FileSystemConnectionOptions(false, username, password, s3SchemeProps); + return new FileSystemConnectionFactory(FileScheme.S3, options, "bucket", -1, false, false, 0); + } + } diff --git a/server/src/test/java/com/mirth/connect/connectors/file/filesystems/S3ConnectionTest.java b/server/src/test/java/com/mirth/connect/connectors/file/filesystems/S3ConnectionTest.java index 147e35da8..d7b62976c 100644 --- a/server/src/test/java/com/mirth/connect/connectors/file/filesystems/S3ConnectionTest.java +++ b/server/src/test/java/com/mirth/connect/connectors/file/filesystems/S3ConnectionTest.java @@ -305,6 +305,21 @@ public void testGetCustomHeaders() throws Exception { assertEquals("Value", s3Conn.getCustomHeaders().get("X-Custom-Header")); } + @Test + public void testPassivateRestoresCustomHeaders() throws Exception { + S3Connection s3Conn = getConnection(); + s3Conn.schemeProps.getCustomHeaders().put("X-Custom-Header", Collections.singletonList("Created")); + Map> messageHeaders = new HashMap>(); + messageHeaders.put("X-Custom-Header", Collections.singletonList("Message")); + + s3Conn.setCustomHeaders(messageHeaders); + assertEquals("Message", s3Conn.getCustomHeaders().get("X-Custom-Header")); + + // Returning the connection to the pool puts back the headers it was created with + s3Conn.passivate(); + assertEquals("Created", s3Conn.getCustomHeaders().get("X-Custom-Header")); + } + @Test public void testAddMetadataIfNotNull() throws Exception { S3Connection s3Conn = getConnection();