fix(iam): take every access key status the model publishes (#5968)

UpdateAccessKey refused the Expired that statusType permits, answered a
message of its own making, and read the status only after it had looked the
key up, so a bad key carrying a bad status answered NoSuchEntity 404 where the
shape is what AWS answers for. The reference's Valid Values line on the
operation reads "Active | Inactive | Expired" and the pinned model's
statusType holds those same three.

The fix is one call rather than a new rule. requireStatusFromEnum already
serves UpdateSigningCertificate, UpdateSSHPublicKey and
UpdateServiceSpecificCredential: it validates before each of those lookups and
answers the rendering a recording of the third shows, naming neither the
offending value nor the permitted set. UpdateAccessKey was the one operation
of the four not calling it, so it calls it, and the helper's javadoc and the
set behind it say four instead of three.

UserName was the other half. The page carries the sentence DeleteAccessKey
carries, "if the UserName is not specified, the user name is determined
implicitly based on the AWS access key ID used to sign the request", and the
handler passed the raw parameter straight through, so a call that omitted it
compared the key's owner against null and answered NoSuchEntity. It resolves
through resolveUserName now, as GetUser, ListAccessKeys and DeleteAccessKey
do, and AccessKeyId is read through requireParam, as the sibling handlers read
the ids they require.

AWS::IAM::AccessKey refused Expired as well, and its own Allowed values line
in the CloudFormation template reference reads "Active | Inactive | Expired".
Leaving it would have been the same drift on a second surface, and taking
Expired on the API while refusing it in a template is worse than either
alone. The provisioner keeps its own guard, which runs before a key is created
so that a refusal cannot orphan one, and its own message, which names the
resource it refuses.

One more drift came out of reading the method back, and it is the one that
mattered. updateAccessKey is a read-modify-write that took no lock, where each
of the three sibling status operations holds its family's. There was no access
key lock at all: createAccessKey counted a user's keys and only then stored
another, and the user rename rewrote each key's owner outside one, the single
credential family that rename did not guard. Measured before the fix, racing
the calls against each other: an update racing a delete wrote the deleted key
back on 80 of 2000 trials, and four callers racing the two-key quota left more
than two on 226 of 500. One accessKeyLock now covers the count and the store,
the lookup and the delete, the read-modify-write, and the rename's loop, and
the owner check that the delete and the update each carried is one helper.
Substituting a fresh monitor for that lock at all four sites fails the quota
case on its first trial and the resurrection case by its eighty-third.

Three more places the lock has to reach, each measured the same way. The rename
read the key list before taking the lock and rewrote it inside, so a delete that
landed in between was undone and the key came back under the new name, where it
authenticates again; the read moves inside the lock, where every other
credential family already reads its own, and putting it back outside fails by
the third trial. createAccessKey confirmed the user before taking the lock and
deleteUser checked for keys without holding it, so a create could store a key
for a user the delete had just removed; the confirmation moves inside the lock,
the way UploadSigningCertificate's already is, and deleteUser holds the lock
across its key check and the delete, outermost of the five it nests, which is
the order UpdateUser leaves intact by taking that lock on its own. Reverting
either half alone puts the orphan back, by the seventeenth trial and by the
second.

Fifteen tests. Seven over the wire: Expired stored and read back, a status
outside the set, an absent status, an absent key id, the order against a key
that is not there, a call that names no user, and another user's key still
answering NoSuchEntity. Three on the service for the three statuses, the
order, and the absent status. One on the provisioner for a template declaring
Expired. And four in IamConcurrencyTest, which raced six collections and
no credential family before this: an update against a delete, four creates
against the quota, a rename against a delete, and a create against DeleteUser.
The two refusals also read the key back, over the wire and on the service, so a
validation that wrote before it refused would not pass them. What is left is
the count: AWS reports "2 validation errors detected" when the id and the
status are both wrong, where every message here leads with one, which is the
follow-up #5280 already carries.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-19 07:45:19 -05:00
1 parent 70328403f0
commit b14537baa7
8 files changed
+521 -74

No files matched your search

@@ -117,6 +117,22 @@ class IamAccessKeyCfnProvisionerTest {
verify(iam, never()).updateAccessKey(anyString(), anyString(), anyString());
}
@Test
void createWithExpiredStatusIsTakenToo() throws Exception {
// The resource's Allowed values line reads "Active | Inactive | Expired", so Expired is a
// status the template may declare and not one to refuse.
AccessKey key = new AccessKey();
key.setAccessKeyId("AKIA1");
key.setSecretAccessKey("secret-1");
when(iam.createAccessKey("alice")).thenReturn(key);
provisioner.provision(resource(), props("{\"UserName\": \"alice\", \"Status\": \"Expired\"}"),
ctx(null));
verify(iam).createAccessKey("alice");
verify(iam).updateAccessKey("alice", "AKIA1", "Expired");
}
@Test
void aBogusStatusIsRejectedBeforeCreatingAKey() {
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(
@@ -0,0 +1,168 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
/**
* {@code UpdateAccessKey} over the wire, for the three things the reference publishes about it that
* the handler did not follow.
*
* <p>The status is a {@code statusType}, whose Valid Values line reads "Active | Inactive |
* Expired", so {@code Expired} is a value the operation takes rather than one to refuse. A value
* outside that set breaks a constraint the model declares, which the Common Errors page answers as
* {@code ValidationError}, and it is read before the key is looked up, so it is answered even when
* the key named does not exist. And "if the UserName is not specified, the user name is determined
* implicitly based on the AWS access key ID used to sign the request", the sentence this operation
* shares with DeleteAccessKey and ListAccessKeys.
*
* <p>The refusal is the rendering {@code IamService.requireStatusFromEnum} already answers for the
* other three operations that take this shape, which names neither the offending value nor the
* permitted set, as AWS's own recording of one of them does not.
*/
@QuarkusTest
class IamAccessKeyStatusIntegrationTest {
private static final String ACCOUNT = "000000000912";
private static final String REGION = "us-east-1";
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void expiredIsAStatusTheOperationTakes() {
String userName = user("expired");
String accessKeyId = accessKeyFor(userName);
update(ACCOUNT, Map.of("UserName", userName, "AccessKeyId", accessKeyId,
"Status", "Expired")).statusCode(200);
admin("ListAccessKeys", Map.of("UserName", userName)).statusCode(200)
.body("ListAccessKeysResponse.ListAccessKeysResult.AccessKeyMetadata.member.Status",
equalTo("Expired"));
}
@Test
void aStatusOutsideTheEnumIsAValidationError() {
String userName = user("bad-status");
String accessKeyId = accessKeyFor(userName);
update(ACCOUNT, Map.of("UserName", userName, "AccessKeyId", accessKeyId,
"Status", "Disabled")).statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
.body("ErrorResponse.Error.Message",
equalTo("1 validation error detected: Value at 'status' failed to satisfy "
+ "constraint: Member must satisfy enum value set"));
assertStatusStillActive(userName);
}
@Test
void anAbsentStatusIsAnsweredTheSameWay() {
String userName = user("absent-status");
String accessKeyId = accessKeyFor(userName);
update(ACCOUNT, Map.of("UserName", userName, "AccessKeyId", accessKeyId)).statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
.body("ErrorResponse.Error.Message", containsString("at 'status'"));
assertStatusStillActive(userName);
}
/** A refused status leaves the key as it was: the value is read before anything is written. */
private void assertStatusStillActive(String userName) {
admin("ListAccessKeys", Map.of("UserName", userName)).statusCode(200)
.body("ListAccessKeysResponse.ListAccessKeysResult.AccessKeyMetadata.member.Status",
equalTo("Active"));
}
@Test
void anAbsentAccessKeyIdNamesItself() {
update(ACCOUNT, Map.of("UserName", user("absent-id"), "Status", "Inactive")).statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
.body("ErrorResponse.Error.Message", containsString("Value null at 'accessKeyId'"));
}
@Test
void theStatusIsReadBeforeTheKeyIsLookedUp() {
// Both are wrong, and the shape is what AWS answers for: the key would otherwise decide,
// which is NoSuchEntity 404 for a key that is not there.
update(ACCOUNT, Map.of("UserName", user("order"), "AccessKeyId", "AKIANOSUCHKEY00000",
"Status", "Disabled")).statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
update(ACCOUNT, Map.of("UserName", user("order-valid"), "AccessKeyId", "AKIANOSUCHKEY00000",
"Status", "Inactive")).statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));
}
@Test
void theSignersOwnKeyNeedsNoUserName() {
String userName = user("implicit");
String accessKeyId = accessKeyFor(userName);
update(accessKeyId, Map.of("AccessKeyId", accessKeyId, "Status", "Inactive"))
.statusCode(200);
admin("ListAccessKeys", Map.of("UserName", userName)).statusCode(200)
.body("ListAccessKeysResponse.ListAccessKeysResult.AccessKeyMetadata.member.Status",
equalTo("Inactive"));
}
@Test
void anotherUsersKeyIsStillNoSuchEntity() {
String owner = user("owner");
String ownerKey = accessKeyFor(owner);
String stranger = user("stranger");
update(ACCOUNT, Map.of("UserName", stranger, "AccessKeyId", ownerKey,
"Status", "Inactive")).statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));
}
private String user(String label) {
String userName = "access-key-status-" + label;
admin("CreateUser", Map.of("UserName", userName)).statusCode(200);
cleanup.register(() -> admin("DeleteUser", Map.of("UserName", userName)).statusCode(200));
return userName;
}
private String accessKeyFor(String userName) {
String accessKeyId = admin("CreateAccessKey", Map.of("UserName", userName)).statusCode(200)
.extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey"
+ ".AccessKeyId");
cleanup.register(() -> admin("DeleteAccessKey",
Map.of("UserName", userName, "AccessKeyId", accessKeyId)).statusCode(200));
return accessKeyId;
}
private static ValidatableResponse update(String accessKeyId, Map<String, String> params) {
return iam(accessKeyId, "UpdateAccessKey", params);
}
private static ValidatableResponse admin(String action, Map<String, String> params) {
return iam(ACCOUNT, action, params);
}
private static ValidatableResponse iam(String accessKeyId, String action,
Map<String, String> params) {
RequestSpecification spec = given()
.header("Authorization", "AWS4-HMAC-SHA256 Credential=" + accessKeyId
+ "/20261018/" + REGION + "/iam/aws4_request, SignedHeaders=host, "
+ "Signature=abc")
.contentType("application/x-www-form-urlencoded")
.formParam("Action", action)
.formParam("Version", "2010-05-08");
params.forEach(spec::formParam);
return spec.when().post("/").then();
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.iam.model.IamPolicy;
@@ -15,6 +16,8 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.IntConsumer;
import java.util.function.ToIntFunction;
import java.util.stream.Stream;
@@ -397,6 +400,175 @@ class IamConcurrencyTest {
}
}
@Test
void anUpdateCannotResurrectADeletedAccessKey() throws Exception {
// UpdateAccessKey reads a key, sets its status and writes it back, so without a lock the
// write lands after a delete that ran in between and the credential comes back. Measured
// at 80 of 2000 trials before the lock.
ExecutorService pool = Executors.newFixedThreadPool(THREADS);
try {
for (int trial = 0; trial < 2000; trial++) {
IamService iam = newIamService();
iam.createUser("racer", "/");
String keyId = iam.createAccessKey("racer").getAccessKeyId();
CountDownLatch start = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(2);
List<String> unexpected = new CopyOnWriteArrayList<>();
pool.execute(raceStep(start, done, unexpected,
() -> iam.updateAccessKey("racer", keyId, "Inactive")));
pool.execute(raceStep(start, done, unexpected,
() -> iam.deleteAccessKey("racer", keyId)));
start.countDown();
assertTrue(done.await(30, TimeUnit.SECONDS), "access key workers stalled");
if (!iam.listAccessKeys("racer").isEmpty() || !unexpected.isEmpty()) {
fail("access key trial " + trial + ": the deleted key is still listed"
+ ", unexpectedErrors=" + unexpected);
}
}
} finally {
pool.shutdownNow();
}
}
@Test
void concurrentAccessKeyCreatesStayInsideTheQuota() throws Exception {
// AccessKeysPerUser is 2, counted and then written, so without a lock four callers racing
// the count all pass it. Measured at 226 of 500 trials before the lock.
ExecutorService pool = Executors.newFixedThreadPool(THREADS);
try {
for (int trial = 0; trial < 500; trial++) {
IamService iam = newIamService();
iam.createUser("racer", "/");
CountDownLatch start = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(4);
List<String> unexpected = new CopyOnWriteArrayList<>();
for (int i = 0; i < 4; i++) {
pool.execute(raceStep(start, done, unexpected, () -> iam.createAccessKey("racer")));
}
start.countDown();
assertTrue(done.await(30, TimeUnit.SECONDS), "access key workers stalled");
int stored = iam.listAccessKeys("racer").size();
if (stored != 2 || !unexpected.isEmpty()) {
fail("access key quota trial " + trial + ": stored=" + stored
+ " unexpectedErrors=" + unexpected);
}
}
} finally {
pool.shutdownNow();
}
}
@Test
void aRenameCannotResurrectADeletedAccessKey() throws Exception {
// UpdateUser rewrites each key's owner. Reading that list before taking the lock lets a
// DeleteAccessKey land in between, and the loop then writes the deleted key back under the
// new name, where it authenticates again.
ExecutorService pool = Executors.newFixedThreadPool(THREADS);
try {
for (int trial = 0; trial < 2000; trial++) {
IamService iam = newIamService();
iam.createUser("racer", "/");
String keyId = iam.createAccessKey("racer").getAccessKeyId();
CountDownLatch start = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(2);
List<String> unexpected = new CopyOnWriteArrayList<>();
AtomicBoolean deleted = new AtomicBoolean();
pool.execute(raceStep(start, done, unexpected,
() -> iam.updateUser("racer", "renamed", null)));
pool.execute(raceStep(start, done, unexpected, () -> {
iam.deleteAccessKey("racer", keyId);
deleted.set(true);
}));
start.countDown();
assertTrue(done.await(30, TimeUnit.SECONDS), "rename workers stalled");
// The delete can lose the race, the key having moved to the new name before it
// looked, and then the key is meant to still be there. What may never happen is a
// delete that answered 200 and a key that is still stored.
boolean stored = iam.findUserNameByAccessKeyId(keyId).isPresent();
if ((deleted.get() && stored) || !unexpected.isEmpty()) {
fail("rename trial " + trial + ": deleted=" + deleted.get()
+ " stillStored=" + stored + " unexpectedErrors=" + unexpected);
}
}
} finally {
pool.shutdownNow();
}
}
@Test
void anAccessKeyCannotBeCreatedForAUserBeingDeleted() throws Exception {
// CreateAccessKey confirming the user before taking the lock, and DeleteUser checking for
// keys without holding it, leaves the pair free to interleave: the create passes the check
// and stores a key for a user the delete has just removed.
ExecutorService pool = Executors.newFixedThreadPool(THREADS);
try {
for (int trial = 0; trial < 2000; trial++) {
IamService iam = newIamService();
iam.createUser("racer", "/");
CountDownLatch start = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(2);
List<String> unexpected = new CopyOnWriteArrayList<>();
AtomicReference<String> created = new AtomicReference<>();
pool.execute(raceStep(start, done, unexpected,
() -> created.set(iam.createAccessKey("racer").getAccessKeyId())));
pool.execute(raceStep(start, done, unexpected, () -> iam.deleteUser("racer")));
start.countDown();
assertTrue(done.await(30, TimeUnit.SECONDS), "delete-user workers stalled");
boolean userGone = userIsGone(iam);
boolean orphan = userGone && created.get() != null
&& iam.findUserNameByAccessKeyId(created.get()).isPresent();
if (orphan || !unexpected.isEmpty()) {
fail("delete-user trial " + trial + ": a key is stored for a user that is gone"
+ ", unexpectedErrors=" + unexpected);
}
}
} finally {
pool.shutdownNow();
}
}
private static boolean userIsGone(IamService iam) {
try {
iam.getUser("racer");
return false;
} catch (AwsException e) {
return true;
}
}
/**
* One racer: waits for the start, runs the step, and keeps any error that is not one of the
* refusals the race is allowed to produce, a key already gone, a quota already full or a user
* that still has a key when the delete looks.
*/
private static Runnable raceStep(CountDownLatch start, CountDownLatch done,
List<String> unexpected, Runnable step) {
return () -> {
try {
start.await(10, TimeUnit.SECONDS);
step.run();
} catch (AwsException e) {
if (!"NoSuchEntity".equals(e.getErrorCode())
&& !"LimitExceeded".equals(e.getErrorCode())
&& !"DeleteConflict".equals(e.getErrorCode())) {
unexpected.add(e.getErrorCode());
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
done.countDown();
}
};
}
private static String[] createPolicies(IamService iam, String prefix) {
String[] arns = new String[N];
for (int i = 0; i < N; i++) {
@@ -2030,6 +2030,52 @@ class IamServiceTest {
assertTrue(iamService.listAccessKeys("alice").isEmpty());
}
@Test
void anAccessKeyTakesEveryStatusTheModelPublishes() {
// statusType is Active, Inactive or Expired, which is what the reference's Valid Values
// line on UpdateAccessKey lists, so Expired is a value to store rather than to refuse.
iamService.createUser("alice", "/");
AccessKey key = iamService.createAccessKey("alice");
for (String status : List.of("Inactive", "Expired", "Active")) {
iamService.updateAccessKey("alice", key.getAccessKeyId(), status);
assertEquals(status, iamService.listAccessKeys("alice").getFirst().getStatus());
}
}
@Test
void anAccessKeyStatusIsReadBeforeTheKeyIsFound() {
// The key does not exist either, and the status is what answers: AWS reads a request's
// shape before it resolves anything, so the lookup's NoSuchEntity does not get there first.
iamService.createUser("alice", "/");
AwsException error = assertThrows(AwsException.class,
() -> iamService.updateAccessKey("alice", "AKIANOSUCHKEY00000", "Disabled"));
assertEquals("ValidationError", error.getErrorCode());
// The rendering the three sibling operations already answer with, taken from a recording
// of UpdateServiceSpecificCredential: AWS names neither the value nor the permitted set.
assertEquals("1 validation error detected: Value at 'status' failed to satisfy "
+ "constraint: Member must satisfy enum value set", error.getMessage());
}
@Test
void anAbsentAccessKeyStatusIsAnsweredLikeAnInvalidOne() {
// The shared helper reads a null as a value outside the enum, which is how the other three
// statusType operations answer one. Changing that would change all four, so it stays.
iamService.createUser("alice", "/");
AccessKey key = iamService.createAccessKey("alice");
AwsException error = assertThrows(AwsException.class,
() -> iamService.updateAccessKey("alice", key.getAccessKeyId(), null));
assertEquals("ValidationError", error.getErrorCode());
assertEquals("1 validation error detected: Value at 'status' failed to satisfy "
+ "constraint: Member must satisfy enum value set", error.getMessage());
// And the key is as it was: the status is read before the lookup, so nothing is written.
assertEquals("Active", iamService.listAccessKeys("alice").getFirst().getStatus());
}
@Test
void aSessionWithNoRoleAndNoRecordedIssuerIsNoCredential() {
// How GetSessionToken stored its sessions before it recorded the key that minted them. Such