mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(iam,sts): hold a GetSessionToken session to the operations it may reach (#8775)
AWS limits the credentials GetSessionToken returns twice over, and Floci held them to neither (STS API Reference, GetSessionToken, "Permissions"): "You cannot call any IAM API operations unless MFA authentication information is included in the request", and "You cannot call any AWS STS API except AssumeRole or GetCallerIdentity". A session minted without a device reached every IAM operation and the whole of STS with whatever its user's policies allowed. Under enforcement such a session is now refused every IAM operation unless an MFA device minted it, and every STS operation but AssumeRole and GetCallerIdentity whether or not one did, carrying the sentence GetSessionToken and GetFederationToken already answer a session caller with. The IAM half names what the credentials do not hold. AWS publishes no sentence for either refusal, so both are Floci's own wording, and the STS page records that along with the difference between the reference's two bullets and the user guide's compressed one, which this follows the reference on. A federated session keeps the limits it already carried, an assumed-role session carries none of these, and the sessions Floci mints for a presigned URL, for a delegation and for its own signing all name a role or a presigned action, so none of them is one of these.
This commit is contained in:
1 parent
d7c2616c72
commit
57c1704083
9 files changed
+319
-56
No files matched your search
@@ -1343,6 +1343,12 @@ conditioned on MFA reads:
|
||||
the session then carries differs by operation, as it does on AWS: a `GetSessionToken` session is
|
||||
MFA-authenticated on its own requests, while an assumed-role session is not, "once the user has
|
||||
assumed the role, no further MFA checks are made".
|
||||
- **A device decides what a session token may reach.** Under enforcement a `GetSessionToken` session
|
||||
calls IAM only where a device minted it, "you cannot call any IAM API operations unless MFA
|
||||
authentication information is included in the request", and reaches no STS operation but
|
||||
`AssumeRole` and `GetCallerIdentity` either way. The refusal names the operation and what the
|
||||
credentials do not carry; see [STS MFA](sts.md#mfa). An assumed-role session carries no such
|
||||
limit.
|
||||
|
||||
What a device still does not reach is the console sign-in AWS also gates on one, there being no
|
||||
sign-in here, and the hardware and FIDO device types above, so the device behind a session is
|
||||
|
||||
+26
-5
@@ -291,7 +291,8 @@ When `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true`, credentials from `GetSession
|
||||
are evaluated as the identity whose long-term key signed the call, as on AWS:
|
||||
|
||||
- `GetSessionToken` credentials have the permissions of that IAM user, or of the account root when its key minted them,
|
||||
still bounded by the account's service control policies.
|
||||
still bounded by the account's service control policies. Whatever those allow, they reach no IAM operation unless an
|
||||
MFA device minted the session, and no STS operation but `AssumeRole` and `GetCallerIdentity`; see [MFA](#mfa).
|
||||
- `GetFederationToken` credentials have no permissions without a session policy (`Policy`). With one, they have the
|
||||
intersection of that policy and the permissions of the IAM user that minted them, never those of a role that shares
|
||||
the federated user's name. A resource policy naming the federated user's ARN can grant access on its own, but not
|
||||
@@ -352,10 +353,30 @@ permission to make the call is read against that same context, since AWS denies
|
||||
invalid TOTP", so an identity policy conditioned on MFA for `sts:AssumeRole` is satisfied by the
|
||||
device the call carries.
|
||||
|
||||
One difference from AWS is known and open: AWS says temporary credentials from a `GetSessionToken`
|
||||
request "can access IAM and AWS STS API operations *only* if you include MFA information in the
|
||||
request for credentials". Floci does not hold a session to that: one minted without a device reaches
|
||||
IAM and STS with whatever its user's policies allow.
|
||||
What a session token then reaches is narrower than its policies, and under
|
||||
[enforcement](iam.md#iam-enforcement-mode) Floci holds it to that. The reference limits these
|
||||
credentials twice over (`GetSessionToken`, "Permissions"): "You cannot call any IAM API operations
|
||||
unless MFA authentication information is included in the request", and "You cannot call any AWS STS
|
||||
API except AssumeRole or GetCallerIdentity". So a session minted behind a device calls IAM as its
|
||||
own user may, one minted without a device is refused every IAM operation whatever its policies
|
||||
allow, and neither reaches an STS operation other than `AssumeRole` and `GetCallerIdentity`. The
|
||||
refusal is `AccessDenied` with `Cannot call <Operation> with session credentials`, the sentence
|
||||
`GetSessionToken` and `GetFederationToken` already answer a session caller with, and the IAM half
|
||||
adds `that include no MFA information` to name what the credentials do not carry. AWS publishes no
|
||||
sentence for either refusal, so both are Floci's own wording for the case.
|
||||
|
||||
Two readings of the rule differ, and Floci follows the API reference. The IAM User Guide's
|
||||
"Choosing between GetSessionToken and AssumeRole" compresses the pair into one sentence, that such
|
||||
credentials "can access IAM and AWS STS API operations *only* if you include MFA information in the
|
||||
request for credentials", which reads as though a device opened the rest of STS as well. The
|
||||
reference publishes the two bullets apart and conditions only the IAM one on MFA, so here a device
|
||||
buys IAM and no more of STS. The two readings agree on a session that carries no device.
|
||||
|
||||
These limits are read where every other authorization decision is, so they apply under
|
||||
`FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true` and nowhere else, while the two operations that take
|
||||
long-term credentials only refuse a session caller with either setting, as above. An assumed-role
|
||||
session carries none of them: AWS keeps `GetFederationToken` and `GetSessionToken` from it and
|
||||
nothing further, and those two operations turn it away themselves.
|
||||
|
||||
## Trust Policy Enforcement
|
||||
|
||||
|
||||
@@ -79,7 +79,10 @@ import java.util.regex.Pattern;
|
||||
* </ul>
|
||||
*
|
||||
* <p>Authenticated temporary callers of {@code sts:GetFederationToken} are refused here with
|
||||
* the same operation-specific error as the handler, before policy evaluation.
|
||||
* the same operation-specific error as the handler, before policy evaluation. A
|
||||
* {@code GetSessionToken} session is refused the same way for an operation its credentials cannot
|
||||
* reach at all: any IAM operation when no MFA device minted the session, and any STS operation but
|
||||
* {@code AssumeRole} and {@code GetCallerIdentity}.
|
||||
*
|
||||
* <p>Evaluates the caller's identity policies, optional session policy, and optional
|
||||
* permissions boundary, as well as applicable resource policies via {@link ResourcePolicyProvider}.
|
||||
@@ -463,6 +466,16 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
return;
|
||||
}
|
||||
|
||||
// What a GetSessionToken session may reach is narrower than its policies, and the refusal
|
||||
// is the credential's rather than any statement's. Only IAM and STS actions can earn it,
|
||||
// and both services answer in the Query envelope.
|
||||
Optional<String> sessionTokenRefusal = iamService.sessionTokenRefusal(akid, action);
|
||||
if (sessionTokenRefusal.isPresent()) {
|
||||
LOG.debugv("Rejecting {0} signed with a session token that cannot reach it: {1}", action, akid);
|
||||
ctx.abortWith(queryXmlAccessDenied(sessionTokenRefusal.get()));
|
||||
return;
|
||||
}
|
||||
|
||||
// Service control policies from the caller's organization, when the Organizations
|
||||
// service is present and SCP enforcement is enabled. Resolved lazily via Instance
|
||||
// to avoid a hard IAM → Organizations dependency.
|
||||
|
||||
@@ -111,8 +111,7 @@ import java.util.stream.Stream;
|
||||
@ApplicationScoped
|
||||
public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
|
||||
public static final String FEDERATION_TOKEN_SESSION_MESSAGE =
|
||||
"Cannot call GetFederationToken with session credentials";
|
||||
public static final String FEDERATION_TOKEN_SESSION_MESSAGE = sessionCredentialRefusal("GetFederationToken");
|
||||
|
||||
private static final int USER_INLINE_POLICY_SIZE_LIMIT = 2_048;
|
||||
private static final int GROUP_INLINE_POLICY_SIZE_LIMIT = 5_120;
|
||||
@@ -132,6 +131,16 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
*/
|
||||
private static final String FEDERATED_USER_SESSION_LIMITS =
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Action\":[\"iam:*\",\"sts:*\"],\"Resource\":\"*\"}]}";
|
||||
/**
|
||||
* The STS operations a GetSessionToken session reaches, every other one being refused whatever
|
||||
* its policies allow: "You cannot call any AWS STS API except AssumeRole or GetCallerIdentity"
|
||||
* (STS API Reference, GetSessionToken, "Permissions"). GetCallerIdentity is named here for the
|
||||
* reading rather than for the filter, which answers it before it reads a policy at all.
|
||||
*/
|
||||
private static final Set<String> STS_ACTIONS_A_SESSION_TOKEN_REACHES =
|
||||
Set.of("sts:AssumeRole", "sts:GetCallerIdentity");
|
||||
/** What the IAM half of that refusal adds, naming what the credentials do not carry. */
|
||||
private static final String WITHOUT_MFA_INFORMATION = " that include no MFA information";
|
||||
/**
|
||||
* What the account password policy's {@code AllowUsersToChangePassword} authorizes. The guide:
|
||||
* the option "gives users access to the iam:ChangePassword action for only their user and to
|
||||
@@ -5610,6 +5619,73 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
return user.filter(candidate -> issuerUserId.equals(candidate.getUserId()));
|
||||
}
|
||||
|
||||
/**
|
||||
* The sentence a {@code GetSessionToken} session is refused with for an operation its
|
||||
* credentials cannot reach, whatever its policies allow, and empty for every other credential.
|
||||
* AWS limits them twice over (STS API Reference, GetSessionToken, "Permissions"): "You cannot
|
||||
* call any IAM API operations unless MFA authentication information is included in the
|
||||
* request", and "You cannot call any AWS STS API except AssumeRole or GetCallerIdentity".
|
||||
*
|
||||
* <p>The MFA half reads the device the session was minted behind rather than this request,
|
||||
* which is where AWS puts it: such credentials reach IAM "only if you include MFA information
|
||||
* in the request for credentials". The STS half is not conditioned on a device, the reference
|
||||
* publishing the two bullets apart, so AssumeRole and GetCallerIdentity are reachable either
|
||||
* way and no other STS operation is.
|
||||
*
|
||||
* <p>Asked only about the two namespaces it can refuse, so no request on another service pays
|
||||
* for the session read. {@code sts:GetSessionToken} and {@code sts:GetFederationToken} are
|
||||
* refused ahead of this, by the operations themselves and with the same sentence, whichever
|
||||
* temporary credential calls them.
|
||||
*/
|
||||
public Optional<String> sessionTokenRefusal(String accessKeyId, String action) {
|
||||
if (action == null || !isTemporaryAccessKey(accessKeyId)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
int namespaceEnd = action.indexOf(':');
|
||||
if (namespaceEnd <= 0) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String namespace = action.substring(0, namespaceEnd);
|
||||
boolean iamAction = "iam".equals(namespace);
|
||||
if (!iamAction && !"sts".equals(namespace)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (!iamAction && STS_ACTIONS_A_SESSION_TOKEN_REACHES.contains(action)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Optional<SessionCredential> session = findSessionForCallerContext(accessKeyId)
|
||||
.filter(IamService::isSessionTokenSession);
|
||||
if (session.isEmpty() || (iamAction && session.get().getMfaAuthenticatedAt() != null)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String operation = action.substring(namespaceEnd + 1);
|
||||
return Optional.of(iamAction
|
||||
? sessionCredentialRefusal(operation) + WITHOUT_MFA_INFORMATION
|
||||
: sessionCredentialRefusal(operation));
|
||||
}
|
||||
|
||||
/**
|
||||
* What Floci refuses a session credential an operation does not take with. AWS publishes no
|
||||
* sentence for any of these, and they are one rule: an operation a session token cannot reach,
|
||||
* whether that is {@code GetSessionToken} itself, {@code GetFederationToken}, or another the
|
||||
* reference keeps from it.
|
||||
*/
|
||||
public static String sessionCredentialRefusal(String operation) {
|
||||
return "Cannot call " + operation + " with session credentials";
|
||||
}
|
||||
|
||||
/**
|
||||
* A session {@code GetSessionToken} minted, which acts as the identity whose long-term key
|
||||
* minted it: nothing in the role ARN slot, so neither a role session nor the federated user
|
||||
* {@code GetFederationToken} writes there, no delegation approver, and not one Floci minted
|
||||
* for a presigned URL of its own.
|
||||
*/
|
||||
private static boolean isSessionTokenSession(SessionCredential session) {
|
||||
return session.getDelegatedApproverArn() == null
|
||||
&& session.getRoleArn() == null
|
||||
&& session.getPresignedAction() == null;
|
||||
}
|
||||
|
||||
/**
|
||||
* GetSessionToken credentials have the permissions of the identity that minted them: an IAM
|
||||
* user's own policies and boundary, or the account root's, which the enforcement filter still
|
||||
@@ -5819,13 +5895,13 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
if (isFederatedUserSession(session)) {
|
||||
return withFederatedUserLimits(federatedUserContext(session));
|
||||
}
|
||||
if (session.getRoleArn() == null) {
|
||||
if (session.getPresignedAction() != null) {
|
||||
// A locally minted identity session can carry a restrictive session policy.
|
||||
return session.getSessionPolicyDocument() == null ? null
|
||||
: new CallerContext(List.of(SCOPED_IDENTITY_SESSION_BASE_POLICY),
|
||||
session.getSessionPolicyDocument(), null);
|
||||
}
|
||||
if (session.getRoleArn() == null && session.getPresignedAction() != null) {
|
||||
// A locally minted identity session can carry a restrictive session policy.
|
||||
return session.getSessionPolicyDocument() == null ? null
|
||||
: new CallerContext(List.of(SCOPED_IDENTITY_SESSION_BASE_POLICY),
|
||||
session.getSessionPolicyDocument(), null);
|
||||
}
|
||||
if (isSessionTokenSession(session)) {
|
||||
return sessionTokenContext(session);
|
||||
}
|
||||
if (isAccountRootArn(session.getRoleArn())) {
|
||||
|
||||
@@ -413,7 +413,7 @@ public class StsQueryHandler {
|
||||
|
||||
private Response handleGetSessionToken(MultivaluedMap<String, String> params) {
|
||||
if (IamService.isTemporaryAccessKey(callerAccessKeyId())) {
|
||||
return AwsQueryResponse.error("AccessDenied", "Cannot call GetSessionToken with session credentials",
|
||||
return AwsQueryResponse.error("AccessDenied", IamService.sessionCredentialRefusal("GetSessionToken"),
|
||||
AwsNamespaces.STS, 403);
|
||||
}
|
||||
Response integerMembers =
|
||||
|
||||
@@ -806,6 +806,59 @@ class IamServiceTest {
|
||||
assertNotACredential(service, "ASIAFROMSESSION");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSessionTokenReachesIamOnlyWhereADeviceMintedIt() {
|
||||
IamService service = iamService(false);
|
||||
service.createUser("alice", "/");
|
||||
String aliceKey = service.createAccessKey("alice").getAccessKeyId();
|
||||
service.registerIssuedSession("ASIANODEVICE", "secret", "token", null,
|
||||
Instant.now().plusSeconds(3600), null, "000000000000", aliceKey);
|
||||
service.registerIssuedSession("ASIABEHINDDEVICE", "secret", "token", null,
|
||||
Instant.now().plusSeconds(3600), null, "000000000000", aliceKey);
|
||||
service.recordSessionMfa("ASIABEHINDDEVICE", Instant.now());
|
||||
|
||||
// "You cannot call any IAM API operations unless MFA authentication information is
|
||||
// included in the request."
|
||||
assertEquals("Cannot call ListUsers with session credentials that include no MFA information",
|
||||
service.sessionTokenRefusal("ASIANODEVICE", "iam:ListUsers").orElseThrow());
|
||||
assertTrue(service.sessionTokenRefusal("ASIABEHINDDEVICE", "iam:ListUsers").isEmpty());
|
||||
// "You cannot call any AWS STS API except AssumeRole or GetCallerIdentity", which is not
|
||||
// conditioned on a device, so the one minted behind it reaches no more of STS than the other.
|
||||
assertEquals("Cannot call GetAccessKeyInfo with session credentials",
|
||||
service.sessionTokenRefusal("ASIABEHINDDEVICE", "sts:GetAccessKeyInfo").orElseThrow());
|
||||
assertTrue(service.sessionTokenRefusal("ASIANODEVICE", "sts:AssumeRole").isEmpty());
|
||||
assertTrue(service.sessionTokenRefusal("ASIANODEVICE", "sts:GetCallerIdentity").isEmpty());
|
||||
// Every other namespace is the policies' business rather than the credential's, and an
|
||||
// action that names none is nobody's to refuse.
|
||||
assertTrue(service.sessionTokenRefusal("ASIANODEVICE", "s3:GetObject").isEmpty());
|
||||
assertTrue(service.sessionTokenRefusal("ASIANODEVICE", "iam").isEmpty());
|
||||
assertTrue(service.sessionTokenRefusal("ASIANODEVICE", null).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyASessionTokenCarriesTheseLimits() {
|
||||
IamService service = iamService(false);
|
||||
service.createUser("alice", "/");
|
||||
String aliceKey = service.createAccessKey("alice").getAccessKeyId();
|
||||
service.createRole("Worker", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
|
||||
service.registerSession("ASIAROLESESSION", "secret", "token",
|
||||
"arn:aws:iam::000000000000:role/Worker", Instant.now().plusSeconds(3600), null,
|
||||
"000000000000", "s", "AROAWORKER:s");
|
||||
service.registerIssuedSession("ASIAFEDERATED", "secret", "token",
|
||||
"arn:aws:sts::000000000000:federated-user/Bob", Instant.now().plusSeconds(3600),
|
||||
null, "000000000000", aliceKey);
|
||||
|
||||
// An assumed-role session reaches whatever its role allows: AWS keeps GetFederationToken
|
||||
// and GetSessionToken from it, and both operations turn it away themselves.
|
||||
assertTrue(service.sessionTokenRefusal("ASIAROLESESSION", "iam:ListUsers").isEmpty());
|
||||
assertTrue(service.sessionTokenRefusal("ASIAROLESESSION", "sts:GetAccessKeyInfo").isEmpty());
|
||||
// A federated session carries limits of its own, as the Deny in the context it resolves to.
|
||||
assertTrue(service.sessionTokenRefusal("ASIAFEDERATED", "iam:ListUsers").isEmpty());
|
||||
// A long-term key carries none, and neither does a key no session matches.
|
||||
assertTrue(service.sessionTokenRefusal(aliceKey, "iam:ListUsers").isEmpty());
|
||||
assertTrue(service.sessionTokenRefusal("ASIANOSUCHSESSION", "iam:ListUsers").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSessionTokenMintedWithADeactivatedKeyIsNoCredential() {
|
||||
IamService service = iamService(false);
|
||||
|
||||
+11
-1
@@ -2,6 +2,7 @@ package io.floci.aws.services.iam;
|
||||
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.EnforcementFixtures;
|
||||
import io.floci.aws.testing.EnforcementFixtures.MfaDevice;
|
||||
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
|
||||
import io.floci.aws.testing.IamEnforcementProfile;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
@@ -73,7 +74,9 @@ class PrincipalTagEnforcementIntegrationTest {
|
||||
StsClient sts = AwsTestClients.create(StsClient.builder(), keys.accessKeyId(), keys.secretAccessKey(),
|
||||
Region.US_EAST_1)) {
|
||||
admin.tagUser(r -> r.userName(name).tags(tag("Team", "platform")));
|
||||
Credentials session = sts.getSessionToken().credentials();
|
||||
// A session token reaches an IAM operation only where a device minted it, so the
|
||||
// device is what makes this probe reachable; what decides it is still the user's tags.
|
||||
Credentials session = sessionBehindADevice(sts, name);
|
||||
try (IamClient caller = sessionClient(session)) {
|
||||
caller.listUsers();
|
||||
admin.untagUser(r -> r.userName(name).tagKeys("Team"));
|
||||
@@ -205,6 +208,13 @@ class PrincipalTagEnforcementIntegrationTest {
|
||||
return AwsTestClients.create(IamClient.builder(), keys.accessKeyId(), keys.secretAccessKey(), Region.US_EAST_1);
|
||||
}
|
||||
|
||||
/** A session minted behind a virtual device enabled for the user, the way a client sets one up. */
|
||||
private Credentials sessionBehindADevice(StsClient sts, String userName) {
|
||||
MfaDevice device = EnforcementFixtures.enableMfaDevice(baseUri.getPort(), auth(ACCOUNT, "iam"), userName);
|
||||
return sts.getSessionToken(r -> r.serialNumber(device.serialNumber())
|
||||
.tokenCode(device.codeNow())).credentials();
|
||||
}
|
||||
|
||||
private IamClient sessionClient(Credentials session) {
|
||||
return AwsTestClients.create(IamClient.builder(), sessionCredentials(session), Region.US_EAST_1, baseUri);
|
||||
}
|
||||
|
||||
@@ -1,19 +1,18 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import io.floci.aws.core.common.Totp;
|
||||
import io.floci.aws.testing.EnforcementFixtures;
|
||||
import io.floci.aws.testing.EnforcementFixtures.MfaDevice;
|
||||
import io.floci.aws.testing.S3IamEnforcementProfile;
|
||||
import io.floci.aws.testutil.S3RequestSigner;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.RestAssured;
|
||||
import io.restassured.response.ExtractableResponse;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
@@ -51,6 +50,8 @@ class StsMfaEnforcementIntegrationTest {
|
||||
|
||||
private static final String CODE = "ErrorResponse.Error.Code";
|
||||
|
||||
private static final String MESSAGE = "ErrorResponse.Error.Message";
|
||||
|
||||
/** Allows the listing only where the request was authenticated with a device. */
|
||||
private static final String LIST_WITH_MFA = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
@@ -71,6 +72,11 @@ class StsMfaEnforcementIntegrationTest {
|
||||
{"Effect":"Allow","Action":"sts:AssumeRole","Resource":"*",
|
||||
"Condition":{"Bool":{"aws:MultiFactorAuthPresent":"true"}}}]}""";
|
||||
|
||||
/** Allows both namespaces with no condition at all, so only the credential itself can refuse. */
|
||||
private static final String LIST_AND_MINT = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":["iam:ListUsers","sts:*"],"Resource":"*"}]}""";
|
||||
|
||||
/** Allows the listing only while the authentication is recent. */
|
||||
private static final String LIST_WHILE_FRESH = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
@@ -82,7 +88,7 @@ class StsMfaEnforcementIntegrationTest {
|
||||
void aSessionMintedBehindADeviceIsTheOneThatCarriesThePresentKeyAsTrue() {
|
||||
String userName = unique("mfa-present");
|
||||
S3RequestSigner user = userWithPolicy(userName, LIST_WITH_MFA);
|
||||
Device device = enabledDeviceFor(userName);
|
||||
MfaDevice device = enabledDeviceFor(userName);
|
||||
|
||||
// The same user, the same policy, two sessions: the key is the only difference between them.
|
||||
listUsers(sessionWith(user, device), 200);
|
||||
@@ -95,7 +101,7 @@ class StsMfaEnforcementIntegrationTest {
|
||||
void theDenyTheGuideRecommendsRefusesALongTermKeyAndAnMfaLessSession() {
|
||||
String userName = unique("mfa-ifexists");
|
||||
S3RequestSigner user = userWithPolicy(userName, LIST_DENIED_WITHOUT_MFA);
|
||||
Device device = enabledDeviceFor(userName);
|
||||
MfaDevice device = enabledDeviceFor(userName);
|
||||
|
||||
// "This combination of Deny, BoolIfExists, and false denies requests that are not
|
||||
// authenticated using MFA... It also denies requests that are made using long-term
|
||||
@@ -109,7 +115,7 @@ class StsMfaEnforcementIntegrationTest {
|
||||
void theAgeIsPublishedOnlyWhereThereIsAnAuthenticationToMeasure() {
|
||||
String userName = unique("mfa-age");
|
||||
S3RequestSigner user = userWithPolicy(userName, LIST_WHILE_FRESH);
|
||||
Device device = enabledDeviceFor(userName);
|
||||
MfaDevice device = enabledDeviceFor(userName);
|
||||
|
||||
// The device was just used, so the age is inside the hour the policy allows.
|
||||
listUsers(sessionWith(user, device), 200);
|
||||
@@ -122,7 +128,7 @@ class StsMfaEnforcementIntegrationTest {
|
||||
void aCodeTheDeviceDidNotProduceAuthenticatesNothing() {
|
||||
String userName = unique("mfa-code");
|
||||
S3RequestSigner user = userWithPolicy(userName, LIST_WITH_MFA);
|
||||
Device device = enabledDeviceFor(userName);
|
||||
MfaDevice device = enabledDeviceFor(userName);
|
||||
|
||||
// "An incorrect MFA code causes the API to return an access denied error."
|
||||
getSessionToken(user, device.serialNumber(), "000000").statusCode(403)
|
||||
@@ -131,7 +137,7 @@ class StsMfaEnforcementIntegrationTest {
|
||||
getSessionToken(user, device.serialNumber(), null).statusCode(403);
|
||||
getSessionToken(user, null, device.codeNow()).statusCode(403);
|
||||
// A device enabled for somebody else is not this caller's to present.
|
||||
Device other = enabledDeviceFor(unique("mfa-other"));
|
||||
MfaDevice other = enabledDeviceFor(unique("mfa-other"));
|
||||
getSessionToken(user, other.serialNumber(), other.codeNow()).statusCode(403);
|
||||
}
|
||||
|
||||
@@ -139,7 +145,7 @@ class StsMfaEnforcementIntegrationTest {
|
||||
void aTrustPolicyThatTestsForMfaTakesTheDeviceTheAssumePresents() {
|
||||
String userName = unique("mfa-trust");
|
||||
S3RequestSigner user = userWithPolicy(userName, LIST_WITH_MFA);
|
||||
Device device = enabledDeviceFor(userName);
|
||||
MfaDevice device = enabledDeviceFor(userName);
|
||||
String roleName = unique("mfa-role");
|
||||
createRoleRequiringMfa(roleName, userName);
|
||||
|
||||
@@ -153,7 +159,7 @@ class StsMfaEnforcementIntegrationTest {
|
||||
void aRoleSessionAssumedWithADeviceStillCarriesNoAuthenticationOfItsOwn() {
|
||||
String userName = unique("mfa-chain-user");
|
||||
S3RequestSigner user = userWithPolicy(userName, LIST_WITH_MFA);
|
||||
Device device = enabledDeviceFor(userName);
|
||||
MfaDevice device = enabledDeviceFor(userName);
|
||||
String roleName = unique("mfa-chain-role");
|
||||
createRoleRequiringMfa(roleName, userName);
|
||||
|
||||
@@ -169,7 +175,7 @@ class StsMfaEnforcementIntegrationTest {
|
||||
void aCodeThatMintedASessionMintsNoSecondOne() {
|
||||
String userName = unique("mfa-replay");
|
||||
S3RequestSigner user = userWithPolicy(userName, LIST_WITH_MFA);
|
||||
Device device = enabledDeviceFor(userName);
|
||||
MfaDevice device = enabledDeviceFor(userName);
|
||||
String code = device.codeNow();
|
||||
|
||||
getSessionToken(user, device.serialNumber(), code).statusCode(200);
|
||||
@@ -184,7 +190,7 @@ class StsMfaEnforcementIntegrationTest {
|
||||
void thePolicyForTheAssumeItselfSeesTheDeviceTheCallPresents() {
|
||||
String userName = unique("mfa-identity");
|
||||
S3RequestSigner user = userWithPolicy(userName, ASSUME_WITH_MFA);
|
||||
Device device = enabledDeviceFor(userName);
|
||||
MfaDevice device = enabledDeviceFor(userName);
|
||||
String roleName = unique("mfa-identity-role");
|
||||
createRoleTrustingUser(roleName, userName);
|
||||
|
||||
@@ -200,7 +206,7 @@ class StsMfaEnforcementIntegrationTest {
|
||||
void aSessionMintedBehindADeviceAssumesARoleThatRequiresOneWithoutPresentingItAgain() {
|
||||
String userName = unique("mfa-carry");
|
||||
S3RequestSigner user = userWithPolicy(userName, LIST_WITH_MFA);
|
||||
Device device = enabledDeviceFor(userName);
|
||||
MfaDevice device = enabledDeviceFor(userName);
|
||||
String roleName = unique("mfa-carry-role");
|
||||
createRoleRequiringMfa(roleName, userName);
|
||||
|
||||
@@ -211,17 +217,59 @@ class StsMfaEnforcementIntegrationTest {
|
||||
assumeRole(sessionWith(user, null), roleName, null, null).statusCode(403);
|
||||
}
|
||||
|
||||
/** A virtual device and its seed, which is what produces the codes a client sends. */
|
||||
private record Device(String serialNumber, String seed) {
|
||||
@Test
|
||||
void anIamCallFromASessionNoDeviceMintedIsRefusedHoweverItsPoliciesRead() {
|
||||
String userName = unique("mfa-iam-reach");
|
||||
S3RequestSigner user = userWithPolicy(userName, LIST_AND_MINT);
|
||||
MfaDevice device = enabledDeviceFor(userName);
|
||||
|
||||
String codeNow() {
|
||||
return Totp.codeAt(seed, Totp.stepAt(Instant.now()));
|
||||
}
|
||||
// "You cannot call any IAM API operations unless MFA authentication information is included
|
||||
// in the request." Nothing in these policies says otherwise, so the credential is what
|
||||
// refuses, and only the session that used no device.
|
||||
listUsers(user, 200);
|
||||
listUsers(sessionWith(user, device), 200);
|
||||
listing(sessionWith(user, null)).statusCode(403)
|
||||
.body(CODE, equalTo("AccessDenied"))
|
||||
.body(MESSAGE, equalTo(
|
||||
"Cannot call ListUsers with session credentials that include no MFA information"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSessionReachesNoStsOperationButAssumeRoleAndGetCallerIdentity() {
|
||||
String userName = unique("mfa-sts-reach");
|
||||
S3RequestSigner user = userWithPolicy(userName, LIST_AND_MINT);
|
||||
MfaDevice device = enabledDeviceFor(userName);
|
||||
String roleName = unique("mfa-sts-reach-role");
|
||||
createRoleTrustingUser(roleName, userName);
|
||||
S3RequestSigner session = sessionWith(user, null);
|
||||
|
||||
// "You cannot call any AWS STS API except AssumeRole or GetCallerIdentity."
|
||||
assumeRole(session, roleName, null, null).statusCode(200);
|
||||
given().filter(session).formParam("Action", "GetCallerIdentity")
|
||||
.when().post("/").then().statusCode(200);
|
||||
accessKeyInfo(session).statusCode(403).body(CODE, equalTo("AccessDenied"))
|
||||
.body(MESSAGE, equalTo("Cannot call GetAccessKeyInfo with session credentials"));
|
||||
// A device buys the IAM half and not this one: the reference publishes the two bullets apart.
|
||||
accessKeyInfo(sessionWith(user, device)).statusCode(403).body(CODE, equalTo("AccessDenied"));
|
||||
// The long-term key that minted them reaches the operation, which then answers for the id
|
||||
// it was asked about rather than for the credentials asking.
|
||||
accessKeyInfo(user).statusCode(400).body(CODE, equalTo("ValidationError"));
|
||||
}
|
||||
|
||||
private static void listUsers(S3RequestSigner caller, int status) {
|
||||
given().filter(caller).formParam("Action", "ListUsers").formParam("Version", "2010-05-08")
|
||||
.when().post("/").then().statusCode(status);
|
||||
listing(caller).statusCode(status);
|
||||
}
|
||||
|
||||
private static ValidatableResponse listing(S3RequestSigner caller) {
|
||||
return given().filter(caller).formParam("Action", "ListUsers").formParam("Version", "2010-05-08")
|
||||
.when().post("/").then();
|
||||
}
|
||||
|
||||
/** Asked about an id IAM never issued, so the operation itself answers whoever reaches it. */
|
||||
private static ValidatableResponse accessKeyInfo(S3RequestSigner caller) {
|
||||
return given().filter(caller).formParam("Action", "GetAccessKeyInfo")
|
||||
.formParam("AccessKeyId", "AKIAIOSFODNN7EXAMPLE")
|
||||
.when().post("/").then();
|
||||
}
|
||||
|
||||
private static ValidatableResponse getSessionToken(S3RequestSigner caller, String serialNumber,
|
||||
@@ -237,7 +285,7 @@ class StsMfaEnforcementIntegrationTest {
|
||||
}
|
||||
|
||||
/** The caller's own session, minted behind {@code device} when one is given. */
|
||||
private static S3RequestSigner sessionWith(S3RequestSigner caller, Device device) {
|
||||
private static S3RequestSigner sessionWith(S3RequestSigner caller, MfaDevice device) {
|
||||
ExtractableResponse<Response> issued = (device == null
|
||||
? getSessionToken(caller, null, null)
|
||||
: getSessionToken(caller, device.serialNumber(), device.codeNow()))
|
||||
@@ -261,7 +309,7 @@ class StsMfaEnforcementIntegrationTest {
|
||||
return request.when().post("/").then();
|
||||
}
|
||||
|
||||
private static S3RequestSigner assumedSession(S3RequestSigner caller, String roleName, Device device) {
|
||||
private static S3RequestSigner assumedSession(S3RequestSigner caller, String roleName, MfaDevice device) {
|
||||
ExtractableResponse<Response> issued =
|
||||
assumeRole(caller, roleName, device.serialNumber(), device.codeNow())
|
||||
.statusCode(200).extract();
|
||||
@@ -290,23 +338,11 @@ class StsMfaEnforcementIntegrationTest {
|
||||
}
|
||||
|
||||
/** A virtual device created and enabled for a fresh user, the way a client sets one up. */
|
||||
private static Device enabledDeviceFor(String userName) {
|
||||
private static MfaDevice enabledDeviceFor(String userName) {
|
||||
if (!userExists(userName)) {
|
||||
iam("CreateUser", "UserName", userName);
|
||||
}
|
||||
String base = "CreateVirtualMFADeviceResponse.CreateVirtualMFADeviceResult.VirtualMFADevice.";
|
||||
ExtractableResponse<Response> created = given().header("Authorization", auth(ACCOUNT, "iam"))
|
||||
.formParam("Action", "CreateVirtualMFADevice")
|
||||
.formParam("VirtualMFADeviceName", userName + "-device")
|
||||
.when().post("/").then().statusCode(200).extract();
|
||||
String seed = new String(Base64.getDecoder().decode(
|
||||
created.path(base + "Base32StringSeed").toString().trim()), StandardCharsets.UTF_8);
|
||||
String serialNumber = created.path(base + "SerialNumber");
|
||||
long step = Totp.stepAt(Instant.now());
|
||||
iam("EnableMFADevice", "UserName", userName, "SerialNumber", serialNumber,
|
||||
"AuthenticationCode1", Totp.codeAt(seed, step - 1),
|
||||
"AuthenticationCode2", Totp.codeAt(seed, step));
|
||||
return new Device(serialNumber, seed);
|
||||
return EnforcementFixtures.enableMfaDevice(RestAssured.port, auth(ACCOUNT, "iam"), userName);
|
||||
}
|
||||
|
||||
private static boolean userExists(String userName) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.floci.aws.testing;
|
||||
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import io.floci.aws.core.common.Totp;
|
||||
import io.restassured.filter.Filter;
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
@@ -12,6 +13,7 @@ import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
@@ -53,8 +55,9 @@ public final class EnforcementFixtures {
|
||||
|
||||
/**
|
||||
* Deletes an IAM user, and first everything IAM wants gone before it will: inline policies,
|
||||
* access keys, group memberships and attached managed policies. The IAM API reference lists
|
||||
* all four among the items to remove "before attempting to delete a user", and Floci answers
|
||||
* access keys, group memberships, attached managed policies and any MFA device, which is
|
||||
* deactivated and then deleted as the virtual device it is. The IAM API reference lists all
|
||||
* five among the items to remove "before attempting to delete a user", and Floci answers
|
||||
* {@code DeleteConflict} for each of them.
|
||||
*
|
||||
* @param authorization an IAM-scoped header. Signing with an account id reaches that
|
||||
@@ -93,9 +96,54 @@ public final class EnforcementFixtures {
|
||||
iam(port, authorization, "DetachUserPolicy", "UserName", userName,
|
||||
"PolicyArn", policyArn).statusCode(200);
|
||||
}
|
||||
for (String serialNumber : iam(port, authorization, "ListMFADevices", "UserName", userName)
|
||||
.statusCode(200).extract().xmlPath()
|
||||
.getList("ListMFADevicesResponse.ListMFADevicesResult.MFADevices.member.SerialNumber",
|
||||
String.class)) {
|
||||
iam(port, authorization, "DeactivateMFADevice", "UserName", userName,
|
||||
"SerialNumber", serialNumber).statusCode(200);
|
||||
iam(port, authorization, "DeleteVirtualMFADevice", "SerialNumber", serialNumber).statusCode(200);
|
||||
}
|
||||
iam(port, authorization, "DeleteUser", "UserName", userName).statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* A virtual MFA device enabled for a user, holding the seed its codes come from so a caller
|
||||
* can present one.
|
||||
*/
|
||||
public record MfaDevice(String serialNumber, String seed) {
|
||||
|
||||
/** A code for the current time step, which authenticates once and is then spent. */
|
||||
public String codeNow() {
|
||||
return Totp.codeAt(seed, Totp.stepAt(Instant.now()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a virtual MFA device for {@code userName} and enables it with the two consecutive
|
||||
* codes {@code EnableMFADevice} requires, which is how a client sets one up, and returns it
|
||||
* with the seed to produce further codes from. {@link #removeUser} deactivates and deletes it
|
||||
* with the user.
|
||||
*
|
||||
* <p>The seed arrives base64-encoded, as AWS returns {@code Base32StringSeed}, and the codes
|
||||
* are computed over the base32 text inside it.
|
||||
*
|
||||
* @param authorization an IAM-scoped header for the account the user belongs to
|
||||
*/
|
||||
public static MfaDevice enableMfaDevice(int port, String authorization, String userName) {
|
||||
String member = "CreateVirtualMFADeviceResponse.CreateVirtualMFADeviceResult.VirtualMFADevice.";
|
||||
XmlPath created = iam(port, authorization, "CreateVirtualMFADevice",
|
||||
"VirtualMFADeviceName", userName + "-device").statusCode(200).extract().xmlPath();
|
||||
String seed = new String(Base64.getDecoder().decode(
|
||||
created.getString(member + "Base32StringSeed").trim()), StandardCharsets.UTF_8);
|
||||
String serialNumber = created.getString(member + "SerialNumber");
|
||||
long step = Totp.stepAt(Instant.now());
|
||||
iam(port, authorization, "EnableMFADevice", "UserName", userName, "SerialNumber", serialNumber,
|
||||
"AuthenticationCode1", Totp.codeAt(seed, step - 1),
|
||||
"AuthenticationCode2", Totp.codeAt(seed, step)).statusCode(200);
|
||||
return new MfaDevice(serialNumber, seed);
|
||||
}
|
||||
|
||||
/** The access key {@link #createUser} issued, with the secret a request signer needs. */
|
||||
public record UserCredentials(String accessKeyId, String secretAccessKey) {
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user