diff --git a/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java b/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java index 10b4cc370b..ccc9fdd484 100644 --- a/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java +++ b/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java @@ -307,6 +307,16 @@ public class AccountAwareStorageBackend implements StorageBackend return delegate.get(accountId + "/" + key); } + /** + * An unprefixed pre-multi-account entry, read in place (never migrated). Such entries belong + * to {@code defaultAccountId}, as in {@link #scanAllAccountEntries}, so any other account + * gets empty. + */ + public Optional getLegacyForAccount(String accountId, String key) { + return defaultAccountId.equals(accountId) && !hasAccountPrefix(key) + ? delegate.get(key) : Optional.empty(); + } + /** * Returns an explicitly scoped entry, or safely migrates a matching legacy unscoped entry. * diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java index 3e45bf929e..8942b38ae8 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java @@ -1955,12 +1955,14 @@ public class IamQueryHandler { private Response handleGetAccessKeyLastUsed(MultivaluedMap params) { // Access-key usage is not modeled, so return the IAM API's documented // "never used" shape: an AccessKeyLastUsed with ServiceName=N/A and Region=N/A - // and NO LastUsedDate. UserName is optional and its type is non-empty - // (length 1-128); since the emulator exposes no AccessKeyId→UserName lookup, - // the element is omitted rather than emitted empty — an empty string could be - // rejected by a strict client, and callers that need the owner already have it - // from the preceding ListAccessKeys call. - String result = new XmlBuilder() + // and NO LastUsedDate. UserName names the key's owner; Terraform's + // aws_iam_access_key import reads it and fails on "empty response" without it. + // Its type is non-empty (length 1-128), so for a key the emulator does not + // hold the element is omitted rather than emitted empty. + XmlBuilder xml = new XmlBuilder(); + iamService.findAccessKeyOwnerInThisAccount(getParam(params, "AccessKeyId")) + .ifPresent(userName -> xml.elem("UserName", userName)); + String result = xml .start("AccessKeyLastUsed") .elem("ServiceName", "N/A") .elem("Region", "N/A") diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java index 73ecf17d5f..537ae87117 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java @@ -777,6 +777,25 @@ public class IamService implements SessionAccountLookup, ResourceProvider { return accessKeys.get(accessKeyId).map(AccessKey::getUserName); } + /** + * The owner of a key in the calling account, for a read that is not the owner's own request. + * Unlike {@link #findUserNameByAccessKeyId}, this never migrates: an unprefixed + * pre-multi-account key belongs to the default account and is only read in place, so another + * account asking (even one with a same-named user) neither learns the owner nor moves the key. + */ + public Optional findAccessKeyOwnerInThisAccount(String accessKeyId) { + if (accessKeyId == null) { + return Optional.empty(); + } + if (!(accessKeys instanceof AccountAwareStorageBackend aware)) { + return findUserNameByAccessKeyId(accessKeyId); + } + String accountId = aware.accountId(); + return aware.getForAccount(accountId, accessKeyId) + .or(() -> aware.getLegacyForAccount(accountId, accessKeyId)) + .map(AccessKey::getUserName); + } + public void deleteUser(String userName) { synchronized (resourceNameLock) { IamUser user = getUser(userName); diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java index b391a485ff..5e344cf539 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java @@ -443,7 +443,7 @@ public class ResourceArnBuilder { if (accessKeyId == null || accessKeyId.isBlank() || iamService == null) { return List.of("*"); } - return iamService.get().findUserNameByAccessKeyId(accessKeyId) + return iamService.get().findAccessKeyOwnerInThisAccount(accessKeyId) .flatMap(userName -> storedIamEntity("user", userName, accountId)) .map(stored -> List.of(stored.arn())) .orElse(List.of("*")); diff --git a/src/test/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackendTest.java b/src/test/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackendTest.java index 92452d191e..d89845abda 100644 --- a/src/test/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackendTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackendTest.java @@ -62,6 +62,19 @@ class AccountAwareStorageBackendTest { assertEquals("owned", raw.get("111111111111/resource").orElseThrow()); } + @Test + void legacyLookupReadsUnprefixedKeyInPlaceOnlyForDefaultAccount() { + InMemoryStorage raw = new InMemoryStorage<>(); + raw.put("resource", "legacy"); + AccountAwareStorageBackend storage = + new AccountAwareStorageBackend<>(raw, null, "111111111111"); + + assertEquals("legacy", storage.getLegacyForAccount("111111111111", "resource").orElseThrow()); + assertTrue(storage.getLegacyForAccount("222222222222", "resource").isEmpty()); + assertEquals("legacy", raw.get("resource").orElseThrow()); + assertTrue(raw.get("111111111111/resource").isEmpty()); + } + @Test void guardedLegacyLookupLeavesRejectedRawValueUntouched() { InMemoryStorage raw = new InMemoryStorage<>(); diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.java index 59f6a15c16..d57ffdde82 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.java @@ -691,7 +691,29 @@ class IamIntegrationTest { .statusCode(200) .contentType("application/xml") .body("GetAccessKeyLastUsedResponse.GetAccessKeyLastUsedResult" - + ".AccessKeyLastUsed.ServiceName", equalTo("N/A")); + + ".AccessKeyLastUsed.ServiceName", equalTo("N/A")) + .body(not(containsString(""))); + } + + @Test + @Order(49) + void getAccessKeyLastUsedReturnsOwningUserName() { + // Terraform's aws_iam_access_key import resolves the owner from this field. + createUser("last-used-owner"); + String keyId = createAccessKeyFor("last-used-owner"); + given() + .formParam("Action", "GetAccessKeyLastUsed") + .formParam("AccessKeyId", keyId) + .header("Authorization", + "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request") + .when() + .post("/") + .then() + .statusCode(200) + .body("GetAccessKeyLastUsedResponse.GetAccessKeyLastUsedResult.UserName", + equalTo("last-used-owner")) + .body("GetAccessKeyLastUsedResponse.GetAccessKeyLastUsedResult" + + ".AccessKeyLastUsed.Region", equalTo("N/A")); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java index 750f682d2a..7f4dd3f00c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.RequestContext; import io.github.hectorvent.floci.core.common.Totp; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.InMemoryStorage; @@ -24,6 +25,7 @@ import io.github.hectorvent.floci.services.iam.model.PolicyVersion; import io.github.hectorvent.floci.services.iam.model.SessionCredential; import io.github.hectorvent.floci.services.iam.model.VirtualMfaDevice; import io.github.hectorvent.floci.testing.MutableClock; +import jakarta.enterprise.inject.Instance; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -45,6 +47,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiPredicate; import java.util.function.Predicate; @@ -1270,6 +1273,44 @@ class IamServiceTest { assertEquals("alicia", iamService.findUserNameByAccessKeyId(keyId).orElseThrow()); } + @Test + void anotherAccountCannotClaimALegacyAccessKeyThroughItsOwnerLookup() { + assertLegacyKeyStaysWithTheDefaultAccount(false); + } + + @Test + void aSameNamedUserInAnotherAccountCannotClaimALegacyAccessKey() { + assertLegacyKeyStaysWithTheDefaultAccount(true); + } + + /** One shared key store, two accounts told apart by the request context, as in a real boot. */ + @SuppressWarnings("unchecked") + private static void assertLegacyKeyStaysWithTheDefaultAccount(boolean strangerHasSameNamedUser) { + AtomicReference caller = new AtomicReference<>("000000000000"); + RequestContext context = Mockito.mock(RequestContext.class); + Mockito.when(context.getAccountId()).thenAnswer(inv -> caller.get()); + Instance contexts = Mockito.mock(Instance.class); + Mockito.when(contexts.get()).thenReturn(context); + InMemoryStorage raw = new InMemoryStorage<>(); + raw.put("AKIALEGACYEXAMPLE", new AccessKey("AKIALEGACYEXAMPLE", "secret", "worker")); + AccountAwareStorageBackend keys = new AccountAwareStorageBackend<>(raw, contexts, "000000000000"); + IamService owner = iamService(false, keys); + IamService stranger = iamService(false, keys); + owner.createUser("worker", "/"); + + caller.set("111122223333"); + if (strangerHasSameNamedUser) { + stranger.createUser("worker", "/"); + } + assertTrue(stranger.findAccessKeyOwnerInThisAccount("AKIALEGACYEXAMPLE").isEmpty()); + assertTrue(raw.get("AKIALEGACYEXAMPLE").isPresent(), "the stranger's lookup must leave the key unmoved"); + assertTrue(raw.get("111122223333/AKIALEGACYEXAMPLE").isEmpty(), "the stranger's lookup must not copy the key"); + + caller.set("000000000000"); + assertEquals("worker", owner.findAccessKeyOwnerInThisAccount("AKIALEGACYEXAMPLE").orElseThrow()); + assertTrue(raw.get("AKIALEGACYEXAMPLE").isPresent(), "the owner's read must not migrate either"); + } + @Test void renamingAUserUpdatesItsGroupMembership() { iamService.createUser("alice", "/"); diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java index f13e0f56ec..f64fe2a854 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java @@ -1,6 +1,11 @@ package io.github.hectorvent.floci.services.iam; import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.RequestContext; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.iam.model.AccessKey; import io.github.hectorvent.floci.services.iam.model.IamGroup; import io.github.hectorvent.floci.services.iam.model.IamRole; import io.github.hectorvent.floci.services.iam.model.IamUser; @@ -27,6 +32,7 @@ import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -329,11 +335,39 @@ class ResourceArnBuilderTest { void iamNamesTheUserOwningAnAccessKey() { String arn = "arn:aws:iam::000000000000:user/bob"; IamService store = storeHolding("bob", "/", arn); - when(store.findUserNameByAccessKeyId("AKIAEXAMPLE")).thenReturn(Optional.of("bob")); + when(store.findAccessKeyOwnerInThisAccount("AKIAEXAMPLE")).thenReturn(Optional.of("bob")); assertEquals(arn, resourceOf(backedBy(store), "Action=GetAccessKeyLastUsed&AccessKeyId=AKIAEXAMPLE")); } + /** + * The enforcement filter resolves the key's owner before the handler runs, so the resolver + * must not migrate a pre-multi-account key into the caller's partition either: another + * account asking about it, even one with a same-named user, gets the wildcard and leaves the + * key where it was. + */ + @Test + void iamDoesNotLetAnotherAccountClaimALegacyAccessKeyThroughTheOwnerLookup() { + String stranger = "111122223333"; + RequestContext context = mock(RequestContext.class); + when(context.getAccountId()).thenReturn(stranger); + @SuppressWarnings("unchecked") + Instance contexts = mock(Instance.class); + when(contexts.get()).thenReturn(context); + InMemoryStorage raw = new InMemoryStorage<>(); + raw.put("AKIALEGACYEXAMPLE", new AccessKey("AKIALEGACYEXAMPLE", "secret", "worker")); + IamService iam = new IamService(new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), + new AccountAwareStorageBackend<>(raw, contexts, ACCOUNT), new InMemoryStorage<>(), + new InMemoryStorage<>(), new RegionResolver("us-east-1", ACCOUNT), false); + iam.createUser("worker", "/"); + + setFormBody("Action=GetAccessKeyLastUsed&AccessKeyId=AKIALEGACYEXAMPLE"); + assertEquals(List.of("*"), backedBy(iam).buildResources("iam", ctx, "us-east-1", stranger)); + assertTrue(raw.get("AKIALEGACYEXAMPLE").isPresent(), "the lookup must leave the key unmoved"); + assertTrue(raw.get(stranger + "/AKIALEGACYEXAMPLE").isEmpty(), "the lookup must not copy the key"); + } + /** * A hardware MFA device's {@code SerialNumber} is a bare serial rather than an ARN, so there * is nothing to pass through and nothing a policy could be written against.