feat(iam): model server certificates (#4975)

Replace the ListServerCertificates stub with the server-certificate
lifecycle: UploadServerCertificate, GetServerCertificate,
UpdateServerCertificate, DeleteServerCertificate, ListServerCertificates
and the tag operations.

The uploaded material is really parsed, because two of the upload's
modeled errors cannot be answered otherwise. CertificateBody, and every
certificate in CertificateChain rather than only its first block, must be
readable PEM or the upload is MalformedCertificate; the private key must
match the certificate's public key or it is KeyPairMismatch. The match is
a sign-then-verify check, so it holds for RSA and EC alike. All of it goes
through core.common.Pem rather than a second copy of the parsing.

Expiration is read from the certificate's own notAfter rather than stored
separately, so it cannot drift from what it describes. ServerCertificateId
uses AWS's ASCA prefix. The private key is stored and never returned: AWS
marks privateKeyType sensitive and models it only on the upload, so
neither reader echoes it back, and ListServerCertificates returns metadata
only as AWS documents.

Request shapes are enforced from the wire model: the 16384-character caps
on the body and key, the much larger 2097152 cap on the chain, and the
per-account quota of 20 that the User Guide's table publishes, counted
under the same lock as the write. A rename that only changes case is
allowed, excluding the certificate from its own duplicate check by id the
way updateUser does.

GetAccountSummary's ServerCertificates count is now backed by the store
instead of a hardcoded zero.

ResourceArnBuilder gains an iam case naming the certificate an operation
targets, so a policy statement scoped to one certificate constrains it
under enforcement. Every other IAM action still resolves to *, which is
long-standing behaviour rather than something this adds; documented in
docs/services/iam.md and tracked in #4979.

DeleteServerCertificate does not raise the in-use DeleteConflict AWS
returns when a load balancer still references the certificate. Floci
cannot determine that yet, because ELB Classic and CloudFront store
certificate identifiers without resolving them against IAM. Documented,
and tracked in #4875.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-02 23:51:47 -05:00
1 parent 543f01618f
commit d0c7c23f6b
16 files changed
+2090 -22

No files matched your search

@@ -230,7 +230,7 @@ class IamServicePersistenceTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), devices,
new InMemoryStorage<>(), devices, new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"), false, null);
}
@@ -2304,6 +2304,7 @@ class IamServiceTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), credentialReports, new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"), false, null);
AwsException ex = assertThrows(AwsException.class, withExpiredReport::getCredentialReport);
@@ -2321,6 +2322,7 @@ class IamServiceTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), credentialReports, new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"), false, null);
IamService.CredentialReportGeneration generation = withExpiredReport.generateCredentialReport();
@@ -1,7 +1,10 @@
package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.iam.model.ServerCertificate;
import jakarta.enterprise.inject.Instance;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.UriInfo;
@@ -15,6 +18,7 @@ import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -50,6 +54,177 @@ class ResourceArnBuilderTest {
}).when(ctx).setProperty(any(), any());
}
/** Query-protocol services carry their parameters in a form body, as IAM does. */
private void setFormBody(String form) {
contextProperties.clear();
byte[] bytes = form.getBytes(StandardCharsets.UTF_8);
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
when(ctx.getMediaType()).thenReturn(MediaType.APPLICATION_FORM_URLENCODED_TYPE);
when(ctx.getEntityStream()).thenReturn(in);
doAnswer(inv -> {
InputStream newIn = inv.getArgument(0);
when(ctx.getEntityStream()).thenReturn(newIn);
return null;
}).when(ctx).setEntityStream(any(InputStream.class));
}
// ── IAM ──────────────────────────────────────────────────────────────────────
/**
* A builder whose store holds one certificate under {@code name} with {@code arn}, which is
* what the check reads for every operation acting on a certificate that already exists.
*/
private ResourceArnBuilder backedBy(String name, String arn) {
ServerCertificate stored = new ServerCertificate();
stored.setServerCertificateName(name);
stored.setArn(arn);
IamService service = mock(IamService.class);
when(service.findServerCertificate(name)).thenReturn(Optional.of(stored));
@SuppressWarnings("unchecked")
Instance<IamService> instance = mock(Instance.class);
when(instance.get()).thenReturn(service);
return new ResourceArnBuilder(new ObjectMapper(), instance);
}
/**
* The resource a certificate-specific policy statement has to match. Without this the action
* is evaluated against {@code *}, so a deny naming the certificate never applies.
*/
@Test
void iamNamesTheServerCertificateBeingActedOn() {
String arn = "arn:aws:iam::000000000000:server-certificate/my-cert";
setFormBody("Action=DeleteServerCertificate&ServerCertificateName=my-cert");
assertEquals(arn, backedBy("my-cert", arn).build("iam", ctx, "us-east-1", "000000000000"));
}
@Test
void iamNamesTheCertificateForEveryOperationThatTakesOne() {
String arn = "arn:aws:iam::000000000000:server-certificate/c1";
ResourceArnBuilder stored = backedBy("c1", arn);
for (String action : List.of("GetServerCertificate", "UpdateServerCertificate",
"DeleteServerCertificate", "TagServerCertificate", "UntagServerCertificate",
"ListServerCertificateTags")) {
setFormBody("Action=" + action + "&ServerCertificateName=c1");
assertEquals(arn, stored.build("iam", ctx, "us-east-1", "000000000000"), action);
}
// The upload is the one that mints rather than reads: nothing is stored yet.
setFormBody("Action=UploadServerCertificate&ServerCertificateName=c1");
assertEquals(arn, builder.build("iam", ctx, "us-east-1", "000000000000"));
}
/**
* The one invariant behind every way this has been got wrong: for an operation acting on a
* certificate that exists, the ARN the permission check uses is that certificate's own stored
* ARN -- whatever spelling named the operation, and whatever partition signed the request.
*
* <p>Enumerated rather than sampled, because each defect so far hid in a combination the
* narrower tests did not reach: the mapping missing entirely, then {@code Operation} skipping
* it, then the partition coming from the signing region. Nothing here derives an ARN, so a
* regression has to show up as a mismatch.
*/
@Test
void iamChecksEveryRouteAndSigningRegionAgainstTheStoredArn() {
for (String storedArn : List.of(
"arn:aws:iam::000000000000:server-certificate/c1",
"arn:aws-cn:iam::000000000000:server-certificate/team/c1",
"arn:aws-us-gov:iam::000000000000:server-certificate/deep/nested/c1")) {
ResourceArnBuilder stored = backedBy("c1", storedArn);
for (String action : List.of("GetServerCertificate", "UpdateServerCertificate",
"DeleteServerCertificate", "TagServerCertificate", "UntagServerCertificate",
"ListServerCertificateTags")) {
for (String spelling : List.of("Action", "Operation")) {
for (String region : List.of("us-east-1", "cn-north-1", "us-gov-west-1")) {
setFormBody(spelling + "=" + action + "&ServerCertificateName=c1");
assertEquals(storedArn,
stored.build("iam", ctx, region, "000000000000"),
action + " named by " + spelling + ", signed in " + region);
}
}
}
}
}
/**
* Nothing stored under that name means nothing to name: the operation fails as NoSuchEntity
* regardless, and minting an ARN for an absent resource would hand a policy something to match.
*/
@Test
void iamFallsBackToTheWildcardWhenNoCertificateIsStored() {
setFormBody("Action=DeleteServerCertificate&ServerCertificateName=absent");
assertEquals("*", backedBy("other", "arn:aws:iam::000000000000:server-certificate/other")
.build("iam", ctx, "us-east-1", "000000000000"));
}
/**
* An upload names a certificate that does not exist yet, so its path has to come from the
* request. Taking it from the store would resolve to the root path and let a policy scoped to
* one path authorize an upload into another.
*/
@Test
void iamTakesTheUploadPathFromTheRequest() {
setFormBody("Action=UploadServerCertificate&ServerCertificateName=c1&Path=/team/");
assertEquals("arn:aws:iam::000000000000:server-certificate/team/c1",
builder.build("iam", ctx, "us-east-1", "000000000000"));
// Written without surrounding slashes, it still lands as a path segment.
setFormBody("Action=UploadServerCertificate&ServerCertificateName=c1&Path=team");
assertEquals("arn:aws:iam::000000000000:server-certificate/team/c1",
builder.build("iam", ctx, "us-east-1", "000000000000"));
// Omitted, it is the root path.
setFormBody("Action=UploadServerCertificate&ServerCertificateName=c1");
assertEquals("arn:aws:iam::000000000000:server-certificate/c1",
builder.build("iam", ctx, "us-east-1", "000000000000"));
}
/**
* IAM is global, so the ARN carries no region. An upload creates the certificate in the
* caller's own partition, so that is the partition its ARN is minted in.
*/
@Test
void iamMintsAnUploadedCertificateArnInTheRequestPartition() {
setFormBody("Action=UploadServerCertificate&ServerCertificateName=my-cert");
assertEquals("arn:aws-cn:iam::000000000000:server-certificate/my-cert",
builder.build("iam", ctx, "cn-north-1", "000000000000"));
setFormBody("Action=UploadServerCertificate&ServerCertificateName=my-cert");
assertEquals("arn:aws-us-gov:iam::000000000000:server-certificate/my-cert",
builder.build("iam", ctx, "us-gov-west-1", "000000000000"));
}
/**
* An existing certificate stays in the partition it was created in, so the check reads the
* partition from its stored ARN. Deriving it from the caller's signing region instead would
* name an ARN no resource has, and a deny on the certificate's real ARN would not match it.
*/
@Test
void iamKeepsTheStoredPartitionWhateverRegionSignedTheRequest() {
String arn = "arn:aws:iam::000000000000:server-certificate/my-cert";
ResourceArnBuilder stored = backedBy("my-cert", arn);
setFormBody("Action=DeleteServerCertificate&ServerCertificateName=my-cert");
assertEquals(arn, stored.build("iam", ctx, "cn-north-1", "000000000000"));
setFormBody("Action=DeleteServerCertificate&ServerCertificateName=my-cert");
assertEquals(arn, stored.build("iam", ctx, "us-gov-west-1", "000000000000"));
}
/**
* ListServerCertificates names no certificate, and every other IAM action is still unmapped,
* so both resolve to the wildcard rather than to a fabricated ARN.
*/
@Test
void iamFallsBackToTheWildcardWhenNoCertificateIsNamed() {
setFormBody("Action=ListServerCertificates&PathPrefix=/team/");
assertEquals("*", builder.build("iam", ctx, "us-east-1", "000000000000"));
setFormBody("Action=DeleteUser&UserName=bob");
assertEquals("*", builder.build("iam", ctx, "us-east-1", "000000000000"));
setFormBody("Action=DeleteServerCertificate");
assertEquals("*", builder.build("iam", ctx, "us-east-1", "000000000000"));
}
private void setJsonBody(String json) {
contextProperties.clear();
byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
@@ -0,0 +1,260 @@
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.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
/**
* A policy statement naming a single server certificate has to bind to that certificate and no
* other. Building the target ARN is only half of it; these drive the whole path, so a statement
* that is silently inert would fail here rather than pass unnoticed.
*/
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class ServerCertificateIamEnforcementIntegrationTest {
private static final String ACCOUNT_ID = "000000000000";
private static final String REGION = "us-east-1";
private static final CertificateGenerator GENERATOR = new CertificateGenerator();
private static String arn(String pathAndName) {
return "arn:aws:iam::" + ACCOUNT_ID + ":server-certificate/" + pathAndName;
}
@Test
void aDenyNamingOneCertificateLeavesTheOthersAlone() {
String suffix = suffix();
String denied = "deny-" + suffix;
String allowed = "keep-" + suffix;
upload(denied, null);
upload(allowed, null);
String akid = userWith("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"iam:*","Resource":"*"},
{"Effect":"Deny","Action":"iam:DeleteServerCertificate","Resource":"%s"}]}"""
.formatted(arn(denied)));
userIam(akid, "DeleteServerCertificate", Map.of("ServerCertificateName", denied))
.statusCode(403).body(containsString("AccessDenied"));
userIam(akid, "DeleteServerCertificate", Map.of("ServerCertificateName", allowed))
.statusCode(200);
}
/**
* The reference gives the resource as {@code server-certificate/${CertificateNameWithPath}}, so
* a certificate at {@code /team/} is only named by an ARN carrying that path. The second half is
* what makes this discriminating: the same ARN without the path must not match.
*/
@Test
void theStoredPathIsPartOfTheArn() {
String suffix = suffix();
String name = "pathed-" + suffix;
upload(name, "/team/");
String withPath = userWith("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"iam:*","Resource":"*"},
{"Effect":"Deny","Action":"iam:GetServerCertificate","Resource":"%s"}]}"""
.formatted(arn("team/" + name)));
userIam(withPath, "GetServerCertificate", Map.of("ServerCertificateName", name))
.statusCode(403).body(containsString("AccessDenied"));
String withoutPath = userWith("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"iam:*","Resource":"*"},
{"Effect":"Deny","Action":"iam:GetServerCertificate","Resource":"%s"}]}"""
.formatted(arn(name)));
userIam(withoutPath, "GetServerCertificate", Map.of("ServerCertificateName", name))
.statusCode(200);
}
@Test
void aResourceScopedAllowGrantsThatCertificateOnly() {
String suffix = suffix();
String granted = "allow-" + suffix;
String other = "other-" + suffix;
upload(granted, null);
upload(other, null);
String akid = userWith("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"iam:GetServerCertificate","Resource":"%s"}]}"""
.formatted(arn(granted)));
userIam(akid, "GetServerCertificate", Map.of("ServerCertificateName", granted))
.statusCode(200);
userIam(akid, "GetServerCertificate", Map.of("ServerCertificateName", other))
.statusCode(403).body(containsString("AccessDenied"));
}
/**
* An upload has no stored path to read, so its ARN comes from the request's own {@code Path}.
* The same name at a different path is a different resource and stays allowed.
*/
@Test
void anUploadIsAuthorizedAgainstThePathItAsksFor() {
String name = "upload-" + suffix();
String akid = userWith("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"iam:*","Resource":"*"},
{"Effect":"Deny","Action":"iam:UploadServerCertificate","Resource":"%s"}]}"""
.formatted(arn("team/" + name)));
CertificateGenerator.GeneratedCertificate pair = material();
uploadAs(akid, name, "/team/", pair)
.statusCode(403).body(containsString("AccessDenied"));
uploadAs(akid, name, null, pair)
.statusCode(200);
}
/**
* The Query controller accepts the legacy {@code Operation} parameter when {@code Action} is
* absent, and dispatches on it. The resource has to be resolved from the same place, or a
* caller can name the operation that way and have the deny evaluated against {@code *}.
*/
@Test
void theLegacyOperationParameterIsAuthorizedAgainstTheCertificateToo() {
String name = "legacy-" + suffix();
upload(name, null);
String akid = userWith("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"iam:*","Resource":"*"},
{"Effect":"Deny","Action":"iam:DeleteServerCertificate","Resource":"%s"}]}"""
.formatted(arn(name)));
given()
.header("Authorization", auth(akid, "iam"))
.contentType("application/x-www-form-urlencoded")
.formParam("Operation", "DeleteServerCertificate")
.formParam("Version", "2010-05-08")
.formParam("ServerCertificateName", name)
.when().post("/").then()
.statusCode(403).body(containsString("AccessDenied"));
}
/**
* A certificate stays in the partition it was created in, which is why the service re-mints a
* moved ARN beside its current one. The permission check has to read the partition from the
* stored ARN for the same reason: deriving it from the caller's signing region would let a
* request signed in another partition be checked against an ARN that names no real resource,
* and a deny on the certificate's actual ARN would not match it.
*/
@Test
void signingInAnotherPartitionDoesNotEscapeTheDeny() {
String name = "partition-" + suffix();
upload(name, null);
String akid = userWith("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"iam:*","Resource":"*"},
{"Effect":"Deny","Action":"iam:DeleteServerCertificate","Resource":"%s"}]}"""
.formatted(arn(name)));
given()
.header("Authorization", auth(akid, "iam", "cn-north-1"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteServerCertificate")
.formParam("Version", "2010-05-08")
.formParam("ServerCertificateName", name)
.when().post("/").then()
.statusCode(403).body(containsString("AccessDenied"));
}
/**
* The reference lists no resource type for {@code ListServerCertificates}, so it is checked
* against {@code *} and a statement naming one certificate cannot reach it.
*/
@Test
void theListIsNotScopedToACertificate() {
String name = "listed-" + suffix();
upload(name, null);
String akid = userWith("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"iam:*","Resource":"*"},
{"Effect":"Deny","Action":"iam:ListServerCertificates","Resource":"%s"}]}"""
.formatted(arn(name)));
userIam(akid, "ListServerCertificates", Map.of()).statusCode(200);
}
private static String suffix() {
return UUID.randomUUID().toString().substring(0, 8);
}
private static CertificateGenerator.GeneratedCertificate material() {
return GENERATOR.generateSelfSignedCertificate(
"certs.test.local", List.of(), KeyAlgorithm.EC_prime256v1);
}
private static void upload(String name, String path) {
uploadAs(ACCOUNT_ID, name, path, material()).statusCode(200);
}
private static ValidatableResponse uploadAs(String akid, String name, String path,
CertificateGenerator.GeneratedCertificate pair) {
RequestSpecification spec = given()
.header("Authorization", auth(akid, "iam"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "UploadServerCertificate")
.formParam("Version", "2010-05-08")
.formParam("ServerCertificateName", name)
.formParam("CertificateBody", pair.certificatePem())
.formParam("PrivateKey", pair.privateKeyPem());
if (path != null) {
spec.formParam("Path", path);
}
return spec.when().post("/").then();
}
/** An IAM user in {@link #ACCOUNT_ID} carrying {@code policy} inline. */
private static String userWith(String policy) {
String user = "cert-iam-" + suffix();
adminIam("CreateUser", Map.of("UserName", user)).statusCode(200);
adminIam("PutUserPolicy", Map.of("UserName", user, "PolicyName", "p",
"PolicyDocument", policy)).statusCode(200);
return adminIam("CreateAccessKey", Map.of("UserName", user)).statusCode(200)
.extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
}
private static ValidatableResponse adminIam(String action, Map<String, String> params) {
return iamCall(ACCOUNT_ID, action, params);
}
private static ValidatableResponse userIam(String akid, String action, Map<String, String> params) {
return iamCall(akid, action, params);
}
private static ValidatableResponse iamCall(String akid, String action, Map<String, String> params) {
RequestSpecification spec = given()
.header("Authorization", auth(akid, "iam"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", action)
.formParam("Version", "2010-05-08");
params.forEach(spec::formParam);
return spec.when().post("/").then();
}
private static String auth(String accessKeyId, String service) {
return auth(accessKeyId, service, REGION);
}
private static String auth(String accessKeyId, String service, String region) {
return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260919/" + region + "/" + service
+ "/aws4_request, SignedHeaders=host, Signature=abc";
}
}
@@ -0,0 +1,525 @@
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.hasItem;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The server-certificate lifecycle over the wire. Material is generated rather than hardcoded, so
* the upload path is exercised with certificates and keys that genuinely belong together, and the
* rejection paths with ones that genuinely do not.
*
* <p>IAM state is shared across the suite, so every test names its own entities uniquely. The
* per-account quota is deliberately not exercised here: filling it would starve every other test
* in the suite of its budget. {@code ServerCertificateStateTest} covers it against an isolated
* store instead.
*/
@QuarkusTest
class ServerCertificateIntegrationTest {
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);
}
private static CertificateGenerator.GeneratedCertificate material() {
return GENERATOR.generateSelfSignedCertificate("certs.test.local", List.of(), KeyAlgorithm.RSA_2048);
}
private static String upload(String name, CertificateGenerator.GeneratedCertificate pair) {
return iam("UploadServerCertificate")
.formParam("ServerCertificateName", name)
.formParam("CertificateBody", pair.certificatePem())
.formParam("PrivateKey", pair.privateKeyPem())
.when().post("/").then().statusCode(200)
.extract().path("UploadServerCertificateResponse.UploadServerCertificateResult"
+ ".ServerCertificateMetadata.Arn");
}
/**
* The reason the key is parsed rather than stored blind. Two separate calls to
* {@code material()} produce unrelated pairs, so this is a genuine mismatch rather than
* malformed input, and it must be distinguished from one.
*/
@Test
void uploadRejectsAKeyThatDoesNotMatchTheCertificate() {
iam("UploadServerCertificate")
.formParam("ServerCertificateName", "sc-mismatch-" + suffix())
.formParam("CertificateBody", material().certificatePem())
.formParam("PrivateKey", material().privateKeyPem())
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("KeyPairMismatch"));
}
@Test
void uploadAcceptsAMatchingPairAndMintsAscaMetadata() {
String name = "sc-ok-" + suffix();
CertificateGenerator.GeneratedCertificate pair = material();
String base = "UploadServerCertificateResponse.UploadServerCertificateResult"
+ ".ServerCertificateMetadata.";
iam("UploadServerCertificate")
.formParam("ServerCertificateName", name)
.formParam("CertificateBody", pair.certificatePem())
.formParam("PrivateKey", pair.privateKeyPem())
.when().post("/").then()
.statusCode(200)
.body(base + "ServerCertificateName", equalTo(name))
.body(base + "Arn", equalTo("arn:aws:iam::000000000000:server-certificate/" + name))
.body(base + "Path", equalTo("/"))
.body(base + "ServerCertificateId", containsString("ASCA"))
// Read off the certificate's own notAfter, so it must be present.
.body(base + "Expiration", containsString("Z"));
}
/** An EC pair must work too: the key-pair check uses a different signature algorithm for it. */
@Test
void uploadAcceptsAnEcKeyPair() {
String name = "sc-ec-" + suffix();
CertificateGenerator.GeneratedCertificate pair = GENERATOR.generateSelfSignedCertificate(
"ec.certs.test.local", List.of(), KeyAlgorithm.EC_prime256v1);
iam("UploadServerCertificate")
.formParam("ServerCertificateName", name)
.formParam("CertificateBody", pair.certificatePem())
.formParam("PrivateKey", pair.privateKeyPem())
.when().post("/").then().statusCode(200);
}
@Test
void unreadableMaterialIsMalformedCertificate() {
CertificateGenerator.GeneratedCertificate pair = material();
iam("UploadServerCertificate")
.formParam("ServerCertificateName", "sc-bad-body-" + suffix())
.formParam("CertificateBody", "not a pem at all")
.formParam("PrivateKey", pair.privateKeyPem())
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("MalformedCertificate"));
iam("UploadServerCertificate")
.formParam("ServerCertificateName", "sc-bad-key-" + suffix())
.formParam("CertificateBody", pair.certificatePem())
.formParam("PrivateKey", "not a pem at all")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("MalformedCertificate"));
iam("UploadServerCertificate")
.formParam("ServerCertificateName", "sc-bad-chain-" + suffix())
.formParam("CertificateBody", pair.certificatePem())
.formParam("PrivateKey", pair.privateKeyPem())
.formParam("CertificateChain", "not a pem at all")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("MalformedCertificate"));
}
/**
* {@code certificateBodyType} and {@code privateKeyType} are both capped at 16384, and
* {@code certificateChainType} at 2097152. Material past a cap is a request-shape error, not a
* malformed certificate, so it has to be distinguished from unreadable PEM.
*/
@Test
void materialPastItsModeledLengthIsAValidationError() {
CertificateGenerator.GeneratedCertificate pair = material();
String tooLong = "A".repeat(16385);
iam("UploadServerCertificate")
.formParam("ServerCertificateName", "sc-long-body-" + suffix())
.formParam("CertificateBody", tooLong)
.formParam("PrivateKey", pair.privateKeyPem())
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
iam("UploadServerCertificate")
.formParam("ServerCertificateName", "sc-long-key-" + suffix())
.formParam("CertificateBody", pair.certificatePem())
.formParam("PrivateKey", tooLong)
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
// A chain of the same size is well within its own, much larger, limit, so it must be
// judged by parseability rather than by the body's cap.
iam("UploadServerCertificate")
.formParam("ServerCertificateName", "sc-long-chain-" + suffix())
.formParam("CertificateBody", pair.certificatePem())
.formParam("PrivateKey", pair.privateKeyPem())
.formParam("CertificateChain", tooLong)
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("MalformedCertificate"));
}
/**
* A PEM reader stops at the first block, so a chain whose first certificate is valid and whose
* second is not would otherwise be stored and only fail whenever something tried to use it.
*/
@Test
void aChainWithABrokenLaterCertificateIsRejected() {
CertificateGenerator.GeneratedCertificate pair = material();
String goodThenBad = material().certificatePem()
+ "-----BEGIN CERTIFICATE-----\nnot base64 at all\n-----END CERTIFICATE-----\n";
iam("UploadServerCertificate")
.formParam("ServerCertificateName", "sc-badchain2-" + suffix())
.formParam("CertificateBody", pair.certificatePem())
.formParam("PrivateKey", pair.privateKeyPem())
.formParam("CertificateChain", goodThenBad)
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("MalformedCertificate"));
// A chain of two good certificates is still accepted, so the check is per block rather
// than a refusal of anything with more than one.
String twoGood = material().certificatePem() + material().certificatePem();
iam("UploadServerCertificate")
.formParam("ServerCertificateName", "sc-goodchain2-" + suffix())
.formParam("CertificateBody", pair.certificatePem())
.formParam("PrivateKey", pair.privateKeyPem())
.formParam("CertificateChain", twoGood)
.when().post("/").then().statusCode(200);
}
/**
* An omitted chain is allowed, but a present one must be a chain. {@code certificateChainType}
* has a minimum of 1, so an empty value breaks the request shape, while whitespace satisfies
* the length and fails as a certificate. Neither may be quietly stored as "no chain".
*/
@Test
void aPresentButEmptyOrBlankChainIsRejected() {
CertificateGenerator.GeneratedCertificate pair = material();
iam("UploadServerCertificate")
.formParam("ServerCertificateName", "sc-emptychain-" + suffix())
.formParam("CertificateBody", pair.certificatePem())
.formParam("PrivateKey", pair.privateKeyPem())
.formParam("CertificateChain", "")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
iam("UploadServerCertificate")
.formParam("ServerCertificateName", "sc-blankchain-" + suffix())
.formParam("CertificateBody", pair.certificatePem())
.formParam("PrivateKey", pair.privateKeyPem())
.formParam("CertificateChain", " \n ")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("MalformedCertificate"));
// Omitting it entirely is still fine, and the certificate then has no chain to return.
String name = "sc-nochain-" + suffix();
upload(name, pair);
String got = iam("GetServerCertificate").formParam("ServerCertificateName", name)
.when().post("/").then().statusCode(200).extract().asString();
assertTrue(!got.contains("CertificateChain"), "an absent chain is omitted, not empty");
}
/**
* Names are compared case-insensitively, so the duplicate check has to exclude the certificate
* being renamed or changing only the case of its own name reports a collision with itself.
*/
@Test
void aCaseOnlyRenameIsAllowed() {
String name = "SCCase" + suffix();
upload(name, material());
iam("UpdateServerCertificate")
.formParam("ServerCertificateName", name)
.formParam("NewServerCertificateName", name.toLowerCase())
.when().post("/").then().statusCode(200);
iam("GetServerCertificate").formParam("ServerCertificateName", name.toLowerCase())
.when().post("/").then()
.statusCode(200)
.body("GetServerCertificateResponse.GetServerCertificateResult.ServerCertificate"
+ ".ServerCertificateMetadata.ServerCertificateName", equalTo(name.toLowerCase()));
}
@Test
void uploadingTheSameNameTwiceIsEntityAlreadyExists() {
String name = "sc-dup-" + suffix();
upload(name, material());
CertificateGenerator.GeneratedCertificate second = material();
iam("UploadServerCertificate")
.formParam("ServerCertificateName", name)
.formParam("CertificateBody", second.certificatePem())
.formParam("PrivateKey", second.privateKeyPem())
.when().post("/").then()
.statusCode(409)
.body("ErrorResponse.Error.Code", equalTo("EntityAlreadyExists"));
}
/** The private key is stored but no reader returns it: AWS models it only on the upload. */
@Test
void readersNeverReturnThePrivateKey() {
String name = "sc-nokey-" + suffix();
CertificateGenerator.GeneratedCertificate pair = material();
upload(name, pair);
String get = iam("GetServerCertificate").formParam("ServerCertificateName", name)
.when().post("/").then().statusCode(200).extract().asString();
assertTrue(get.contains("CertificateBody"), "the certificate body is part of the shape");
assertTrue(!get.contains("PrivateKey"), "but the private key is never echoed back");
assertTrue(!get.contains("PRIVATE KEY"), "nor its PEM header");
String list = iam("ListServerCertificates").when().post("/").then().statusCode(200)
.extract().asString();
assertTrue(!list.contains("PrivateKey"));
assertTrue(!list.contains("CertificateBody"), "the listing is metadata only");
}
@Test
void getReturnsTheChainWhenOneWasUploaded() {
String name = "sc-chain-" + suffix();
CertificateGenerator.GeneratedCertificate pair = material();
CertificateGenerator.GeneratedCertificate chain = material();
iam("UploadServerCertificate")
.formParam("ServerCertificateName", name)
.formParam("CertificateBody", pair.certificatePem())
.formParam("PrivateKey", pair.privateKeyPem())
.formParam("CertificateChain", chain.certificatePem())
.when().post("/").then().statusCode(200);
iam("GetServerCertificate").formParam("ServerCertificateName", name)
.when().post("/").then()
.statusCode(200)
.body("GetServerCertificateResponse.GetServerCertificateResult.ServerCertificate"
+ ".CertificateChain", containsString("BEGIN CERTIFICATE"));
}
@Test
void listFiltersByPathPrefixAndPaginates() {
String tag = suffix();
CertificateGenerator.GeneratedCertificate a = material();
CertificateGenerator.GeneratedCertificate b = material();
iam("UploadServerCertificate").formParam("ServerCertificateName", "sc-pa-" + tag)
.formParam("Path", "/team-" + tag + "/")
.formParam("CertificateBody", a.certificatePem()).formParam("PrivateKey", a.privateKeyPem())
.when().post("/").then().statusCode(200);
iam("UploadServerCertificate").formParam("ServerCertificateName", "sc-pb-" + tag)
.formParam("Path", "/team-" + tag + "/")
.formParam("CertificateBody", b.certificatePem()).formParam("PrivateKey", b.privateKeyPem())
.when().post("/").then().statusCode(200);
List<String> scoped = iam("ListServerCertificates")
.formParam("PathPrefix", "/team-" + tag + "/").formParam("MaxItems", "1000")
.when().post("/").then().statusCode(200)
.extract().xmlPath().getList("ListServerCertificatesResponse.ListServerCertificatesResult"
+ ".ServerCertificateMetadataList.member.ServerCertificateName", String.class);
assertTrue(scoped.contains("sc-pa-" + tag));
assertTrue(scoped.contains("sc-pb-" + tag));
assertTrue(scoped.size() == 2, "the prefix excluded everything else, got " + scoped);
String marker = iam("ListServerCertificates")
.formParam("PathPrefix", "/team-" + tag + "/").formParam("MaxItems", "1")
.when().post("/").then().statusCode(200)
.body("ListServerCertificatesResponse.ListServerCertificatesResult.IsTruncated",
equalTo("true"))
.extract().path("ListServerCertificatesResponse.ListServerCertificatesResult.Marker");
assertNotNull(marker, "a truncated page carries a Marker");
}
@Test
void updateRenamesAndMovesTheCertificate() {
String name = "sc-rename-" + suffix();
String renamed = "sc-renamed-" + suffix();
upload(name, material());
iam("UpdateServerCertificate")
.formParam("ServerCertificateName", name)
.formParam("NewServerCertificateName", renamed)
.formParam("NewPath", "/moved/")
.when().post("/").then().statusCode(200);
iam("GetServerCertificate").formParam("ServerCertificateName", renamed)
.when().post("/").then()
.statusCode(200)
.body("GetServerCertificateResponse.GetServerCertificateResult.ServerCertificate"
+ ".ServerCertificateMetadata.Path", equalTo("/moved/"))
.body("GetServerCertificateResponse.GetServerCertificateResult.ServerCertificate"
+ ".ServerCertificateMetadata.Arn",
equalTo("arn:aws:iam::000000000000:server-certificate/moved/" + renamed));
iam("GetServerCertificate").formParam("ServerCertificateName", name)
.when().post("/").then()
.statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));
}
@Test
void renamingOntoATakenNameIsEntityAlreadyExists() {
String first = "sc-taken-a-" + suffix();
String second = "sc-taken-b-" + suffix();
upload(first, material());
upload(second, material());
iam("UpdateServerCertificate")
.formParam("ServerCertificateName", first)
.formParam("NewServerCertificateName", second)
.when().post("/").then()
.statusCode(409)
.body("ErrorResponse.Error.Code", equalTo("EntityAlreadyExists"));
}
@Test
void deleteRemovesItAndIsThenNoSuchEntity() {
String name = "sc-delete-" + suffix();
upload(name, material());
iam("DeleteServerCertificate").formParam("ServerCertificateName", name)
.when().post("/").then().statusCode(200);
iam("DeleteServerCertificate").formParam("ServerCertificateName", name)
.when().post("/").then()
.statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));
}
@Test
void unknownCertificateIsNoSuchEntity() {
iam("GetServerCertificate").formParam("ServerCertificateName", "sc-missing-" + suffix())
.when().post("/").then()
.statusCode(404)
.body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));
}
@Test
void tagsRoundTripSortedByKeyAndPaginate() {
String name = "sc-tags-" + suffix();
upload(name, material());
iam("TagServerCertificate").formParam("ServerCertificateName", name)
.formParam("Tags.member.1.Key", "zone").formParam("Tags.member.1.Value", "b")
.formParam("Tags.member.2.Key", "env").formParam("Tags.member.2.Value", "test")
.when().post("/").then().statusCode(200);
String base = "ListServerCertificateTagsResponse.ListServerCertificateTagsResult.";
iam("ListServerCertificateTags").formParam("ServerCertificateName", name)
.when().post("/").then()
.statusCode(200)
.body(base + "Tags.member[0].Key", equalTo("env"))
.body(base + "Tags.member[1].Key", equalTo("zone"));
iam("ListServerCertificateTags").formParam("ServerCertificateName", name)
.formParam("MaxItems", "1")
.when().post("/").then()
.statusCode(200)
.body(base + "IsTruncated", equalTo("true"))
.body(base + "Tags.member.Key", equalTo("env"));
iam("UntagServerCertificate").formParam("ServerCertificateName", name)
.formParam("TagKeys.member.1", "zone")
.when().post("/").then().statusCode(200);
iam("ListServerCertificateTags").formParam("ServerCertificateName", name)
.when().post("/").then()
.statusCode(200)
.body(base + "Tags.member.Key", equalTo("env"));
}
@Test
void tagsGivenAtUploadAreKeptAndReturned() {
String name = "sc-uploadtag-" + suffix();
CertificateGenerator.GeneratedCertificate pair = material();
iam("UploadServerCertificate")
.formParam("ServerCertificateName", name)
.formParam("CertificateBody", pair.certificatePem())
.formParam("PrivateKey", pair.privateKeyPem())
.formParam("Tags.member.1.Key", "owner").formParam("Tags.member.1.Value", "platform")
.when().post("/").then()
.statusCode(200)
.body("UploadServerCertificateResponse.UploadServerCertificateResult.Tags.member.Key",
equalTo("owner"));
iam("ListServerCertificateTags").formParam("ServerCertificateName", name)
.when().post("/").then()
.statusCode(200)
.body("ListServerCertificateTagsResponse.ListServerCertificateTagsResult"
+ ".Tags.member.Value", equalTo("platform"));
}
/**
* With no Authorization header there is no SigV4 credential scope to resolve, so the
* controller routes on the action name alone through {@code AwsQueryController.IAM_ACTIONS}.
* An action missing from that set falls through to SQS and answers UnsupportedOperation, so
* every new operation has to be listed there. The whole scenario stays unauthenticated to
* keep the upload and the reads in one account context.
*/
@Test
void certificateActionsRouteViaTheActionFallbackWhenAuthHeaderAbsent() {
String name = "sc-fallback-" + suffix();
CertificateGenerator.GeneratedCertificate pair = material();
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "UploadServerCertificate")
.formParam("ServerCertificateName", name)
.formParam("CertificateBody", pair.certificatePem())
.formParam("PrivateKey", pair.privateKeyPem())
.when().post("/").then()
.statusCode(200)
.body("UploadServerCertificateResponse.UploadServerCertificateResult"
+ ".ServerCertificateMetadata.ServerCertificateName", equalTo(name));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ListServerCertificates")
.formParam("MaxItems", "1000")
.when().post("/").then()
.statusCode(200)
.body("ListServerCertificatesResponse.ListServerCertificatesResult"
+ ".ServerCertificateMetadataList.member.ServerCertificateName",
hasItem(name));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteServerCertificate")
.formParam("ServerCertificateName", name)
.when().post("/").then().statusCode(200);
}
/** The account summary counts the store rather than reporting a hardcoded zero. */
@Test
void theAccountSummaryCountsStoredCertificates() {
long before = summaryValue("ServerCertificates");
upload("sc-summary-" + suffix(), material());
assertTrue(summaryValue("ServerCertificates") == before + 1,
"ServerCertificates did not follow the store");
assertTrue(summaryValue("ServerCertificatesQuota") == 20L, "the documented quota");
}
private static long summaryValue(String key) {
String value = iam("GetAccountSummary").when().post("/").then().statusCode(200)
.extract().path("GetAccountSummaryResponse.GetAccountSummaryResult.SummaryMap.entry"
+ ".find { it.key == '" + key + "' }.value");
assertNotNull(value, key + " missing from the summary map");
return Long.parseLong(value);
}
}
@@ -0,0 +1,293 @@
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.ServerCertificate;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
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 server-certificate store that the wire tests cannot reach: that it survives
* a restart, that one account cannot see another's, and that its check-then-write paths hold when
* two requests race.
*
* <p>A server certificate holds a private key, so account isolation here is the same class of
* concern as an MFA seed: a leak across accounts would hand over usable key material.
*/
class ServerCertificateStateTest {
private static final String ACCOUNT_A = "000000000000";
private static final String ACCOUNT_B = "111111111111";
private static final CertificateGenerator GENERATOR = new CertificateGenerator();
private static CertificateGenerator.GeneratedCertificate material() {
return GENERATOR.generateSelfSignedCertificate("state.test.local", List.of(), KeyAlgorithm.RSA_2048);
}
/**
* For the trial-heavy tests below. What they exercise is the locking, which does not care which
* algorithm the key uses, and an EC key is generated far more cheaply than an RSA one: using
* RSA here cost most of this class's runtime for no extra coverage.
*/
private static CertificateGenerator.GeneratedCertificate cheapMaterial() {
return GENERATOR.generateSelfSignedCertificate("state.test.local", List.of(),
KeyAlgorithm.EC_prime256v1);
}
@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, ServerCertificate> 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<>(),
certificates,
new RegionResolver("us-east-1", defaultAccount), false, null);
}
/**
* The private key and the expiry both have to survive a restart. The expiry is read from the
* certificate at upload, so if it failed to round trip the certificate would come back
* claiming no expiry at all rather than visibly breaking.
*/
@Test
void aServerCertificateSurvivesRestart(@TempDir Path dir) {
PersistentStorage<String, ServerCertificate> first =
new PersistentStorage<>(dir.resolve("iam-server-certificates.json"), new TypeReference<>() {});
first.load();
CertificateGenerator.GeneratedCertificate pair = material();
ServerCertificate created = newService(first, ACCOUNT_A)
.uploadServerCertificate("persisted", "/team/", pair.certificatePem(),
pair.privateKeyPem(), null, Map.of("env", "prod"));
PersistentStorage<String, ServerCertificate> reopened =
new PersistentStorage<>(dir.resolve("iam-server-certificates.json"), new TypeReference<>() {});
reopened.load();
ServerCertificate reloaded = newService(reopened, ACCOUNT_A).getServerCertificate("persisted");
assertEquals(created.getCertificateBody(), reloaded.getCertificateBody());
assertEquals(created.getPrivateKey(), reloaded.getPrivateKey(), "the private key must survive");
assertEquals(created.getServerCertificateId(), reloaded.getServerCertificateId());
assertEquals(created.getArn(), reloaded.getArn());
assertEquals("/team/", reloaded.getPath());
assertEquals("prod", reloaded.getTags().get("env"));
assertEquals(created.getExpiration(), reloaded.getExpiration(), "the expiry must survive");
}
@Test
void anotherAccountCanNeitherSeeNorReachACertificate() {
AtomicReference<String> account = new AtomicReference<>(ACCOUNT_A);
AccountAwareStorageBackend<ServerCertificate> certificates = new AccountAwareStorageBackend<>(
new InMemoryStorage<>(), requestContextFor(account), ACCOUNT_A);
IamService service = newService(certificates, ACCOUNT_A);
CertificateGenerator.GeneratedCertificate pair = material();
service.uploadServerCertificate("scoped", "/", pair.certificatePem(), pair.privateKeyPem(),
null, Map.of());
account.set(ACCOUNT_B);
assertTrue(service.listServerCertificates(null).isEmpty(),
"account B must not see account A's certificates");
assertEquals("NoSuchEntity",
assertThrows(AwsException.class, () -> service.getServerCertificate("scoped")).getErrorCode());
assertEquals("NoSuchEntity",
assertThrows(AwsException.class, () -> service.deleteServerCertificate("scoped")).getErrorCode());
// The key must not be reachable through the tag reader either.
assertThrows(AwsException.class, () -> service.listServerCertificateTags("scoped"));
// Account B may use the same name without colliding, and that must not disturb A's copy.
CertificateGenerator.GeneratedCertificate other = material();
service.uploadServerCertificate("scoped", "/", other.certificatePem(), other.privateKeyPem(),
null, Map.of());
assertEquals(other.privateKeyPem(), service.getServerCertificate("scoped").getPrivateKey());
account.set(ACCOUNT_A);
assertEquals(pair.privateKeyPem(), service.getServerCertificate("scoped").getPrivateKey(),
"account A's key was replaced by account B's upload");
}
private static int raceTogether(Runnable... actions) throws InterruptedException {
AtomicInteger succeeded = new AtomicInteger();
CountDownLatch start = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(actions.length);
ExecutorService pool = Executors.newFixedThreadPool(actions.length);
try {
for (Runnable action : actions) {
pool.submit(() -> {
try {
start.await();
action.run();
succeeded.incrementAndGet();
} catch (AwsException expected) {
// One side of a race is meant to lose; the count is the assertion.
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
done.countDown();
}
});
}
start.countDown();
assertTrue(done.await(10, TimeUnit.SECONDS), "actions did not finish");
} finally {
pool.shutdownNow();
}
return succeeded.get();
}
/** Two uploads of one name: the loser must be told, not silently replace the winner's key. */
@Test
void onlyOneOfTwoUploadsOfTheSameNameSucceeds() throws InterruptedException {
for (int trial = 0; trial < 100; trial++) {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
CertificateGenerator.GeneratedCertificate a = cheapMaterial();
CertificateGenerator.GeneratedCertificate b = cheapMaterial();
int won = raceTogether(
() -> service.uploadServerCertificate("contended", "/", a.certificatePem(),
a.privateKeyPem(), null, Map.of()),
() -> service.uploadServerCertificate("contended", "/", b.certificatePem(),
b.privateKeyPem(), null, Map.of()));
assertEquals(1, won, "both uploads were told they stored the certificate");
assertEquals(1, service.listServerCertificates(null).size());
}
}
/**
* Concurrent uploads must not push the account past its quota. Counted and written under one
* lock, exactly 20 can land; an unguarded count would let several read 19 together.
*/
@Test
void theAccountQuotaHoldsUnderConcurrentUploads() throws InterruptedException {
for (int trial = 0; trial < 10; trial++) {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
Runnable[] uploads = new Runnable[24];
for (int i = 0; i < uploads.length; i++) {
String name = "quota-" + i;
CertificateGenerator.GeneratedCertificate pair = cheapMaterial();
uploads[i] = () -> service.uploadServerCertificate(name, "/", pair.certificatePem(),
pair.privateKeyPem(), null, Map.of());
}
raceTogether(uploads);
assertEquals(20, service.listServerCertificates(null).size(),
"the per-account quota let more than 20 certificates through");
}
}
/** Renaming must not lose the material, the id, the expiry or the tags. */
@Test
void renameKeepsEverythingButTheNameAndArn() {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
CertificateGenerator.GeneratedCertificate pair = material();
ServerCertificate before = service.uploadServerCertificate("before", "/", pair.certificatePem(),
pair.privateKeyPem(), pair.certificatePem(), Map.of("env", "prod"));
String originalId = before.getServerCertificateId();
Instant originalExpiry = before.getExpiration();
service.updateServerCertificate("before", "after", "/moved/");
ServerCertificate after = service.getServerCertificate("after");
assertEquals(originalId, after.getServerCertificateId(), "the id is immutable across a rename");
assertEquals(originalExpiry, after.getExpiration());
assertEquals(pair.privateKeyPem(), after.getPrivateKey());
assertEquals(pair.certificatePem(), after.getCertificateChain());
assertEquals("prod", after.getTags().get("env"));
assertEquals("/moved/", after.getPath());
assertTrue(after.getArn().endsWith(":server-certificate/moved/after"), after.getArn());
assertEquals("NoSuchEntity",
assertThrows(AwsException.class, () -> service.getServerCertificate("before")).getErrorCode());
}
/**
* A rename racing a delete. Counting entries is not enough: that still passes if the rename
* reports success while losing the material, or if a worker dies on something other than an
* AwsException. So each side's outcome is recorded and checked against the state it implies.
*/
@Test
void renamingNeverRacesADeleteIntoLosingTheCertificate() throws InterruptedException {
List<String> broken = new CopyOnWriteArrayList<>();
for (int trial = 0; trial < 100; trial++) {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
CertificateGenerator.GeneratedCertificate pair = cheapMaterial();
service.uploadServerCertificate("from", "/", pair.certificatePem(), pair.privateKeyPem(),
null, Map.of());
AtomicReference<String> renameOutcome = new AtomicReference<>("not-run");
AtomicReference<String> deleteOutcome = new AtomicReference<>("not-run");
raceTogether(
() -> renameOutcome.set(record(() -> service.updateServerCertificate("from", "to", null))),
() -> deleteOutcome.set(record(() -> service.deleteServerCertificate("from"))));
String state = "trial " + trial + " rename=" + renameOutcome.get()
+ " delete=" + deleteOutcome.get();
if (renameOutcome.get().startsWith("threw:") || deleteOutcome.get().startsWith("threw:")) {
broken.add(state + " (unexpected exception)");
continue;
}
List<ServerCertificate> remaining = service.listServerCertificates(null);
if (remaining.size() > 1) {
broken.add(state + " left " + remaining.size() + " entries");
} else if ("ok".equals(renameOutcome.get())) {
// The rename won, so the certificate must exist under the new name, intact.
if (remaining.size() != 1 || !"to".equals(remaining.get(0).getServerCertificateName())
|| !pair.privateKeyPem().equals(remaining.get(0).getPrivateKey())) {
broken.add(state + " renamed but the material did not follow");
}
} else if ("ok".equals(deleteOutcome.get()) && !remaining.isEmpty()) {
broken.add(state + " deleted but a certificate remains");
}
}
assertTrue(broken.isEmpty(), "rename racing delete left inconsistent state: " + broken);
}
/** Runs an action, reporting "ok", its AWS error code, or an unexpected throwable. */
private static String record(Runnable action) {
try {
action.run();
return "ok";
} catch (AwsException e) {
return e.getErrorCode();
} catch (RuntimeException e) {
return "threw:" + e.getClass().getSimpleName();
}
}
}
@@ -50,6 +50,7 @@ class VirtualMfaAccountScopeTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), devices,
new InMemoryStorage<>(),
new RegionResolver("us-east-1", ACCOUNT_A), false, null);
VirtualMfaDevice device = service.createVirtualMfaDevice("shared-name", "/", Map.of());
@@ -87,6 +88,7 @@ class VirtualMfaAccountScopeTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), devices,
new InMemoryStorage<>(),
new RegionResolver("us-east-1", ACCOUNT_A), false, null);
VirtualMfaDevice inA = service.createVirtualMfaDevice("same-name", "/", Map.of());
@@ -37,6 +37,7 @@ class VirtualMfaConcurrencyTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("eu-central-1", "000000000000"), false, null);
}
@@ -566,6 +566,32 @@ class VirtualMfaIntegrationTest {
.body("ListMFADeviceTagsResponse.ListMFADeviceTagsResult.IsTruncated", equalTo("false"));
}
/**
* The MFA actions were missing from {@code AwsQueryController.IAM_ACTIONS} as well, so an
* unauthenticated client reached SQS instead of IAM. Pinned here because the two families
* regressed the same way and nothing else covers this routing for MFA.
*/
@Test
void mfaActionsRouteViaTheActionFallbackWhenAuthHeaderAbsent() {
String name = "mfa-fallback-" + suffix();
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateVirtualMFADevice")
.formParam("VirtualMFADeviceName", name)
.when().post("/").then()
.statusCode(200)
.body("CreateVirtualMFADeviceResponse.CreateVirtualMFADeviceResult"
+ ".VirtualMFADevice.SerialNumber",
equalTo("arn:aws:iam::000000000000:mfa/" + name));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteVirtualMFADevice")
.formParam("SerialNumber", "arn:aws:iam::000000000000:mfa/" + name)
.when().post("/").then().statusCode(200);
}
@Test
void tagsRoundTripAndAreListedSortedByKey() {
Device device = createDevice("mfa-tags-" + suffix());