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

@@ -9,6 +9,7 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -27,6 +28,8 @@ import java.util.Set;
public class IamAccessKeyCfnProvisioner implements CfnResourceProvisioner {
private static final String TYPE = "AWS::IAM::AccessKey";
/** The resource's own Allowed values line, which matches the IAM API's {@code statusType}. */
private static final List<String> STATUS_VALUES = List.of("Active", "Inactive", "Expired");
private static final String SERIAL_ATTR = "__FlociAccessKeySerial";
private final IamService iamService;
@@ -48,13 +51,14 @@ public class IamAccessKeyCfnProvisioner implements CfnResourceProvisioner {
throw new AwsException("ValidationError", "AWS::IAM::AccessKey requires a UserName.", 400);
}
String serial = serialOf(props, ctx);
// Status (Active/Inactive) is a mutable property. Validate it up front, before any key is
// created, so a bad value fails cleanly: a user is capped at two keys, so creating one and
// only then rejecting the status could orphan it.
// Status is a mutable property whose Allowed values line reads "Active | Inactive |
// Expired", the same three the IAM API's statusType publishes. Validate it up front,
// before any key is created, so a bad value fails cleanly: a user is capped at two keys,
// so creating one and only then rejecting the status could orphan it.
String status = ctx.resolveOptional(props, "Status");
if (status != null && !"Active".equals(status) && !"Inactive".equals(status)) {
if (status != null && !STATUS_VALUES.contains(status)) {
throw new AwsException("ValidationError",
"AWS::IAM::AccessKey Status must be Active or Inactive.", 400);
"AWS::IAM::AccessKey Status must be Active, Inactive or Expired.", 400);
}
Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());
@@ -75,8 +79,8 @@ public class IamAccessKeyCfnProvisioner implements CfnResourceProvisioner {
r.getAttributes().put("Id", key.getAccessKeyId());
r.getAttributes().put("SecretAccessKey", key.getSecretAccessKey());
r.getAttributes().put(SERIAL_ATTR, serial);
// A new key is Active; only touch it when the template asked for Inactive.
if ("Inactive".equals(status)) {
// A new key is Active; only touch it when the template asked for something else.
if (status != null && !"Active".equals(status)) {
iamService.updateAccessKey(userName, key.getAccessKeyId(), status);
}
// On a createOnly change this new key replaced the prior one; record it so the displaced
@@ -284,7 +284,7 @@ public class IamQueryHandler {
case "CreateAccessKey" -> handleCreateAccessKey(params);
case "DeleteAccessKey" -> handleDeleteAccessKey(params, authorization);
case "ListAccessKeys" -> handleListAccessKeys(params, authorization);
case "UpdateAccessKey" -> handleUpdateAccessKey(params);
case "UpdateAccessKey" -> handleUpdateAccessKey(params, authorization);
case "GetAccessKeyLastUsed" -> handleGetAccessKeyLastUsed(params);
case "ListOrganizationsFeatures" -> handleListOrganizationsFeatures(params);
@@ -358,8 +358,8 @@ public class IamQueryHandler {
return Response.ok(AwsQueryResponse.envelope("CreateUser", AwsNamespaces.IAM, result)).build();
}
// UserName is optional on GetUser/ListAccessKeys/DeleteAccessKey: real AWS determines
// it implicitly from the access key that signed the request. Mirrors moto: an access
// UserName is optional on GetUser/ListAccessKeys/DeleteAccessKey/UpdateAccessKey: real AWS
// determines it implicitly from the access key that signed the request. Mirrors moto: an access
// key that maps to no stored IAM user is the documented NoSuchEntity error.
private String resolveUserName(MultivaluedMap<String, String> params, String authorization) {
String userName = getParam(params, "UserName");
@@ -1964,9 +1964,12 @@ public class IamQueryHandler {
return Response.ok(AwsQueryResponse.envelope("ListAccessKeys", AwsNamespaces.IAM, xml.build())).build();
}
private Response handleUpdateAccessKey(MultivaluedMap<String, String> params) {
iamService.updateAccessKey(getParam(params, "UserName"),
getParam(params, "AccessKeyId"), getParam(params, "Status"));
private Response handleUpdateAccessKey(MultivaluedMap<String, String> params, String authorization) {
// "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 same sentence DeleteAccessKey carries.
// Read the way the other three statusType operations read theirs, the status included.
iamService.updateAccessKey(resolveUserName(params, authorization),
requireParam(params, "AccessKeyId"), getParam(params, "Status"));
return Response.ok(AwsQueryResponse.envelopeNoResult("UpdateAccessKey", AwsNamespaces.IAM)).build();
}
@@ -279,9 +279,10 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
private static final String CREDENTIAL_STATUS_ACTIVE = "Active";
private static final String CREDENTIAL_STATUS_EXPIRED = "Expired";
/**
* statusType's values, shared by signing certificates and SSH public keys: Active, Inactive
* and Expired. Each operation's prose explains only the first two, so the third is easy to
* reject by mistake, while the API Reference lists all three as valid.
* statusType's values, shared by access keys, signing certificates, SSH public keys and
* service-specific credentials: Active, Inactive and Expired. Each operation's prose explains
* only the first two, so the third is easy to reject by mistake, while the API Reference lists
* all three as valid on each of them.
*/
private static final Set<String> CREDENTIAL_STATUSES =
Set.of(CREDENTIAL_STATUS_ACTIVE, "Inactive", CREDENTIAL_STATUS_EXPIRED);
@@ -401,6 +402,14 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
private final Object signingCertificateLock = new Object();
private final Object sshPublicKeyLock = new Object();
private final Object serviceCredentialLock = new Object();
/**
* Guards every check-then-write on an access key, the way its three sibling credential
* families are guarded. Both halves of this family need it: CreateAccessKey counts a user's
* keys and only then stores another, so two requests racing the quota would both pass a check
* for two; and UpdateAccessKey reads a key, changes its status and writes it back, so an
* update racing a delete would store the key the delete had just removed.
*/
private final Object accessKeyLock = new Object();
/**
* Guards every check-then-write on an MFA device. Assignment is the reason it has to exist:
* EnableMFADevice reads the device to confirm it is unassigned and reads the user's device
@@ -835,39 +844,43 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must delete policies first.", 409);
}
if (!userAccessKeys(userName).isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must delete access keys first.", 409);
}
// Both locks are held across the delete rather than just the checks: UploadSigningCertificate
// UploadSigningCertificate and EnableMFADevice confirm the user under their own lock, so
// none of them can interleave into a credential owned by a deleted user. Taken in this
// order here and in UpdateUser, and nowhere else in more than one, so it cannot deadlock.
synchronized (serviceCredentialLock) {
// AWS lists these among the items to remove first, under their CodeCommit
// name: "Git credentials (DeleteServiceSpecificCredential)". Unlike the
// cases above it has no message of its own: AWS falls back to the generic
// referenced-objects wording here.
if (!userServiceCredentials(userName).isEmpty()) {
// The credential locks are held across the delete rather than just the checks:
// CreateAccessKey, UploadSigningCertificate and EnableMFADevice each confirm the user
// under their own lock, so none of them can interleave into a credential owned by a
// user that is already gone. Access keys are the outermost of the five here, and
// UpdateUser takes that lock on its own rather than inside the others, so no two of
// them are ever held in opposite orders.
synchronized (accessKeyLock) {
if (!userAccessKeys(userName).isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must remove referenced objects first.", 409);
"Cannot delete entity, must delete access keys first.", 409);
}
synchronized (sshPublicKeyLock) {
if (!userSshPublicKeys(userName).isEmpty()) {
synchronized (serviceCredentialLock) {
// AWS lists these among the items to remove first, under their CodeCommit
// name: "Git credentials (DeleteServiceSpecificCredential)". Unlike the
// cases above it has no message of its own: AWS falls back to the generic
// referenced-objects wording here.
if (!userServiceCredentials(userName).isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must delete SSH public keys first.", 409);
"Cannot delete entity, must remove referenced objects first.", 409);
}
synchronized (signingCertificateLock) {
if (!userSigningCertificates(userName).isEmpty()) {
synchronized (sshPublicKeyLock) {
if (!userSshPublicKeys(userName).isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must delete signing certificates first.", 409);
"Cannot delete entity, must delete SSH public keys first.", 409);
}
synchronized (mfaDeviceLock) {
if (!mfaDevicesForUser(userName).isEmpty()) {
synchronized (signingCertificateLock) {
if (!userSigningCertificates(userName).isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must deactivate MFA device first.", 409);
"Cannot delete entity, must delete signing certificates first.", 409);
}
synchronized (mfaDeviceLock) {
if (!mfaDevicesForUser(userName).isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must deactivate MFA device first.", 409);
}
users.delete(userName);
}
users.delete(userName);
}
}
}
@@ -904,7 +917,6 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
throw new AwsException("EntityAlreadyExists",
"User with name " + newUserName + " already exists.", 409);
}
List<AccessKey> keysToMove = userAccessKeys(userName);
// The rename publishes the user under its new name and moves the credentials that
// DeleteUser refuses to delete a user over: its MFA devices, its signing
// certificates and its SSH public keys. Each moves under the lock DeleteUser checks it with, because split
@@ -955,9 +967,15 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
loginProfiles.put(newUserName, profile);
});
}
for (AccessKey key : keysToMove) {
key.setUserName(newUserName);
accessKeys.put(key.getAccessKeyId(), key);
synchronized (accessKeyLock) {
// Read inside the lock that rewrites them, the way each credential above is
// read inside its own: a DeleteAccessKey landing between a read taken earlier
// and this loop would be undone, the deleted key coming back under the new
// name and still authenticating.
for (AccessKey key : userAccessKeys(userName)) {
key.setUserName(newUserName);
accessKeys.put(key.getAccessKeyId(), key);
}
}
for (String groupName : user.getGroupNames()) {
groups.get(groupName).ifPresent(group -> {
@@ -2231,31 +2249,30 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
// =========================================================================
public AccessKey createAccessKey(String userName) {
getUser(userName); // validates existence
long existingCount = accessKeys.scan(k -> true).stream()
.filter(ak -> userName.equals(ak.getUserName()))
.count();
if (existingCount >= 2) {
throw new AwsException("LimitExceeded",
"Cannot exceed quota for AccessKeysPerUser: 2", 409);
synchronized (accessKeyLock) {
// Confirmed under the lock, not before it, the way UploadSigningCertificate confirms
// its own: DeleteUser checks for access keys holding this same lock, so the two cannot
// interleave into a key owned by a user that no longer exists.
getUser(userName);
long existingCount = userAccessKeys(userName).size();
if (existingCount >= 2) {
throw new AwsException("LimitExceeded",
"Cannot exceed quota for AccessKeysPerUser: 2", 409);
}
String keyId = "AKIA" + randomId(16);
String secretKey = randomSecret(40);
AccessKey key = new AccessKey(keyId, secretKey, userName);
accessKeys.put(keyId, key);
LOG.infov("Created access key for user: {0}", userName);
return key;
}
String keyId = "AKIA" + randomId(16);
String secretKey = randomSecret(40);
AccessKey key = new AccessKey(keyId, secretKey, userName);
accessKeys.put(keyId, key);
LOG.infov("Created access key for user: {0}", userName);
return key;
}
public void deleteAccessKey(String userName, String accessKeyId) {
AccessKey key = accessKeys.get(accessKeyId)
.orElseThrow(() -> new AwsException("NoSuchEntity",
"Access key " + accessKeyId + " not found.", 404));
if (!key.getUserName().equals(userName)) {
throw new AwsException("NoSuchEntity",
"Access key " + accessKeyId + " does not belong to user " + userName + ".", 404);
synchronized (accessKeyLock) {
AccessKey key = userAccessKey(userName, accessKeyId);
accessKeys.delete(key.getAccessKeyId());
}
accessKeys.delete(accessKeyId);
}
public List<AccessKey> listAccessKeys(String userName) {
@@ -2269,7 +2286,22 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
.toList();
}
/**
* Sets an access key's status, validated before the key is looked up the way the other three
* {@code statusType} operations validate theirs: a status outside the enum is answered for the
* status whether or not the key exists.
*/
public void updateAccessKey(String userName, String accessKeyId, String status) {
requireStatusFromEnum(status);
synchronized (accessKeyLock) {
AccessKey key = userAccessKey(userName, accessKeyId);
key.setStatus(status);
accessKeys.put(accessKeyId, key);
}
}
/** The user's key with this id, or the NoSuchEntity each of these operations answers. */
private AccessKey userAccessKey(String userName, String accessKeyId) {
AccessKey key = accessKeys.get(accessKeyId)
.orElseThrow(() -> new AwsException("NoSuchEntity",
"Access key " + accessKeyId + " not found.", 404));
@@ -2277,12 +2309,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
throw new AwsException("NoSuchEntity",
"Access key " + accessKeyId + " does not belong to user " + userName + ".", 404);
}
if (!"Active".equals(status) && !"Inactive".equals(status)) {
throw new AwsException("ValidationError",
"Status must be Active or Inactive.", 400);
}
key.setStatus(status);
accessKeys.put(accessKeyId, key);
return key;
}
// =========================================================================
@@ -3284,12 +3311,12 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return getServerCertificate(name).getTags();
}
// Credential status, shared by the three operations that take statusType
// Credential status, shared by the four operations that take statusType
// =========================================================================
/**
* {@code statusType}, shared by UpdateSigningCertificate, UpdateSSHPublicKey and
* UpdateServiceSpecificCredential. One rendering serves all three because one front end
* {@code statusType}, shared by UpdateAccessKey, UpdateSigningCertificate, UpdateSSHPublicKey
* and UpdateServiceSpecificCredential. One rendering serves all four because one front end
* validates one shape: the recording is of UpdateServiceSpecificCredential, and AWS names
* neither the offending value nor the permitted set, unlike this message elsewhere in the
* tree. Matched rather than made uniform.