diff --git a/docs/services/iam.md b/docs/services/iam.md index d2ca2d577d..bccb60b19c 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -898,6 +898,42 @@ with `UpdateUser` carries all of them to the new name, along with its login prof group membership. Unlike AWS, Floci does not rewrite policy documents that name the user's ARN, so a resource or trust policy that referred to the old name still refers to it after a rename. +### What a session's token costs, and when it is refused + +AWS holds a session token to one limit: STS "has replaced the packed policy size and the overall +session token size limits with a single token size limit of 4,096 bytes", so "the assembled session +token must fit within 4,096 bytes" and "the separate packed policy limit, which made failures hard +to predict, has been removed". A request whose token will not fit is refused with +`PackedPolicyTooLarge` 400, whose "error message reports the session token size and the maximum +allowed size, both in bytes": `Serialized token too large for session. Token size of bytes +exceeds the maximum allowed limit of 4096 bytes.` What a session that does fit consumed is +published as a percentage. `SessionTokenUtilization` is "the percentage of the 4,096-byte limit +consumed", and `PackedPolicySize` "now reports the same value as SessionTokenUtilization", kept +"for backward compatibility" where the API reference marks it deprecated. + +This emulator refused nothing and published that member as a flat zero on every session, so a +caller could neither see what its session cost nor be told it was over. Both are answered now, on +the four operations that carry state into the token they mint: `AssumeRole`, `AssumeRoleWithSAML`, +`AssumeRoleWithWebIdentity` and `GetFederationToken`. The refusal is read before anything is +minted, which is where AWS answers it. A token asked through `MinimumSessionTokenSize` to be the +limit itself therefore leaves nothing to carry a policy or a tag on top of it, and a request that +asks for both is refused. `GetDelegatedAccessToken` carries no such state, and the member stays out +of its response as the model deprecates it there. `SessionTokenSize` and `SessionTokenUtilization`, +the two members the model now carries beside `PackedPolicySize`, are not published yet. + +The measure is this emulator's own and the number will differ from AWS's. It is the token this +emulator will mint for the request, whose length `MinimumSessionTokenSize` can ask to be raised, +plus the state the request asks to carry into it in UTF-8 bytes: the inline document, every policy +ARN, and every tag key and value. AWS assembles the real thing instead, and its size follows the +input in neither direction. STS "serializes and compresses your session policies and tags when +assembling the token", where "compression results vary based on the actual content, not just its +length" and "two sets of tags with identical character counts can produce different token sizes", +so a repetitive set can assemble smaller than the bytes it was written in. The one size recorded +here ran larger than its input: for a request of 50 tags with 124-character keys and 256-character +values, every field inside its own limit, AWS reported 26092 bytes against the limit of 4096, where +those fields are about 19000 bytes of input. A recording of a second size would let the measure be +calibrated, and that is the only thing this reading waits on. + ### Policy Simulation | Action | Description | diff --git a/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java b/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java index 45b617ffb5..91a3a59ddb 100644 --- a/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java +++ b/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java @@ -34,6 +34,7 @@ import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.UriInfo; import org.jboss.logging.Logger; +import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.security.interfaces.RSAPublicKey; import java.time.Clock; @@ -46,6 +47,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.concurrent.ThreadLocalRandom; /** @@ -142,6 +144,15 @@ public class StsQueryHandler { public Response handle(String action, MultivaluedMap params) { LOG.debugv("STS action: {0}", action); + // A session whose token will not fit is refused before anything is minted, on every + // operation that carries state into the token it mints. + if (PACKED_SESSION_OPERATIONS.contains(action)) { + AssembledSession session = assembledSession(params); + if (session.tooLarge()) { + return session.refusal(); + } + } + return switch (action) { case "AssumeRole" -> handleAssumeRole(params); case "GetCallerIdentity" -> handleGetCallerIdentity(params); @@ -224,11 +235,94 @@ public class StsQueryHandler { .elem("Arn", assumedRoleArn) .elem("AssumedRoleId", assumedRoleId) .end("AssumedRoleUser") - .elem("PackedPolicySize", "0") + .elem("PackedPolicySize", assembledSession(params).utilization()) .build(); return Response.ok(AwsQueryResponse.envelope("AssumeRole", AwsNamespaces.STS, result)).build(); } + /** + * The one limit AWS enforces on a session token, which its refusal names as well. AWS "has + * replaced the packed policy size and the overall session token size limits with a single + * token size limit of 4,096 bytes": "the assembled session token must fit within 4,096 bytes", + * and "the separate packed policy limit, which made failures hard to predict, has been + * removed". + */ + private static final int SESSION_TOKEN_LIMIT = 4096; + + /** The operations that carry state into the token they mint and model the refusal for it. */ + private static final Set PACKED_SESSION_OPERATIONS = Set.of( + "AssumeRole", "AssumeRoleWithSAML", "AssumeRoleWithWebIdentity", "GetFederationToken"); + + /** + * What a request's session token comes to, and what that costs against the limit it is held + * to. + * + *

AWS "serializes and compresses your session policies and tags when assembling the token", + * refuses a token that will not fit with {@code PackedPolicyTooLarge} 400, whose "error + * message reports the session token size and the maximum allowed size, both in bytes", and + * reports what a session that does fit consumed: {@code SessionTokenUtilization} is "the + * percentage of the 4,096-byte limit consumed", and {@code PackedPolicySize} "now reports the + * same value as SessionTokenUtilization", kept "for backward compatibility" where the API + * reference calls it deprecated. This emulator refused nothing and published that member as a + * flat zero on every session, so a caller could neither see what its session cost nor be told + * it was over. + * + *

The measure is this emulator's own: the token it will mint for the request, whose length + * {@code MinimumSessionTokenSize} can ask to be raised, plus the state the request asks to + * carry into it, in UTF-8 bytes. AWS's assembly is unpublished and its size does not read off + * the input in either direction, since "compression results vary based on the actual content, + * not just its length" and "two sets of tags with identical character counts can produce + * different token sizes", while the one size recorded here ran larger than the bytes going in, + * 26092 for a request carrying about 19000. So this number will differ from AWS's, and + * {@code docs/services/iam.md} records the figure that was recorded so a later one can + * calibrate the reading. + */ + private record AssembledSession(int bytes) { + + boolean tooLarge() { + return bytes > SESSION_TOKEN_LIMIT; + } + + /** + * The member's own unit, truncated as AWS's own recorded pair reports it: a token of 2532 + * bytes is published as 61. + */ + String utilization() { + return Integer.toString(bytes * 100 / SESSION_TOKEN_LIMIT); + } + + Response refusal() { + return AwsQueryResponse.error("PackedPolicyTooLarge", + "Serialized token too large for session. Token size of " + bytes + + " bytes exceeds the maximum allowed limit of " + + SESSION_TOKEN_LIMIT + " bytes.", AwsNamespaces.STS, 400); + } + } + + /** + * What the request's token comes to: the length this emulator will mint for it, and the state + * it asks to carry, which is the inline document, every policy ARN, and every tag key and + * value. {@code TransitiveTagKeys} names tags already counted, so it adds nothing of its own, + * which is what AWS says of its own packing as well: "the transitive status of a session tag + * does not impact its packed binary size". + */ + private AssembledSession assembledSession(MultivaluedMap params) { + StringBuilder state = new StringBuilder(); + String document = params.getFirst("Policy"); + if (document != null) { + state.append(document); + } + for (AwsQueryLists.IndexedMember arn : AwsQueryLists.members(params, "PolicyArns", null)) { + String value = params.getFirst(arn.prefix() + ".arn"); + if (value != null) { + state.append(value); + } + } + tagClaims(params).forEach((key, value) -> state.append(key).append(value)); + return new AssembledSession(sessionTokenLength(params) + + state.toString().getBytes(StandardCharsets.UTF_8).length); + } + /** * What a call's MFA parameters authenticated: the instant the device was used, or the denial * that answers a device the caller cannot present. Both {@code GetSessionToken} and @@ -528,7 +622,7 @@ public class StsQueryHandler { .elem("Arn", assumedRoleArn) .elem("AssumedRoleId", assumedRoleId) .end("AssumedRoleUser") - .elem("PackedPolicySize", "0") + .elem("PackedPolicySize", assembledSession(params).utilization()) .elem("Provider", provider) .elem("Audience", audience) .elem("SubjectFromWebIdentityToken", subject) @@ -726,7 +820,7 @@ public class StsQueryHandler { String result = new XmlBuilder() .raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration)) .start("AssumedRoleUser").elem("Arn", assumedRoleArn).elem("AssumedRoleId", assumedRoleId).end("AssumedRoleUser") - .elem("PackedPolicySize", "0").elem("Issuer", verified.issuer()).elem("Audience", "urn:amazon:webservices") + .elem("PackedPolicySize", assembledSession(params).utilization()).elem("Issuer", verified.issuer()).elem("Audience", "urn:amazon:webservices") .elem("NameQualifier", verified.nameQualifier()).elem("SubjectType", verified.subjectType()).elem("Subject", verified.subject()).build(); return Response.ok(AwsQueryResponse.envelope("AssumeRoleWithSAML", AwsNamespaces.STS, result)).build(); } @@ -782,7 +876,7 @@ public class StsQueryHandler { .elem("FederatedUserId", federatedUserId) .elem("Arn", federatedUserArn) .end("FederatedUser") - .elem("PackedPolicySize", "0") + .elem("PackedPolicySize", assembledSession(params).utilization()) .build(); return Response.ok(AwsQueryResponse.envelope("GetFederationToken", AwsNamespaces.STS, result)).build(); } @@ -1233,15 +1327,22 @@ public class StsQueryHandler { } /** - * The session token for a request: the length its {@code MinimumSessionTokenSize} asks for, - * never under the 200 characters this emulator mints by default. Every operation that models - * the member answers it from here, so the floor is written once, and the model holds the value - * to the 0 to 4096 it declares ahead of this. A request asking for less than the floor is - * answered with the floor, which is what "minimum" asks for. + * The session token for a request, the length {@link #sessionTokenLength} gives it. Every + * operation that models the member answers it from here, so the floor is written once. */ private String sessionToken(MultivaluedMap params) { - return randomSecret(Math.max(SESSION_TOKEN_LENGTH, - getIntParam(params, "MinimumSessionTokenSize", 0))); + return randomSecret(sessionTokenLength(params)); + } + + /** + * How long the token for a request will be: the length its {@code MinimumSessionTokenSize} + * asks for, never under the 200 characters this emulator mints by default, which is what a + * minimum asks for, and never over the limit a token is held to, so a value outside the 0 to + * 4096 the model declares is answered by the shape rather than read as a size here. + */ + private int sessionTokenLength(MultivaluedMap params) { + return Math.max(SESSION_TOKEN_LENGTH, + Math.min(getIntParam(params, "MinimumSessionTokenSize", 0), SESSION_TOKEN_LIMIT)); } private String randomSecret(int length) { diff --git a/src/test/java/io/floci/aws/services/iam/StsPackedSessionIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/StsPackedSessionIntegrationTest.java new file mode 100644 index 0000000000..befc764001 --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/StsPackedSessionIntegrationTest.java @@ -0,0 +1,192 @@ +package io.floci.aws.services.iam; + +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +/** + * What a request asks to carry into its session token, and what AWS does when the token will not + * fit the one limit it is held to. A session over that limit is refused with + * {@code PackedPolicyTooLarge} rather than minted, and {@code PackedPolicySize} reports the + * percentage of the limit the session consumes, which is what the member is defined as, rather + * than a flat zero. + * + *

{@code docs/services/iam.md} records the measure, which is this emulator's own, and the one + * recorded size that shows AWS's assembly running larger than the bytes going in. + */ +@QuarkusTest +class StsPackedSessionIntegrationTest { + + private static final String STS_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20261118/us-east-1/sts/aws4_request"; + + private static final String CODE = "ErrorResponse.Error.Code"; + private static final String MESSAGE = "ErrorResponse.Error.Message"; + + /** Every field inside its own declared limit, and the set as a whole far past the packed one. */ + private static final int TAGS = 50; + private static final int KEY_LENGTH = 124; + private static final int VALUE_LENGTH = 256; + + private static final String IAM_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20261118/us-east-1/iam/aws4_request"; + + private static final String TRUST_POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":" + + "[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"*\"}," + + "\"Action\":\"sts:AssumeRole\"}]}"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + private static RequestSpecification sts(String action) { + return given().header("Authorization", STS_AUTH).formParam("Action", action); + } + + private static RequestSpecification iam(String action) { + return given().header("Authorization", IAM_AUTH).formParam("Action", action); + } + + /** + * A role of this class's own, assumable by anything, because the two cases that reach the + * operation need one to exist and a role another class creates is not this class's to rely on. + */ + private String roleArn() { + String roleName = "packed-session-role-" + Long.toString(System.nanoTime(), 36); + iam("CreateRole").formParam("RoleName", roleName) + .formParam("AssumeRolePolicyDocument", TRUST_POLICY) + .when().post("/").then().statusCode(200); + cleanup.register(() -> iam("DeleteRole").formParam("RoleName", roleName) + .when().post("/").then().statusCode(200)); + return "arn:aws:iam::000000000000:role/" + roleName; + } + + private static String repeat(char c, int length) { + return String.valueOf(c).repeat(length); + } + + /** A tag set of the recorded shape: 50 tags, each key 124 characters and each value 256. */ + private static RequestSpecification withRecordedTagSet(RequestSpecification request) { + for (int i = 1; i <= TAGS; i++) { + String index = String.format("%03d", i); + request = request + .formParam("Tags.member." + i + ".Key", index + repeat('k', KEY_LENGTH - 3)) + .formParam("Tags.member." + i + ".Value", index + repeat('v', VALUE_LENGTH - 3)); + } + return request; + } + + /** The length this emulator mints a token at when the request asks for nothing longer. */ + private static final int MINTED_TOKEN_LENGTH = 200; + + /** The limit a session token is held to, which the refusal names. */ + private static final int LIMIT = 4096; + + /** What the measure reports for that set: the token it would be carried in, and the set. */ + private static int recordedSetBytes() { + return MINTED_TOKEN_LENGTH + TAGS * (KEY_LENGTH + VALUE_LENGTH); + } + + /** + * The request AWS refuses: every member inside its own limit and the packed state far over. + * Nothing is minted, and the sentence names the size and the limit. + */ + @Test + void anOversizedSessionIsRefusedRatherThanMinted() { + withRecordedTagSet(sts("AssumeRole") + .formParam("RoleArn", roleArn()) + .formParam("RoleSessionName", "packed-session")) + .when().post("/").then().statusCode(400) + .body(CODE, equalTo("PackedPolicyTooLarge")) + .body(MESSAGE, equalTo("Serialized token too large for session. Token size of " + + recordedSetBytes() + + " bytes exceeds the maximum allowed limit of " + LIMIT + " bytes.")); + } + + /** The same holds for the federated session, which models the same error. */ + @Test + void anOversizedFederatedSessionIsRefusedTheSameWay() { + withRecordedTagSet(sts("GetFederationToken").formParam("Name", "packed-federated")) + .when().post("/").then().statusCode(400) + .body(CODE, equalTo("PackedPolicyTooLarge")); + } + + /** And for a web identity session, whose state is its documents rather than tags. */ + @Test + void anOversizedWebIdentitySessionIsRefusedTheSameWay() { + RequestSpecification request = sts("AssumeRoleWithWebIdentity") + .formParam("RoleArn", roleArn()) + .formParam("RoleSessionName", "packed-web") + .formParam("WebIdentityToken", "a.b.c"); + for (int i = 1; i <= 3; i++) { + request = request.formParam("PolicyArns.member." + i + ".arn", + "arn:aws:iam::000000000000:policy/" + repeat('p', 1900)); + } + request.when().post("/").then().statusCode(400) + .body(CODE, equalTo("PackedPolicyTooLarge")); + } + + /** + * A session whose token fits is minted and reports what the session consumes, where the member + * used to read zero whatever the request asked to carry. + */ + @Test + void aSessionWithinTheLimitReportsWhatItCosts() { + String document = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Action\":\"s3:GetObject\",\"Resource\":\"arn:aws:s3:::" + + repeat('b', 1000) + "/*\"}]}"; + int percent = (MINTED_TOKEN_LENGTH + document.length()) * 100 / LIMIT; + sts("AssumeRole").formParam("RoleArn", roleArn()) + .formParam("RoleSessionName", "packed-within") + .formParam("Policy", document) + .when().post("/").then().statusCode(200) + .body("AssumeRoleResponse.AssumeRoleResult.PackedPolicySize", + equalTo(Integer.toString(percent))); + } + + /** + * A session carrying nothing still reports what its own token costs, the member being the + * percentage of the limit the token consumes rather than the cost of the state alone. + */ + @Test + void aSessionCarryingNothingReportsWhatItsTokenCosts() { + sts("AssumeRole").formParam("RoleArn", roleArn()) + .formParam("RoleSessionName", "packed-empty") + .when().post("/").then().statusCode(200) + .body("AssumeRoleResponse.AssumeRoleResult.PackedPolicySize", + equalTo(Integer.toString(MINTED_TOKEN_LENGTH * 100 / LIMIT))); + } + + /** + * A token asked to be as long as the limit allows consumes all of it, which is the case the + * old reading answered with a zero: {@code MinimumSessionTokenSize} raises the token "to at + * least this size, regardless of its actual content", and nothing is carried on top of it. + */ + @Test + void aTokenPaddedToTheLimitReportsAllOfIt() { + sts("AssumeRole").formParam("RoleArn", roleArn()) + .formParam("RoleSessionName", "packed-padded") + .formParam("MinimumSessionTokenSize", Integer.toString(LIMIT)) + .when().post("/").then().statusCode(200) + .body("AssumeRoleResponse.AssumeRoleResult.PackedPolicySize", equalTo("100")); + } + + /** State on top of a token already at the limit does not fit, and the sentence names the size. */ + @Test + void stateOnTopOfAPaddedTokenIsRefused() { + sts("AssumeRole").formParam("RoleArn", roleArn()) + .formParam("RoleSessionName", "packed-padded-over") + .formParam("MinimumSessionTokenSize", Integer.toString(LIMIT)) + .formParam("Tags.member.1.Key", "team") + .formParam("Tags.member.1.Value", "payments") + .when().post("/").then().statusCode(400) + .body(CODE, equalTo("PackedPolicyTooLarge")) + .body(MESSAGE, equalTo("Serialized token too large for session. Token size of " + + (LIMIT + "team".length() + "payments".length()) + + " bytes exceeds the maximum allowed limit of " + LIMIT + " bytes.")); + } +}