Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(iam): answer AWS's own errors for a malformed service-credential id, and for DeleteUser (#5239)

Priamo Germosen3a8f974554b5
diff --git a/docs/services/iam.md b/docs/services/iam.md
index 4f017efbdd..f970206d0e 100644
--- a/docs/services/iam.md
+++ b/docs/services/iam.md
@@ -744,6 +744,19 @@ code `NotSupportedService`, on both `CreateServiceSpecificCredential` and
a real service that simply does not support these credentials. A client written against the model,
catching the modelled exception, would catch nothing.
+A bad `ServiceSpecificCredentialId` splits two ways on `UpdateServiceSpecificCredential`,
+`ResetServiceSpecificCredential` and `DeleteServiceSpecificCredential`. The id is matched against
+the model's `[\w]+` before anything goes looking for it, so one carrying characters outside that
+class is a `ValidationError` with status 400 quoting the pattern, while an id that satisfies the
+pattern and names no credential of that user is `NoSuchEntity` with status 404 and the message
+"No such credential `<id>` exists". The published length of 20 to 128 is enforced the same way, and
+an id breaking both constraints is reported as two validation errors rather than one.
+
+A user that still owns a credential cannot be deleted: `DeleteUser` is `DeleteConflict` with status
+409. Where access keys, policies and group memberships each get a message naming what is in the
+way, this case does not, and AWS answers the generic "Cannot delete entity, must remove referenced
+objects first." Deleting the credential first lets the user go.
+
**A credential has one of two shapes, decided by the service:**
| Service | Shape |
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 a39d91e555..2b0d29f10c 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
@@ -173,6 +173,13 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
private static final int ROLE_NAME_MAX_LENGTH = 64;
/** groupNameType / instanceProfileNameType: 1-128 characters of {@code [\w+=,.@-]}. */
private static final Pattern IAM_RESOURCE_NAME_PATTERN = Pattern.compile("[\\w+=,.@-]{1,128}");
+ /**
+ * serviceSpecificCredentialId, kept as the model spells it because the pattern is quoted
+ * back in the error message. AWS checks the format before it looks for the credential.
+ */
+ private static final Pattern SERVICE_CREDENTIAL_ID_PATTERN = Pattern.compile("[\\w]+");
+ private static final int SERVICE_CREDENTIAL_ID_MIN_LENGTH = 20;
+ private static final int SERVICE_CREDENTIAL_ID_MAX_LENGTH = 128;
/** pathType: a bare slash, or a slash-delimited run of {@code !}-{@code ~}. */
private static final Pattern IAM_PATH_PATTERN = Pattern.compile("(/)|(/[\\x21-\\x7E]+/)");
private static final int IAM_PATH_MAX_LENGTH = 512;
@@ -727,11 +734,12 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
// 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)".
+ // 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 service-specific credentials "
- + "first.", 409);
+ "Cannot delete entity, must remove referenced objects first.", 409);
}
synchronized (sshPublicKeyLock) {
if (!userSshPublicKeys(userName).isEmpty()) {
@@ -2727,6 +2735,24 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return getServerCertificate(name).getTags();
}
+ // Credential status, shared by the three operations that take statusType
+ // =========================================================================
+
+ /**
+ * {@code statusType}, shared by UpdateSigningCertificate, UpdateSSHPublicKey and
+ * UpdateServiceSpecificCredential. One rendering serves all three 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.
+ */
+ private void requireStatusFromEnum(String status) {
+ if (status == null || !CREDENTIAL_STATUSES.contains(status)) {
+ throw new AwsException("ValidationError",
+ "1 validation error detected: Value at 'status' failed to satisfy "
+ + "constraint: Member must satisfy enum value set", 400);
+ }
+ }
+
// Signing certificates
// =========================================================================
@@ -2782,12 +2808,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
public void updateSigningCertificate(String userName, String certificateId, String status) {
- if (status == null || !CREDENTIAL_STATUSES.contains(status)) {
- throw new AwsException("ValidationError",
- "Value '" + status + "' at 'status' failed to satisfy constraint: Member must "
- + "satisfy enum value set: [" + String.join(", ",
- CREDENTIAL_STATUSES) + "]", 400);
- }
+ requireStatusFromEnum(status);
synchronized (signingCertificateLock) {
SigningCertificate certificate = userSigningCertificate(userName, certificateId);
certificate.setStatus(status);
@@ -2951,12 +2972,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
public void updateSshPublicKey(String userName, String keyId, String status) {
- if (status == null || !CREDENTIAL_STATUSES.contains(status)) {
- throw new AwsException("ValidationError",
- "Value '" + status + "' at 'status' failed to satisfy constraint: Member must "
- + "satisfy enum value set: [" + String.join(", ",
- CREDENTIAL_STATUSES) + "]", 400);
- }
+ requireStatusFromEnum(status);
synchronized (sshPublicKeyLock) {
SshPublicKey stored = userSshPublicKey(userName, keyId);
stored.setStatus(status);
@@ -3231,12 +3247,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
public void updateServiceSpecificCredential(String userName, String credentialId,
String status) {
- if (status == null || !CREDENTIAL_STATUSES.contains(status)) {
- throw new AwsException("ValidationError",
- "Value '" + status + "' at 'status' failed to satisfy constraint: Member must "
- + "satisfy enum value set: [" + String.join(", ",
- CREDENTIAL_STATUSES) + "]", 400);
- }
+ requireCredentialIdFormat(credentialId);
+ requireStatusFromEnum(status);
synchronized (serviceCredentialLock) {
ServiceSpecificCredential credential = userServiceCredential(userName, credentialId);
credential.setStatus(status);
@@ -3250,6 +3262,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
*/
public ServiceSpecificCredential resetServiceSpecificCredential(String userName,
String credentialId) {
+ requireCredentialIdFormat(credentialId);
synchronized (serviceCredentialLock) {
ServiceSpecificCredential credential = userServiceCredential(userName, credentialId);
if (LONG_TERM_API_KEY_SERVICES.contains(credential.getServiceName())) {
@@ -3263,23 +3276,66 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
public void deleteServiceSpecificCredential(String userName, String credentialId) {
+ requireCredentialIdFormat(credentialId);
synchronized (serviceCredentialLock) {
ServiceSpecificCredential credential = userServiceCredential(userName, credentialId);
serviceCredentials.delete(credential.getServiceSpecificCredentialId());
}
}
+ /**
+ * The id has to satisfy the model before anything looks for it: AWS answers a malformed one
+ * with a {@code ValidationError} naming the constraint it broke, and only a well-formed id
+ * that matches nothing gets {@code NoSuchEntity}. Different mistakes, different answers.
+ *
+ * <p>The API Reference publishes a length of 20 to 128 as well as the pattern, so both are
+ * checked, and both are reported when both are broken, in the order it prints them. The
+ * pattern message is the one recorded against AWS; the length wording is the form AWS uses for
+ * a member carrying both bounds, which {@link #validateLoginProfilePassword} spells the same
+ * way.
+ */
+ private void requireCredentialIdFormat(String credentialId) {
+ String id = credentialId == null ? "" : credentialId;
+ List<String> violations = new ArrayList<>();
+ if (id.length() < SERVICE_CREDENTIAL_ID_MIN_LENGTH
+ || id.length() > SERVICE_CREDENTIAL_ID_MAX_LENGTH) {
+ violations.add("Member must have length less than or equal to "
+ + SERVICE_CREDENTIAL_ID_MAX_LENGTH + " and greater than or equal to "
+ + SERVICE_CREDENTIAL_ID_MIN_LENGTH);
+ }
+ if (!SERVICE_CREDENTIAL_ID_PATTERN.matcher(id).matches()) {
+ violations.add("Member must satisfy regular expression pattern: [\\w]+");
+ }
+ if (violations.isEmpty()) {
+ return;
+ }
+ StringBuilder message = new StringBuilder()
+ .append(violations.size())
+ .append(violations.size() == 1 ? " validation error detected: "
+ : " validation errors detected: ");
+ for (int i = 0; i < violations.size(); i++) {
+ if (i > 0) {
+ message.append("; ");
+ }
+ message.append("Value at 'serviceSpecificCredentialId' failed to satisfy constraint: ")
+ .append(violations.get(i));
+ }
+ throw new AwsException("ValidationError", message.toString(), 400);
+ }
+
+ /** AWS's wording for an id that matches the pattern and no credential. */
+ private AwsException noSuchCredential(String credentialId) {
+ return new AwsException("NoSuchEntity",
+ "No such credential " + credentialId + " exists", 404);
+ }
+
/** A credential of that id belonging to that user, reported missing when it belongs elsewhere. */
private ServiceSpecificCredential userServiceCredential(String userName, String credentialId) {
getUser(userName); // validates existence
ServiceSpecificCredential credential = serviceCredentials.get(credentialId)
- .orElseThrow(() -> new AwsException("NoSuchEntity",
- "The Service Specific Credential with id " + credentialId
- + " cannot be found.", 404));
+ .orElseThrow(() -> noSuchCredential(credentialId));
if (!userName.equals(credential.getUserName())) {
- throw new AwsException("NoSuchEntity",
- "The Service Specific Credential with id " + credentialId
- + " cannot be found.", 404);
+ throw noSuchCredential(credentialId);
}
return credential;
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ServiceSpecificCredentialIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ServiceSpecificCredentialIntegrationTest.java
index 54f0133b8e..2e2cf452d1 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/ServiceSpecificCredentialIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/ServiceSpecificCredentialIntegrationTest.java
@@ -577,7 +577,13 @@ class ServiceSpecificCredentialIntegrationTest {
.formParam("ServiceSpecificCredentialId", id)
.formParam("Status", status)
.when().post("/").then().statusCode(400)
- .body(containsString("ValidationError"));
+ .body(containsString("ValidationError"))
+ .body(containsString("1 validation error detected"))
+ .body(containsString("Member must satisfy enum value set"))
+ // AWS names neither the offending value nor the permitted set. The trailing colon
+ // is the tell for the set, and "Deleted" for the value.
+ .body(not(containsString("enum value set:")))
+ .body(not(containsString("Deleted")));
}
iam("UpdateServiceSpecificCredential")
@@ -597,6 +603,116 @@ class ServiceSpecificCredentialIntegrationTest {
.body(containsString("serviceSpecificCredentialId"));
}
+ /**
+ * A malformed id and an unknown one are different mistakes, and AWS answers them differently.
+ * The id is checked against the model's {@code [\w]+} before anything looks for it, so one
+ * carrying hyphens is a {@code ValidationError} quoting the pattern, while an id that
+ * satisfies the pattern and names no credential is {@code NoSuchEntity}. Both are recorded
+ * against real AWS in LocalStack's validated IAM snapshots, for all three operations.
+ */
+ @Test
+ void aMalformedCredentialIdIsAValidationErrorRatherThanNotFound() {
+ String userName = user();
+ create(userName, CODECOMMIT);
+
+ for (String action : List.of("UpdateServiceSpecificCredential",
+ "ResetServiceSpecificCredential", "DeleteServiceSpecificCredential")) {
+ iam(action)
+ .formParam("UserName", userName)
+ .formParam("ServiceSpecificCredentialId",
+ "totally-wrong-credential-id-with-hyphens")
+ .formParam("Status", "Inactive")
+ .when().post("/").then().statusCode(400)
+ .body(containsString("ValidationError"))
+ .body(containsString("serviceSpecificCredentialId"))
+ .body(containsString("Member must satisfy regular expression pattern"))
+ .body(not(containsString("NoSuchEntity")));
+ }
+ }
+
+ /**
+ * The id's other published constraint is a length of 20 to 128. A short id satisfies
+ * {@code [\w]+} and still fails, and one that breaks both constraints is reported as two
+ * validation errors rather than one, which is what the counted prefix is for.
+ */
+ @Test
+ void anIdOutsideItsPublishedLengthIsAValidationError() {
+ String userName = user();
+ create(userName, CODECOMMIT);
+
+ for (String id : List.of("tooshort", "W".repeat(129))) {
+ iam("DeleteServiceSpecificCredential")
+ .formParam("UserName", userName)
+ .formParam("ServiceSpecificCredentialId", id)
+ .when().post("/").then().statusCode(400)
+ .body(containsString("1 validation error detected"))
+ .body(containsString("Member must have length less than or equal to 128 and "
+ + "greater than or equal to 20"))
+ .body(not(containsString("NoSuchEntity")));
+ }
+
+ // Short and outside the pattern at once: both constraints are reported.
+ iam("DeleteServiceSpecificCredential")
+ .formParam("UserName", userName)
+ .formParam("ServiceSpecificCredentialId", "has-hyphens")
+ .when().post("/").then().statusCode(400)
+ .body(containsString("2 validation errors detected"))
+ .body(containsString("Member must have length"))
+ .body(containsString("Member must satisfy regular expression pattern"));
+
+ // And an id of exactly the minimum length is accepted as well formed, so the bound is not
+ // off by one: it reaches the lookup and is reported missing rather than malformed.
+ iam("DeleteServiceSpecificCredential")
+ .formParam("UserName", userName)
+ .formParam("ServiceSpecificCredentialId", "A".repeat(20))
+ .when().post("/").then().statusCode(404)
+ .body(containsString("NoSuchEntity"));
+ }
+
+ @Test
+ void aWellFormedButUnknownCredentialIdIsReportedAsNoSuchCredential() {
+ String userName = user();
+ create(userName, CODECOMMIT);
+
+ for (String action : List.of("UpdateServiceSpecificCredential",
+ "ResetServiceSpecificCredential", "DeleteServiceSpecificCredential")) {
+ iam(action)
+ .formParam("UserName", userName)
+ .formParam("ServiceSpecificCredentialId", "satisfiesregexbutstillinvalid")
+ .formParam("Status", "Inactive")
+ .when().post("/").then().statusCode(404)
+ .body(containsString("NoSuchEntity"))
+ .body(containsString("No such credential satisfiesregexbutstillinvalid exists"))
+ .body(not(containsString("ValidationError")));
+ }
+ }
+
+ /**
+ * A live credential blocks {@code DeleteUser} with 409 {@code DeleteConflict}. This one has no
+ * message of its own: where access keys and policies each name themselves, AWS falls back to
+ * the generic referenced-objects wording here.
+ */
+ @Test
+ void aLiveCredentialBlocksDeletingItsUser() {
+ String userName = user();
+ String id = create(userName, CODECOMMIT);
+
+ iam("DeleteUser").formParam("UserName", userName)
+ .when().post("/").then().statusCode(409)
+ .body(containsString("DeleteConflict"))
+ .body(containsString("Cannot delete entity, must remove referenced objects first."));
+
+ // Remove the credential and the same delete succeeds, so the credential is what blocked it
+ // rather than anything else the user still owns.
+ iam("DeleteServiceSpecificCredential")
+ .formParam("UserName", userName)
+ .formParam("ServiceSpecificCredentialId", id)
+ .when().post("/").then().statusCode(200);
+
+ iam("DeleteUser").formParam("UserName", userName)
+ .when().post("/").then().statusCode(200);
+ }
+
/**
* Without an Authorization header the Query controller infers the service from the action name
* alone, so these have to be in its IAM set or they fall through to SQS.
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ServiceSpecificCredentialStateTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ServiceSpecificCredentialStateTest.java
index c00d3db98e..5acf80f0a5 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/ServiceSpecificCredentialStateTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/ServiceSpecificCredentialStateTest.java
@@ -292,7 +292,11 @@ class ServiceSpecificCredentialStateTest {
}
}
- /** AWS lists the service-specific credential among the items to remove before a user. */
+ /**
+ * AWS lists the service-specific credential among the items to remove before a user. Unlike the
+ * access-key and policy cases it gets no message of its own: the recorded answer is the generic
+ * referenced-objects wording, so the message deliberately does not name the credential.
+ */
@Test
void aUserWithACredentialCannotBeDeleted() {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
@@ -303,8 +307,8 @@ class ServiceSpecificCredentialStateTest {
AwsException refused = assertThrows(AwsException.class,
() -> service.deleteUser("blocked-user"));
assertEquals("DeleteConflict", refused.getErrorCode());
- assertTrue(refused.getMessage().contains("service-specific credential"),
- "the message should name what is in the way: " + refused.getMessage());
+ assertEquals("Cannot delete entity, must remove referenced objects first.",
+ refused.getMessage());
service.deleteServiceSpecificCredential("blocked-user", id);
service.deleteUser("blocked-user");
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/SigningCertificateIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/SigningCertificateIntegrationTest.java
index b82ed67432..12af088b06 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/SigningCertificateIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/SigningCertificateIntegrationTest.java
@@ -139,7 +139,13 @@ class SigningCertificateIntegrationTest {
.formParam("CertificateId", id)
.formParam("Status", "Revoked")
.when().post("/").then().statusCode(400)
- .body(containsString("ValidationError"));
+ .body(containsString("ValidationError"))
+ // statusType is one shape across the three operations that take it, and AWS renders it
+ // without the offending value or the permitted set.
+ .body(containsString("1 validation error detected"))
+ .body(containsString("Member must satisfy enum value set"))
+ .body(not(containsString("enum value set:")))
+ .body(not(containsString("Revoked")));
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/SshPublicKeyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/SshPublicKeyIntegrationTest.java
index 808ea4eadf..c22dfb8c72 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/SshPublicKeyIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/SshPublicKeyIntegrationTest.java
@@ -217,6 +217,30 @@ class SshPublicKeyIntegrationTest {
}
}
+ /**
+ * And nothing outside the enum. {@code statusType} is one shape across the three operations
+ * that take it, so this is the same answer AWS gives on UpdateServiceSpecificCredential, where
+ * it was recorded: the offending value and the permitted set are both absent.
+ */
+ @Test
+ void theStatusTakesNothingOutsideTheEnum() {
+ String userName = user();
+ String id = upload(userName, SshPublicKeys.toOpenSsh(generated()));
+
+ for (String status : List.of("inactive", "Revoked", "")) {
+ iam("UpdateSSHPublicKey")
+ .formParam("UserName", userName)
+ .formParam("SSHPublicKeyId", id)
+ .formParam("Status", status)
+ .when().post("/").then().statusCode(400)
+ .body(containsString("ValidationError"))
+ .body(containsString("1 validation error detected"))
+ .body(containsString("Member must satisfy enum value set"))
+ .body(not(containsString("enum value set:")))
+ .body(not(containsString("Revoked")));
+ }
+ }
+
@Test
void deleteRemovesIt() {
String userName = user();