Light, fluffy, and always free - The AWS Local Emulator alternative
fix(sqs): set SenderId from caller principal instead of queue owner (#5066)
Vũ Thế Huy840d1bb6c1bf
diff --git a/docs/services/lambda.md b/docs/services/lambda.mdindex 73fefbc259..f6a3f1f6ea 100644--- a/docs/services/lambda.md+++ b/docs/services/lambda.md@@ -844,7 +844,7 @@ FLOCI_DNS_EXTRA_SUFFIXES=localhost.localstack.cloud,localhost.example.internal### Real AWS Credentials-By default, a Lambda function whose execution role exists in Floci's IAM store receives temporary credentials for that role. SDK calls made by the function identify as `assumed-role/<role>/floci-session`, and IAM enforcement evaluates the role's policies. If the role is unknown to Floci, the container keeps the compatibility fallback described below.+By default, a Lambda function whose execution role exists in Floci's IAM store receives temporary credentials for that role. SDK calls made by the function identify as `assumed-role/<role>/<function-name>`, and IAM enforcement evaluates the role's policies. If the role is unknown to Floci, the container keeps the compatibility fallback described below.For hybrid local/cloud testing, where some services are emulated and others hit real AWS, you can mount your host `~/.aws` directory into Lambda containers:diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AccountContextFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/AccountContextFilter.javaindex f19791c60b..25c0267b44 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/AccountContextFilter.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/AccountContextFilter.java@@ -70,13 +70,18 @@ public class AccountContextFilter implements ContainerRequestFilter {Object pinnedAccount = ctx.getProperty(PINNED_ACCOUNT_PROPERTY);if (pinnedAccount != null) {requestContext.setAccountId(pinnedAccount.toString());+ requestContext.setAccessKeyId(null);+ requestContext.setSessionToken(null);applyRegion(regionResolver.resolveRegionFromAuth(null));return;}+ String sessionToken = extractSessionToken(ctx);String auth = ctx.getHeaderString("Authorization");- if (auth != null && !auth.isEmpty()) {- String akid = accountResolver.extractAccessKeyId(auth);+ String akid = auth != null && !auth.isEmpty() ? accountResolver.extractAccessKeyId(auth) : null;+ if (akid != null) {requestContext.setAccountId(resolveAccount(akid, accountResolver.resolve(auth)));+ requestContext.setAccessKeyId(akid);+ requestContext.setSessionToken(sessionToken);String region = regionResolver.resolveRegionFromAuth(auth);applyRegion(region);rejectUnknownRegion(ctx, region, SigV4CredentialScope.serviceName(auth));@@ -84,9 +89,11 @@ public class AccountContextFilter implements ContainerRequestFilter {} else {String credential = ctx.getUriInfo().getQueryParameters().getFirst("X-Amz-Credential");if (credential != null && !credential.isEmpty()) {- String akid = accountResolver.extractPresignedAccessKeyId(credential);+ String presignedAkid = accountResolver.extractPresignedAccessKeyId(credential);requestContext.setAccountId(- resolveAccount(akid, accountResolver.resolveFromPresignedCredential(credential)));+ resolveAccount(presignedAkid, accountResolver.resolveFromPresignedCredential(credential)));+ requestContext.setAccessKeyId(presignedAkid);+ requestContext.setSessionToken(sessionToken);String region = regionResolver.resolveRegionFromPresignedCredential(credential);applyRegion(region);rejectUnknownRegion(ctx, region, SigV4CredentialScope.serviceNameFromCredential(credential));@@ -94,11 +101,25 @@ public class AccountContextFilter implements ContainerRequestFilter {SigV4CredentialScope.serviceNameFromCredential(credential).orElse(null));} else {requestContext.setAccountId(accountResolver.resolve(null));+ requestContext.setAccessKeyId(null);+ requestContext.setSessionToken(null);applyRegion(regionResolver.resolveRegionFromAuth(null));}}}+ private String extractSessionToken(ContainerRequestContext ctx) {+ String token = ctx.getHeaderString("X-Amz-Security-Token");+ if (token != null && !token.isBlank()) {+ return token.trim();+ }+ token = ctx.getUriInfo().getQueryParameters().getFirst("X-Amz-Security-Token");+ if (token != null && !token.isBlank()) {+ return token.trim();+ }+ return null;+ }+/*** The region and its partition travel together: the SigV4 credential scope is the only* place a request says which partition it belongs to (a China client signs {@code cn-north-1}diff --git a/src/main/java/io/github/hectorvent/floci/core/common/RequestContext.java b/src/main/java/io/github/hectorvent/floci/core/common/RequestContext.javaindex d93d390927..cb7adced20 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/RequestContext.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/RequestContext.java@@ -13,6 +13,8 @@ public class RequestContext {private String accountId;private String region;private String partition;+ private String accessKeyId;+ private String sessionToken;public String getAccountId() {return accountId;@@ -42,4 +44,20 @@ public class RequestContext {public void setPartition(String partition) {this.partition = partition;}++ public String getAccessKeyId() {+ return accessKeyId;+ }++ public void setAccessKeyId(String accessKeyId) {+ this.accessKeyId = accessKeyId;+ }++ public String getSessionToken() {+ return sessionToken;+ }++ public void setSessionToken(String sessionToken) {+ this.sessionToken = sessionToken;+ }}diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentials.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentials.javaindex 8f44ca8061..d365222af0 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentials.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentials.java@@ -96,6 +96,7 @@ final class Ec2InstanceCredentials {role.getArn(), now.plusSeconds(3600), null, account);session.setEc2InstanceId(instance.getInstanceId());session.setEc2RoleId(role.getRoleId());+ session.setAssumedRoleId(role.getRoleId() + ":" + instance.getInstanceId());iam.registerEc2InstanceSession(session);history.add(new Issued(session, role.getRoleId(), instance.getIamInstanceProfileArn()));return Optional.of(session);diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskRoleCredentials.java b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskRoleCredentials.javaindex 452a5f32a8..f5b4f47437 100644--- a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskRoleCredentials.java+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsTaskRoleCredentials.java@@ -74,6 +74,11 @@ public class EcsTaskRoleCredentials {"ASIA" + random(UPPER_ALPHANUMERIC, 16), randomBase64(30), randomBase64(48),roleArn, now.plusSeconds(ttlSeconds), null, accountId);session.setEcsTaskArn(taskArn);+ String taskSessionName = taskArn.contains("/") ? taskArn.substring(taskArn.lastIndexOf('/') + 1) : taskArn;+ session.setRoleSessionName(taskSessionName);+ if (role.get().getRoleId() != null) {+ session.setAssumedRoleId(role.get().getRoleId() + ":" + taskSessionName);+ }iamService.registerEcsTaskRoleSession(session);String path = "/v2/credentials/" + UUID.randomUUID();diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsController.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsController.javaindex f7d44cc5a3..7a26928e5a 100644--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsController.java+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsController.java@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.eks.model.Cluster;import io.github.hectorvent.floci.services.eks.model.EksPodIdentityCredentialsResponse;import io.github.hectorvent.floci.services.eks.model.PodIdentityAssociation;import io.github.hectorvent.floci.services.iam.IamService;+import io.github.hectorvent.floci.services.iam.model.IamRole;import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;import jakarta.ws.rs.GET;@@ -133,8 +134,15 @@ public class EksPodIdentityCredentialsController {String sessionToken = randomSecret(200);Instant expiration = Instant.now().plus(Duration.ofHours(1));+ String sessionName = podIdentitySessionName(cluster.getName(), association.serviceAccount());+ String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : roleArn;+ Optional<IamRole> role = iamService.findRole(roleAccountId, roleName);+ String assumedRoleId = role.map(IamRole::getRoleId).filter(id -> !id.isBlank())+ .map(id -> id + ":" + sessionName)+ .orElse(null);+iamService.registerSession(accessKeyId, secretAccessKey, sessionToken, roleArn,- expiration, association.policy(), callerAccountId);+ expiration, association.policy(), callerAccountId, sessionName, assumedRoleId);EksPodIdentityCredentialsResponse response = new EksPodIdentityCredentialsResponse(accessKeyId,@@ -169,4 +177,15 @@ public class EksPodIdentityCredentialsController {}return sb.toString();}++ private String podIdentitySessionName(String clusterName, String serviceAccount) {+ String randomSuffix = randomId(8);+ String prefix = "eks-";+ String base = prefix + (clusterName != null && !clusterName.isBlank() ? clusterName + "-" : "") + serviceAccount;+ int maxBaseLen = 64 - 1 - randomSuffix.length();+ if (base.length() > maxBaseLen) {+ base = base.substring(0, maxBaseLen);+ }+ return base + "-" + randomSuffix;+ }}diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.javaindex d996de1c1d..7d3d5743ce 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java@@ -3424,12 +3424,22 @@ public class IamService implements SessionAccountLookup, ResourceProvider {/** Stores a non-expiring Lambda execution-role session with its session token. */public void registerLambdaExecutionRoleSession(String accountId, String sessionAccessKeyId,String secretAccessKey, String sessionToken, String roleArn) {+ registerLambdaExecutionRoleSession(accountId, sessionAccessKeyId, secretAccessKey, sessionToken, roleArn,+ null, null);+ }++ /** Stores a non-expiring Lambda execution-role session with its session token and assumed role ID. */+ public void registerLambdaExecutionRoleSession(String accountId, String sessionAccessKeyId,+ String secretAccessKey, String sessionToken, String roleArn,+ String roleSessionName, String assumedRoleId) {if (accountId == null || accountId.isBlank()) {throw new IllegalArgumentException("Lambda function account ID must not be blank");}SessionCredential session = new SessionCredential(sessionAccessKeyId, secretAccessKey, sessionToken, roleArn, null, null, accountId);session.setLambdaExecutionRole(true);+ session.setRoleSessionName(roleSessionName);+ session.setAssumedRoleId(assumedRoleId);if (sessions instanceof AccountAwareStorageBackend<SessionCredential> aware) {aware.putForAccount(accountId, sessionAccessKeyId, session);} else {@@ -3750,16 +3760,60 @@ public class IamService implements SessionAccountLookup, ResourceProvider {}public Optional<String> resolveCallerUserId(String accessKeyId) {- Optional<SessionCredential> sessionOpt = findSessionForCallerContext(accessKeyId);- if (sessionOpt.isEmpty()) {+ return resolveCallerUserId(accessKeyId, null);+ }++ public Optional<String> resolveCallerUserId(String accessKeyId, String sessionToken) {+ if (accessKeyId == null || accessKeyId.isBlank()) {return Optional.empty();}- SessionCredential session = sessionOpt.get();- if (session.getExpiration() != null && session.getExpiration().isBefore(Instant.now())) {- deleteSession(accessKeyId, session);- return Optional.empty();++ Optional<AccessKey> akOpt = accessKeys.get(accessKeyId);+ if (akOpt.isPresent()) {+ String userName = akOpt.get().getUserName();+ return users.get(userName).map(IamUser::getUserId);}- return Optional.ofNullable(session.getAssumedRoleId());++ Optional<SessionCredential> sessionOpt = findSessionForCallerContext(accessKeyId);+ if (sessionOpt.isPresent()) {+ SessionCredential session = sessionOpt.get();+ if (session.getExpiration() != null && session.getExpiration().isBefore(Instant.now())) {+ deleteSession(accessKeyId, session);+ return Optional.empty();+ }+ if (isTemporaryAccessKey(accessKeyId) && session.getSessionToken() != null+ && !hasMatchingSessionToken(session, sessionToken)) {+ return Optional.empty();+ }+ if (session.getAssumedRoleId() != null) {+ return Optional.of(session.getAssumedRoleId());+ } else if (session.getEc2RoleId() != null && session.getEc2InstanceId() != null) {+ return Optional.of(session.getEc2RoleId() + ":" + session.getEc2InstanceId());+ } else if (session.getRoleArn() != null) {+ String roleArn = session.getRoleArn();+ String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : roleArn;+ String accountId = AwsArnUtils.accountOrDefault(roleArn,+ session.getOriginAccountId() != null ? session.getOriginAccountId() : regionResolver.getAccountId());+ Optional<IamRole> roleOpt = findRole(accountId, roleName);+ String roleId = roleOpt.map(IamRole::getRoleId).filter(id -> !id.isBlank()).orElse(null);+ if (roleId != null) {+ String sessionName = session.getRoleSessionName();+ if (sessionName == null || sessionName.isBlank()) {+ if (session.getEc2InstanceId() != null) {+ sessionName = session.getEc2InstanceId();+ } else if (session.getEcsTaskArn() != null) {+ String taskArn = session.getEcsTaskArn();+ sessionName = taskArn.contains("/") ? taskArn.substring(taskArn.lastIndexOf('/') + 1) : taskArn;+ } else {+ sessionName = "floci-session";+ }+ }+ return Optional.of(roleId + ":" + sessionName);+ }+ }+ }++ return Optional.empty();}/** Temporary credentials are the ones STS mints, distinguished by the {@code ASIA} prefix. */diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.javaindex 42efacc2d0..8f16295cd5 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java@@ -133,7 +133,8 @@ public class StsQueryHandler {String sessionRoleArn = canonicalRoleArn(role, accountId, roleName);String assumedRoleArn = assumedRoleArn(sessionRoleArn, accountId, roleName, sessionName);- String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;+ String roleId = (role != null && role.getRoleId() != null) ? role.getRoleId() : ("AROA" + randomId(16));+ String assumedRoleId = roleId + ":" + sessionName;// Register session so IAM enforcement can resolve the role's policies, RDS/ElastiCache// IAM token validation can find the temporary secret key, and account routing can map@@ -237,9 +238,13 @@ public class StsQueryHandler {String accountId = regionResolver.getAccountId();String authorization = headers == null ? null : headers.getHeaderString("Authorization");String accessKeyId = authorization == null ? null : accountResolver.extractAccessKeyId(authorization);+ String sessionToken = headers == null ? null : headers.getHeaderString("X-Amz-Security-Token");+ if (sessionToken == null && params != null) {+ sessionToken = getParam(params, "X-Amz-Security-Token");+ }String arn = iamService.resolveCallerArn(accessKeyId).orElse(regionResolver.buildGlobalArn("iam", accountId, "root"));- String userId = iamService.resolveCallerUserId(accessKeyId).orElse(accountId);+ String userId = iamService.resolveCallerUserId(accessKeyId, sessionToken).orElse(accountId);String result = new XmlBuilder().elem("UserId", userId).elem("Account", accountId)diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/LambdaExecutionRoleCredentials.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/LambdaExecutionRoleCredentials.javaindex 4a69fdd8ef..639798caa4 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/LambdaExecutionRoleCredentials.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/LambdaExecutionRoleCredentials.java@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.lambda.launcher;import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.services.iam.IamService;+import io.github.hectorvent.floci.services.iam.model.IamRole;import io.github.hectorvent.floci.services.iam.model.SessionCreds;import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;import jakarta.enterprise.context.ApplicationScoped;@@ -74,7 +75,8 @@ public class LambdaExecutionRoleCredentials {}String roleAccountId = AwsArnUtils.accountOrDefault(roleArn, functionAccountId);- if (iamService.findRole(roleAccountId, roleName).isEmpty()) {+ Optional<IamRole> role = iamService.findRole(roleAccountId, roleName);+ if (role.isEmpty()) {return Optional.empty();}@@ -82,9 +84,11 @@ public class LambdaExecutionRoleCredentials {"ASIA" + random(UPPER_ALPHANUMERIC, 16),random(SECRET_CHARACTERS, 40),random(SECRET_CHARACTERS, 200));+ String functionName = function.getFunctionName();+ String assumedRoleId = role.get().getRoleId() != null ? role.get().getRoleId() + ":" + functionName : null;iamService.registerLambdaExecutionRoleSession(functionAccountId, credentials.accessKeyId(), credentials.secretAccessKey(),- credentials.sessionToken(), roleArn);+ credentials.sessionToken(), roleArn, functionName, assumedRoleId);return Optional.of(credentials);}diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.javaindex f42f128d62..81a978b2e7 100644--- a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java+++ b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.common.Resettable;+import io.github.hectorvent.floci.core.common.ServicePrincipals;import io.github.hectorvent.floci.core.common.SsrfProtection;import io.github.hectorvent.floci.core.resource.ExplorerResource;import io.github.hectorvent.floci.core.resource.ResourceProvider;@@ -1948,7 +1949,7 @@ public class SnsService implements Resettable, ResourceProvider {for (int attempt = 1; attempt <= SQS_SUBSCRIPTION_DELIVERY_ATTEMPTS; attempt++) {try {sqsService.sendMessage(queueUrl, body, null, messageGroupId,- messageDeduplicationId, sqsAttributes, region);+ messageDeduplicationId, sqsAttributes, null, ServicePrincipals.of("sns"), region);LOG.debugv("Delivered SNS message to SQS: {0} ({1}) raw={2}",sub.getEndpoint(), queueUrl, rawDelivery);return;@@ -1977,7 +1978,8 @@ public class SnsService implements Resettable, ResourceProvider {deadLetterDeduplicationId = sha256(messageId + "\0" + sub.getSubscriptionArn());}sqsService.sendMessage(sqsArnToUrl(deadLetterTargetArn), body, null,- deadLetterGroupId, deadLetterDeduplicationId, sqsAttributes, deadLetterRegion);+ deadLetterGroupId, deadLetterDeduplicationId, sqsAttributes, null,+ ServicePrincipals.of("sns"), deadLetterRegion);LOG.warnv("SNS delivery to {0} failed after {1} attempts; sent notification to subscription DLQ {2}",sub.getEndpoint(), SQS_SUBSCRIPTION_DELIVERY_ATTEMPTS, deadLetterTargetArn);return;diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsJsonHandler.javaindex 626f17565e..ba4d50dca8 100644--- a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsJsonHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsJsonHandler.java@@ -224,7 +224,8 @@ public class SqsJsonHandler {.path("AWSTraceHeader").path("StringValue").asText(null);Message msg = sqsService.sendMessage(queueUrl, messageBody, delaySeconds,- messageGroupId, messageDeduplicationId, messageAttributes, awsTraceHeader, region);+ messageGroupId, messageDeduplicationId, messageAttributes, awsTraceHeader,+ sqsService.resolveCallerSenderId(queueUrl), region);ObjectNode response = objectMapper.createObjectNode();response.put("MessageId", msg.getMessageId());@@ -263,7 +264,7 @@ public class SqsJsonHandler {List<Message> messages = sqsService.receiveMessage(queueUrl, maxMessages,visibilityTimeout, waitTimeSeconds, region);- String senderId = sqsService.senderIdFor(queueUrl);+ String defaultSenderId = sqsService.senderIdFor(queueUrl);ObjectNode response = objectMapper.createObjectNode();// Match AWS: omit the Messages field entirely when no messages are@@ -286,6 +287,7 @@ public class SqsJsonHandler {}msgNode.put("Body", msg.getBody());+ String senderId = msg.getSenderId() != null ? msg.getSenderId() : defaultSenderId;writeSystemAttributesJson(msgNode, msg, requestedAttrs, senderId);if (!selectedMessageAttrs.isEmpty()) {@@ -409,12 +411,13 @@ public class SqsJsonHandler {sqsService.validateBatchPayloadSize(queueUrl, region, totalSize);+ String senderId = sqsService.resolveCallerSenderId(queueUrl);for (ParsedEntry parsed : parsedEntries) {String id = parsed.id();try {Message msg = sqsService.sendMessage(queueUrl, parsed.body(), parsed.delay(),parsed.groupId(), parsed.dedupId(), parsed.attributes(),- parsed.awsTraceHeader(), region);+ parsed.awsTraceHeader(), senderId, region);ObjectNode success = objectMapper.createObjectNode();success.put("Id", id);success.put("MessageId", msg.getMessageId());diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsQueryHandler.javaindex 3d1720553d..5c1f7f0743 100644--- a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsQueryHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsQueryHandler.java@@ -250,7 +250,8 @@ public class SqsQueryHandler {}Message msg = sqsService.sendMessage(queueUrl, body, delaySeconds, messageGroupId,- messageDeduplicationId, messageAttributes, awsTraceHeader, region);+ messageDeduplicationId, messageAttributes, awsTraceHeader,+ sqsService.resolveCallerSenderId(queueUrl), region);XmlBuilder xml = new XmlBuilder().elem("MessageId", msg.getMessageId())@@ -276,7 +277,7 @@ public class SqsQueryHandler {Set<String> requestedMessageAttrs = new LinkedHashSet<>(collectIndexed(params, "MessageAttributeName."));List<Message> messages = sqsService.receiveMessage(queueUrl, maxMessages, visibilityTimeout, waitTimeSeconds, region);- String senderId = sqsService.senderIdFor(queueUrl);+ String defaultSenderId = sqsService.senderIdFor(queueUrl);XmlBuilder xml = new XmlBuilder();for (Message msg : messages) {@@ -291,6 +292,7 @@ public class SqsQueryHandler {xml.elem("MD5OfMessageAttributes", messageAttrsMd5);}xml.elem("Body", msg.getBody());+ String senderId = msg.getSenderId() != null ? msg.getSenderId() : defaultSenderId;writeSystemAttributesXml(xml, msg, requestedAttrs, senderId);if (!selectedMessageAttrs.isEmpty()) {for (Map.Entry<String, MessageAttributeValue> entry : selectedMessageAttrs.entrySet()) {@@ -403,12 +405,13 @@ public class SqsQueryHandler {sqsService.validateBatchPayloadSize(queueUrl, region, totalSize);+ String senderId = sqsService.resolveCallerSenderId(queueUrl);for (ParsedEntry parsed : parsedEntries) {String id = parsed.id();try {Message msg = sqsService.sendMessage(queueUrl, parsed.body(), parsed.delay(),parsed.groupId(), parsed.dedupId(), parsed.attributes(),- parsed.awsTraceHeader(), region);+ parsed.awsTraceHeader(), senderId, region);xml.start("SendMessageBatchResultEntry").elem("Id", id).elem("MessageId", msg.getMessageId())diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.javaindex f3ac7d7871..37ff8cd4d2 100644--- a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java+++ b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.AwsRegions;import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.common.RequestContext;import io.github.hectorvent.floci.core.common.Resettable;import io.github.hectorvent.floci.core.resource.ExplorerResource;import io.github.hectorvent.floci.core.resource.ResourceProvider;@@ -17,12 +18,14 @@ import io.github.hectorvent.floci.core.resource.SupportedResourceType;import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.iam.IamService;import io.github.hectorvent.floci.services.sns.SnsService;import io.github.hectorvent.floci.services.sqs.model.Message;import io.github.hectorvent.floci.services.sqs.model.MessageAttributeValue;import io.github.hectorvent.floci.services.sqs.model.Queue;import jakarta.annotation.PreDestroy;import jakarta.enterprise.context.ApplicationScoped;+import jakarta.enterprise.inject.Instance;import jakarta.inject.Inject;import org.jboss.logging.Logger;@@ -272,15 +275,24 @@ public class SqsService implements Resettable, ResourceProvider {private final SnsService snsService;private final Clock clock;private final String receiptHandleSecret;+ private final Instance<RequestContext> requestContextInstance;+ private final IamService iamService;public SqsService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,SnsService snsService) {this(storageFactory, config, regionResolver, snsService, Clock.systemUTC());}- @Injectpublic SqsService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,SnsService snsService, Clock clock) {+ this(storageFactory, config, regionResolver, snsService, clock, null, null);+ }++ @Inject+ public SqsService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,+ SnsService snsService, Clock clock,+ Instance<RequestContext> requestContextInstance,+ IamService iamService) {this(storageFactory.create("sqs", "sqs-queues.json",new TypeReference<Map<String, Queue>>() {@@ -301,7 +313,9 @@ public class SqsService implements Resettable, ResourceProvider {config.services().sqs().clearFifoDeduplicationCacheOnPurge(),snsService,clock,- config.services().sqs().receiptHandleSecret()+ config.services().sqs().receiptHandleSecret(),+ requestContextInstance,+ iamService);}@@ -320,6 +334,14 @@ public class SqsService implements Resettable, ResourceProvider {new RegionResolver("us-east-1", "000000000000"), false, null, clock); // partition-literal: test-shaped constructor default}+ SqsService(StorageBackend<String, Queue> queueStore,+ int defaultVisibilityTimeout, int maxMessageSize, String baseUrl, Clock clock,+ Instance<RequestContext> requestContextInstance, IamService iamService) {+ this(queueStore, null, null, null, defaultVisibilityTimeout, maxMessageSize, baseUrl,+ new RegionResolver("us-east-1", "000000000000"), false, null, clock, // partition-literal: test-shaped constructor default+ ReceiptHandle.DEFAULT_SECRET, requestContextInstance, iamService);+ }+SqsService(StorageBackend<String, Queue> queueStore, StorageBackend<String, List<Message>> messageStore,StorageBackend<String, Map<String, Long>> dedupStore,int defaultVisibilityTimeout, int maxMessageSize, String baseUrl,@@ -363,6 +385,18 @@ public class SqsService implements Resettable, ResourceProvider {int defaultVisibilityTimeout, int maxMessageSize, String baseUrl,RegionResolver regionResolver, boolean clearFifoDeduplicationCacheOnPurge,SnsService snsService, Clock clock, String receiptHandleSecret) {+ this(queueStore, messageStore, dedupStore, dedupIdentityStore, defaultVisibilityTimeout, maxMessageSize,+ baseUrl, regionResolver, clearFifoDeduplicationCacheOnPurge, snsService, clock,+ receiptHandleSecret, null, null);+ }++ SqsService(StorageBackend<String, Queue> queueStore, StorageBackend<String, List<Message>> messageStore,+ StorageBackend<String, Map<String, Long>> dedupStore,+ StorageBackend<String, Map<String, Map<String, String>>> dedupIdentityStore,+ int defaultVisibilityTimeout, int maxMessageSize, String baseUrl,+ RegionResolver regionResolver, boolean clearFifoDeduplicationCacheOnPurge,+ SnsService snsService, Clock clock, String receiptHandleSecret,+ Instance<RequestContext> requestContextInstance, IamService iamService) {this.queueStore = queueStore;this.messageStore = messageStore;this.dedupStore = dedupStore;@@ -376,6 +410,8 @@ public class SqsService implements Resettable, ResourceProvider {this.snsService = snsService;this.clock = clock;this.receiptHandleSecret = receiptHandleSecret;+ this.requestContextInstance = requestContextInstance;+ this.iamService = iamService;this.moveTasksByHandle = new MoveTaskStore(clock);loadPersistedMessages();loadPersistedDedup();@@ -755,6 +791,35 @@ public class SqsService implements Resettable, ResourceProvider {return filtered;}+ /**+ * Resolves the principal of the in-flight request. Only the SQS protocol handlers may call this,+ * because only there is the request scope known to belong to a real SendMessage caller. Internal+ * producers (SNS, S3 notifications, EventBridge...) run on someone else's request thread and must+ * not inherit that identity: they pass an explicit senderId or get the queue owner by default.+ */+ public String resolveCallerSenderId(String queueUrl) {+ if (requestContextInstance != null) {+ try {+ RequestContext ctx = requestContextInstance.get();+ if (ctx != null) {+ String akid = ctx.getAccessKeyId();+ if (akid != null && iamService != null) {+ Optional<String> principalId = iamService.resolveCallerUserId(akid, ctx.getSessionToken());+ if (principalId.isPresent()) {+ return principalId.get();+ }+ }+ if (ctx.getAccountId() != null) {+ return ctx.getAccountId();+ }+ }+ } catch (RuntimeException ignored) {+ // outside request scope or unsatisfied bean resolution, fall through to default+ }+ }+ return senderIdFor(queueUrl);+ }+public Message sendMessage(String queueUrl, String body, Integer delaySeconds, String region) {return sendMessage(queueUrl, body, delaySeconds, null, null, region);}@@ -778,6 +843,16 @@ public class SqsService implements Resettable, ResourceProvider {Map<String, MessageAttributeValue> messageAttributes,String awsTraceHeader,String region) {+ return sendMessage(queueUrl, body, delaySeconds, messageGroupId, messageDeduplicationId,+ messageAttributes, awsTraceHeader, null, region);+ }++ public Message sendMessage(String queueUrl, String body, Integer delaySeconds,+ String messageGroupId, String messageDeduplicationId,+ Map<String, MessageAttributeValue> messageAttributes,+ String awsTraceHeader,+ String senderId,+ String region) {String storageKey = regionKey(region, queueUrl);Queue queue = getQueueByUrl(storageKey, queueUrl).orElseThrow(() -> new AwsException("AWS.SimpleQueueService.NonExistentQueue",@@ -792,6 +867,7 @@ public class SqsService implements Resettable, ResourceProvider {}int queueDelaySeconds = parseNonNegativeSecondsAttribute(queue.getAttributes().get("DelaySeconds"));+ String effectiveSenderId = senderId != null ? senderId : senderIdFor(queueUrl);// Resolve the effective delay:// - FIFO queues only support queue-level DelaySeconds per AWS SQS,@@ -872,6 +948,7 @@ public class SqsService implements Resettable, ResourceProvider {// continues tracking the deduplication ID for the full interval.// Return the original identity without re-enqueueing a message.Message response = new Message(body);+ response.setSenderId(effectiveSenderId);if (identity != null) {response.setMessageId(identity.messageId());response.setSequenceNumber(identity.sequenceNumber());@@ -890,6 +967,7 @@ public class SqsService implements Resettable, ResourceProvider {persistDedup(storageKey);Message message = new Message(body);+ message.setSenderId(effectiveSenderId);message.setMessageGroupId(messageGroupId);message.setMessageDeduplicationId(dedupId);message.setSequenceNumber(sequenceCounter.incrementAndGet());@@ -919,6 +997,7 @@ public class SqsService implements Resettable, ResourceProvider {// Standard queue. MessageGroupId is retained for ReceiveMessage to// return (fair queues); it has no effect on standard-queue delivery.Message message = new Message(body);+ message.setSenderId(effectiveSenderId);message.setMessageGroupId(messageGroupId);message.setAwsTraceHeader(awsTraceHeader);if (effectiveDelaySeconds > 0) {@@ -1844,11 +1923,9 @@ public class SqsService implements Resettable, ResourceProvider {}/**- * SQS reports SenderId as the principal that called SendMessage. Floci- * has no per-call IAM context, so it falls back to the account that owns- * the queue (parsed from the queue URL when present), otherwise the- * account from the current request context, otherwise the configured- * default account.+ * Default SenderId for messages with no caller principal (internal producers such as SNS,+ * S3 notifications or EventBridge): the account that owns the queue (parsed from the queue+ * URL when present), otherwise the configured default account.*/public String senderIdFor(String queueUrl) {String fromUrl = accountFromQueueUrl(normalizeQueueUrl(queueUrl));diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/model/Message.java b/src/main/java/io/github/hectorvent/floci/services/sqs/model/Message.javaindex b68ee7c91f..f97ff672a0 100644--- a/src/main/java/io/github/hectorvent/floci/services/sqs/model/Message.java+++ b/src/main/java/io/github/hectorvent/floci/services/sqs/model/Message.java@@ -46,6 +46,8 @@ public class Message {// on ReceiveMessage when requested.private String awsTraceHeader;+ private String senderId;+// The retention period starts over when a message is moved to a FIFO DLQ or by a message// move task. A standard DLQ keeps the original enqueue time.private Instant retentionStartTimestamp;@@ -86,6 +88,7 @@ public class Message {copy.sequenceNumber = sequenceNumber;copy.originalSourceQueueUrl = originalSourceQueueUrl;copy.awsTraceHeader = awsTraceHeader;+ copy.senderId = this.senderId;copy.retentionStartTimestamp = Instant.now();// receiveCount 0, firstReceiveTimestamp / receiptHandle / visibleAt null: a fresh life.return copy;@@ -136,6 +139,9 @@ public class Message {public String getAwsTraceHeader() { return awsTraceHeader; }public void setAwsTraceHeader(String awsTraceHeader) { this.awsTraceHeader = awsTraceHeader; }+ public String getSenderId() { return senderId; }+ public void setSenderId(String senderId) { this.senderId = senderId; }+public Instant getRetentionStartTimestamp() { return retentionStartTimestamp; }public void setRetentionStartTimestamp(Instant retentionStartTimestamp) { this.retentionStartTimestamp = retentionStartTimestamp; }diff --git a/src/test/java/io/github/hectorvent/floci/core/common/AccountContextFilterTest.java b/src/test/java/io/github/hectorvent/floci/core/common/AccountContextFilterTest.javaindex ebe4a6a232..b7e07027d2 100644--- a/src/test/java/io/github/hectorvent/floci/core/common/AccountContextFilterTest.java+++ b/src/test/java/io/github/hectorvent/floci/core/common/AccountContextFilterTest.java@@ -15,6 +15,7 @@ import java.util.Map;import java.util.Optional;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;import static org.mockito.Mockito.mock;@@ -391,15 +392,86 @@ class AccountContextFilterTest {assertTrue(body.contains("polygondwanaland-west-1"), body);}+ @Test+ void populatesAccessKeyIdInRequestContextFromAuthHeader() {+ String auth = "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20261001/us-east-1/sqs/aws4_request, "+ + "SignedHeaders=host, Signature=abc";+ ContainerRequestContext ctx = mockContext(auth, null);+ filter.filter(ctx);+ assertEquals("AKIAIOSFODNN7EXAMPLE", requestContext.getAccessKeyId());+ }++ @Test+ void populatesAccessKeyIdInRequestContextFromPresignedQuery() {+ ContainerRequestContext ctx = mockContext(null,+ "AKIAIOSFODNN7EXAMPLE/20261001/us-east-1/sqs/aws4_request", "AWS4-HMAC-SHA256");+ filter.filter(ctx);+ assertEquals("AKIAIOSFODNN7EXAMPLE", requestContext.getAccessKeyId());+ }++ @Test+ void accessKeyIdIsNullWhenNoAuthInfo() {+ ContainerRequestContext ctx = mockContext(null, null);+ filter.filter(ctx);+ assertNull(requestContext.getAccessKeyId());+ }++ @Test+ void resolvesFromPresignedCredentialWhenAlgorithmIsMissing() {+ ContainerRequestContext ctx = mockContext(null,+ "AKIAIOSFODNN7EXAMPLE/20261001/us-east-1/sqs/aws4_request", null);+ filter.filter(ctx);+ assertEquals("AKIAIOSFODNN7EXAMPLE", requestContext.getAccessKeyId());+ assertEquals(DEFAULT_ACCOUNT, requestContext.getAccountId());+ assertEquals("us-east-1", requestContext.getRegion());+ }++ @Test+ void populatesSessionTokenInRequestContextFromHeader() {+ String auth = "AWS4-HMAC-SHA256 Credential=ASIAIOSFODNN7EXAMPLE/20261001/us-east-1/sqs/aws4_request, "+ + "SignedHeaders=host, Signature=abc";+ ContainerRequestContext ctx = mockContext(auth, null, null, "my-session-token");+ filter.filter(ctx);+ assertEquals("ASIAIOSFODNN7EXAMPLE", requestContext.getAccessKeyId());+ assertEquals("my-session-token", requestContext.getSessionToken());+ }++ @Test+ void populatesSessionTokenInRequestContextFromPresignedQuery() {+ ContainerRequestContext ctx = mockContext(null,+ "ASIAIOSFODNN7EXAMPLE/20261001/us-east-1/sqs/aws4_request", "AWS4-HMAC-SHA256", "query-token");+ filter.filter(ctx);+ assertEquals("ASIAIOSFODNN7EXAMPLE", requestContext.getAccessKeyId());+ assertEquals("query-token", requestContext.getSessionToken());+ }+private ContainerRequestContext mockContext(String authHeader, String xAmzCredential) {+ return mockContext(authHeader, xAmzCredential, xAmzCredential != null ? "AWS4-HMAC-SHA256" : null, null);+ }++ private ContainerRequestContext mockContext(String authHeader, String xAmzCredential, String xAmzAlgorithm) {+ return mockContext(authHeader, xAmzCredential, xAmzAlgorithm, null);+ }++ private ContainerRequestContext mockContext(String authHeader, String xAmzCredential,+ String xAmzAlgorithm, String xAmzSecurityToken) {ContainerRequestContext ctx = mock(ContainerRequestContext.class);when(ctx.getHeaderString("Authorization")).thenReturn(authHeader);+ if (xAmzSecurityToken != null) {+ when(ctx.getHeaderString("X-Amz-Security-Token")).thenReturn(xAmzSecurityToken);+ }UriInfo uriInfo = mock(UriInfo.class);MultivaluedMap<String, String> queryParams = new MultivaluedHashMap<>();if (xAmzCredential != null) {queryParams.add("X-Amz-Credential", xAmzCredential);}+ if (xAmzAlgorithm != null) {+ queryParams.add("X-Amz-Algorithm", xAmzAlgorithm);+ }+ if (xAmzSecurityToken != null && authHeader == null) {+ queryParams.add("X-Amz-Security-Token", xAmzSecurityToken);+ }when(uriInfo.getQueryParameters()).thenReturn(queryParams);when(uriInfo.getPath()).thenReturn("/");when(ctx.getUriInfo()).thenReturn(uriInfo);diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsControllerTest.javaindex 58f3e76d1a..d0dfe64526 100644--- a/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsControllerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityCredentialsControllerTest.java@@ -137,9 +137,12 @@ class EksPodIdentityCredentialsControllerTest {assertNotNull(creds.expiration());ArgumentCaptor<String> akidCaptor = ArgumentCaptor.forClass(String.class);+ ArgumentCaptor<String> sessionNameCaptor = ArgumentCaptor.forClass(String.class);verify(iamService).registerSession(akidCaptor.capture(), eq(creds.secretAccessKey()),- eq(creds.token()), eq(ROLE_ARN), any(Instant.class), eq(null), eq(ACCOUNT_ID));+ eq(creds.token()), eq(ROLE_ARN), any(Instant.class), eq(null), eq(ACCOUNT_ID),+ sessionNameCaptor.capture(), any());assertEquals(creds.accessKeyId(), akidCaptor.getValue());+ assertTrue(sessionNameCaptor.getValue().startsWith("eks-" + CLUSTER_NAME + "-" + SERVICE_ACCOUNT + "-"));}@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.javaindex c2ddbaa17a..ec85aa1633 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java@@ -32,6 +32,7 @@ import java.time.Instant;import java.util.Base64;import java.util.List;import java.util.Map;+import java.util.Optional;import static org.junit.jupiter.api.Assertions.*;@@ -138,7 +139,7 @@ class IamServiceTest {sessions.put(accessKeyId, restored);assertEquals("arn:aws:sts::123456789012:assumed-role/TestRole/my-custom-session-name",service.resolveCallerArn(accessKeyId).orElseThrow());- assertEquals(restored.getAssumedRoleId(), service.resolveCallerUserId(accessKeyId).orElseThrow());+ assertEquals(restored.getAssumedRoleId(), service.resolveCallerUserId(accessKeyId, restored.getSessionToken()).orElseThrow());}@Test@@ -2384,11 +2385,12 @@ class IamServiceTest {* changes: otherwise a changed password would still report the original creation time.*/@Test- void updateLoginProfilePasswordChangeMovesPasswordLastChanged() {+ void updateLoginProfilePasswordChangeMovesPasswordLastChanged() throws InterruptedException {iamService.createUser("cred-report-changed-user", "/");iamService.createLoginProfile("cred-report-changed-user", "Original-P4ss!", false);Instant createdAt = iamService.getLoginProfile("cred-report-changed-user").getPasswordLastChanged();+ Thread.sleep(20);iamService.updateLoginProfile("cred-report-changed-user", "Updated-P4ss!", null);Instant changedAt = iamService.getLoginProfile("cred-report-changed-user").getPasswordLastChanged();@@ -2451,4 +2453,88 @@ class IamServiceTest {generation.description());assertDoesNotThrow(withExpiredReport::getCredentialReport);}++ @Test+ void resolveCallerUserIdReturnsUserIdForIamUser() {+ IamUser user = iamService.createUser("testuser", "/");+ AccessKey ak = iamService.createAccessKey("testuser");+ Optional<String> userIdOpt = iamService.resolveCallerUserId(ak.getAccessKeyId());+ assertTrue(userIdOpt.isPresent());+ assertEquals(user.getUserId(), userIdOpt.get());+ }++ @Test+ void resolveCallerUserIdReturnsAssumedRoleIdForSession() {+ iamService.registerSession("ASIATESTKEY", "test-secret", "token",+ "arn:aws:iam::000000000000:role/testrole", Instant.now().plusSeconds(3600), null,+ "000000000000", "my-session", "AROATESTROLE:my-session");++ Optional<String> userIdOpt = iamService.resolveCallerUserId("ASIATESTKEY", "token");+ assertTrue(userIdOpt.isPresent());+ assertEquals("AROATESTROLE:my-session", userIdOpt.get());+ }++ @Test+ void resolveCallerUserIdReturnsEc2AssumedRoleIdForEc2Session() {+ SessionCredential session = new SessionCredential(+ "ASIAEC2KEY", "test-secret", "token", "arn:aws:iam::000000000000:role/ec2role",+ Instant.now().plusSeconds(3600), null, "000000000000");+ session.setEc2InstanceId("i-1234567890abcdef0");+ session.setEc2RoleId("AROAEC2ROLE");+ iamService.registerEc2InstanceSession(session);++ Optional<String> userIdOpt = iamService.resolveCallerUserId("ASIAEC2KEY", "token");+ assertTrue(userIdOpt.isPresent());+ assertEquals("AROAEC2ROLE:i-1234567890abcdef0", userIdOpt.get());+ }++ @Test+ void resolveCallerUserIdResolvesFromRoleArnWhenAssumedRoleIdNotExplicitlySet() {+ IamRole role = iamService.createRole("UnsetAssumedRole", "/", "{}", null, 3600, null);+ iamService.registerSession(+ "ASIAROLEARNKEY", "test-secret", "token", role.getArn(),+ Instant.now().plusSeconds(3600), null, "000000000000",+ "custom-session", null);++ Optional<String> userIdOpt = iamService.resolveCallerUserId("ASIAROLEARNKEY", "token");+ assertTrue(userIdOpt.isPresent());+ assertEquals(role.getRoleId() + ":custom-session", userIdOpt.get());+ }++ @Test+ void resolveCallerUserIdReturnsAssumedRoleIdForLambdaExecutionRole() {+ IamRole role = iamService.createRole("LambdaFuncRole", "/", "{}", null, 3600, null);+ String assumedRoleId = role.getRoleId() + ":my-function";+ iamService.registerLambdaExecutionRoleSession(+ "000000000000", "ASIALAMBDAKEY", "secret", "token", role.getArn(),+ "my-function", assumedRoleId);++ Optional<String> userIdOpt = iamService.resolveCallerUserId("ASIALAMBDAKEY", "token");+ assertTrue(userIdOpt.isPresent());+ assertEquals(assumedRoleId, userIdOpt.get());+ }++ @Test+ void resolveCallerUserIdRejectsTemporaryCredentialsWhenSessionTokenMismatchesOrMissing() {+ IamRole role = iamService.createRole("TokenCheckRole", "/", "{}", null, 3600, null);+ String assumedRoleId = role.getRoleId() + ":token-check-session";+ iamService.registerSession(+ "ASIATOKENCHECKKEY", "test-secret", "correct-token", role.getArn(),+ Instant.now().plusSeconds(3600), null, "000000000000",+ "token-check-session", assumedRoleId);++ // Matching token -> resolves+ Optional<String> validOpt = iamService.resolveCallerUserId("ASIATOKENCHECKKEY", "correct-token");+ assertTrue(validOpt.isPresent());+ assertEquals(assumedRoleId, validOpt.get());++ // Wrong token -> empty+ Optional<String> wrongOpt = iamService.resolveCallerUserId("ASIATOKENCHECKKEY", "wrong-token");+ assertTrue(wrongOpt.isEmpty());++ // Null token -> empty+ Optional<String> nullOpt = iamService.resolveCallerUserId("ASIATOKENCHECKKEY", null);+ assertTrue(nullOpt.isEmpty());+ }}+diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/LambdaExecutionRoleCredentialsTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/LambdaExecutionRoleCredentialsTest.javaindex d64c37b7e5..2c243d580e 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/LambdaExecutionRoleCredentialsTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/LambdaExecutionRoleCredentialsTest.java@@ -12,6 +12,7 @@ import org.junit.jupiter.api.Test;import java.util.Optional;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotEquals;import static org.junit.jupiter.api.Assertions.assertNotNull;import static org.junit.jupiter.api.Assertions.assertTrue;@@ -59,7 +60,7 @@ class LambdaExecutionRoleCredentialsTest {assertNotNull(caller);assertEquals(java.util.List.of(POLICY), caller.identityPolicies());assertEquals(- "arn:aws:sts::000000000000:assumed-role/LambdaExecutionRole/floci-session",+ "arn:aws:sts::000000000000:assumed-role/LambdaExecutionRole/function",iamService.resolveCallerArn(session.accessKeyId()).orElseThrow());}@@ -105,6 +106,24 @@ class LambdaExecutionRoleCredentialsTest {}}+ @Test+ void differentFunctionsSharingSameRoleMintDistinctAssumedRoleIds() {+ LambdaFunction func1 = function(ROLE_ARN);+ func1.setFunctionName("func-1");+ LambdaFunction func2 = function(ROLE_ARN);+ func2.setFunctionName("func-2");++ SessionCreds session1 = credentials.forFunction(func1).orElseThrow();+ SessionCreds session2 = credentials.forFunction(func2).orElseThrow();++ String userId1 = iamService.resolveCallerUserId(session1.accessKeyId(), session1.sessionToken()).orElseThrow();+ String userId2 = iamService.resolveCallerUserId(session2.accessKeyId(), session2.sessionToken()).orElseThrow();++ assertNotEquals(userId1, userId2);+ assertTrue(userId1.endsWith(":func-1"), "First function user ID should end with function name");+ assertTrue(userId2.endsWith(":func-2"), "Second function user ID should end with function name");+ }+private static LambdaFunction function(String roleArn) {LambdaFunction function = new LambdaFunction();function.setFunctionName("function");diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/LambdaExecutionRoleIamEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/LambdaExecutionRoleIamEnforcementIntegrationTest.javaindex d3d6251e91..425e62fea4 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/LambdaExecutionRoleIamEnforcementIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/LambdaExecutionRoleIamEnforcementIntegrationTest.java@@ -73,7 +73,7 @@ class LambdaExecutionRoleIamEnforcementIntegrationTest {.body("GetCallerIdentityResponse.GetCallerIdentityResult.Account", equalTo(ACCOUNT_ID)).body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn",equalTo("arn:aws:sts::" + ACCOUNT_ID- + ":assumed-role/" + roleName + "/floci-session"));+ + ":assumed-role/" + roleName + "/" + function.getFunctionName()));} finally {executionRoleCredentials.unregister(ACCOUNT_ID, credentials.accessKeyId());iamService.deleteRolePolicy(roleName, "RuntimePolicy");@@ -113,7 +113,7 @@ class LambdaExecutionRoleIamEnforcementIntegrationTest {SessionCreds credentials = executionRoleCredentials.forFunction(version).orElseThrow();try {org.junit.jupiter.api.Assertions.assertEquals(- "arn:aws:sts::" + ACCOUNT_ID + ":assumed-role/" + roleName + "/floci-session",+ "arn:aws:sts::" + ACCOUNT_ID + ":assumed-role/" + roleName + "/" + functionName,iamService.resolveCallerArn(credentials.accessKeyId()).orElseThrow());} finally {executionRoleCredentials.unregister(diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.javaindex 97f1af02bd..6f4b4a95a2 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/StsQueryHandlerTest.java@@ -502,6 +502,24 @@ class StsQueryHandlerTest {extract(ARN, (String) response.getEntity()));}+ @Test+ void assumeRoleUsesRolesOwnRoleIdForAssumedRoleId() {+ IamRole role = new IamRole();+ role.setRoleName("sender");+ role.setRoleId("AROAKX9OBMP2TSQJZ48H");+ role.setArn("arn:aws:iam::000000000000:role/sender");+ StsQueryHandler handler = newHandler(role);++ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();+ params.add("RoleArn", role.getArn());+ params.add("RoleSessionName", "my-session");++ Response response = handler.handle("AssumeRole", params);+ assertEquals(200, response.getStatus());+ String body = (String) response.getEntity();+ assertTrue(body.contains("<AssumedRoleId>AROAKX9OBMP2TSQJZ48H:my-session</AssumedRoleId>"), body);+ }+private static String extract(Pattern pattern, String body) {Matcher matcher = pattern.matcher(body);assertTrue(matcher.find(), "expected " + pattern + " in " + body);diff --git a/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.javaindex 9cbe96126c..8aab5b2e3c 100644--- a/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.common.ServicePrincipals;import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;import io.github.hectorvent.floci.core.storage.InMemoryStorage;import io.github.hectorvent.floci.services.firehose.FirehoseService;@@ -150,12 +151,14 @@ class SnsServiceTest {service.subscribe(topic.getTopicArn(), "sqs", queueArn, REGION, Map.of());doThrow(new AwsException("ServiceUnavailable", "temporarily unavailable", 503)).doReturn(new Message("delivered"))- .when(sqs).sendMessage(eq(queueUrl), anyString(), isNull(), isNull(), isNull(), anyMap(), eq(REGION));+ .when(sqs).sendMessage(eq(queueUrl), anyString(), isNull(), isNull(), isNull(), anyMap(),+ isNull(), eq(ServicePrincipals.of("sns")), eq(REGION));String messageId = service.publish(topic.getTopicArn(), null, "payload", null, REGION);assertNotNull(messageId);- verify(sqs, times(2)).sendMessage(eq(queueUrl), anyString(), isNull(), isNull(), isNull(), anyMap(), eq(REGION));+ verify(sqs, times(2)).sendMessage(eq(queueUrl), anyString(), isNull(), isNull(), isNull(), anyMap(),+ isNull(), eq(ServicePrincipals.of("sns")), eq(REGION));}@Test@@ -171,15 +174,18 @@ class SnsServiceTest {service.subscribe(topic.getTopicArn(), "sqs", queueArn, REGION,Map.of("RedrivePolicy", "{\"deadLetterTargetArn\":\"" + dlqArn + "\"}"));doThrow(new AwsException("AWS.SimpleQueueService.NonExistentQueue", "unavailable", 400))- .when(sqs).sendMessage(eq(queueUrl), anyString(), isNull(), isNull(), isNull(), anyMap(), eq(REGION));+ .when(sqs).sendMessage(eq(queueUrl), anyString(), isNull(), isNull(), isNull(), anyMap(),+ isNull(), eq(ServicePrincipals.of("sns")), eq(REGION));String messageId = service.publish(topic.getTopicArn(), null,"payload", "subject", REGION);assertNotNull(messageId, "SNS Publish acceptance is independent of downstream SQS delivery");- verify(sqs, times(3)).sendMessage(eq(queueUrl), anyString(), isNull(), isNull(), isNull(), anyMap(), eq(REGION));+ verify(sqs, times(3)).sendMessage(eq(queueUrl), anyString(), isNull(), isNull(), isNull(), anyMap(),+ isNull(), eq(ServicePrincipals.of("sns")), eq(REGION));ArgumentCaptor<String> deadLetterBody = ArgumentCaptor.forClass(String.class);- verify(sqs).sendMessage(eq(dlqUrl), deadLetterBody.capture(), isNull(), isNull(), isNull(), anyMap(), eq(REGION));+ verify(sqs).sendMessage(eq(dlqUrl), deadLetterBody.capture(), isNull(), isNull(), isNull(), anyMap(),+ isNull(), eq(ServicePrincipals.of("sns")), eq(REGION));JsonNode envelope = new ObjectMapper().readTree(deadLetterBody.getValue());assertEquals("Notification", envelope.path("Type").asText());assertEquals(topic.getTopicArn(), envelope.path("TopicArn").asText());diff --git a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsIntegrationTest.javaindex be8238ebc4..83d78027c0 100644--- a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsIntegrationTest.java@@ -948,6 +948,69 @@ class SqsIntegrationTest {}}+ @Test+ void receiveMessageReturnsPerMessageSenderId() {+ String testQueueUrl = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateQueue")+ .formParam("QueueName", "per-message-sender-id-queue")+ .when().post("/").then().statusCode(200)+ .extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");++ try {+ String auth1 = "AWS4-HMAC-SHA256 Credential=111122223333/20260215/us-east-1/sqs/aws4_request, "+ + "SignedHeaders=host, Signature=abc";+ String auth2 = "AWS4-HMAC-SHA256 Credential=444455556666/20260215/us-east-1/sqs/aws4_request, "+ + "SignedHeaders=host, Signature=abc";++ given()+ .header("Authorization", auth1)+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "SendMessage")+ .formParam("QueueUrl", testQueueUrl)+ .formParam("MessageBody", "msg-sender-1")+ .when().post("/").then().statusCode(200);++ given()+ .header("Authorization", auth2)+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "SendMessage")+ .formParam("QueueUrl", testQueueUrl)+ .formParam("MessageBody", "msg-sender-2")+ .when().post("/").then().statusCode(200);++ XmlPath xml = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "ReceiveMessage")+ .formParam("QueueUrl", testQueueUrl)+ .formParam("MaxNumberOfMessages", "10")+ .formParam("VisibilityTimeout", "0")+ .formParam("MessageSystemAttributeName.1", "SenderId")+ .when().post("/").then().statusCode(200)+ .body(containsString("<Value>111122223333</Value>"))+ .body(containsString("<Value>444455556666</Value>"))+ .extract().xmlPath();++ List<String> bodies = xml.getList(+ "ReceiveMessageResponse.ReceiveMessageResult.Message.Body", String.class);+ assertEquals(2, bodies.size());+ int idx1 = bodies.indexOf("msg-sender-1");+ int idx2 = bodies.indexOf("msg-sender-2");+ assertTrue(idx1 >= 0 && idx2 >= 0);++ List<String> senderIds = xml.getList(+ "ReceiveMessageResponse.ReceiveMessageResult.Message.Attribute.Value", String.class);+ assertEquals("111122223333", senderIds.get(idx1));+ assertEquals("444455556666", senderIds.get(idx2));+ } finally {+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DeleteQueue")+ .formParam("QueueUrl", testQueueUrl)+ .when().post("/");+ }+ }+private static Map<String, String> allQueueAttributes(String url) {XmlPath xml = given().contentType("application/x-www-form-urlencoded")diff --git a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsInternalProducerSenderIdIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsInternalProducerSenderIdIntegrationTest.javanew file mode 100644index 0000000000..aca6e055d8--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsInternalProducerSenderIdIntegrationTest.java@@ -0,0 +1,226 @@+package io.github.hectorvent.floci.services.sqs;++import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.path.xml.XmlPath;+import io.restassured.response.ValidatableResponse;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.equalTo;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotEquals;+import static org.junit.jupiter.api.Assertions.assertNotNull;++/**+ * Internal producers (S3 notifications, EventBridge targets) send to SQS on the thread of the+ * request that triggered them. The SenderId must not be the role session of that request.+ */+@QuarkusTest+class SqsInternalProducerSenderIdIntegrationTest {++ private static final String IAM_AUTHORIZATION =+ "AWS4-HMAC-SHA256 Credential=test/20261001/us-east-1/iam/aws4_request";+ private static final String STS_AUTHORIZATION =+ "AWS4-HMAC-SHA256 Credential=test/20261001/us-east-1/sts/aws4_request";+ private static final String ASSUME_ROLE_POLICY_DOCUMENT =+ "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","+ + "\"Principal\":{\"AWS\":\"*\"},\"Action\":\"sts:AssumeRole\"}]}";+ private static final String QUEUE_OWNER_ACCOUNT = "000000000000";++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ void s3NotificationSenderIdIsNotUploaderRoleSession() {+ String roleName = "sqs-s3-notif-role";+ String bucket = "sqs-s3-notif-sender-bucket";+ String queueName = "sqs-s3-notif-sender-queue";+ String queueUrl = null;++ try {+ AssumedRole role = assumeRole(roleName, "s3-uploader");+ queueUrl = createQueue(queueName);+ String queueArn = queueArn(queueUrl);++ given().when().put("/" + bucket).then().statusCode(200);+ given()+ .header("x-amz-skip-destination-validation", "true")+ .contentType("application/xml")+ .queryParam("notification", "")+ .body("""+ <NotificationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">+ <QueueConfiguration>+ <Id>sender-id-notif</Id>+ <Queue>%s</Queue>+ <Event>s3:ObjectCreated:*</Event>+ </QueueConfiguration>+ </NotificationConfiguration>+ """.formatted(queueArn))+ .when().put("/" + bucket)+ .then().statusCode(200);++ given()+ .header("Authorization", signedAuthorization(role.accessKeyId(), "s3"))+ .header("X-Amz-Security-Token", role.sessionToken())+ .contentType("text/plain")+ .body("payload")+ .when().put("/" + bucket + "/uploaded.txt")+ .then().statusCode(200);++ String senderId = receiveSenderId(queueUrl);+ assertNotEquals(role.assumedRoleId(), senderId);+ assertEquals(QUEUE_OWNER_ACCOUNT, senderId);+ } finally {+ given().when().delete("/" + bucket + "/uploaded.txt");+ given().when().delete("/" + bucket);+ deleteQueue(queueUrl);+ deleteRole(roleName);+ }+ }++ @Test+ void eventBridgeSenderIdIsNotPutEventsCallerRoleSession() {+ String roleName = "sqs-eb-sender-role";+ String queueName = "sqs-eb-sender-queue";+ String ruleName = "sqs-eb-sender-rule";+ String queueUrl = null;++ try {+ AssumedRole role = assumeRole(roleName, "eb-publisher");+ queueUrl = createQueue(queueName);+ String queueArn = queueArn(queueUrl);++ given()+ .contentType("application/x-amz-json-1.1")+ .header("X-Amz-Target", "AWSEvents.PutRule")+ .body("{\"Name\":\"" + ruleName + "\",\"EventBusName\":\"default\","+ + "\"EventPattern\":\"{\\\"source\\\":[\\\"test.sender-id\\\"]}\"}")+ .when().post("/").then().statusCode(200);+ given()+ .contentType("application/x-amz-json-1.1")+ .header("X-Amz-Target", "AWSEvents.PutTargets")+ .body("{\"Rule\":\"" + ruleName + "\",\"EventBusName\":\"default\","+ + "\"Targets\":[{\"Id\":\"t1\",\"Arn\":\"" + queueArn + "\"}]}")+ .when().post("/").then().statusCode(200)+ .body("FailedEntryCount", equalTo(0));++ given()+ .contentType("application/x-amz-json-1.1")+ .header("Authorization", signedAuthorization(role.accessKeyId(), "events"))+ .header("X-Amz-Security-Token", role.sessionToken())+ .header("X-Amz-Target", "AWSEvents.PutEvents")+ .body("{\"Entries\":[{\"EventBusName\":\"default\",\"Source\":\"test.sender-id\","+ + "\"DetailType\":\"SenderIdTest\",\"Detail\":\"{}\"}]}")+ .when().post("/").then().statusCode(200)+ .body("FailedEntryCount", equalTo(0));++ String senderId = receiveSenderId(queueUrl);+ assertNotEquals(role.assumedRoleId(), senderId);+ assertEquals(QUEUE_OWNER_ACCOUNT, senderId);+ } finally {+ given()+ .contentType("application/x-amz-json-1.1")+ .header("X-Amz-Target", "AWSEvents.RemoveTargets")+ .body("{\"Rule\":\"" + ruleName + "\",\"EventBusName\":\"default\",\"Ids\":[\"t1\"]}")+ .when().post("/");+ given()+ .contentType("application/x-amz-json-1.1")+ .header("X-Amz-Target", "AWSEvents.DeleteRule")+ .body("{\"Name\":\"" + ruleName + "\",\"EventBusName\":\"default\"}")+ .when().post("/");+ deleteQueue(queueUrl);+ deleteRole(roleName);+ }+ }++ private record AssumedRole(String accessKeyId, String sessionToken, String assumedRoleId) {}++ private AssumedRole assumeRole(String roleName, String sessionName) {+ String roleArn = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateRole")+ .formParam("RoleName", roleName)+ .formParam("AssumeRolePolicyDocument", ASSUME_ROLE_POLICY_DOCUMENT)+ .header("Authorization", IAM_AUTHORIZATION)+ .when().post("/").then().statusCode(200)+ .extract().xmlPath().getString("CreateRoleResponse.CreateRoleResult.Role.Arn");++ ValidatableResponse assumed = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "AssumeRole")+ .formParam("RoleArn", roleArn)+ .formParam("RoleSessionName", sessionName)+ .header("Authorization", STS_AUTHORIZATION)+ .when().post("/").then().statusCode(200);+ XmlPath xml = assumed.extract().xmlPath();+ return new AssumedRole(+ xml.getString("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId"),+ xml.getString("AssumeRoleResponse.AssumeRoleResult.Credentials.SessionToken"),+ xml.getString("AssumeRoleResponse.AssumeRoleResult.AssumedRoleUser.AssumedRoleId"));+ }++ private String signedAuthorization(String accessKeyId, String service) {+ return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20261001/us-east-1/" + service+ + "/aws4_request, SignedHeaders=host, Signature=abc";+ }++ private String createQueue(String queueName) {+ return given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateQueue")+ .formParam("QueueName", queueName)+ .when().post("/").then().statusCode(200)+ .extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");+ }++ private String queueArn(String queueUrl) {+ return given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "GetQueueAttributes")+ .formParam("QueueUrl", queueUrl)+ .formParam("AttributeName.1", "QueueArn")+ .when().post("/").then().statusCode(200)+ .extract().xmlPath().getString(+ "GetQueueAttributesResponse.GetQueueAttributesResult.Attribute.find { it.Name == 'QueueArn' }.Value");+ }++ private String receiveSenderId(String queueUrl) {+ String senderId = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "ReceiveMessage")+ .formParam("QueueUrl", queueUrl)+ .formParam("MaxNumberOfMessages", "1")+ .formParam("VisibilityTimeout", "0")+ .formParam("WaitTimeSeconds", "5")+ .formParam("AttributeName.1", "SenderId")+ .when().post("/").then().statusCode(200)+ .extract().xmlPath()+ .getString("ReceiveMessageResponse.ReceiveMessageResult.Message.Attribute.find { it.Name == 'SenderId' }.Value");+ assertNotNull(senderId, "no message with a SenderId arrived in the queue");+ return senderId;+ }++ private void deleteQueue(String queueUrl) {+ if (queueUrl == null) {+ return;+ }+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DeleteQueue")+ .formParam("QueueUrl", queueUrl)+ .when().post("/");+ }++ private void deleteRole(String roleName) {+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DeleteRole")+ .formParam("RoleName", roleName)+ .header("Authorization", IAM_AUTHORIZATION)+ .when().post("/");+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsJsonProtocolTest.java b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsJsonProtocolTest.javaindex 3ffc2e46c2..fc563d1359 100644--- a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsJsonProtocolTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsJsonProtocolTest.java@@ -713,4 +713,52 @@ class SqsJsonProtocolTest {.when().post("/");}}++ @Test+ void receiveMessageReturnsPerMessageSenderId() {+ String testQueueUrl = given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.CreateQueue")+ .body("{\"QueueName\":\"json-sender-id-per-message-queue\"}")+ .when().post("/").then().statusCode(200)+ .extract().jsonPath().getString("QueueUrl");++ try {+ String auth1 = "AWS4-HMAC-SHA256 Credential=111122223333/20260215/us-east-1/sqs/aws4_request, "+ + "SignedHeaders=host;x-amz-date;x-amz-security-token, Signature=abc";+ String auth2 = "AWS4-HMAC-SHA256 Credential=444455556666/20260215/us-east-1/sqs/aws4_request, "+ + "SignedHeaders=host;x-amz-date;x-amz-security-token, Signature=abc";++ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.SendMessage")+ .header("Authorization", auth1)+ .body("{\"QueueUrl\":\"" + testQueueUrl + "\",\"MessageBody\":\"msg-sender-1\"}")+ .when().post("/").then().statusCode(200);++ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.SendMessage")+ .header("Authorization", auth2)+ .body("{\"QueueUrl\":\"" + testQueueUrl + "\",\"MessageBody\":\"msg-sender-2\"}")+ .when().post("/").then().statusCode(200);++ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.ReceiveMessage")+ .body("{\"QueueUrl\":\"" + testQueueUrl + "\","+ + "\"MaxNumberOfMessages\":10,"+ + "\"VisibilityTimeout\":0,"+ + "\"MessageSystemAttributeNames\":[\"SenderId\"]}")+ .when().post("/").then().statusCode(200)+ .body("Messages", hasSize(2))+ .body("Messages.Attributes.SenderId", hasItems("111122223333", "444455556666"));+ } finally {+ given()+ .contentType(CONTENT_TYPE)+ .header("X-Amz-Target", "AmazonSQS.DeleteQueue")+ .body("{\"QueueUrl\":\"" + testQueueUrl + "\"}")+ .when().post("/");+ }+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsPrincipalSenderIdIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsPrincipalSenderIdIntegrationTest.javanew file mode 100644index 0000000000..bdb7addb7d--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsPrincipalSenderIdIntegrationTest.java@@ -0,0 +1,521 @@+package io.github.hectorvent.floci.services.sqs;++import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.path.xml.XmlPath;+import io.restassured.response.ValidatableResponse;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import java.util.List;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;++@QuarkusTest+class SqsPrincipalSenderIdIntegrationTest {++ private static final String IAM_AUTHORIZATION =+ "AWS4-HMAC-SHA256 Credential=test/20261001/us-east-1/iam/aws4_request";+ private static final String STS_AUTHORIZATION =+ "AWS4-HMAC-SHA256 Credential=test/20261001/us-east-1/sts/aws4_request";+ private static final String ASSUME_ROLE_POLICY_DOCUMENT =+ "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","+ + "\"Principal\":{\"AWS\":\"*\"},\"Action\":\"sts:AssumeRole\"}]}";++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ void senderIdMatchesAssumedRoleIdWhenSentByAssumedRole() {+ String roleName = "sqs-sender-role-test";+ String sessionName = "sqs-role-session";+ String queueName = "sqs-assumed-role-queue";+ String queueUrl = null;++ try {+ ValidatableResponse roleResp = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateRole")+ .formParam("RoleName", roleName)+ .formParam("AssumeRolePolicyDocument", ASSUME_ROLE_POLICY_DOCUMENT)+ .header("Authorization", IAM_AUTHORIZATION)+ .when().post("/").then().statusCode(200);++ String roleId = roleResp.extract().xmlPath().getString(+ "CreateRoleResponse.CreateRoleResult.Role.RoleId");+ String roleArn = roleResp.extract().xmlPath().getString(+ "CreateRoleResponse.CreateRoleResult.Role.Arn");++ ValidatableResponse assumed = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "AssumeRole")+ .formParam("RoleArn", roleArn)+ .formParam("RoleSessionName", sessionName)+ .header("Authorization", STS_AUTHORIZATION)+ .when().post("/").then().statusCode(200);++ String accessKeyId = assumed.extract().xmlPath().getString(+ "AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId");+ String sessionToken = assumed.extract().xmlPath().getString(+ "AssumeRoleResponse.AssumeRoleResult.Credentials.SessionToken");+ String assumedRoleId = assumed.extract().xmlPath().getString(+ "AssumeRoleResponse.AssumeRoleResult.AssumedRoleUser.AssumedRoleId");++ assertEquals(roleId + ":" + sessionName, assumedRoleId);++ queueUrl = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateQueue")+ .formParam("QueueName", queueName)+ .when().post("/").then().statusCode(200)+ .extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");++ String authHeader = "AWS4-HMAC-SHA256 Credential=" + accessKeyId+ + "/20261001/us-east-1/sqs/aws4_request, SignedHeaders=host, Signature=abc";++ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", authHeader)+ .header("X-Amz-Security-Token", sessionToken)+ .formParam("Action", "SendMessage")+ .formParam("QueueUrl", queueUrl)+ .formParam("MessageBody", "hello-from-assumed-role")+ .when().post("/").then().statusCode(200);++ XmlPath xml = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "ReceiveMessage")+ .formParam("QueueUrl", queueUrl)+ .formParam("MaxNumberOfMessages", "1")+ .formParam("VisibilityTimeout", "0")+ .formParam("AttributeName.1", "SenderId")+ .when().post("/").then().statusCode(200)+ .body(containsString("<Name>SenderId</Name>"))+ .body(containsString("<Value>" + assumedRoleId + "</Value>"))+ .extract().xmlPath();++ String senderId = xml.getString("ReceiveMessageResponse.ReceiveMessageResult.Message.Attribute.Value");+ assertEquals(assumedRoleId, senderId);+ assertEquals(roleId + ":" + sessionName, senderId);+ } finally {+ deleteQueue(queueUrl);+ deleteRole(roleName);+ }+ }++ @Test+ void senderIdMatchesUserIdWhenSentByIamUser() {+ String userName = "sqs-sender-user-test";+ String queueName = "sqs-iam-user-queue";+ String queueUrl = null;+ String accessKeyId = null;++ try {+ XmlPath userResp = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateUser")+ .formParam("UserName", userName)+ .header("Authorization", IAM_AUTHORIZATION)+ .when().post("/").then().statusCode(200)+ .extract().xmlPath();++ String userId = userResp.getString("CreateUserResponse.CreateUserResult.User.UserId");+ assertTrue(userId.startsWith("AIDA"), "IAM UserId should start with AIDA");++ XmlPath keyResp = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateAccessKey")+ .formParam("UserName", userName)+ .header("Authorization", IAM_AUTHORIZATION)+ .when().post("/").then().statusCode(200)+ .extract().xmlPath();++ accessKeyId = keyResp.getString(+ "CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");++ queueUrl = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateQueue")+ .formParam("QueueName", queueName)+ .when().post("/").then().statusCode(200)+ .extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");++ String authHeader = "AWS4-HMAC-SHA256 Credential=" + accessKeyId+ + "/20261001/us-east-1/sqs/aws4_request, SignedHeaders=host, Signature=abc";++ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", authHeader)+ .formParam("Action", "SendMessage")+ .formParam("QueueUrl", queueUrl)+ .formParam("MessageBody", "hello-from-iam-user")+ .when().post("/").then().statusCode(200);++ XmlPath xml = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "ReceiveMessage")+ .formParam("QueueUrl", queueUrl)+ .formParam("MaxNumberOfMessages", "1")+ .formParam("VisibilityTimeout", "0")+ .formParam("AttributeName.1", "SenderId")+ .when().post("/").then().statusCode(200)+ .body(containsString("<Name>SenderId</Name>"))+ .body(containsString("<Value>" + userId + "</Value>"))+ .extract().xmlPath();++ String senderId = xml.getString("ReceiveMessageResponse.ReceiveMessageResult.Message.Attribute.Value");+ assertEquals(userId, senderId);+ assertTrue(senderId.startsWith("AIDA"));+ } finally {+ deleteQueue(queueUrl);+ deleteAccessKey(userName, accessKeyId);+ deleteUser(userName);+ }+ }++ @Test+ void queueWithMultipleSendersPreservesIndividualSenderIds() {+ String roleName = "sqs-multi-sender-role";+ String sessionName = "multi-session";+ String userName = "sqs-multi-sender-user";+ String queueName = "sqs-multi-sender-queue";+ String queueUrl = null;+ String userAccessKeyId = null;++ try {+ ValidatableResponse roleResp = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateRole")+ .formParam("RoleName", roleName)+ .formParam("AssumeRolePolicyDocument", ASSUME_ROLE_POLICY_DOCUMENT)+ .header("Authorization", IAM_AUTHORIZATION)+ .when().post("/").then().statusCode(200);++ String roleId = roleResp.extract().xmlPath().getString(+ "CreateRoleResponse.CreateRoleResult.Role.RoleId");+ String roleArn = roleResp.extract().xmlPath().getString(+ "CreateRoleResponse.CreateRoleResult.Role.Arn");++ ValidatableResponse assumed = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "AssumeRole")+ .formParam("RoleArn", roleArn)+ .formParam("RoleSessionName", sessionName)+ .header("Authorization", STS_AUTHORIZATION)+ .when().post("/").then().statusCode(200);++ String roleAccessKeyId = assumed.extract().xmlPath().getString(+ "AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId");+ String roleSessionToken = assumed.extract().xmlPath().getString(+ "AssumeRoleResponse.AssumeRoleResult.Credentials.SessionToken");+ String expectedAssumedRoleId = roleId + ":" + sessionName;++ XmlPath userResp = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateUser")+ .formParam("UserName", userName)+ .header("Authorization", IAM_AUTHORIZATION)+ .when().post("/").then().statusCode(200)+ .extract().xmlPath();++ String expectedUserId = userResp.getString("CreateUserResponse.CreateUserResult.User.UserId");++ XmlPath keyResp = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateAccessKey")+ .formParam("UserName", userName)+ .header("Authorization", IAM_AUTHORIZATION)+ .when().post("/").then().statusCode(200)+ .extract().xmlPath();++ userAccessKeyId = keyResp.getString(+ "CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");++ queueUrl = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateQueue")+ .formParam("QueueName", queueName)+ .when().post("/").then().statusCode(200)+ .extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");++ String roleAuth = "AWS4-HMAC-SHA256 Credential=" + roleAccessKeyId+ + "/20261001/us-east-1/sqs/aws4_request, SignedHeaders=host, Signature=abc";+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", roleAuth)+ .header("X-Amz-Security-Token", roleSessionToken)+ .formParam("Action", "SendMessage")+ .formParam("QueueUrl", queueUrl)+ .formParam("MessageBody", "msg-assumed-role")+ .when().post("/").then().statusCode(200);++ String userAuth = "AWS4-HMAC-SHA256 Credential=" + userAccessKeyId+ + "/20261001/us-east-1/sqs/aws4_request, SignedHeaders=host, Signature=abc";+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", userAuth)+ .formParam("Action", "SendMessage")+ .formParam("QueueUrl", queueUrl)+ .formParam("MessageBody", "msg-iam-user")+ .when().post("/").then().statusCode(200);++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "SendMessage")+ .formParam("QueueUrl", queueUrl)+ .formParam("MessageBody", "msg-default-account")+ .when().post("/").then().statusCode(200);++ XmlPath xml = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "ReceiveMessage")+ .formParam("QueueUrl", queueUrl)+ .formParam("MaxNumberOfMessages", "10")+ .formParam("VisibilityTimeout", "0")+ .formParam("AttributeName.1", "SenderId")+ .when().post("/").then().statusCode(200)+ .extract().xmlPath();++ List<String> bodies = xml.getList(+ "ReceiveMessageResponse.ReceiveMessageResult.Message.Body", String.class);+ assertEquals(3, bodies.size());+ int roleIdx = bodies.indexOf("msg-assumed-role");+ int userIdx = bodies.indexOf("msg-iam-user");+ int defaultIdx = bodies.indexOf("msg-default-account");+ assertTrue(roleIdx >= 0, "Assumed role message should be present");+ assertTrue(userIdx >= 0, "IAM user message should be present");+ assertTrue(defaultIdx >= 0, "Default account message should be present");++ List<String> senderIds = xml.getList(+ "ReceiveMessageResponse.ReceiveMessageResult.Message.Attribute.Value", String.class);+ assertEquals(expectedAssumedRoleId, senderIds.get(roleIdx));+ assertEquals(expectedUserId, senderIds.get(userIdx));+ assertEquals("000000000000", senderIds.get(defaultIdx));+ } finally {+ deleteQueue(queueUrl);+ deleteAccessKey(userName, userAccessKeyId);+ deleteUser(userName);+ deleteRole(roleName);+ }+ }++ @Test+ void senderIdIsSnsServicePrincipalWhenDeliveredFromSnsSubscription() {+ String queueName = "sns-sender-id-queue";+ String topicName = "sns-sender-id-topic";+ String queueUrl = null;+ String topicArn = null;+ String subscriptionArn = null;++ try {+ queueUrl = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateQueue")+ .formParam("QueueName", queueName)+ .when().post("/").then().statusCode(200)+ .extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");++ String queueArn = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "GetQueueAttributes")+ .formParam("QueueUrl", queueUrl)+ .formParam("AttributeName.1", "QueueArn")+ .when().post("/").then().statusCode(200)+ .extract().xmlPath().getString("GetQueueAttributesResponse.GetQueueAttributesResult.Attribute.find { it.Name == 'QueueArn' }.Value");++ topicArn = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateTopic")+ .formParam("Name", topicName)+ .when().post("/").then().statusCode(200)+ .extract().xmlPath().getString("CreateTopicResponse.CreateTopicResult.TopicArn");++ subscriptionArn = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "Subscribe")+ .formParam("TopicArn", topicArn)+ .formParam("Protocol", "sqs")+ .formParam("Endpoint", queueArn)+ .when().post("/").then().statusCode(200)+ .extract().xmlPath().getString("SubscribeResponse.SubscribeResult.SubscriptionArn");++ String authHeader = "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20261001/us-east-1/sns/aws4_request, SignedHeaders=host, Signature=abc";+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", authHeader)+ .formParam("Action", "Publish")+ .formParam("TopicArn", topicArn)+ .formParam("Message", "hello-from-sns")+ .when().post("/").then().statusCode(200);++ XmlPath xml = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "ReceiveMessage")+ .formParam("QueueUrl", queueUrl)+ .formParam("MaxNumberOfMessages", "1")+ .formParam("VisibilityTimeout", "0")+ .formParam("AttributeName.1", "SenderId")+ .when().post("/").then().statusCode(200)+ .body(containsString("<Name>SenderId</Name>"))+ .extract().xmlPath();++ String senderId = xml.getString("ReceiveMessageResponse.ReceiveMessageResult.Message.Attribute.Value");+ assertEquals("sns.amazonaws.com", senderId);+ } finally {+ if (subscriptionArn != null && !subscriptionArn.isEmpty()) {+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "Unsubscribe")+ .formParam("SubscriptionArn", subscriptionArn)+ .when().post("/");+ }+ if (topicArn != null) {+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DeleteTopic")+ .formParam("TopicArn", topicArn)+ .when().post("/");+ }+ deleteQueue(queueUrl);+ }+ }++ @Test+ void senderIdIsNotAttributedToRoleWhenSessionTokenIsMissingOrInvalid() {+ String roleName = "sqs-sender-untrusted-role-test";+ String sessionName = "test-untrusted-session";+ String queueName = "sqs-untrusted-role-queue";+ String queueUrl = null;++ try {+ ValidatableResponse roleResp = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateRole")+ .formParam("RoleName", roleName)+ .formParam("AssumeRolePolicyDocument", ASSUME_ROLE_POLICY_DOCUMENT)+ .header("Authorization", IAM_AUTHORIZATION)+ .when().post("/").then().statusCode(200);++ String roleId = roleResp.extract().xmlPath().getString(+ "CreateRoleResponse.CreateRoleResult.Role.RoleId");+ String roleArn = roleResp.extract().xmlPath().getString(+ "CreateRoleResponse.CreateRoleResult.Role.Arn");++ ValidatableResponse assumed = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "AssumeRole")+ .formParam("RoleArn", roleArn)+ .formParam("RoleSessionName", sessionName)+ .header("Authorization", STS_AUTHORIZATION)+ .when().post("/").then().statusCode(200);++ String roleAccessKeyId = assumed.extract().xmlPath().getString(+ "AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId");+ String assumedRoleId = roleId + ":" + sessionName;++ queueUrl = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateQueue")+ .formParam("QueueName", queueName)+ .when().post("/").then().statusCode(200)+ .extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");++ String roleAuth = "AWS4-HMAC-SHA256 Credential=" + roleAccessKeyId+ + "/20261001/us-east-1/sqs/aws4_request, SignedHeaders=host, Signature=abc";++ // 1. SendMessage without X-Amz-Security-Token -> must not be attributed to assumedRoleId+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", roleAuth)+ .formParam("Action", "SendMessage")+ .formParam("QueueUrl", queueUrl)+ .formParam("MessageBody", "msg-no-token")+ .when().post("/").then().statusCode(200);++ // 2. SendMessage with invalid X-Amz-Security-Token -> must not be attributed to assumedRoleId+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", roleAuth)+ .header("X-Amz-Security-Token", "invalid-token")+ .formParam("Action", "SendMessage")+ .formParam("QueueUrl", queueUrl)+ .formParam("MessageBody", "msg-bad-token")+ .when().post("/").then().statusCode(200);++ XmlPath xml = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "ReceiveMessage")+ .formParam("QueueUrl", queueUrl)+ .formParam("MaxNumberOfMessages", "10")+ .formParam("VisibilityTimeout", "0")+ .formParam("AttributeName.1", "SenderId")+ .when().post("/").then().statusCode(200)+ .extract().xmlPath();++ List<String> senderIds = xml.getList(+ "ReceiveMessageResponse.ReceiveMessageResult.Message.Attribute.Value", String.class);+ assertEquals(2, senderIds.size());+ for (String senderId : senderIds) {+ assertNotEquals(assumedRoleId, senderId);+ assertEquals("000000000000", senderId);+ }+ } finally {+ deleteQueue(queueUrl);+ deleteRole(roleName);+ }+ }++ private void deleteQueue(String queueUrl) {+ if (queueUrl == null) {+ return;+ }+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DeleteQueue")+ .formParam("QueueUrl", queueUrl)+ .when().post("/");+ }++ private void deleteRole(String roleName) {+ if (roleName == null) {+ return;+ }+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DeleteRole")+ .formParam("RoleName", roleName)+ .header("Authorization", IAM_AUTHORIZATION)+ .when().post("/");+ }++ private void deleteAccessKey(String userName, String accessKeyId) {+ if (userName == null || accessKeyId == null) {+ return;+ }+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DeleteAccessKey")+ .formParam("UserName", userName)+ .formParam("AccessKeyId", accessKeyId)+ .header("Authorization", IAM_AUTHORIZATION)+ .when().post("/");+ }++ private void deleteUser(String userName) {+ if (userName == null) {+ return;+ }+ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DeleteUser")+ .formParam("UserName", userName)+ .header("Authorization", IAM_AUTHORIZATION)+ .when().post("/");+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsServiceTest.javaindex aef61e9094..6e225175fc 100644--- a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsServiceTest.java@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.common.RequestContext;import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;import io.github.hectorvent.floci.core.storage.InMemoryStorage;+import io.github.hectorvent.floci.services.iam.IamService;import io.github.hectorvent.floci.services.sns.SnsService;import io.github.hectorvent.floci.services.sqs.model.Message;import io.github.hectorvent.floci.services.sqs.model.MessageAttributeValue;@@ -23,6 +24,7 @@ import java.time.Instant;import java.util.ArrayList;import java.util.List;import java.util.Map;+import java.util.Optional;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;@@ -32,6 +34,8 @@ import java.util.concurrent.atomic.AtomicBoolean;import java.util.concurrent.atomic.AtomicReference;import static org.junit.jupiter.api.Assertions.*;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.eq;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;@@ -2372,4 +2376,108 @@ class SqsServiceTest {sqsService.changeMessageVisibility(queueUrl, receiptHandle, 10, region);}}++ @Test+ void copyForRedrivePreservesSenderId() {+ Message message = new Message("body");+ message.setSenderId("AIDAEXAMPLE");+ Message copy = message.copyForRedrive();+ assertEquals("AIDAEXAMPLE", copy.getSenderId());+ }++ @Test+ void sendMessageStampsSenderIdFromCallerPrincipal() {+ String region = "us-east-1";+ @SuppressWarnings("unchecked")+ Instance<RequestContext> requestContextInstance = mock(Instance.class);+ RequestContext requestContext = new RequestContext();+ requestContext.setAccessKeyId("AKIAIOSFODNN7EXAMPLE");+ requestContext.setAccountId("123456789012");+ when(requestContextInstance.get()).thenReturn(requestContext);++ IamService iamService = mock(IamService.class);+ when(iamService.resolveCallerUserId(eq("AKIAIOSFODNN7EXAMPLE"), any())).thenReturn(Optional.of("AIDAUSER123"));++ SqsService service = new SqsService(new InMemoryStorage<>(), 30, 1048576, BASE_URL, clock,+ requestContextInstance, iamService);+ Queue queue = service.createQueue("sender-id-queue", null, region);++ assertEquals("AIDAUSER123", service.resolveCallerSenderId(queue.getQueueUrl()));+ }++ @Test+ void sendMessageWithoutExplicitSenderIdIgnoresRequestScopeCaller() {+ String region = "us-east-1";+ @SuppressWarnings("unchecked")+ Instance<RequestContext> requestContextInstance = mock(Instance.class);+ RequestContext requestContext = new RequestContext();+ requestContext.setAccessKeyId("AKIAIOSFODNN7EXAMPLE");+ requestContext.setAccountId("123456789012");+ when(requestContextInstance.get()).thenReturn(requestContext);++ IamService iamService = mock(IamService.class);+ when(iamService.resolveCallerUserId(eq("AKIAIOSFODNN7EXAMPLE"), any())).thenReturn(Optional.of("AIDAUSER123"));++ SqsService service = new SqsService(new InMemoryStorage<>(), 30, 1048576, BASE_URL, clock,+ requestContextInstance, iamService);+ Queue queue = service.createQueue("internal-producer-queue", null, region);+ Message message = service.sendMessage(queue.getQueueUrl(), "hello", 0, region);++ assertEquals(service.senderIdFor(queue.getQueueUrl()), message.getSenderId());+ }++ @Test+ void sendMessageFallsBackToAccountIdWhenNoCallerPrincipal() {+ String region = "us-east-1";+ @SuppressWarnings("unchecked")+ Instance<RequestContext> requestContextInstance = mock(Instance.class);+ RequestContext requestContext = new RequestContext();+ requestContext.setAccessKeyId("AKIAOTHERKEY");+ requestContext.setAccountId("123456789012");+ when(requestContextInstance.get()).thenReturn(requestContext);++ IamService iamService = mock(IamService.class);+ when(iamService.resolveCallerUserId(eq("AKIAOTHERKEY"), any())).thenReturn(Optional.empty());++ SqsService service = new SqsService(new InMemoryStorage<>(), 30, 1048576, BASE_URL, clock,+ requestContextInstance, iamService);+ Queue queue = service.createQueue("sender-id-fallback-queue", null, region);++ assertEquals("123456789012", service.resolveCallerSenderId(queue.getQueueUrl()));+ }++ @Test+ void sendMessageOutsideRequestContextFallsBackToQueueOwnerAccount() {+ String region = "us-east-1";+ RegionResolver customResolver = new RegionResolver("us-east-1", "999988887777");+ SqsService service = new SqsService(new InMemoryStorage<>(), null, null, null,+ 30, 1048576, BASE_URL, customResolver, false, null, clock,+ ReceiptHandle.DEFAULT_SECRET, null, null);+ Queue queue = service.createQueue("foreign-account-queue", null, region);+ Message message = service.sendMessage(queue.getQueueUrl(), "hello", 0, region);++ assertEquals("999988887777", message.getSenderId());+ }++ @Test+ void sendMessageUsesExplicitSenderIdWhenProvided() {+ String region = "us-east-1";+ @SuppressWarnings("unchecked")+ Instance<RequestContext> requestContextInstance = mock(Instance.class);+ RequestContext requestContext = new RequestContext();+ requestContext.setAccessKeyId("AKIAIOSFODNN7EXAMPLE");+ requestContext.setAccountId("123456789012");+ when(requestContextInstance.get()).thenReturn(requestContext);++ IamService iamService = mock(IamService.class);+ when(iamService.resolveCallerUserId(eq("AKIAIOSFODNN7EXAMPLE"), any())).thenReturn(Optional.of("AIDAUSER123"));++ SqsService service = new SqsService(new InMemoryStorage<>(), 30, 1048576, BASE_URL, clock,+ requestContextInstance, iamService);+ Queue queue = service.createQueue("sender-id-explicit-queue", null, region);+ Message message = service.sendMessage(queue.getQueueUrl(), "hello", 0, null, null, null, null,+ "sns.amazonaws.com", region);++ assertEquals("sns.amazonaws.com", message.getSenderId());+ }}