diff --git a/docs/services/iam.md b/docs/services/iam.md index 0ced23f51c..d2ba1633db 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -765,6 +765,28 @@ request itself still passes through the filter). Both are deliberate non-goals would require IAM to resolve the caller's organization directly, which is the dependency the lazily-resolved `ScpProvider` exists to avoid. +## Unsigned requests + +With enforcement on, a request carrying no `Authorization` header is refused with +`403 MissingAuthenticationToken` when its wire shape names a management operation: a JSON, CBOR or +Query request, identified by `X-Amz-Target`, an rpcv2 path or an `Action` parameter. + +Two carve-outs, both deliberate. + +**Operations AWS serves without credentials are still allowed.** Signing up or signing in to a +Cognito user pool, and `AssumeRoleWithWebIdentity`, happen before the caller has any AWS +credentials, so AWS marks them as needing none and Floci does the same. The list is taken from the +`authtype: none` trait in AWS's own service models and covers the Cognito user-pool and identity +flows and the two web-identity and SAML `AssumeRole` calls. A Cognito `Admin*` operation is not in that set and does require a signature. + +The refusal arrives in the encoding the request used: XML for Query, CBOR for a CBOR request, JSON +otherwise. + +**REST requests are not checked.** The same filter sees the API Gateway execute path, Lambda +function URLs, CloudFront serving, the Cognito OIDC endpoints and Floci's own health endpoint, all +of which are unsigned by design, and a REST request does not say which service will serve it. An +unsigned REST call therefore still reaches the service, including an unsigned S3 call. + ## Bypass rules Enforcement is deliberately permissive in a few cases, so that enabling it does not break workloads @@ -773,6 +795,8 @@ the emulator cannot reason about: | Case | Behaviour | | --- | --- | | Unresolvable action | Allowed. An action the registry cannot resolve is not evaluated. | +| No `Authorization` header, RPC protocol | **Rejected** with `403 MissingAuthenticationToken`, unless the operation is one AWS itself serves without credentials. | +| No `Authorization` header, REST protocol | Allowed. This filter also sees the API Gateway execute path, Lambda function URLs, CloudFront serving and the Cognito OIDC endpoints, which are unsigned by design. | | `sts:GetCallerIdentity` | Always allowed — AWS returns caller identity even when a policy denies it. | | Access key that exists nowhere | **Rejected** with `403`, in each protocol's own vocabulary: `InvalidAccessKeyId` for S3, `InvalidClientTokenId` for Query services, `UnrecognizedClientException` for JSON services. Allowing it would let any string authorize the request. | | Known credential with no mappable caller context | Allowed. A stored session carrying no role ARN is a real credential, so it is not treated as unauthenticated. | diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsCborContentTypeFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsCborContentTypeFilter.java index e4478d7bad..87c206c22d 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsCborContentTypeFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsCborContentTypeFilter.java @@ -12,7 +12,7 @@ import jakarta.ws.rs.ext.Provider; @Priority(Priorities.HEADER_DECORATOR) public class AwsCborContentTypeFilter implements ContainerRequestFilter { - static final String ORIGINAL_CONTENT_TYPE_HEADER = "X-Floci-Original-Content-Type"; + public static final String ORIGINAL_CONTENT_TYPE_HEADER = "X-Floci-Original-Content-Type"; private static final String AWS_CBOR_1_1_MEDIA_TYPE = "application/x-amz-cbor-1.1"; private static final String GENERIC_CBOR_MEDIA_TYPE = "application/cbor"; diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java index b7d97a00a7..8b6073519d 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java @@ -497,19 +497,7 @@ public class AwsJsonCborController { } private Response cborErrorResponse(AwsException e, String protocolHeader, String mediaType) { - try { - byte[] errBytes = CBOR_MAPPER.writeValueAsBytes( - new AwsErrorResponse(e.jsonType(), e.getMessage())); - String queryErrorFault = (e.getHttpStatus() < 500) ? "Sender" : "Receiver"; - return Response.status(e.getHttpStatus()) - .header(protocolHeader, "rpc-v2-cbor") - .header("x-amzn-query-error", e.getErrorCode() + ";" + queryErrorFault) - .type(mediaType) - .entity(errBytes) - .build(); - } catch (Exception ex) { - return Response.status(e.getHttpStatus()).build(); - } + return CborErrorResponses.of(e, mediaType); } private String responseContentType(HttpHeaders httpHeaders) { diff --git a/src/main/java/io/github/hectorvent/floci/core/common/CborErrorResponses.java b/src/main/java/io/github/hectorvent/floci/core/common/CborErrorResponses.java new file mode 100644 index 0000000000..1328e1ce9d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/CborErrorResponses.java @@ -0,0 +1,44 @@ +package io.github.hectorvent.floci.core.common; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.cbor.CBORFactory; +import jakarta.ws.rs.core.Response; + +/** + * The one shape a CBOR error takes: a CBOR-encoded {@link AwsErrorResponse}, the + * {@code smithy-protocol} header, and the query-error header AWS sends alongside it. Shared so the + * rpcv2 controller and {@link IamEnforcementFilter} cannot drift into answering the same failure + * two different ways, which is how a CBOR client ends up unable to decode a rejection. + */ +public final class CborErrorResponses { + + public static final String AWS_CBOR_1_1_MEDIA_TYPE = "application/x-amz-cbor-1.1"; + public static final String GENERIC_CBOR_MEDIA_TYPE = "application/cbor"; + + private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory()); + + private CborErrorResponses() { + } + + /** The CBOR media type matching what the request sent, defaulting to the generic one. */ + public static String mediaTypeFor(String requestContentType) { + return requestContentType != null && requestContentType.contains("x-amz-cbor") + ? AWS_CBOR_1_1_MEDIA_TYPE + : GENERIC_CBOR_MEDIA_TYPE; + } + + public static Response of(AwsException e, String mediaType) { + try { + byte[] body = CBOR_MAPPER.writeValueAsBytes(new AwsErrorResponse(e.jsonType(), e.getMessage())); + String fault = e.getHttpStatus() < 500 ? "Sender" : "Receiver"; + return Response.status(e.getHttpStatus()) + .header("smithy-protocol", "rpc-v2-cbor") + .header("x-amzn-query-error", e.getErrorCode() + ";" + fault) + .type(mediaType) + .entity(body) + .build(); + } catch (Exception ex) { + return Response.status(e.getHttpStatus()).build(); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java index 4c65547222..ce36a14709 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java @@ -30,6 +30,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -71,6 +72,76 @@ public class IamEnforcementFilter implements ContainerRequestFilter { /** AWS's wording for a credential it does not recognise. */ private static final String INVALID_SECURITY_TOKEN = "The security token included in the request is invalid."; + /** AWS's wording for a request that carries no credentials at all. */ + private static final String MISSING_AUTHENTICATION_TOKEN = + "The request must contain a valid AWS access key ID or X.509 certificate."; + + /** + * Operations AWS itself serves without credentials, so an unsigned call on one is a normal + * client rather than an unauthenticated caller. Taken from the {@code authtype: none} trait in + * botocore's service models (Smithy's {@code noAuth}), restricted to the operations Floci + * serves. Keyed by service because the name alone is not enough: {@code GetUser} needs no + * credentials on {@code cognito-idp} and requires them on {@code iam}. + * + *

Add to this when Floci starts serving another operation AWS marks {@code noAuth}. + * Omitting one makes enforcement refuse a call AWS accepts; adding one that AWS does sign + * leaves that operation unauthenticated. + * + *

Only an operation reachable over a checked protocol needs an entry, since + * {@link WireProtocol#REST} is not checked at all. {@code signin}, {@code sso} and + * {@code sso-oidc} also carry {@code noAuth} operations and are absent for that reason rather + * than by oversight: the SSO portal calls are served on REST routes, and the {@code sso} JSON + * target reaches SSO Admin, whose operations AWS does sign. + */ + private static final Map> NO_AUTH_OPERATIONS = Map.of( + "cognito-idp", Set.of( + "AssociateSoftwareToken", + "ChangePassword", + "CompleteWebAuthnRegistration", + "ConfirmDevice", + "ConfirmForgotPassword", + "ConfirmSignUp", + "DeleteUser", + "DeleteUserAttributes", + "DeleteWebAuthnCredential", + "ForgetDevice", + "ForgotPassword", + "GetDevice", + "GetTokensFromRefreshToken", + "GetUser", + "GetUserAttributeVerificationCode", + "GetUserAuthFactors", + "GlobalSignOut", + "InitiateAuth", + "ListDevices", + "ListWebAuthnCredentials", + "ResendConfirmationCode", + "RespondToAuthChallenge", + "RevokeToken", + "SetUserMFAPreference", + "SetUserSettings", + "SignUp", + "StartWebAuthnRegistration", + "UpdateAuthEventFeedback", + "UpdateDeviceStatus", + "UpdateUserAttributes", + "VerifySoftwareToken", + "VerifyUserAttribute"), + "cognito-identity", Set.of( + "GetCredentialsForIdentity", + "GetId", + "GetOpenIdToken", + "UnlinkIdentity")); + + /** + * The same for the Query protocol, where the claim carries no service: an unsigned Query + * request has no credential scope to derive one from. Both names are unique across the Query + * services Floci serves, so the operation alone identifies them. + */ + private static final Set NO_AUTH_QUERY_OPERATIONS = Set.of( + "AssumeRoleWithSAML", + "AssumeRoleWithWebIdentity"); + /** * Implicit identity policy for the account-root principal: full access, bounded only by SCPs. * The account root is not a registered IAM identity, so it has no stored identity policy. @@ -182,6 +253,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { auth = presignedCredentialAsAuthorization(ctx); } if (auth == null) { + refuseUnsignedManagementCall(ctx); return; } @@ -906,6 +978,80 @@ public class IamEnforcementFilter implements ContainerRequestFilter { return Response.status(403).type(MediaType.APPLICATION_JSON).entity(body).build(); } + /** + * Refuses an unsigned request whose wire shape makes it a management API call. A JSON, CBOR or + * Query claim exists only for a request carrying {@code X-Amz-Target}, an rpcv2 path or an + * {@code Action} parameter, and no public data plane speaks any of those, so an unsigned one is + * an unauthenticated call on a control-plane API. + * + *

REST is deliberately left alone. This single filter also sees the API Gateway execute + * path, Lambda function URLs, CloudFront serving, the Cognito OIDC endpoints and Floci's own + * health endpoint, all unsigned by design, and a {@code rest()} claim cannot tell those from an + * unsigned S3 call. Separating them needs the route to name its service, which the catalog does + * not yet carry for the REST services; that half is tracked with the other route-derived gap. + */ + private void refuseUnsignedManagementCall(ContainerRequestContext ctx) { + if (!(ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim) + || claim.protocol() == WireProtocol.REST + || servesWithoutCredentials(claim, ctx)) { + return; + } + LOG.debugv("Refusing unsigned {0} request under IAM enforcement", claim.protocol()); + ctx.abortWith(missingAuthenticationTokenResponse(claim.protocol(), ctx)); + } + + /** Whether the operation this request names is one AWS serves without credentials. */ + private boolean servesWithoutCredentials(ProtocolClaim claim, ContainerRequestContext ctx) { + if (claim.protocol() == WireProtocol.AWS_QUERY) { + return NO_AUTH_QUERY_OPERATIONS.contains(queryOperation(ctx)); + } + if (claim.service() == null || claim.operation() == null) { + // Nothing names the operation, so there is nothing to match against the list. Refusing + // is the safe side of that: an unsigned request whose shape cannot even be read is not + // one of the public flows. + return false; + } + return NO_AUTH_OPERATIONS + .getOrDefault(claim.service().externalKey(), Set.of()) + .contains(claim.operation()); + } + + /** + * The {@code Action} a Query request names, via the registry so the form body is read and put + * back the one way this codebase already does it. The scope passed in is a placeholder: for a + * Query request the registry returns {@code :} and only the suffix is wanted. + */ + private String queryOperation(ContainerRequestContext ctx) { + String resolved = actionRegistry.resolve("", ctx); + return resolved == null ? null : resolved.substring(resolved.indexOf(':') + 1); + } + + /** + * AWS answers a request carrying no credentials with {@code MissingAuthenticationToken} at 403, + * "The request must contain a valid AWS access key ID or X.509 certificate." The JSON form of + * the name carries the {@code Exception} suffix, as {@code ApiGatewayExecuteController} already + * returns for the same failure on its own path. + */ + static Response missingAuthenticationTokenResponse(WireProtocol protocol, ContainerRequestContext ctx) { + if (protocol == WireProtocol.RPCV2_CBOR || protocol == WireProtocol.AWS_CBOR_TARGET) { + // A CBOR client cannot read a JSON body, so the rejection has to arrive in the encoding + // the request used, the same shape the rpcv2 controller returns for its own errors. + String requestContentType = ctx.getHeaderString(AwsCborContentTypeFilter.ORIGINAL_CONTENT_TYPE_HEADER); + if (requestContentType == null) { + requestContentType = ctx.getHeaderString("Content-Type"); + } + return CborErrorResponses.of( + new AwsException("MissingAuthenticationTokenException", MISSING_AUTHENTICATION_TOKEN, 403), + CborErrorResponses.mediaTypeFor(requestContentType)); + } + if (isFormEncoded(ctx.getMediaType())) { + return queryXmlError("MissingAuthenticationToken", MISSING_AUTHENTICATION_TOKEN); + } + String body = "{\"__type\":\"MissingAuthenticationTokenException\",\"message\":\"" + + MISSING_AUTHENTICATION_TOKEN + "\"}"; + return Response.status(403).type(MediaType.APPLICATION_JSON).entity(body).build(); + } + private static Response jsonAccessDenied(String message) { String body = "{\"__type\":\"AccessDeniedException\",\"message\":\"" + message + "\"}"; return Response.status(403).type(MediaType.APPLICATION_JSON).entity(body).build(); diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksIrsaDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksIrsaDockerIntegrationTest.java index bc21e02906..d097a9ab30 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eks/EksIrsaDockerIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksIrsaDockerIntegrationTest.java @@ -44,6 +44,16 @@ class EksIrsaDockerIntegrationTest { private static final Logger LOG = Logger.getLogger(EksIrsaDockerIntegrationTest.class); private static final String FORM = "application/x-www-form-urlencoded"; + + /** + * The root stand-in credential, for the IAM fixtures this test sets up. Those are ordinary + * management calls that AWS signs, and this test runs with enforcement on, so they carry a + * credential. The AssumeRoleWithWebIdentity calls under test stay unsigned on purpose: AWS + * serves that operation without credentials, which is the whole point of web identity. + */ + private static final String SETUP_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/iam/aws4_request, " + + "SignedHeaders=host, Signature=setup"; private static final String ACCOUNT = "000000000000"; public static final class Profile implements QuarkusTestProfile { @@ -317,6 +327,7 @@ class EksIrsaDockerIntegrationTest { private String createRole(String name, String trustPolicy) { return given() .contentType(FORM) + .header("Authorization", SETUP_AUTH) .formParam("Action", "CreateRole") .formParam("Version", "2010-05-08") .formParam("RoleName", name) @@ -332,6 +343,7 @@ class EksIrsaDockerIntegrationTest { try { given() .contentType(FORM) + .header("Authorization", SETUP_AUTH) .formParam("Action", "DeleteRole") .formParam("Version", "2010-05-08") .formParam("RoleName", name) diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/UnknownAccessKeyEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/UnknownAccessKeyEnforcementIntegrationTest.java index 8b12923592..6a5f7798ee 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/UnknownAccessKeyEnforcementIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/UnknownAccessKeyEnforcementIntegrationTest.java @@ -1,12 +1,21 @@ package io.github.hectorvent.floci.services.iam; import io.github.hectorvent.floci.testing.IamEnforcementProfile; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.nio.charset.StandardCharsets; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * With enforcement on, an access key that exists nowhere must be rejected rather than waved @@ -16,6 +25,11 @@ import static org.hamcrest.Matchers.containsString; @TestProfile(IamEnforcementProfile.class) class UnknownAccessKeyEnforcementIntegrationTest { + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + private static final String UNKNOWN_KEY_AUTH = "AWS4-HMAC-SHA256 Credential=AKIADOESNOTEXIST0000/20260101/us-east-1/%s/aws4_request, " + "SignedHeaders=host, Signature=not-a-real-signature"; @@ -43,6 +57,102 @@ class UnknownAccessKeyEnforcementIntegrationTest { .body(containsString("InvalidAccessKeyId")); } + @Test + void anUnsignedJsonServiceCallIsRefused() { + given() + .contentType("application/x-amz-json-1.0") + .header("X-Amz-Target", "DynamoDB_20120810.ListTables") + .body("{}") + .when() + .post("/") + .then() + .statusCode(403) + .body(containsString("MissingAuthenticationToken")); + } + + @Test + void anUnsignedQueryCallIsRefused() { + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateUser") + .formParam("UserName", "unsigned-user") + .formParam("Version", "2010-05-08") + .when() + .post("/") + .then() + .statusCode(403) + .body(containsString("MissingAuthenticationToken")); + } + + @Test + void anUnsignedCborCallIsRefusedInCbor() { + byte[] body = given() + .contentType("application/x-amz-cbor-1.1") + .header("X-Amz-Target", "Kinesis_20131202.ListStreams") + .body(new byte[] {(byte) 0xa0}) + .when() + .post("/") + .then() + .statusCode(403) + .header("smithy-protocol", "rpc-v2-cbor") + .contentType("application/x-amz-cbor-1.1") + .extract().asByteArray(); + + // CBOR text strings carry their content literally, so the type is readable in the bytes + // without decoding. A JSON body would have been unreadable to the client that sent this. + assertTrue(new String(body, StandardCharsets.ISO_8859_1).contains("MissingAuthenticationToken"), + "the rejection must arrive CBOR-encoded, not as JSON"); + } + + @ParameterizedTest + @ValueSource(strings = {"InitiateAuth", "SignUp", "ForgotPassword", "ConfirmSignUp", "GetUser"}) + void anUnsignedCognitoFlowAwsServesWithoutCredentialsIsNotRefused(String operation) { + // AWS marks these noAuth: the user has no AWS credentials yet, which is the point of them. + // They must reach the service and fail on their own merits, not on a missing signature. + given() + .contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "AWSCognitoIdentityProviderService." + operation) + .body("{}") + .when() + .post("/") + .then() + .body("__type", not(equalTo("MissingAuthenticationTokenException"))); + } + + @Test + void anUnsignedAssumeRoleWithWebIdentityIsNotRefused() { + // Also noAuth: the web identity token is the credential, so AWS requires no signature. + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "AssumeRoleWithWebIdentity") + .formParam("Version", "2011-06-15") + .formParam("RoleArn", "arn:aws:iam::000000000000:role/web-identity-role") + .formParam("RoleSessionName", "unsigned-session") + .formParam("WebIdentityToken", "dummy-token") + .when() + .post("/") + .then() + .body(not(containsString("MissingAuthenticationToken"))); + } + + @Test + void aQueryManagementCallSignedWithTheRootStandInIsAllowed() { + // What a test fixture does when it sets up IAM state under enforcement, and what + // EksIrsaDockerIntegrationTest relies on now that an unsigned CreateRole is refused. + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/iam/aws4_request, " + + "SignedHeaders=host, Signature=setup") + .formParam("Action", "CreateRole") + .formParam("Version", "2010-05-08") + .formParam("RoleName", "root-stand-in-created-role") + .formParam("AssumeRolePolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[]}") + .when() + .post("/") + .then() + .statusCode(200); + } + @Test void theRootStandInKeyStillWorks() { given()