Skip to content

Send each message's custom headers and credentials on pooled S3 connections - #512

Open
pacmano1 wants to merge 6 commits into
OpenIntegrationEngine:mainfrom
pacmano1:fix/s3-custom-headers-per-message
Open

pacmano1 wants to merge 6 commits into
OpenIntegrationEngine:mainfrom
pacmano1:fix/s3-custom-headers-per-message

Conversation

@pacmano1

@pacmano1 pacmano1 commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Closes #511.

The File Writer fills in ${...} variables in S3 custom headers for every message, but the pooled S3Connection kept the headers of the message that created the pool, so every later write sent the first message's values. Credentials had the same problem with Use Default Credential Provider Chain on: credentials taken from the message, such as ${user}, stuck at the first message's (found by Jon in review).

Change

  • FileDispatcher.send: after borrowing a connection, an S3 connection gets this message's headers.
  • S3Connection: keeps the headers in its own field (setCustomHeaders). It starts with the ones it was created with, and returning it to the pool puts those back. Not in schemeProps, because every connection in a pool shares the first message's S3SchemeProperties.
  • FileSystemConnectionFactory.getPoolKey: the S3 key includes the username and password whenever they're set. It left them out whenever the default chain was on, but S3Connection signs with them whenever they're set. Credentials that are set still take priority over the default chain, as before. With the default chain on and none set, every message still shares one pool.
  • Nothing else changes: other schemes, and the File Reader, which keeps its own headers. A header name on two rows still sends only the last value; that's noted on S3 File Writer: Custom HTTP Headers are stored as object metadata, not sent as headers #513.

Thread safety: Donkey clones the connector properties for each message, including a copy of the header map, and the pool hands a connection to one sender until it's returned, so the headers set on a borrowed connection belong to that sender's message.

Tests

  • FileDispatcherTest: two sends through one pooled S3Connection with a mocked S3 client, plain and with Write to Temporary File (the move uploads again), checking x-test-id on each upload. Both fail on main (expected:<[dir/message.txt=1, dir/message.txt=2]> but was:<[dir/message.txt=1, dir/message.txt=1]>).
  • S3ConnectionTest.testPassivateRestoresCustomHeaders: returning the connection to the pool puts back the headers it was created with.
  • FileSystemConnectionFactoryTest: three S3 pool keys. Default chain on with credentials set fails on main (s3://@us-west-2); default chain off, and on with no credentials, give the same keys as before.
  • Full build: donkey 36, server 881, client 21, command 6, no failures.

How to verify

Headers need an S3 bucket and credentials the engine can use, for example AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN and AWS_REGION in the engine's environment, with Use Default Credential Provider Chain on.

  1. New channel: Channel Reader source; source transformer JavaScript step $c('clinic', String(msg));; File Writer in S3 mode, S3 Bucket <bucket>/s3-headers, file name ${message.messageId}.txt, template ${message.rawData}; in Amazon S3 Advanced Settings, Custom HTTP Headers x-amz-meta-clinic = ${clinic} and x-test-id = ${message.messageId}.
  2. Deploy, then send clinic A and clinic B.
  3. aws s3api head-object --bucket <bucket> --key s3-headers/2.txt --query Metadata
    • Before: {"clinic": "clinic A", "x-test-id": "1"}
    • After: {"clinic": "clinic B", "x-test-id": "2"}

Credentials are easiest to see without AWS. Set AWS_ENDPOINT_URL_S3 in the engine's environment to an HTTP server that logs each request's Authorization header (it starts AWS4-HMAC-SHA256 Credential=<access key id>/) and answers 200.

  1. Same channel, but the transformer step is var p = String(msg).split(','); $c('user', p[0]); $c('pass', p[1]);, and the File Writer's Username is ${user} and Password ${pass}, with Use Default Credential Provider Chain still on.
  2. Send AKIAMSGONE,secretone and AKIAMSGTWO,secrettwo.
    • Before: both PUTs are signed with AKIAMSGONE.
    • After: the second is signed with AKIAMSGTWO.

Headers were live-tested against real S3 on Java 21 in October, on top of #506 (AWS SDK 2.55.12). Before: 2.txt carried message 1's values, with Keep Connection Open on and off. After: every object carried its own message's values, with Keep Connection Open on and off, and with the destination queue on and 2 threads (6 messages).

After the review changes, main and this branch were run side by side on Java 17 against a stand-in endpoint as above. On main, every message after the first carried message 1's headers with Keep Connection Open on and off, with 2 queue threads, and on both temporary file paths (anonymous re-upload, and the keyed server-side copy of the .tmp upload), and credentials from the message stuck at message 1's. On this branch each message carried its own headers and was signed with its own credentials. Blank credentials used the default chain on both.

Co-authored with Claude Code.

@mgaffigan

Copy link
Copy Markdown
Contributor

Can we test this in CI? s3mock or similar?

mgaffigan
mgaffigan previously approved these changes Oct 24, 2026
@github-actions

github-actions Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Test Results

  147 files  +1    147 suites  +1   5m 2s ⏱️ +55s
  997 tests +6    997 ✅ +6  0 💤 ±0  0 ❌ ±0 
1 315 runs  +6  1 309 ✅ +6  6 💤 ±0  0 ❌ ±0 

Results for commit f43bb6a. ± Comparison against base commit 8e5e63d.

♻️ This comment has been updated with latest results.

@pacmano1

Copy link
Copy Markdown
Contributor Author

Moto works for an end-to-end test. With #506's SDK, AWS_ENDPOINT_URL_S3 points the File connector at it with no code change, and MOTO_S3_CUSTOM_ENDPOINTS lets Moto take the SDK's bucket-in-host-name requests. Against motoserver/moto:5.2.4, #506 alone wrote message 2 with message 1's headers; #506 plus this fix wrote each message's own.

s3mock doesn't: it only reads the bucket from the path, and the SDK has no environment switch for path style. MinIO is gone from Docker Hub, and current LocalStack needs an account token.

So a Moto job in the integration harness can cover this without touching AWS. I only tried it on #506's SDK, not main's, so I'd add it as its own PR once #506 is in. Real AWS through GitHub OIDC is the other option, but it needs an AWS account the project is comfortable with.

gibson9583
gibson9583 previously approved these changes Oct 30, 2026

@gibson9583 gibson9583 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks safe to merge.

@jonbartels jonbartels left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fix works for the plain File Writer path, but a few things to address. See inline comments.

if (MapUtils.isNotEmpty(source)) {
for (Entry<String, List<String>> entry : source.entrySet()) {
for (String value : entry.getValue()) {
headers.put(entry.getKey(), value);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pre-existing, but this function is being rewritten: put inside the value loop keeps only the last value of a multi-valued header (['a','b'] -> b). Join the values or otherwise preserve them.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this one alone. Joining the values changes what gets written for anyone with a name on two rows today. It goes with #513, which changes how these headers are sent anyway. Added it there.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jonbartels is this blocking? I don't want to re-approve if you have further changes.

int stsDuration;
// Set by the File Writer for each message. 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<String, List<String>> customHeaders;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The root cause is wider than headers. The pool factory (FileSystemConnectionFactory) and each S3Connection keep the first message's FileSystemConnectionOptions. With the default credential chain on, username/password aren't in the pool key, but createCredentialsProvider still uses them when non-blank, so templated per-message credentials get stuck at message 1's values too. Fix here or file a follow-up?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed here in 058d352. The S3 pool key now includes the username and password whenever they're set, the same rule createCredentialsProvider uses. Credentials that are set still beat the default chain, as the tooltips say, so nothing changes for anyone else.

Measured against a stand-in S3 endpoint that logs the key each request is signed with. Default chain on, credentials from the message: on main, message 2 was signed with message 1's key, Keep Connection Open on or off. On this branch, with its own. Blank credentials still use the default chain.

Co-authored with Claude Code.


ThreadUtils.checkInterruptedStatus();
fileSystemConnection = fileConnector.getConnection(fileSystemOptions);
if (fileSystemConnection instanceof S3Connection && fileDispatcherProperties.getSchemeProperties() instanceof S3SchemeProperties) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An S3-only instanceof special case in the dispatcher. A general hook, e.g. FileSystemConnection.setOptions(options) on borrow or passing options into writeFile/move, would cover every scheme and every per-message option (see the credentials comment).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kept it S3-only. The file name and contents go in on every write. Apart from those, custom headers are the only per-message value any scheme applies to a connection that's already open. Everything that picks a connection (host, credentials, region, SFTP keys, FTP initial commands) is in that scheme's pool key, so a message with different values already gets a different connection. S3 credentials with the default chain on were the exception you found. A setOptions hook would have one implementation that does anything.

It wouldn't fix the credentials case either. The S3 client gets its credentials when the connection is built, so handing new ones to a borrowed connection changes nothing short of reconnecting. That fix is in the pool key, 058d352.

If another scheme ever gets a per-request value, that's the time for the hook.

Co-authored with Claude Code.

return ListObjectsV2Request.builder().bucket(bucketName).prefix(prefix).delimiter(DELIMITER);
}

public void setCustomHeaders(Map<String, List<String>> customHeaders) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

customHeaders is never cleared when the connection returns to the pool. Any caller that skips setCustomHeaders sends the previous message's (possibly message-derived) headers. Set customHeaders = null in passivate().

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 057702a. passivate() puts back the headers the connection was created with. With your next comment there's no null to go back to.

fileSystemConnection = fileConnector.getConnection(fileSystemOptions);
if (fileSystemConnection instanceof S3Connection && fileDispatcherProperties.getSchemeProperties() instanceof S3SchemeProperties) {
// A pooled connection keeps the headers it was created with; send this message's
((S3Connection) fileSystemConnection).setCustomHeaders(((S3SchemeProperties) fileDispatcherProperties.getSchemeProperties()).getCustomHeaders());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: the getSchemeProperties() instanceof S3SchemeProperties check is redundant. An S3Connection only comes from an S3 pool, so instanceof S3Connection alone is enough.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With Tony's pattern-matching version (321aad2) that check is now the cast, so I kept it.


Map<String, String> getCustomHeaders() {
Map<String, String> headers = new HashMap<String, String>();
Map<String, List<String>> source = customHeaders != null ? customHeaders : schemeProps.getCustomHeaders();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: the null fallback leaves two sources of truth for headers. Initialize customHeaders from schemeProps in the constructor and drop the ternary.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 057702a.

*/
@Test
public void pooledS3ConnectionSendsEachMessagesHeaders() throws Exception {
S3Connection connection = new S3Connection(new FileSystemConnectionOptions(true, null, null, schemeProperties("1")), 10000);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This builds a real S3Client that never gets closed before the field is swapped by reflection, so each run leaks a client. Close it first or add a package-private test constructor.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Closed before the swap, 194b6e3. A package-private constructor can't help here: the test is in connectors.file and S3Connection is in connectors.file.filesystems.

TestFileDispatcher dispatcher = new TestFileDispatcher();
dispatcher.setFileConnector(fileConnector);

assertEquals(Status.SENT, dispatcher.send(dispatcherProperties("1"), new ConnectorMessage()).getStatus());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please also cover the temporary-file path (setTemporary(true) -> writeFile + move). move re-sends getCustomHeaders() and isn't exercised here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 194b6e3: two messages with Write to Temporary File on, anonymous, so the move downloads the file and uploads it again. Both uploads carry each message's headers. Also checked the keyed path live: the .tmp upload carries the right headers and the move is a server-side copy.

@tonygermano tonygermano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left one inline suggestion.

The test uses Guice, which was removed in #519

The strategy used in that PR I think should work for this test as well.

pacmano1 and others added 5 commits November 24, 2026 11:31
The File Writer fills in ${...} variables in the S3 custom headers for
every message, but the pooled S3Connection kept the headers of the
message that created it. The pool key is only the credentials and the
region, so every later message reused the first message's values.

The File Writer now hands the borrowed connection the current message's
headers before writing. They live on the connection, not in its
S3SchemeProperties, because every connection in a pool shares the
properties of the message that created the pool. A borrowed connection
belongs to one sender until it is returned, so this is safe with several
queue or processing threads. Other schemes and the File Reader are
unchanged.

Reported as NextGen Connect issue 5116.

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Finnegan's Owner <44065187+pacmano1@users.noreply.github.com>
FileDispatcherTest swapped a mocked client into the S3Connection by
reflection without closing the real one the constructor built. Close it
first.

Also send two messages with Write to Temporary File on. On an anonymous
connection the move downloads the .tmp file and uploads it again with
the custom headers, so both uploads must carry the current message's
headers.

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Finnegan's Owner <44065187+pacmano1@users.noreply.github.com>
S3Connection read the headers set for the current message and fell back
to its scheme properties when none were set. It now starts with the
headers it was created with and reads only its own field, and returning
the connection to the pool puts those headers back, so a borrower that
doesn't set headers never sends the previous message's.

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Finnegan's Owner <44065187+pacmano1@users.noreply.github.com>
Co-authored-by: Tony Germano <tony@germano.name>
Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Finnegan's Owner <44065187+pacmano1@users.noreply.github.com>
With Use Default Credential Provider Chain on, the S3 pool key left out
the username and password, but S3Connection still signs with them
whenever they are set. A File Writer whose credentials come from the
message, such as ${user}, signed every later message with the first
message's credentials, with Keep Connection Open on or off.

Put them in the key whenever they are set, the same rule
S3Connection.createCredentialsProvider uses. Credentials that are set
still take priority over the default chain, as before. With the default
chain on and no credentials set, every message still shares one pool.

Reported by Jon Bartels in the review of this pull request.

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Finnegan's Owner <44065187+pacmano1@users.noreply.github.com>
@pacmano1
pacmano1 dismissed stale reviews from gibson9583 and mgaffigan via 058d352 November 24, 2026 20:10
@pacmano1
pacmano1 force-pushed the fix/s3-custom-headers-per-message branch from a86b5c3 to 058d352 Compare November 24, 2026 20:10
The comment said passivate() "puts the first ones back", which reads as
the first message's headers, the bug this pull request fixes. Say which
headers instead.

FileDispatcherTest matched the download transformer with a raw
ResponseTransformer, which added an unchecked warning to the server test
compile. Give the matcher its types.

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Finnegan's Owner <44065187+pacmano1@users.noreply.github.com>

@tonygermano tonygermano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving. My earlier asks are addressed.

Suggested release note for the PR description (optional, not a condition of merging):

Release Note

The File Writer now sends each message's S3 custom headers and credentials

With Amazon S3 selected, the File Writer reused the first message's custom HTTP headers for every later message while its connection stayed in the pool. A header such as x-amz-meta-clinic = ${clinic} was written with the first message's value on every object. The same happened to a username and password taken from the message when Use Default Credential Provider Chain was on: every message was signed with the first message's credentials.

Each message is now written with its own headers and credentials. Channels that use the same headers and credentials for every message are not affected.

If the credentials are different for each message, the File Writer now keeps a separate pool of connections for each distinct username and password. These pools are released when the connector stops, so a channel with many distinct credentials will hold more connections than before. Other file schemes already behave this way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

5 participants