fix(iam): return UserName from GetAccessKeyLastUsed (#5579)

* fix(iam): return UserName from GetAccessKeyLastUsed

GetAccessKeyLastUsed omitted UserName for every key, so Terraform's
aws_iam_access_key import failed with "fetching IAM Access Key (...)
username via GetAccessKeyLastUsed: empty response". Resolve the owner
of a stored key and emit it; an unknown key still omits the element.

* test(iam): give the GetAccessKeyLastUsed owner test a unique @Order

* fix(iam): do not let another account claim a legacy key through GetAccessKeyLastUsed

* fix(iam): never migrate a legacy key on the GetAccessKeyLastUsed read path

findAccessKeyOwnerInThisAccount adopted an unprefixed legacy key into the
calling account whenever a user of the same name existed there, so another
account with its own `worker` user could read the owner's name and move the
key out of the default account. Read the scoped key, else peek at legacy
keys in place via scanAllAccountEntries, which attributes them to the
default account, as resourcesInCurrentAccount already does. Nothing moves.

The tests now model accounts through a request context over one shared
store instead of two backends with different default accounts.

* perf(iam): look up a legacy access key directly instead of scanning every account

findAccessKeyOwnerInThisAccount fell back to scanAllAccountEntries on every
miss, so an unknown key walked the whole key store. Add
AccountAwareStorageBackend.getLegacyForAccount, a read-only point lookup of an
unprefixed entry that, like scanAllAccountEntries, attributes it to the
default account only.

* fix(iam): resolve GetAccessKeyLastUsed's policy resource without migrating a legacy key

The enforcement filter resolves the key's owner before the handler runs, and it
went through the migrating lookup, so another account could still pull a
pre-multi-account key into its own partition just by asking about it. Use the
same non-migrating lookup the handler uses, so the policy check and the
response agree on who owns the key.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-10-14 00:22:35 -04:00
1 parent 5a90be1049
commit 372d3d11d5
8 files changed
+150 -9

No files matched your search

@@ -62,6 +62,19 @@ class AccountAwareStorageBackendTest {
assertEquals("owned", raw.get("111111111111/resource").orElseThrow());
}
@Test
void legacyLookupReadsUnprefixedKeyInPlaceOnlyForDefaultAccount() {
InMemoryStorage<String, String> raw = new InMemoryStorage<>();
raw.put("resource", "legacy");
AccountAwareStorageBackend<String> 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<String, String> raw = new InMemoryStorage<>();
@@ -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("<UserName>")));
}
@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
@@ -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<String> caller = new AtomicReference<>("000000000000");
RequestContext context = Mockito.mock(RequestContext.class);
Mockito.when(context.getAccountId()).thenAnswer(inv -> caller.get());
Instance<RequestContext> contexts = Mockito.mock(Instance.class);
Mockito.when(contexts.get()).thenReturn(context);
InMemoryStorage<String, AccessKey> raw = new InMemoryStorage<>();
raw.put("AKIALEGACYEXAMPLE", new AccessKey("AKIALEGACYEXAMPLE", "secret", "worker"));
AccountAwareStorageBackend<AccessKey> 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", "/");
@@ -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<RequestContext> contexts = mock(Instance.class);
when(contexts.get()).thenReturn(context);
InMemoryStorage<String, AccessKey> 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.