feat(iam): model signing certificates (#5024)

UploadSigningCertificate, ListSigningCertificates, UpdateSigningCertificate
and DeleteSigningCertificate, stored per user with the documented quota of
two and account-wide duplicate detection compared on the encoded form.

The body is parsed on upload, because MalformedCertificate cannot be
answered without reading it. Status accepts Active, Inactive and Expired:
the API Reference gives all three as valid values even though the
parameter's prose explains only the first two. UserName is optional on
every operation and resolves from the access key that signed the request.

A certificate blocks DeleteUser until it is removed, which AWS lists as a
prerequisite, and follows the user across an UpdateUser rename rather than
being stranded on a name that no longer exists. The credential report's
cert_1 and cert_2 columns are backed by the store instead of always
reporting FALSE, reporting N/A for the rotation date unless the
certificate is Active, as the User Guide defines them.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-03 15:46:37 -05:00
1 parent f074dd3c40
commit 290f952cb1
13 files changed
+1344 -25

No files matched your search

@@ -231,6 +231,7 @@ class IamServicePersistenceTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), devices, new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"), false, null);
}
@@ -2305,6 +2305,7 @@ class IamServiceTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), credentialReports, new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"), false, null);
AwsException ex = assertThrows(AwsException.class, withExpiredReport::getCredentialReport);
@@ -2323,6 +2324,7 @@ class IamServiceTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), credentialReports, new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"), false, null);
IamService.CredentialReportGeneration generation = withExpiredReport.generateCredentialReport();
@@ -79,6 +79,7 @@ class ServerCertificateStateTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
certificates,
new InMemoryStorage<>(),
new RegionResolver("us-east-1", defaultAccount), false, null);
}
@@ -0,0 +1,367 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The signing-certificate lifecycle over the wire. Material is generated rather than hardcoded, so
* the upload path reads real X.509 and the rejection paths reject things that genuinely are not.
*
* <p>IAM state is shared across the suite, so every test makes its own user. The per-user quota is
* only two certificates, which is small enough to exercise here without starving anything else:
* each test owns its user, so it owns that user's whole budget.
*/
@QuarkusTest
class SigningCertificateIntegrationTest {
private static final String IAM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request";
private static final CertificateGenerator GENERATOR = new CertificateGenerator();
private static RequestSpecification iam(String action) {
return given().header("Authorization", IAM_AUTH).formParam("Action", action);
}
private static String suffix() {
return Long.toString(System.nanoTime(), 36);
}
/** EC rather than RSA: these tests generate a lot of material and never check the algorithm. */
private static String certificatePem() {
return GENERATOR.generateSelfSignedCertificate(
"signing.test.local", List.of(), KeyAlgorithm.EC_prime256v1).certificatePem();
}
private static String user() {
String name = "signing-user-" + suffix();
iam("CreateUser").formParam("UserName", name)
.when().post("/").then().statusCode(200);
return name;
}
private static String upload(String userName, String body) {
return iam("UploadSigningCertificate")
.formParam("UserName", userName)
.formParam("CertificateBody", body)
.when().post("/").then().statusCode(200)
.extract().path("UploadSigningCertificateResponse.UploadSigningCertificateResult"
+ ".Certificate.CertificateId");
}
@Test
void uploadReturnsTheCertificateWithAnActiveStatusAndAModelShapedId() {
String userName = user();
String body = certificatePem();
String id = iam("UploadSigningCertificate")
.formParam("UserName", userName)
.formParam("CertificateBody", body)
.when().post("/").then().statusCode(200)
.body("UploadSigningCertificateResponse.UploadSigningCertificateResult.Certificate"
+ ".UserName", equalTo(userName))
.body("UploadSigningCertificateResponse.UploadSigningCertificateResult.Certificate"
+ ".Status", equalTo("Active"))
.body("UploadSigningCertificateResponse.UploadSigningCertificateResult.Certificate"
+ ".CertificateBody", containsString("BEGIN CERTIFICATE"))
.extract().path("UploadSigningCertificateResponse.UploadSigningCertificateResult"
+ ".Certificate.CertificateId");
assertNotNull(id);
// certificateIdType: 24 to 128 characters of [\w]+.
assertTrue(id.length() >= 24 && id.length() <= 128, "id length: " + id.length());
assertTrue(id.matches("\\w+"), "id must be word characters only: " + id);
}
@Test
void theUploadDateIsReturned() {
String userName = user();
upload(userName, certificatePem());
iam("ListSigningCertificates").formParam("UserName", userName)
.when().post("/").then().statusCode(200)
.body("ListSigningCertificatesResponse.ListSigningCertificatesResult.Certificates"
+ ".member.UploadDate", containsString("T"));
}
@Test
void listReturnsTheUsersCertificatesAndNoOneElses() {
String mine = user();
String theirs = user();
String myId = upload(mine, certificatePem());
String theirId = upload(theirs, certificatePem());
iam("ListSigningCertificates").formParam("UserName", mine)
.when().post("/").then().statusCode(200)
.body(containsString(myId))
.body(not(containsString(theirId)));
}
@Test
void theStatusCanBeSetToEveryDocumentedValue() {
String userName = user();
String id = upload(userName, certificatePem());
// The API Reference gives Active, Inactive and Expired as the valid values, even though
// the prose only explains the first two.
for (String status : List.of("Inactive", "Expired", "Active")) {
iam("UpdateSigningCertificate")
.formParam("UserName", userName)
.formParam("CertificateId", id)
.formParam("Status", status)
.when().post("/").then().statusCode(200);
iam("ListSigningCertificates").formParam("UserName", userName)
.when().post("/").then().statusCode(200)
.body("ListSigningCertificatesResponse.ListSigningCertificatesResult.Certificates"
+ ".member.Status", equalTo(status));
}
}
@Test
void anUnknownStatusIsRejected() {
String userName = user();
String id = upload(userName, certificatePem());
iam("UpdateSigningCertificate")
.formParam("UserName", userName)
.formParam("CertificateId", id)
.formParam("Status", "Revoked")
.when().post("/").then().statusCode(400)
.body(containsString("ValidationError"));
}
@Test
void deleteRemovesIt() {
String userName = user();
String id = upload(userName, certificatePem());
iam("DeleteSigningCertificate")
.formParam("UserName", userName)
.formParam("CertificateId", id)
.when().post("/").then().statusCode(200);
iam("ListSigningCertificates").formParam("UserName", userName)
.when().post("/").then().statusCode(200)
.body(not(containsString(id)));
}
@Test
void malformedMaterialIsRejectedAsMalformedCertificate() {
String userName = user();
iam("UploadSigningCertificate")
.formParam("UserName", userName)
.formParam("CertificateBody", "-----BEGIN CERTIFICATE-----\nnot base64\n"
+ "-----END CERTIFICATE-----\n")
.when().post("/").then().statusCode(400)
.body(containsString("MalformedCertificate"));
}
@Test
void anAbsentBodyIsRejected() {
String userName = user();
iam("UploadSigningCertificate").formParam("UserName", userName)
.when().post("/").then().statusCode(400)
.body(containsString("ValidationError"));
}
/** certificateBodyType caps the body at 16384, which is a request-shape error, not bad PEM. */
@Test
void anOverLongBodyIsRejectedBeforeItIsParsed() {
String userName = user();
iam("UploadSigningCertificate")
.formParam("UserName", userName)
.formParam("CertificateBody", "A".repeat(16385))
.when().post("/").then().statusCode(400)
.body(containsString("ValidationError"));
}
/** "Users can have up to two X.509 signing certificates", per the User Guide. */
@Test
void aThirdCertificateExceedsThePerUserQuota() {
String userName = user();
upload(userName, certificatePem());
upload(userName, certificatePem());
iam("UploadSigningCertificate")
.formParam("UserName", userName)
.formParam("CertificateBody", certificatePem())
.when().post("/").then().statusCode(409)
.body(containsString("LimitExceeded"))
.body(containsString("SigningCertificatesPerUser"));
}
/**
* DuplicateCertificate is account-wide: "the same certificate is associated with an IAM user in
* the account", so a second user uploading the same material is refused too.
*/
@Test
void theSameCertificateCannotBeUploadedTwiceInTheAccount() {
String first = user();
String second = user();
String body = certificatePem();
upload(first, body);
iam("UploadSigningCertificate")
.formParam("UserName", second)
.formParam("CertificateBody", body)
.when().post("/").then().statusCode(409)
.body(containsString("DuplicateCertificate"));
}
/**
* The duplicate check compares the encoded certificate rather than the PEM text, so the same
* certificate re-wrapped is still the same certificate.
*/
@Test
void aReindentedCopyOfTheSameCertificateIsStillADuplicate() {
String userName = user();
String body = certificatePem();
upload(userName, body);
// Same DER, different surrounding whitespace.
String reindented = body.replace("\n", "\r\n") + "\n";
iam("UploadSigningCertificate")
.formParam("UserName", userName)
.formParam("CertificateBody", reindented)
.when().post("/").then().statusCode(409)
.body(containsString("DuplicateCertificate"));
}
@Test
void aCertificateOfAnotherUserCannotBeUpdatedOrDeleted() {
String owner = user();
String other = user();
String id = upload(owner, certificatePem());
iam("UpdateSigningCertificate")
.formParam("UserName", other)
.formParam("CertificateId", id)
.formParam("Status", "Inactive")
.when().post("/").then().statusCode(404)
.body(containsString("NoSuchEntity"));
iam("DeleteSigningCertificate")
.formParam("UserName", other)
.formParam("CertificateId", id)
.when().post("/").then().statusCode(404)
.body(containsString("NoSuchEntity"));
}
@Test
void anUnknownUserIsNoSuchEntity() {
iam("ListSigningCertificates").formParam("UserName", "absent-" + suffix())
.when().post("/").then().statusCode(404)
.body(containsString("NoSuchEntity"));
}
/**
* CertificateId is required on both operations. Omitted, it must be a validation error: the
* store is a map that rejects a null key, so passing it through would surface as an unhandled
* failure rather than as the error the model defines.
*/
@Test
void anAbsentCertificateIdIsAValidationError() {
String userName = user();
iam("DeleteSigningCertificate").formParam("UserName", userName)
.when().post("/").then().statusCode(400)
.body(containsString("ValidationError"))
.body(containsString("certificateId"));
// Update validates the status first, so this only reaches the lookup with a valid one.
iam("UpdateSigningCertificate")
.formParam("UserName", userName)
.formParam("Status", "Inactive")
.when().post("/").then().statusCode(400)
.body(containsString("ValidationError"))
.body(containsString("certificateId"));
}
@Test
void anUnknownCertificateIdIsNoSuchEntity() {
String userName = user();
iam("DeleteSigningCertificate")
.formParam("UserName", userName)
.formParam("CertificateId", "ABSENTCERTIFICATEID0000000000")
.when().post("/").then().statusCode(404)
.body(containsString("NoSuchEntity"));
}
/**
* UserName is optional on every one of these operations: the model determines it from the
* access key that signed the request. Signing as the user's own key must reach the user's own
* certificates without naming them.
*/
@Test
void theUserNameIsImpliedFromTheSigningAccessKey() {
String userName = user();
String id = upload(userName, certificatePem());
String akid = iam("CreateAccessKey").formParam("UserName", userName)
.when().post("/").then().statusCode(200)
.extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
given().header("Authorization", "AWS4-HMAC-SHA256 Credential=" + akid
+ "/20260227/us-east-1/iam/aws4_request")
.formParam("Action", "ListSigningCertificates")
.when().post("/").then().statusCode(200)
.body(containsString(id))
.body("ListSigningCertificatesResponse.ListSigningCertificatesResult.Certificates"
+ ".member.UserName", equalTo(userName));
}
@Test
void listHonoursMaxItemsAndMarker() {
String userName = user();
upload(userName, certificatePem());
upload(userName, certificatePem());
String marker = iam("ListSigningCertificates")
.formParam("UserName", userName)
.formParam("MaxItems", "1")
.when().post("/").then().statusCode(200)
.body("ListSigningCertificatesResponse.ListSigningCertificatesResult.IsTruncated",
equalTo("true"))
.extract().path("ListSigningCertificatesResponse.ListSigningCertificatesResult.Marker");
assertNotNull(marker, "a truncated page must carry a marker");
iam("ListSigningCertificates")
.formParam("UserName", userName)
.formParam("Marker", marker)
.when().post("/").then().statusCode(200)
.body("ListSigningCertificatesResponse.ListSigningCertificatesResult.IsTruncated",
equalTo("false"));
}
/**
* 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 and come back
* UnsupportedOperation. The IAM namespace on the error is what proves the routing.
*/
@Test
void certificateActionsRouteViaTheActionFallbackWhenAuthHeaderAbsent() {
for (String action : List.of("UploadSigningCertificate", "ListSigningCertificates",
"UpdateSigningCertificate", "DeleteSigningCertificate")) {
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", action)
.formParam("Version", "2010-05-08")
.when().post("/").then()
.body(containsString("iam.amazonaws.com/doc/2010-05-08"));
}
}
}
@@ -0,0 +1,417 @@
package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.core.type.TypeReference;
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.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import io.github.hectorvent.floci.services.iam.model.CredentialReport;
import io.github.hectorvent.floci.services.iam.model.IamUser;
import io.github.hectorvent.floci.services.iam.model.SigningCertificate;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
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.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* The properties of the signing-certificate store the wire tests cannot reach: that it survives a
* restart, that one account cannot see another's, that the quota holds when uploads race, and that
* the credentials a user owns follow the user through a rename and block a delete.
*/
class SigningCertificateStateTest {
private static final String ACCOUNT_A = "000000000000";
private static final String ACCOUNT_B = "111111111111";
private static final CertificateGenerator GENERATOR = new CertificateGenerator();
/** EC: these tests exercise locking and storage, never the key algorithm. */
private static String certificatePem() {
return GENERATOR.generateSelfSignedCertificate(
"state.test.local", List.of(), KeyAlgorithm.EC_prime256v1).certificatePem();
}
@SuppressWarnings("unchecked")
private static Instance<RequestContext> requestContextFor(AtomicReference<String> accountId) {
RequestContext rc = mock(RequestContext.class);
when(rc.getAccountId()).thenAnswer(invocation -> accountId.get());
Instance<RequestContext> inst = mock(Instance.class);
when(inst.get()).thenReturn(rc);
return inst;
}
private static IamService newService(StorageBackend<String, SigningCertificate> certificates,
String defaultAccount) {
return new IamService(
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(),
certificates,
new RegionResolver("us-east-1", defaultAccount), false, null);
}
private static IamService newService(StorageBackend<String, IamUser> users,
StorageBackend<String, CredentialReport> reports,
StorageBackend<String, SigningCertificate> certificates,
String defaultAccount) {
return new IamService(
users, new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), reports, new InMemoryStorage<>(),
new InMemoryStorage<>(),
certificates,
new RegionResolver("us-east-1", defaultAccount), false, null);
}
@Test
void aCertificateSurvivesARestart(@TempDir Path dir) {
Path file = dir.resolve("signing-certificates.json");
String body = certificatePem();
PersistentStorage<String, SigningCertificate> first =
new PersistentStorage<>(file, new TypeReference<>() {});
first.load();
IamService before = newService(first, ACCOUNT_A);
before.createUser("restart-user", "/");
String id = before.uploadSigningCertificate("restart-user", body).getCertificateId();
before.updateSigningCertificate("restart-user", id, "Inactive");
PersistentStorage<String, SigningCertificate> second =
new PersistentStorage<>(file, new TypeReference<>() {});
second.load();
IamService after = newService(second, ACCOUNT_A);
after.createUser("restart-user", "/");
List<SigningCertificate> reloaded = after.listSigningCertificates("restart-user");
assertEquals(1, reloaded.size());
assertEquals(id, reloaded.getFirst().getCertificateId());
assertEquals(body, reloaded.getFirst().getCertificateBody());
// The status is the part most likely to be dropped on the way through, because a default
// of Active would hide the loss.
assertEquals("Inactive", reloaded.getFirst().getStatus());
}
@Test
void oneAccountCannotSeeAnothersCertificates() {
AtomicReference<String> account = new AtomicReference<>(ACCOUNT_A);
AccountAwareStorageBackend<SigningCertificate> store = new AccountAwareStorageBackend<>(
new InMemoryStorage<>(), requestContextFor(account), ACCOUNT_A);
IamService service = newService(store, ACCOUNT_A);
service.createUser("shared-name", "/");
service.uploadSigningCertificate("shared-name", certificatePem());
assertEquals(1, service.listSigningCertificates("shared-name").size());
// The users store here is not account-aware, so the user is already present under the
// same name. That is what makes this discriminating: only the certificate store is
// scoped, so a leak would show up as account B seeing A's certificate.
account.set(ACCOUNT_B);
assertEquals(0, service.listSigningCertificates("shared-name").size(),
"account B must not see account A's certificate");
// And B filling its own quota must not be refused because A already has certificates.
service.uploadSigningCertificate("shared-name", certificatePem());
service.uploadSigningCertificate("shared-name", certificatePem());
assertEquals(2, service.listSigningCertificates("shared-name").size());
account.set(ACCOUNT_A);
assertEquals(1, service.listSigningCertificates("shared-name").size(),
"account A's view must be unchanged by account B's uploads");
}
/**
* The quota is counted inside the same lock as the write, so concurrent uploads cannot both
* see room for the second-to-last slot. Asserted by counting what actually succeeded, because
* an invariant phrased as "the store holds at most two" passes even with the lock removed.
*/
@Test
void concurrentUploadsCannotExceedTheQuota() throws Exception {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
service.createUser("race-user", "/");
int attempts = 12;
List<String> bodies = new ArrayList<>();
for (int i = 0; i < attempts; i++) {
bodies.add(certificatePem());
}
ExecutorService pool = Executors.newFixedThreadPool(attempts);
CountDownLatch start = new CountDownLatch(1);
AtomicInteger accepted = new AtomicInteger();
try {
for (int i = 0; i < attempts; i++) {
String body = bodies.get(i);
pool.submit(() -> {
start.await();
try {
service.uploadSigningCertificate("race-user", body);
accepted.incrementAndGet();
} catch (AwsException expected) {
// LimitExceeded for the losers, which is the point of the race.
}
return null;
});
}
start.countDown();
pool.shutdown();
assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS), "uploads did not finish");
} finally {
pool.shutdownNow();
}
assertEquals(2, accepted.get(), "exactly the quota should have been accepted");
assertEquals(2, service.listSigningCertificates("race-user").size());
}
/**
* The quota race above uses a different certificate per thread, so it never exercises the
* duplicate check. Uploading the same body from several threads has to leave exactly one
* stored.
*
* <p>This one does not discriminate the lock: with the upload's lock made per-call it still
* passes, because the first write lands long before the other threads finish parsing the
* stored material to compare it. The lock is covered by the quota race, which does fail
* without it. Kept because it pins the outcome rather than the mechanism.
*/
@Test
void concurrentUploadsOfTheSameCertificateLeaveExactlyOne() throws Exception {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
service.createUser("dup-race", "/");
String body = certificatePem();
int threads = 8;
ExecutorService pool = Executors.newFixedThreadPool(threads);
CountDownLatch start = new CountDownLatch(1);
AtomicInteger accepted = new AtomicInteger();
try {
for (int i = 0; i < threads; i++) {
pool.submit(() -> {
start.await();
try {
service.uploadSigningCertificate("dup-race", body);
accepted.incrementAndGet();
} catch (AwsException expected) {
// DuplicateCertificate for the losers.
}
return null;
});
}
start.countDown();
pool.shutdown();
assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS), "uploads did not finish");
} finally {
pool.shutdownNow();
}
assertEquals(1, accepted.get(), "only one upload of the same certificate may succeed");
assertEquals(1, service.listSigningCertificates("dup-race").size());
}
/**
* An upload must never land on a user DeleteUser has just removed. Both hold the signing lock,
* so only two orders exist: the delete is refused because a certificate is there, or the upload
* fails because the user is gone. A certificate owned by a user that does not exist is the
* state neither order may produce, and nothing in the API would ever report it: the owner
* cannot list it, because listing goes through the user.
*
* <p>Asserted against the store rather than through the service, for that reason.
*/
@Test
void anUploadNeverStrandsACertificateOnADeletedUser() throws Exception {
for (int trial = 0; trial < 300; trial++) {
InMemoryStorage<String, SigningCertificate> store = new InMemoryStorage<>();
IamService service = newService(store, ACCOUNT_A);
service.createUser("delete-race", "/");
String body = certificatePem();
ExecutorService pool = Executors.newFixedThreadPool(2);
CountDownLatch start = new CountDownLatch(1);
try {
pool.submit(() -> {
start.await();
try {
service.uploadSigningCertificate("delete-race", body);
} catch (AwsException expected) {
// NoSuchEntity when the delete won.
}
return null;
});
pool.submit(() -> {
start.await();
try {
service.deleteUser("delete-race");
} catch (AwsException expected) {
// DeleteConflict when the upload won.
}
return null;
});
start.countDown();
pool.shutdown();
assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS), "trial did not finish");
} finally {
pool.shutdownNow();
}
boolean userExists;
try {
service.getUser("delete-race");
userExists = true;
} catch (AwsException gone) {
userExists = false;
}
List<SigningCertificate> stored = store.scan(key -> true);
if (!userExists) {
assertTrue(stored.isEmpty(),
"trial " + trial + ": certificate left behind on a deleted user");
}
}
}
/**
* The same hazard on the rename path: a certificate uploaded while a rename is in flight must
* end up under whichever name the user actually has, never stranded on the old one.
*/
@Test
void anUploadNeverStrandsACertificateOnTheOldNameDuringARename() throws Exception {
for (int trial = 0; trial < 300; trial++) {
InMemoryStorage<String, SigningCertificate> store = new InMemoryStorage<>();
IamService service = newService(store, ACCOUNT_A);
service.createUser("rename-race-from", "/");
String body = certificatePem();
ExecutorService pool = Executors.newFixedThreadPool(2);
CountDownLatch start = new CountDownLatch(1);
try {
pool.submit(() -> {
start.await();
try {
service.uploadSigningCertificate("rename-race-from", body);
} catch (AwsException expected) {
// NoSuchEntity when the rename landed first.
}
return null;
});
pool.submit(() -> {
start.await();
service.updateUser("rename-race-from", "rename-race-to", null);
return null;
});
start.countDown();
pool.shutdown();
assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS), "trial did not finish");
} finally {
pool.shutdownNow();
}
for (SigningCertificate certificate : store.scan(key -> true)) {
assertEquals("rename-race-to", certificate.getUserName(),
"trial " + trial + ": certificate stranded on the pre-rename name");
}
}
}
/** AWS lists the signing certificate among the things that must be removed before DeleteUser. */
@Test
void aUserWithACertificateCannotBeDeleted() {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
service.createUser("blocked-user", "/");
String id = service.uploadSigningCertificate("blocked-user", certificatePem())
.getCertificateId();
AwsException refused = assertThrows(AwsException.class,
() -> service.deleteUser("blocked-user"));
assertEquals("DeleteConflict", refused.getErrorCode());
assertTrue(refused.getMessage().contains("signing certificate"),
"the message should name what is in the way: " + refused.getMessage());
service.deleteSigningCertificate("blocked-user", id);
service.deleteUser("blocked-user");
}
/**
* A rename must carry the certificates with it. Left behind, a certificate is stranded on a
* user name that no longer exists: invisible to its owner and undeletable.
*/
@Test
void aRenameCarriesTheCertificates() {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
service.createUser("before-rename", "/");
String id = service.uploadSigningCertificate("before-rename", certificatePem())
.getCertificateId();
service.updateUser("before-rename", "after-rename", null);
List<SigningCertificate> moved = service.listSigningCertificates("after-rename");
assertEquals(1, moved.size(), "the certificate should have followed the rename");
assertEquals(id, moved.getFirst().getCertificateId());
assertEquals("after-rename", moved.getFirst().getUserName());
// And the rename must not leave the user undeletable for a certificate it cannot see.
service.deleteSigningCertificate("after-rename", id);
service.deleteUser("after-rename");
}
/**
* The credential report's cert columns, which the User Guide defines precisely: TRUE only for
* an Active certificate, and N/A for the rotation date when the user has no active one.
*/
@Test
void theCredentialReportReflectsCertificateStatus() {
StorageBackend<String, IamUser> users = new InMemoryStorage<>();
StorageBackend<String, SigningCertificate> certificates = new InMemoryStorage<>();
IamService service = newService(users, new InMemoryStorage<>(), certificates, ACCOUNT_A);
service.createUser("report-user", "/");
String id = service.uploadSigningCertificate("report-user", certificatePem())
.getCertificateId();
String active = reportRowFor(service, "report-user");
assertTrue(active.contains("TRUE"), "an active certificate should report TRUE: " + active);
service.updateSigningCertificate("report-user", id, "Inactive");
// GenerateCredentialReport reuses a report generated in the past four hours, so the
// second row has to come from a service that has not generated one yet.
IamService regenerated = newService(users, new InMemoryStorage<>(), certificates, ACCOUNT_A);
String inactive = reportRowFor(regenerated, "report-user");
String[] columns = inactive.split(",", -1);
// cert_1_active is FALSE, and cert_1_last_rotated is N/A rather than the upload date:
// "If the user does not have an active signing certificate, the value in this field is N/A".
int certActive = columns.length - 5;
assertEquals("FALSE", columns[certActive], "cert_1_active for an Inactive certificate");
assertEquals("N/A", columns[certActive + 1],
"cert_1_last_rotated must be N/A when no active certificate exists");
}
private static String reportRowFor(IamService service, String userName) {
service.generateCredentialReport();
String csv = new String(Base64.getDecoder()
.decode(service.getCredentialReport().base64Content()), StandardCharsets.UTF_8);
return csv.lines()
.filter(line -> line.startsWith(userName + ","))
.findFirst()
.orElseThrow(() -> new AssertionError("no report row for " + userName));
}
}
@@ -51,6 +51,7 @@ class VirtualMfaAccountScopeTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), devices,
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", ACCOUNT_A), false, null);
VirtualMfaDevice device = service.createVirtualMfaDevice("shared-name", "/", Map.of());
@@ -89,6 +90,7 @@ class VirtualMfaAccountScopeTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), devices,
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", ACCOUNT_A), false, null);
VirtualMfaDevice inA = service.createVirtualMfaDevice("same-name", "/", Map.of());
@@ -38,6 +38,7 @@ class VirtualMfaConcurrencyTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("eu-central-1", "000000000000"), false, null);
}