fix(cloudtrail): take sourceIPAddress from the connection (#9254)

CloudTrail's sourceIPAddress is the address a request was made from.
Floci took it from the first X-Forwarded-For entry whenever a request
carried one, so any client could choose the address its S3 calls, and
the S3 calls IAM refused, were recorded from. It now comes from the
connection, read in one place, RequestSourceAddress, which the S3
controller and the IAM enforcement filter both call. Behind a reverse
proxy, Quarkus's proxy settings (proxy-address-forwarding,
allow-x-forwarded, trusted-proxies) make the address a trusted proxy
forwards the source address, and only that proxy's. Quarkus takes the
first address in X-Forwarded-For, so the CloudTrail page says the proxy
must replace a client-sent header rather than append to it.

The integration test reads the trail's log files through
CloudTrailLogFiles, which follows the listing across pages, and calls
CloudTrail through CloudTrailRequests, which the CloudTrail tests that
kept their own copy of that call now use too.

Closes #9116

Co-authored-by: Jeremy Chapeau <jeremy.chapeau@gmail.com>
This commit is contained in:
Priamo GermosenandJeremy Chapeau authored and GitHub committed 2026-11-23 08:10:52 -04:00
1 parent b521ee513c
commit f093a0bc6e
12 files changed
+220 -57

No files matched your search

+22
View File
@@ -40,6 +40,28 @@ and `AWS::S3::Object` data resource ARNs in any of these forms:
- `arn:aws:s3:::bucket/prefix` — keys with the given prefix
- `arn:aws:s3:::bucket/prefix/key` — exact key match
## Source address
`sourceIPAddress` is "the IP address that the request was made from"
([CloudTrail record contents](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-event-reference-record-contents.html)):
the address of the connection Floci received the request on. An `X-Forwarded-For` header is not read on its own,
since any client can send one. Behind a reverse proxy, Quarkus's own proxy settings make the address it forwards
the source address, from the proxies they name only:
```bash
QUARKUS_HTTP_PROXY_PROXY_ADDRESS_FORWARDING=true
QUARKUS_HTTP_PROXY_ALLOW_X_FORWARDED=true
QUARKUS_HTTP_PROXY_TRUSTED_PROXIES=10.0.0.5 # the proxy's address or range
```
Quarkus takes the first address in `X-Forwarded-For`, so the proxy must set the header to the address its own
connection came from, replacing any the client sent (nginx's `proxy_set_header X-Forwarded-For $remote_addr`). A
proxy that appends to the client's header (nginx's `$proxy_add_x_forwarded_for`) leaves the client's choice first,
and that is what gets recorded.
With `floci.tls.enabled`, Floci's own TCP proxy relays every connection to Quarkus, so the source address is the
loopback address.
## Encryption and CloudWatch Logs settings
`CreateTrail` and `UpdateTrail` record `KmsKeyId`, `CloudWatchLogsLogGroupArn` and `CloudWatchLogsRoleArn`, and `DescribeTrails` returns them, so a Terraform `aws_cloudtrail` with encryption or log delivery reads back what it declared. `UpdateTrail` with an empty value clears one, as on AWS. A log group without a role is refused with `InvalidCloudWatchLogsRoleArnException`, and a role without a log group with `InvalidCloudWatchLogsLogGroupArnException`. The settings are recorded only: log files are not encrypted, events are not delivered to the log group, and `KmsKeyId` is stored as sent (an alias is not resolved to the key ARN, and an unknown key is not refused).
@@ -1711,13 +1711,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
var req = rc.request();
if (req != null) {
userAgent = req.getHeader("User-Agent");
String fwd = req.getHeader("X-Forwarded-For");
if (fwd != null && !fwd.isBlank()) {
int comma = fwd.indexOf(',');
sourceIp = (comma > 0 ? fwd.substring(0, comma) : fwd).trim();
} else if (req.remoteAddress() != null) {
sourceIp = req.remoteAddress().host();
}
sourceIp = RequestSourceAddress.of(req);
}
}
} catch (Exception e) {
@@ -0,0 +1,22 @@
package io.floci.aws.core.common;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;
/**
* The address a request was made from, as CloudTrail's {@code sourceIPAddress} names it: the address of the
* connection the request arrived on. An {@code X-Forwarded-For} header is not read on its own, since any client can
* send one. Behind a proxy that Quarkus's own proxy settings trust, Quarkus gives the request the address that proxy
* forwards as its remote address.
*/
public final class RequestSourceAddress {
private RequestSourceAddress() {
}
/** The request's remote host, or null when the connection names none. */
public static String of(HttpServerRequest request) {
SocketAddress remote = request.remoteAddress();
return remote != null ? remote.host() : null;
}
}
@@ -16,6 +16,7 @@ import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestContext;
import io.floci.aws.core.common.RequestSourceAddress;
import io.floci.aws.core.common.ResteasyRequests;
import io.floci.aws.core.common.StreamingResponses;
import io.floci.aws.core.common.UuidShapes;
@@ -197,13 +198,7 @@ public class S3Controller {
if (req != null) {
authHeader = req.getHeader("Authorization");
userAgent = req.getHeader("User-Agent");
String fwd = req.getHeader("X-Forwarded-For");
if (fwd != null && !fwd.isBlank()) {
int comma = fwd.indexOf(',');
sourceIp = (comma > 0 ? fwd.substring(0, comma) : fwd).trim();
} else if (req.remoteAddress() != null) {
sourceIp = req.remoteAddress().host();
}
sourceIp = RequestSourceAddress.of(req);
}
}
} catch (Exception e) {
@@ -0,0 +1,36 @@
package io.floci.aws.core.common;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class RequestSourceAddressTest {
@Test
void aClientSentForwardedForIsNotTheSourceAddress() {
HttpServerRequest request = mock(HttpServerRequest.class);
when(request.remoteAddress()).thenReturn(SocketAddress.inetSocketAddress(54321, "127.0.0.1"));
when(request.getHeader("X-Forwarded-For")).thenReturn("203.0.113.7");
assertEquals("127.0.0.1", RequestSourceAddress.of(request));
}
/** Behind a proxy Quarkus trusts, Quarkus makes the forwarded address the request's remote address. */
@Test
void theRemoteAddressQuarkusGivesTheRequestIsTheSourceAddress() {
HttpServerRequest request = mock(HttpServerRequest.class);
when(request.remoteAddress()).thenReturn(SocketAddress.inetSocketAddress(443, "203.0.113.7"));
assertEquals("203.0.113.7", RequestSourceAddress.of(request));
}
@Test
void aConnectionWithoutAnAddressNamesNone() {
assertNull(RequestSourceAddress.of(mock(HttpServerRequest.class)));
}
}
@@ -2,7 +2,6 @@ package io.floci.aws.services.cloudtrail;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
@@ -11,6 +10,7 @@ import java.io.ByteArrayInputStream;
import java.util.UUID;
import java.util.zip.GZIPInputStream;
import static io.floci.aws.services.cloudtrail.CloudTrailRequests.invokeCloudTrail;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -31,9 +31,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class CloudTrailAdvancedSelectorsIntegrationTest {
private static final String CT_TARGET = "CloudTrail_20131101.";
private static final String JSON11 = "application/x-amz-json-1.1";
@Inject
CloudTrailLogWriter writer;
@@ -161,14 +158,6 @@ class CloudTrailAdvancedSelectorsIntegrationTest {
// --- Helpers ---
private static Response invokeCloudTrail(String action, String body) {
return given()
.header("X-Amz-Target", CT_TARGET + action)
.contentType(JSON11)
.body(body)
.when().post("/");
}
private static void createBucket(String name) {
given().when().put("/" + name).then().statusCode(200);
}
@@ -13,6 +13,7 @@ import java.io.ByteArrayInputStream;
import java.util.UUID;
import java.util.zip.GZIPInputStream;
import static io.floci.aws.services.cloudtrail.CloudTrailRequests.invokeCloudTrail;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
@@ -620,14 +621,6 @@ class CloudTrailIntegrationTest {
.when().post("/");
}
private static Response invokeCloudTrail(String action, String body) {
return given()
.header("X-Amz-Target", CT_TARGET + action)
.contentType(JSON11)
.body(body)
.when().post("/");
}
private static void createBucket(String name) {
given().when().put("/" + name).then().statusCode(200);
}
@@ -2,12 +2,12 @@ package io.floci.aws.services.cloudtrail;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.UUID;
import static io.floci.aws.services.cloudtrail.CloudTrailRequests.invokeCloudTrail;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -19,9 +19,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class CloudTrailListingAndTagsIntegrationTest {
private static final String CT_TARGET = "CloudTrail_20131101.";
private static final String JSON11 = "application/x-amz-json-1.1";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
@@ -155,14 +152,6 @@ class CloudTrailListingAndTagsIntegrationTest {
// --- Helpers ---
private static Response invokeCloudTrail(String action, String body) {
return given()
.header("X-Amz-Target", CT_TARGET + action)
.contentType(JSON11)
.body(body)
.when().post("/");
}
private static void createBucket(String name) {
given().when().put("/" + name).then().statusCode(200);
}
@@ -0,0 +1,51 @@
package io.floci.aws.services.cloudtrail;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.restassured.path.xml.XmlPath;
import io.restassured.specification.RequestSpecification;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;
import static io.restassured.RestAssured.given;
/** Reads the records a trail delivered to its S3 bucket, through the S3 API, as a client of the trail would. */
final class CloudTrailLogFiles {
private static final ObjectMapper MAPPER = new ObjectMapper();
private CloudTrailLogFiles() {
}
/** Every record of every log file in {@code bucket}, in key order, across every page of the listing. */
static List<JsonNode> records(String bucket) throws IOException {
List<JsonNode> records = new ArrayList<>();
for (String key : keys(bucket)) {
byte[] gz = given().when().get("/" + bucket + "/" + key).then().statusCode(200).extract().asByteArray();
try (GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(gz))) {
MAPPER.readTree(in).path("Records").forEach(records::add);
}
}
return records;
}
private static List<String> keys(String bucket) {
List<String> keys = new ArrayList<>();
String token = null;
do {
RequestSpecification listing = given().queryParam("list-type", "2");
if (token != null) {
listing = listing.queryParam("continuation-token", token);
}
XmlPath page = listing.when().get("/" + bucket).then().statusCode(200).extract().xmlPath();
keys.addAll(page.getList("ListBucketResult.Contents.Key"));
token = "true".equals(page.getString("ListBucketResult.IsTruncated"))
? page.getString("ListBucketResult.NextContinuationToken") : null;
} while (token != null);
return keys;
}
}
@@ -6,7 +6,6 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.XmlParser;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
@@ -22,6 +21,7 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import static io.floci.aws.services.cloudtrail.CloudTrailRequests.invokeCloudTrail;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -30,8 +30,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class CloudTrailLogWriterBoundedRetryIntegrationTest {
private static final String CT_TARGET = "CloudTrail_20131101.";
private static final String JSON11 = "application/x-amz-json-1.1";
private static final int RETRY_RECORD_LIMIT = 1024;
private static final int PRODUCED_EVENTS = RETRY_RECORD_LIMIT + 80;
@@ -271,14 +269,6 @@ class CloudTrailLogWriterBoundedRetryIntegrationTest {
return new ObjectMapper().readTree(body);
}
private static Response invokeCloudTrail(String action, String body) {
return given()
.header("X-Amz-Target", CT_TARGET + action)
.contentType(JSON11)
.body(body)
.when().post("/");
}
private static void createBucket(String name) {
given().when().put("/" + name).then().statusCode(200);
}
@@ -0,0 +1,20 @@
package io.floci.aws.services.cloudtrail;
import io.restassured.response.Response;
import static io.restassured.RestAssured.given;
/** CloudTrail's JSON 1.1 calls, as the integration tests send them: the action in {@code X-Amz-Target}. */
final class CloudTrailRequests {
private CloudTrailRequests() {
}
static Response invokeCloudTrail(String action, String body) {
return given()
.header("X-Amz-Target", "CloudTrail_20131101." + action)
.contentType("application/x-amz-json-1.1")
.body(body)
.when().post("/");
}
}
@@ -0,0 +1,62 @@
package io.floci.aws.services.cloudtrail;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.UUID;
import static io.floci.aws.services.cloudtrail.CloudTrailRequests.invokeCloudTrail;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
/**
* {@code sourceIPAddress} is "the IP address that the request was made from"
* (https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-event-reference-record-contents.html):
* the connection's, not an {@code X-Forwarded-For} any client can send.
*/
@QuarkusTest
class CloudTrailSourceAddressIntegrationTest {
@Inject
CloudTrailLogWriter writer;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void aClientSentForwardedForIsNotTheSourceAddress() throws IOException {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String bucket = "ct-src-" + suffix;
String logs = "ct-src-logs-" + suffix;
String trail = "ct-src-" + suffix;
given().when().put("/" + bucket).then().statusCode(200);
given().when().put("/" + logs).then().statusCode(200);
cloudTrail("CreateTrail", "{\"Name\":\"" + trail + "\",\"S3BucketName\":\"" + logs + "\"}");
cloudTrail("PutEventSelectors", "{\"TrailName\":\"" + trail + "\",\"EventSelectors\":[{\"ReadWriteType\":"
+ "\"All\",\"IncludeManagementEvents\":false,\"DataResources\":[{\"Type\":\"AWS::S3::Object\","
+ "\"Values\":[\"arn:aws:s3:::" + bucket + "/\"]}]}]}");
cloudTrail("StartLogging", "{\"Name\":\"" + trail + "\"}");
given().header("X-Forwarded-For", "203.0.113.7").body("x")
.when().put("/" + bucket + "/forwarded.txt").then().statusCode(200);
writer.flushNow();
String recorded = CloudTrailLogFiles.records(logs).stream()
.filter(r -> "forwarded.txt".equals(r.path("requestParameters").path("key").asText()))
.map(r -> r.path("sourceIPAddress").asText())
.findFirst()
.orElseThrow(() -> new AssertionError("no record of the forwarded write in " + logs));
assertThat(recorded, equalTo("127.0.0.1"));
}
private static void cloudTrail(String action, String body) {
invokeCloudTrail(action, body).then().statusCode(200);
}
}