feat(iam): model service-specific credentials (#5084)

Adds CreateServiceSpecificCredential, ListServiceSpecificCredentials,
UpdateServiceSpecificCredential, ResetServiceSpecificCredential and
DeleteServiceSpecificCredential, the five the wire model defines.

A credential takes one of two shapes, decided by the service: CodeCommit and
Keyspaces get a ServiceUserName and a ServicePassword, while the long-term API
key services get a ServiceCredentialAlias and a ServiceCredentialSecret and
accept CredentialAgeDays. The quota is two per service rather than two per user,
and the version behind a service user name's +n suffix is the lowest one free
rather than a count, so deleting out of order cannot mint a name already in use.

A credential blocks DeleteUser until it is removed, the last item on AWS's list
of what to delete first, and follows the user across an UpdateUser rename.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-05 22:57:54 -05:00
1 parent d4b7265b49
commit 9c0102559d
16 files changed
+2307 -39

No files matched your search

@@ -233,6 +233,7 @@ class IamServicePersistenceTest {
new InMemoryStorage<>(), devices, new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"), false, null);
}
@@ -2640,6 +2640,7 @@ class IamServiceTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"), false, null);
AwsException ex = assertThrows(AwsException.class, withExpiredReport::getCredentialReport);
@@ -2660,6 +2661,7 @@ class IamServiceTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"), false, null);
IamService.CredentialReportGeneration generation = withExpiredReport.generateCredentialReport();
@@ -82,6 +82,7 @@ class ServerCertificateStateTest {
certificates,
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", defaultAccount), false, null);
}
@@ -0,0 +1,616 @@
package io.github.hectorvent.floci.services.iam;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
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.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The service-specific credential lifecycle over the wire.
*
* <p>The quota is two per service per user, so each test makes its own user and thereby owns a
* fresh budget for each supported service.
*/
@QuarkusTest
class ServiceSpecificCredentialIntegrationTest {
private static final String IAM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request";
private static final String CODECOMMIT = "codecommit.amazonaws.com";
private static final String CASSANDRA = "cassandra.amazonaws.com";
private static final String BEDROCK = "bedrock.amazonaws.com";
/** The four whose credential is a long-term API key rather than a user name and password. */
private static final List<String> LONG_TERM_KEY_SERVICES = List.of(
BEDROCK, "aws-external-anthropic.amazonaws.com", "cloudwatch.amazonaws.com",
"logs.amazonaws.com");
private static final List<String> PASSWORD_SERVICES = List.of(CODECOMMIT, CASSANDRA);
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 String user() {
String name = "ssc-user-" + suffix();
iam("CreateUser").formParam("UserName", name).when().post("/").then().statusCode(200);
return name;
}
private static String create(String userName, String serviceName) {
return iam("CreateServiceSpecificCredential")
.formParam("UserName", userName)
.formParam("ServiceName", serviceName)
.when().post("/").then().statusCode(200)
.extract().path("CreateServiceSpecificCredentialResponse"
+ ".CreateServiceSpecificCredentialResult.ServiceSpecificCredential"
+ ".ServiceSpecificCredentialId");
}
private static final String CREATE_RESULT =
"CreateServiceSpecificCredentialResponse.CreateServiceSpecificCredentialResult"
+ ".ServiceSpecificCredential.";
@Test
void createReturnsAnAccaIdAUserNameAndAPasswordForCodeCommit() {
String userName = user();
String id = iam("CreateServiceSpecificCredential")
.formParam("UserName", userName)
.formParam("ServiceName", CODECOMMIT)
.when().post("/").then().statusCode(200)
.body(CREATE_RESULT + "UserName", equalTo(userName))
.body(CREATE_RESULT + "ServiceName", equalTo(CODECOMMIT))
.body(CREATE_RESULT + "Status", equalTo("Active"))
// The service user name AWS derives: the IAM user, then the account.
.body(CREATE_RESULT + "ServiceUserName", startsWith(userName + "-at-"))
.extract().path(CREATE_RESULT + "ServiceSpecificCredentialId");
assertNotNull(id);
assertTrue(id.startsWith("ACCA"), "the prefix table gives ACCA: " + id);
// serviceSpecificCredentialId is 20 to 128 word characters.
assertTrue(id.length() >= 20 && id.length() <= 128, "id length: " + id.length());
assertTrue(id.matches("\\w+"), id);
}
/** The password is disclosed here and never again, so it has to be present on the create. */
@Test
void thePasswordIsReturnedOnlyByTheCreate() {
String userName = user();
String password = iam("CreateServiceSpecificCredential")
.formParam("UserName", userName)
.formParam("ServiceName", CODECOMMIT)
.when().post("/").then().statusCode(200)
.extract().path(CREATE_RESULT + "ServicePassword");
assertNotNull(password, "the create must disclose the password");
assertTrue(password.length() >= 20, "a real password, not a placeholder");
// And the list, the only other reader, is defined without it.
iam("ListServiceSpecificCredentials").formParam("UserName", userName)
.when().post("/").then().statusCode(200)
.body(not(containsString("ServicePassword")))
.body(not(containsString(password)));
}
/**
* A long-term API key service's credential is an alias and a secret rather than a user name
* and a password. The model carries both shapes and a credential has exactly one of them.
*
* <p>The alias "includes the IAM user name and a suffix containing version and creation
* information", so it is derived from the user rather than random.
*/
@Test
void everyLongTermApiKeyServiceGetsAnAliasAndASecret() {
for (String service : LONG_TERM_KEY_SERVICES) {
String userName = user();
iam("CreateServiceSpecificCredential")
.formParam("UserName", userName)
.formParam("ServiceName", service)
.when().post("/").then().statusCode(200)
.body(CREATE_RESULT + "ServiceName", equalTo(service))
.body(CREATE_RESULT + "ServiceCredentialAlias", startsWith(userName + "+v1-"))
.body(CREATE_RESULT + "ServiceCredentialSecret", not(equalTo(null)))
.body(not(containsString("ServiceUserName")))
.body(not(containsString("ServicePassword")));
}
}
/** The other two give a user name and a password, and never an alias or a secret. */
@Test
void thePasswordServicesGetAUserNameAndAPassword() {
for (String service : PASSWORD_SERVICES) {
String userName = user();
iam("CreateServiceSpecificCredential")
.formParam("UserName", userName)
.formParam("ServiceName", service)
.when().post("/").then().statusCode(200)
.body(CREATE_RESULT + "ServiceName", equalTo(service))
.body(CREATE_RESULT + "ServiceUserName", startsWith(userName + "-at-"))
.body(CREATE_RESULT + "ServicePassword", not(equalTo(null)))
.body(not(containsString("ServiceCredentialAlias")))
.body(not(containsString("ServiceCredentialSecret")));
}
}
/**
* A legacy per-partition form of a supported service's principal must not be refused for a
* service that is in fact supported, and the stored name folds to the universal form.
*/
@Test
void aLegacyPartitionFormOfASupportedServiceIsAccepted() {
iam("CreateServiceSpecificCredential")
.formParam("UserName", user())
.formParam("ServiceName", "bedrock.amazonaws.com.cn")
.when().post("/").then().statusCode(200)
.body(CREATE_RESULT + "ServiceName", equalTo(BEDROCK));
}
/**
* CredentialAgeDays "is only valid for services that support long-term API keys", so each of
* those four takes it and neither password service does.
*/
@Test
void credentialAgeDaysSetsAnExpiryAndOnlyForLongTermKeyServices() {
for (String service : LONG_TERM_KEY_SERVICES) {
iam("CreateServiceSpecificCredential")
.formParam("UserName", user())
.formParam("ServiceName", service)
.formParam("CredentialAgeDays", "30")
.when().post("/").then().statusCode(200)
.body(CREATE_RESULT + "ExpirationDate", containsString("T"));
}
for (String service : PASSWORD_SERVICES) {
iam("CreateServiceSpecificCredential")
.formParam("UserName", user())
.formParam("ServiceName", service)
.formParam("CredentialAgeDays", "30")
.when().post("/").then().statusCode(400)
.body(containsString("ValidationError"));
}
}
/**
* A present but unparseable {@code CredentialAgeDays} is a validation error, not an absent
* one. Treating it as absent would answer a malformed request with a credential that never
* expires, which is the opposite of what the caller asked for.
*/
@Test
void anEmptyOrNonNumericCredentialAgeIsRejectedRatherThanIgnored() {
for (String days : List.of("", " ", "thirty", "30.5")) {
iam("CreateServiceSpecificCredential")
.formParam("UserName", user())
.formParam("ServiceName", BEDROCK)
.formParam("CredentialAgeDays", days)
.when().post("/").then().statusCode(400)
.body(containsString("ValidationError"))
.body(containsString("credentialAgeDays"))
.body(not(containsString("ExpirationDate")));
}
}
/** credentialAgeDays is 1 to 36600, both in the model and in the User Guide's prose. */
@Test
void aCredentialAgeOutsideTheDocumentedRangeIsRejected() {
for (String days : List.of("0", "-1", "36601")) {
iam("CreateServiceSpecificCredential")
.formParam("UserName", user())
.formParam("ServiceName", BEDROCK)
.formParam("CredentialAgeDays", days)
.when().post("/").then().statusCode(400)
.body(containsString("ValidationError"))
.body(containsString("credentialAgeDays"));
}
// And both ends of the range are accepted, so the bounds are not off by one.
for (String days : List.of("1", "36600")) {
iam("CreateServiceSpecificCredential")
.formParam("UserName", user())
.formParam("ServiceName", BEDROCK)
.formParam("CredentialAgeDays", days)
.when().post("/").then().statusCode(200)
.body(CREATE_RESULT + "ExpirationDate", containsString("T"));
}
}
/**
* A key with an expiry still ahead of it reports the stored status. The reported status is
* derived from the expiry, so this is the half that catches a derivation reporting
* {@code Expired} for everything that merely has a date.
*/
@Test
void aKeyWithAFutureExpiryStillReportsItsStoredStatus() {
String userName = user();
String id = iam("CreateServiceSpecificCredential")
.formParam("UserName", userName)
.formParam("ServiceName", BEDROCK)
.formParam("CredentialAgeDays", "1")
.when().post("/").then().statusCode(200)
.body(CREATE_RESULT + "Status", equalTo("Active"))
.extract().path(CREATE_RESULT + "ServiceSpecificCredentialId");
String member = "ListServiceSpecificCredentialsResponse"
+ ".ListServiceSpecificCredentialsResult.ServiceSpecificCredentials.member.";
iam("ListServiceSpecificCredentials").formParam("UserName", userName)
.when().post("/").then().statusCode(200)
.body(member + "Status", equalTo("Active"));
iam("UpdateServiceSpecificCredential")
.formParam("UserName", userName)
.formParam("ServiceSpecificCredentialId", id)
.formParam("Status", "Inactive")
.when().post("/").then().statusCode(200);
iam("ListServiceSpecificCredentials").formParam("UserName", userName)
.when().post("/").then().statusCode(200)
.body(member + "Status", equalTo("Inactive"));
}
/** Without it, the credential "will not expire", so no expiry is reported. */
@Test
void withoutCredentialAgeDaysThereIsNoExpiry() {
String userName = user();
iam("CreateServiceSpecificCredential")
.formParam("UserName", userName)
.formParam("ServiceName", BEDROCK)
.when().post("/").then().statusCode(200)
.body(not(containsString("ExpirationDate")));
}
/**
* Only the sourced services are supported, and an unsupported one is {@code NoSuchEntity} with
* status 404, not the {@code NotSupportedService} the model would suggest. AWS declares
* {@code ServiceNotSupportedException} on Create and List and then does not raise it: its
* recorded answer is this, for a nonexistent service, a malformed name and an existing but
* unsupported service alike.
*/
@Test
void anUnsupportedServiceIsRefused() {
String userName = user();
for (String service : List.of(
// A plausible name for a service that does not exist.
"nonexistentservice.amazonaws.com",
// A real service that does not support these credentials.
"lambda.amazonaws.com", "s3.amazonaws.com",
// Not a service principal at all.
"o3on3n3onosneo", "codecommit")) {
iam("CreateServiceSpecificCredential")
.formParam("UserName", userName)
.formParam("ServiceName", service)
.when().post("/").then().statusCode(404)
.body(containsString("NoSuchEntity"))
.body(containsString("No such service " + service
+ " is supported for Service Specific Credentials"))
.body(not(containsString("NotSupportedService")));
}
// An absent or blank name never reaches that check: it fails the required-parameter one.
iam("CreateServiceSpecificCredential")
.formParam("UserName", userName).formParam("ServiceName", "")
.when().post("/").then().statusCode(400).body(containsString("ValidationError"));
}
/** The list takes the same filter, so it rejects the same way. */
@Test
void theListRefusesAnUnsupportedServiceFilter() {
iam("ListServiceSpecificCredentials")
.formParam("UserName", user())
.formParam("ServiceName", "nonexistentservice.amazonaws.com")
.when().post("/").then().statusCode(404)
.body(containsString("NoSuchEntity"))
.body(containsString("No such service nonexistentservice.amazonaws.com "
+ "is supported for Service Specific Credentials"));
}
/** A supported service the user holds nothing for is an empty list, not an error. */
@Test
void theListOfASupportedServiceWithNoCredentialsIsEmpty() {
String userName = user();
create(userName, CODECOMMIT);
iam("ListServiceSpecificCredentials")
.formParam("UserName", userName)
.formParam("ServiceName", CASSANDRA)
.when().post("/").then().statusCode(200)
.body(not(containsString("ACCA")));
}
/** All six sourced services are accepted, and the quota is per service, so all six fit. */
@Test
void everySupportedServiceIsAccepted() {
String userName = user();
List<String> services = new ArrayList<>(PASSWORD_SERVICES);
services.addAll(LONG_TERM_KEY_SERVICES);
for (String service : services) {
create(userName, service);
}
iam("ListServiceSpecificCredentials").formParam("UserName", userName)
.when().post("/").then().statusCode(200)
.body("ListServiceSpecificCredentialsResponse"
+ ".ListServiceSpecificCredentialsResult.ServiceSpecificCredentials"
+ ".member.size()", equalTo(services.size()));
}
/**
* The quota is per service, not per user: "a maximum of two sets of service-specific
* credentials for each supported service per IAM user".
*/
@Test
void theQuotaIsTwoPerServiceRatherThanTwoPerUser() {
String userName = user();
create(userName, CODECOMMIT);
create(userName, CODECOMMIT);
iam("CreateServiceSpecificCredential")
.formParam("UserName", userName)
.formParam("ServiceName", CODECOMMIT)
.when().post("/").then().statusCode(409)
.body(containsString("LimitExceeded"));
// But another service still has its own budget, which is what "per service" means.
create(userName, CASSANDRA);
create(userName, CASSANDRA);
}
/**
* Two credentials for one service are told apart by a {@code +n} in the service user name,
* which the API Reference's examples show as {@code anika-at-<account>} and
* {@code anika+1-at-<account>}.
*/
@Test
void theSecondCredentialForAServiceGetsASuffixedServiceUserName() {
String userName = user();
String first = iam("CreateServiceSpecificCredential")
.formParam("UserName", userName).formParam("ServiceName", CODECOMMIT)
.when().post("/").then().statusCode(200)
.extract().path(CREATE_RESULT + "ServiceUserName");
String second = iam("CreateServiceSpecificCredential")
.formParam("UserName", userName).formParam("ServiceName", CODECOMMIT)
.when().post("/").then().statusCode(200)
.extract().path(CREATE_RESULT + "ServiceUserName");
assertEquals(userName + "-at-" + "000000000000", first);
assertEquals(userName + "+1-at-" + "000000000000", second);
assertNotEquals(first, second, "two credentials cannot share a service user name");
}
/**
* Deleting the unsuffixed credential frees its name, and the next create must take that free
* name rather than re-mint the suffixed one that is still in use. A suffix taken from the
* count rather than from what is free gives two live credentials the same service user name,
* which is what the caller authenticates with.
*/
@Test
void recreatingAfterADeleteNeverReusesALiveServiceUserName() {
String userName = user();
String firstId = create(userName, CODECOMMIT);
String secondName = iam("CreateServiceSpecificCredential")
.formParam("UserName", userName).formParam("ServiceName", CODECOMMIT)
.when().post("/").then().statusCode(200)
.extract().path(CREATE_RESULT + "ServiceUserName");
iam("DeleteServiceSpecificCredential")
.formParam("UserName", userName)
.formParam("ServiceSpecificCredentialId", firstId)
.when().post("/").then().statusCode(200);
String replacementName = iam("CreateServiceSpecificCredential")
.formParam("UserName", userName).formParam("ServiceName", CODECOMMIT)
.when().post("/").then().statusCode(200)
.extract().path(CREATE_RESULT + "ServiceUserName");
assertNotEquals(secondName, replacementName,
"the replacement took the name of the credential still in use");
assertEquals(userName + "-at-" + "000000000000", replacementName,
"the freed unsuffixed name is the lowest free one");
}
@Test
void theStatusCanBeSetToEveryDocumentedValue() {
String userName = user();
String id = create(userName, CODECOMMIT);
for (String status : List.of("Inactive", "Expired", "Active")) {
iam("UpdateServiceSpecificCredential")
.formParam("UserName", userName)
.formParam("ServiceSpecificCredentialId", id)
.formParam("Status", status)
.when().post("/").then().statusCode(200);
iam("ListServiceSpecificCredentials").formParam("UserName", userName)
.when().post("/").then().statusCode(200)
.body("ListServiceSpecificCredentialsResponse"
+ ".ListServiceSpecificCredentialsResult.ServiceSpecificCredentials"
+ ".member.Status", equalTo(status));
}
}
/** The reset replaces the secret and keeps everything that identifies the credential. */
@Test
void theResetChangesThePasswordAndNothingElse() {
String userName = user();
String before = iam("CreateServiceSpecificCredential")
.formParam("UserName", userName).formParam("ServiceName", CODECOMMIT)
.when().post("/").then().statusCode(200)
.extract().path(CREATE_RESULT + "ServicePassword");
String id = iam("ListServiceSpecificCredentials").formParam("UserName", userName)
.when().post("/").then().statusCode(200)
.extract().path("ListServiceSpecificCredentialsResponse"
+ ".ListServiceSpecificCredentialsResult.ServiceSpecificCredentials"
+ ".member.ServiceSpecificCredentialId");
String reset = "ResetServiceSpecificCredentialResponse"
+ ".ResetServiceSpecificCredentialResult.ServiceSpecificCredential.";
iam("ResetServiceSpecificCredential")
.formParam("UserName", userName)
.formParam("ServiceSpecificCredentialId", id)
.when().post("/").then().statusCode(200)
.body(reset + "ServiceSpecificCredentialId", equalTo(id))
.body(reset + "ServiceName", equalTo(CODECOMMIT))
.body(reset + "ServicePassword", not(equalTo(before)));
}
@Test
void deleteRemovesIt() {
String userName = user();
String id = create(userName, CODECOMMIT);
iam("DeleteServiceSpecificCredential")
.formParam("UserName", userName)
.formParam("ServiceSpecificCredentialId", id)
.when().post("/").then().statusCode(200);
iam("ListServiceSpecificCredentials").formParam("UserName", userName)
.when().post("/").then().statusCode(200).body(not(containsString(id)));
}
/** "This parameter cannot be specified together with UserName." */
@Test
void allUsersCannotBeCombinedWithAUserName() {
String userName = user();
create(userName, CODECOMMIT);
iam("ListServiceSpecificCredentials")
.formParam("UserName", userName)
.formParam("AllUsers", "true")
.when().post("/").then().statusCode(400)
.body(containsString("ValidationError"));
}
@Test
void allUsersListsBeyondOneUser() {
String first = user();
String second = user();
String firstId = create(first, CODECOMMIT);
String secondId = create(second, CODECOMMIT);
iam("ListServiceSpecificCredentials").formParam("AllUsers", "true")
.when().post("/").then().statusCode(200)
.body(containsString(firstId))
.body(containsString(secondId));
// And a single-user list sees only its own.
iam("ListServiceSpecificCredentials").formParam("UserName", first)
.when().post("/").then().statusCode(200)
.body(containsString(firstId))
.body(not(containsString(secondId)));
}
@Test
void theListCanBeFilteredByService() {
String userName = user();
String codecommitId = create(userName, CODECOMMIT);
String cassandraId = create(userName, CASSANDRA);
iam("ListServiceSpecificCredentials")
.formParam("UserName", userName)
.formParam("ServiceName", CASSANDRA)
.when().post("/").then().statusCode(200)
.body(containsString(cassandraId))
.body(not(containsString(codecommitId)));
}
@Test
void aCredentialOfAnotherUserCannotBeTouched() {
String owner = user();
String other = user();
String id = create(owner, CODECOMMIT);
iam("UpdateServiceSpecificCredential")
.formParam("UserName", other)
.formParam("ServiceSpecificCredentialId", id)
.formParam("Status", "Inactive")
.when().post("/").then().statusCode(404).body(containsString("NoSuchEntity"));
iam("ResetServiceSpecificCredential")
.formParam("UserName", other)
.formParam("ServiceSpecificCredentialId", id)
.when().post("/").then().statusCode(404).body(containsString("NoSuchEntity"));
iam("DeleteServiceSpecificCredential")
.formParam("UserName", other)
.formParam("ServiceSpecificCredentialId", id)
.when().post("/").then().statusCode(404).body(containsString("NoSuchEntity"));
}
/** The model makes both of the create's parameters required, and only the create's. */
@Test
void theCreateRequiresBothUserNameAndServiceName() {
iam("CreateServiceSpecificCredential").formParam("ServiceName", CODECOMMIT)
.when().post("/").then().statusCode(400)
.body(containsString("ValidationError")).body(containsString("userName"));
iam("CreateServiceSpecificCredential").formParam("UserName", user())
.when().post("/").then().statusCode(400)
.body(containsString("ValidationError")).body(containsString("serviceName"));
}
/** {@code Status} is required on the update, and only takes the three enum values. */
@Test
void theUpdateRequiresAStatusFromTheEnum() {
String userName = user();
String id = create(userName, CODECOMMIT);
for (String status : List.of("active", "Deleted", "")) {
iam("UpdateServiceSpecificCredential")
.formParam("UserName", userName)
.formParam("ServiceSpecificCredentialId", id)
.formParam("Status", status)
.when().post("/").then().statusCode(400)
.body(containsString("ValidationError"));
}
iam("UpdateServiceSpecificCredential")
.formParam("UserName", userName)
.formParam("ServiceSpecificCredentialId", id)
.when().post("/").then().statusCode(400)
.body(containsString("ValidationError"));
}
@Test
void anAbsentCredentialIdIsAValidationError() {
String userName = user();
iam("DeleteServiceSpecificCredential").formParam("UserName", userName)
.when().post("/").then().statusCode(400)
.body(containsString("ValidationError"))
.body(containsString("serviceSpecificCredentialId"));
}
/**
* 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.
*/
@Test
void credentialActionsRouteViaTheActionFallbackWhenAuthHeaderAbsent() {
for (String action : List.of("CreateServiceSpecificCredential",
"ListServiceSpecificCredentials", "UpdateServiceSpecificCredential",
"ResetServiceSpecificCredential", "DeleteServiceSpecificCredential")) {
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,675 @@
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.iam.model.ServiceSpecificCredential;
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.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
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 java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
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 service-specific credential store the wire tests cannot reach: that it
* survives a restart, that one account cannot see another's, that the per-service quota holds when
* creates race, and that a user's credentials block a delete and follow a rename.
*/
class ServiceSpecificCredentialStateTest {
private static final String ACCOUNT_A = "000000000000";
private static final String ACCOUNT_B = "111111111111";
private static final String CODECOMMIT = "codecommit.amazonaws.com";
private static final String CASSANDRA = "cassandra.amazonaws.com";
private static final String BEDROCK = "bedrock.amazonaws.com";
private static final String LOGS = "logs.amazonaws.com";
@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, ServiceSpecificCredential> credentials, 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<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
credentials,
new RegionResolver("us-east-1", defaultAccount), false, null);
}
/**
* The secret half is disclosed once and stored, so a restart that lost it would leave a
* credential nobody can authenticate with and no way to tell. Checked on both shapes.
*/
@Test
void aCredentialSurvivesARestart(@TempDir Path dir) {
Path file = dir.resolve("iam-service-credentials.json");
PersistentStorage<String, ServiceSpecificCredential> first =
new PersistentStorage<>(file, new TypeReference<>() {});
first.load();
IamService before = newService(first, ACCOUNT_A);
before.createUser("restart-user", "/");
ServiceSpecificCredential password =
before.createServiceSpecificCredential("restart-user", CODECOMMIT, null);
ServiceSpecificCredential apiKey =
before.createServiceSpecificCredential("restart-user", BEDROCK, 30);
before.updateServiceSpecificCredential("restart-user",
password.getServiceSpecificCredentialId(), "Inactive");
PersistentStorage<String, ServiceSpecificCredential> second =
new PersistentStorage<>(file, new TypeReference<>() {});
second.load();
IamService after = newService(second, ACCOUNT_A);
after.createUser("restart-user", "/");
Map<String, ServiceSpecificCredential> reloaded =
after.listServiceSpecificCredentials("restart-user", null, false).stream()
.collect(Collectors.toMap(
ServiceSpecificCredential::getServiceName, c -> c));
assertEquals(2, reloaded.size());
ServiceSpecificCredential reloadedPassword = reloaded.get(CODECOMMIT);
assertEquals(password.getServiceSpecificCredentialId(),
reloadedPassword.getServiceSpecificCredentialId());
assertEquals(password.getServiceUserName(), reloadedPassword.getServiceUserName());
assertEquals(password.getServicePassword(), reloadedPassword.getServicePassword(),
"the password must survive: it is disclosed once and never recoverable");
// A default of Active would hide the loss of this field, so it is the one to check.
assertEquals("Inactive", reloadedPassword.getStatus());
assertEquals(password.getCreateDate(), reloadedPassword.getCreateDate());
ServiceSpecificCredential reloadedApiKey = reloaded.get(BEDROCK);
assertEquals(apiKey.getServiceCredentialAlias(),
reloadedApiKey.getServiceCredentialAlias());
assertEquals(apiKey.getServiceCredentialSecret(),
reloadedApiKey.getServiceCredentialSecret());
assertEquals(apiKey.getExpirationDate(), reloadedApiKey.getExpirationDate(),
"an expiry that did not survive would make an expired credential usable");
}
/**
* One scoped store behind two services, each defaulting to its own account, because the
* service user name is minted from the account and so has to differ between them.
*/
@Test
void oneAccountCannotSeeAnothersCredentials() {
AtomicReference<String> account = new AtomicReference<>(ACCOUNT_A);
AccountAwareStorageBackend<ServiceSpecificCredential> store =
new AccountAwareStorageBackend<>(
new InMemoryStorage<>(), requestContextFor(account), ACCOUNT_A);
IamService inAccountA = newService(store, ACCOUNT_A);
IamService inAccountB = newService(store, ACCOUNT_B);
inAccountA.createUser("shared-name", "/");
inAccountB.createUser("shared-name", "/");
ServiceSpecificCredential inA =
inAccountA.createServiceSpecificCredential("shared-name", CODECOMMIT, null);
assertEquals(1,
inAccountA.listServiceSpecificCredentials("shared-name", null, false).size());
// Each service has its own users store, so the user is already present under the same name
// on both sides. Only the credential store is shared, so a leak is the only thing that can
// fail this.
account.set(ACCOUNT_B);
assertEquals(0,
inAccountB.listServiceSpecificCredentials("shared-name", null, false).size(),
"account B must not see account A's credential");
// And B filling its own quota must not be refused for what A already holds.
ServiceSpecificCredential inB =
inAccountB.createServiceSpecificCredential("shared-name", CODECOMMIT, null);
inAccountB.createServiceSpecificCredential("shared-name", CODECOMMIT, null);
assertEquals(2,
inAccountB.listServiceSpecificCredentials("shared-name", null, false).size());
// The service user name carries the account, so B's first is not a copy of A's.
assertTrue(inB.getServiceUserName().endsWith("-at-" + ACCOUNT_B), inB.getServiceUserName());
assertNotEquals(inA.getServiceUserName(), inB.getServiceUserName());
// Nor may B reach A's credential by its id, which it can read from nowhere but is a guess
// away in a flat store.
assertThrows(AwsException.class, () -> inAccountB.deleteServiceSpecificCredential(
"shared-name", inA.getServiceSpecificCredentialId()));
account.set(ACCOUNT_A);
assertEquals(1,
inAccountA.listServiceSpecificCredentials("shared-name", null, false).size(),
"account A's view must be unchanged by account B's creates");
}
/**
* The quota is counted inside the same lock as the write, so concurrent creates cannot both
* see room for the last slot. Asserted by counting what actually succeeded, because an
* invariant phrased as "the store holds at most two" passes with the lock removed too.
*/
@Test
void concurrentCreatesCannotExceedTheQuota() throws Exception {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
service.createUser("race-user", "/");
int attempts = 12;
ExecutorService pool = Executors.newFixedThreadPool(attempts);
CountDownLatch start = new CountDownLatch(1);
AtomicInteger accepted = new AtomicInteger();
try {
for (int i = 0; i < attempts; i++) {
pool.submit(() -> {
start.await();
try {
service.createServiceSpecificCredential("race-user", CODECOMMIT, null);
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), "creates did not finish");
} finally {
pool.shutdownNow();
}
assertEquals(2, accepted.get(), "exactly the quota should have been accepted");
assertEquals(2, service.listServiceSpecificCredentials("race-user", null, false).size());
}
/**
* The quota is per service, and three services racing at once is where a count taken over the
* wrong set shows: counting the user's credentials rather than the user's for that service
* would stop after two in total.
*/
@Test
void racingCreatesAcrossServicesEachGetTheirOwnQuota() throws Exception {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
service.createUser("multi-race", "/");
List<String> services = List.of(CODECOMMIT, CASSANDRA, BEDROCK);
int perService = 6;
ExecutorService pool = Executors.newFixedThreadPool(services.size() * perService);
CountDownLatch start = new CountDownLatch(1);
try {
for (String serviceName : services) {
for (int i = 0; i < perService; i++) {
pool.submit(() -> {
start.await();
try {
service.createServiceSpecificCredential(
"multi-race", serviceName, null);
} catch (AwsException expected) {
// LimitExceeded once that service has its two.
}
return null;
});
}
}
start.countDown();
pool.shutdown();
assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS), "creates did not finish");
} finally {
pool.shutdownNow();
}
List<ServiceSpecificCredential> held =
service.listServiceSpecificCredentials("multi-race", null, false);
assertEquals(6, held.size(), "two for each of the three services");
for (String serviceName : services) {
assertEquals(2, held.stream()
.filter(c -> serviceName.equals(c.getServiceName())).count(),
"two for " + serviceName);
}
}
/**
* Two credentials for one service must not share a service user name: it is what the caller
* authenticates with, so a collision makes one of them unusable. The {@code +n} comes from a
* count taken under the lock, which is the only reason racing creates cannot both read zero.
*/
@Test
void racingCreatesNeverShareAServiceUserName() throws Exception {
for (int trial = 0; trial < 60; trial++) {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
service.createUser("suffix-race", "/");
Set<String> names = ConcurrentHashMap.newKeySet();
ExecutorService pool = Executors.newFixedThreadPool(2);
CountDownLatch start = new CountDownLatch(1);
try {
for (int i = 0; i < 2; i++) {
pool.submit(() -> {
start.await();
names.add(service.createServiceSpecificCredential(
"suffix-race", CODECOMMIT, null).getServiceUserName());
return null;
});
}
start.countDown();
pool.shutdown();
assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS), "trial did not finish");
} finally {
pool.shutdownNow();
}
assertEquals(2, names.size(), "trial " + trial
+ ": both credentials got the same service user name " + names);
}
}
/** AWS lists the service-specific credential among the items to remove before a user. */
@Test
void aUserWithACredentialCannotBeDeleted() {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
service.createUser("blocked-user", "/");
String id = service.createServiceSpecificCredential("blocked-user", CODECOMMIT, null)
.getServiceSpecificCredentialId();
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());
service.deleteServiceSpecificCredential("blocked-user", id);
service.deleteUser("blocked-user");
}
/**
* A rename must carry the credentials with it. Left behind, one is stranded on a user name
* that no longer exists: invisible to its owner, because listing goes through the user, and so
* undeletable.
*/
@Test
void aRenameCarriesTheCredentials() {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
service.createUser("before-rename", "/");
ServiceSpecificCredential created =
service.createServiceSpecificCredential("before-rename", CODECOMMIT, null);
service.updateUser("before-rename", "after-rename", null);
List<ServiceSpecificCredential> moved =
service.listServiceSpecificCredentials("after-rename", null, false);
assertEquals(1, moved.size(), "the credential should have followed the rename");
assertEquals(created.getServiceSpecificCredentialId(),
moved.getFirst().getServiceSpecificCredentialId());
assertEquals("after-rename", moved.getFirst().getUserName());
// The service user name is minted from the name at creation and is what the caller
// authenticates with, so the rename leaves it alone rather than silently invalidating it.
assertEquals(created.getServiceUserName(), moved.getFirst().getServiceUserName());
service.deleteServiceSpecificCredential("after-rename",
created.getServiceSpecificCredentialId());
service.deleteUser("after-rename");
}
/**
* A create must never land on a user DeleteUser has just removed. Both hold the credential
* lock, so only two orders exist: the delete is refused because a credential is there, or the
* create fails because the user is gone. A credential owned by a user that does not exist is
* the state neither order may produce, and nothing in the API would report it, so this asserts
* against the store.
*/
@Test
void aCreateNeverStrandsACredentialOnADeletedUser() throws Exception {
for (int trial = 0; trial < 60; trial++) {
InMemoryStorage<String, ServiceSpecificCredential> store = new InMemoryStorage<>();
IamService service = newService(store, ACCOUNT_A);
service.createUser("delete-race", "/");
ExecutorService pool = Executors.newFixedThreadPool(2);
CountDownLatch start = new CountDownLatch(1);
try {
pool.submit(() -> {
start.await();
try {
service.createServiceSpecificCredential("delete-race", CODECOMMIT, null);
} 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 create 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;
}
if (!userExists) {
assertTrue(store.scan(key -> true).isEmpty(),
"trial " + trial + ": credential left behind on a deleted user");
}
}
}
/**
* The same hazard on the rename path. Ran many times because the window between capturing the
* credentials to move and republishing the user is a few statements wide: a handful of trials
* passes even with the rename's lock removed.
*/
@Test
void aCreateNeverStrandsACredentialOnTheOldNameDuringARename() throws Exception {
for (int trial = 0; trial < 300; trial++) {
InMemoryStorage<String, ServiceSpecificCredential> store = new InMemoryStorage<>();
IamService service = newService(store, ACCOUNT_A);
service.createUser("rename-race", "/");
ExecutorService pool = Executors.newFixedThreadPool(2);
CountDownLatch start = new CountDownLatch(1);
try {
pool.submit(() -> {
start.await();
try {
service.createServiceSpecificCredential("rename-race", CODECOMMIT, null);
} catch (AwsException expected) {
// NoSuchEntity when the rename won.
}
return null;
});
pool.submit(() -> {
start.await();
service.updateUser("rename-race", "renamed", null);
return null;
});
start.countDown();
pool.shutdown();
assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS), "trial did not finish");
} finally {
pool.shutdownNow();
}
List<ServiceSpecificCredential> all = store.scan(key -> true);
for (ServiceSpecificCredential credential : all) {
assertEquals("renamed", credential.getUserName(), "trial " + trial
+ ": credential stranded on the pre-rename name");
}
// And it is reachable, which is what being stranded costs.
assertEquals(all.size(),
service.listServiceSpecificCredentials("renamed", null, false).size());
}
}
/**
* The version behind the {@code +n} comes from what is free, not from how many exist. Holding
* only the suffixed credential, a count would mint the same suffix again and two live
* credentials would share the name the caller authenticates with.
*/
@Test
void aFreedServiceUserNameIsReusedAndALiveOneIsNot() {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
service.createUser("suffix-user", "/");
ServiceSpecificCredential first =
service.createServiceSpecificCredential("suffix-user", CODECOMMIT, null);
ServiceSpecificCredential second =
service.createServiceSpecificCredential("suffix-user", CODECOMMIT, null);
assertEquals("suffix-user-at-" + ACCOUNT_A, first.getServiceUserName());
assertEquals("suffix-user+1-at-" + ACCOUNT_A, second.getServiceUserName());
service.deleteServiceSpecificCredential(
"suffix-user", first.getServiceSpecificCredentialId());
ServiceSpecificCredential replacement =
service.createServiceSpecificCredential("suffix-user", CODECOMMIT, null);
assertEquals(first.getServiceUserName(), replacement.getServiceUserName(),
"the freed name is the lowest free one");
assertNotEquals(second.getServiceUserName(), replacement.getServiceUserName(),
"the replacement took the name of the credential still in use");
// The other direction too: free the suffixed one and the suffix comes back, not the base.
service.deleteServiceSpecificCredential(
"suffix-user", second.getServiceSpecificCredentialId());
ServiceSpecificCredential third =
service.createServiceSpecificCredential("suffix-user", CODECOMMIT, null);
assertEquals(second.getServiceUserName(), third.getServiceUserName());
}
/**
* The same reasoning for a long-term key's alias, which carries the same version. Documented
* as including "the IAM user name and a suffix containing version and creation information".
*/
@Test
void aLongTermKeyAliasCarriesTheUserNameAndAFreeVersion() {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
service.createUser("alias-user", "/");
ServiceSpecificCredential first =
service.createServiceSpecificCredential("alias-user", BEDROCK, null);
ServiceSpecificCredential second =
service.createServiceSpecificCredential("alias-user", BEDROCK, null);
String today = DateTimeFormatter.ofPattern("yyyyMMdd").withZone(ZoneOffset.UTC)
.format(first.getCreateDate());
assertEquals("alias-user+v1-" + today, first.getServiceCredentialAlias());
assertEquals("alias-user+v2-" + today, second.getServiceCredentialAlias());
// The alias is the public half, so it must satisfy serviceCredentialAlias's own pattern.
assertTrue(first.getServiceCredentialAlias().matches("[\\w+=,.@-]+"),
first.getServiceCredentialAlias());
assertTrue(first.getServiceCredentialAlias().length() <= 200);
service.deleteServiceSpecificCredential(
"alias-user", first.getServiceSpecificCredentialId());
ServiceSpecificCredential replacement =
service.createServiceSpecificCredential("alias-user", BEDROCK, null);
assertNotEquals(second.getServiceCredentialAlias(),
replacement.getServiceCredentialAlias(),
"the replacement took the alias of the credential still in use");
}
/**
* A credential keeps the service user name it was minted with across a rename, so the freed
* IAM name must not mint that same credential name a second time. Scoping the uniqueness
* check to one user's credentials misses this: the new user holds none.
*/
@Test
void aRenamedUsersNameCannotBeMintedAgainByItsSuccessor() {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
service.createUser("anika", "/");
ServiceSpecificCredential original =
service.createServiceSpecificCredential("anika", CODECOMMIT, null);
assertEquals("anika-at-" + ACCOUNT_A, original.getServiceUserName());
service.updateUser("anika", "bob", null);
assertEquals("anika-at-" + ACCOUNT_A, service
.listServiceSpecificCredentials("bob", null, false)
.getFirst().getServiceUserName(),
"the rename leaves the minted name alone, which is what creates the hazard");
// A brand new user takes the freed IAM name and asks for the same service.
service.createUser("anika", "/");
ServiceSpecificCredential successor =
service.createServiceSpecificCredential("anika", CODECOMMIT, null);
assertNotEquals(original.getServiceUserName(), successor.getServiceUserName(),
"two live credentials would share the name the caller authenticates with");
}
/**
* An alias carries no service, so two services' keys for one user on the same day would
* collide on {@code <user>+v1-<date>} unless the version is checked across the whole store.
* This needs no rename and no delete: it is two creates.
*/
@Test
void twoServicesKeysForOneUserCannotShareAnAliasOnTheSameDay() {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
service.createUser("alias-clash", "/");
ServiceSpecificCredential bedrock =
service.createServiceSpecificCredential("alias-clash", BEDROCK, null);
ServiceSpecificCredential logs =
service.createServiceSpecificCredential("alias-clash", LOGS, null);
assertNotEquals(bedrock.getServiceCredentialAlias(), logs.getServiceCredentialAlias(),
"both were created the same day and the alias has no service in it");
// Both still carry the user name and a version, which is what AWS documents.
assertTrue(bedrock.getServiceCredentialAlias().startsWith("alias-clash+v"),
bedrock.getServiceCredentialAlias());
assertTrue(logs.getServiceCredentialAlias().startsWith("alias-clash+v"),
logs.getServiceCredentialAlias());
}
/** The same hazard for the password shape: two services, one user, no suffix to tell apart. */
@Test
void twoServicesCredentialsForOneUserCannotShareAServiceUserName() {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
service.createUser("name-clash", "/");
ServiceSpecificCredential codecommit =
service.createServiceSpecificCredential("name-clash", CODECOMMIT, null);
ServiceSpecificCredential cassandra =
service.createServiceSpecificCredential("name-clash", CASSANDRA, null);
assertNotEquals(codecommit.getServiceUserName(), cassandra.getServiceUserName());
}
/**
* A key past its {@code ExpirationDate} reports {@code Expired}, and an update to
* {@code Active} cannot undo that: the status is derived on read, so the stored value is left
* as the caller set it while the reported one tells the truth.
*
* <p>The expiry has to be planted directly in the store, because the smallest
* {@code CredentialAgeDays} AWS allows is one day, so no sequence of calls reaches a past
* expiry.
*/
@Test
void aKeyPastItsExpiryReportsExpiredAndCannotBeReactivated() {
InMemoryStorage<String, ServiceSpecificCredential> store = new InMemoryStorage<>();
IamService service = newService(store, ACCOUNT_A);
service.createUser("expiry-user", "/");
ServiceSpecificCredential credential =
service.createServiceSpecificCredential("expiry-user", BEDROCK, 1);
assertEquals("Active", service.reportedStatus(credential));
credential.setExpirationDate(Instant.now().minusSeconds(60));
store.put(credential.getServiceSpecificCredentialId(), credential);
assertEquals("Expired", service.reportedStatus(credential));
assertEquals("Expired", service.reportedStatus(service
.listServiceSpecificCredentials("expiry-user", null, false).getFirst()));
service.updateServiceSpecificCredential(
"expiry-user", credential.getServiceSpecificCredentialId(), "Active");
ServiceSpecificCredential reactivated = service
.listServiceSpecificCredentials("expiry-user", null, false).getFirst();
assertEquals("Active", reactivated.getStatus(),
"the stored status is still what the caller set");
assertEquals("Expired", service.reportedStatus(reactivated),
"but an expired key cannot be made to report Active");
}
/** Expiry is terminal, so it outranks a status the caller set to Inactive. */
@Test
void anExpiredKeyReportsExpiredRatherThanInactive() {
InMemoryStorage<String, ServiceSpecificCredential> store = new InMemoryStorage<>();
IamService service = newService(store, ACCOUNT_A);
service.createUser("inactive-user", "/");
ServiceSpecificCredential credential =
service.createServiceSpecificCredential("inactive-user", BEDROCK, 1);
service.updateServiceSpecificCredential(
"inactive-user", credential.getServiceSpecificCredentialId(), "Inactive");
credential.setExpirationDate(Instant.now().minusSeconds(60));
store.put(credential.getServiceSpecificCredentialId(), credential);
assertEquals("Expired", service.reportedStatus(credential));
}
/** A credential with no expiry, or one still in date, reports exactly what is stored. */
@Test
void aCredentialWithinOrWithoutAnExpiryReportsItsStoredStatus() {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
service.createUser("unexpired-user", "/");
ServiceSpecificCredential noExpiry =
service.createServiceSpecificCredential("unexpired-user", CODECOMMIT, null);
assertNull(noExpiry.getExpirationDate());
assertEquals("Active", service.reportedStatus(noExpiry));
service.updateServiceSpecificCredential(
"unexpired-user", noExpiry.getServiceSpecificCredentialId(), "Inactive");
assertEquals("Inactive", service.reportedStatus(service
.listServiceSpecificCredentials("unexpired-user", CODECOMMIT, false).getFirst()),
"no expiry means the stored status is reported untouched");
ServiceSpecificCredential inDate =
service.createServiceSpecificCredential("unexpired-user", BEDROCK, 36600);
assertEquals("Active", service.reportedStatus(inDate));
}
/** The reset replaces only the secret of the shape the service actually uses. */
@Test
void theResetTouchesOnlyTheSecretOfTheRelevantShape() {
IamService service = newService(new InMemoryStorage<>(), ACCOUNT_A);
service.createUser("reset-user", "/");
ServiceSpecificCredential password =
service.createServiceSpecificCredential("reset-user", CODECOMMIT, null);
String oldPassword = password.getServicePassword();
ServiceSpecificCredential resetPassword = service.resetServiceSpecificCredential(
"reset-user", password.getServiceSpecificCredentialId());
assertNotEquals(oldPassword, resetPassword.getServicePassword());
assertNull(resetPassword.getServiceCredentialSecret(),
"a password credential must not grow an API-key secret on reset");
ServiceSpecificCredential apiKey =
service.createServiceSpecificCredential("reset-user", BEDROCK, null);
String oldSecret = apiKey.getServiceCredentialSecret();
String alias = apiKey.getServiceCredentialAlias();
ServiceSpecificCredential resetApiKey = service.resetServiceSpecificCredential(
"reset-user", apiKey.getServiceSpecificCredentialId());
assertNotEquals(oldSecret, resetApiKey.getServiceCredentialSecret());
assertEquals(alias, resetApiKey.getServiceCredentialAlias(),
"the alias identifies the credential, so a reset keeps it");
assertNull(resetApiKey.getServicePassword(),
"an API-key credential must not grow a password on reset");
}
}
@@ -72,6 +72,7 @@ class SigningCertificateStateTest {
new InMemoryStorage<>(),
certificates,
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", defaultAccount), false, null);
}
@@ -88,6 +89,7 @@ class SigningCertificateStateTest {
new InMemoryStorage<>(),
certificates,
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", defaultAccount), false, null);
}
@@ -75,6 +75,7 @@ class SshPublicKeyStateTest {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(),
keys,
new InMemoryStorage<>(),
new RegionResolver("us-east-1", defaultAccount), false, null);
}
@@ -53,6 +53,7 @@ class VirtualMfaAccountScopeTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", ACCOUNT_A), false, null);
VirtualMfaDevice device = service.createVirtualMfaDevice("shared-name", "/", Map.of());
@@ -93,6 +94,7 @@ class VirtualMfaAccountScopeTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", ACCOUNT_A), false, null);
VirtualMfaDevice inA = service.createVirtualMfaDevice("same-name", "/", Map.of());
@@ -40,6 +40,7 @@ class VirtualMfaConcurrencyTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("eu-central-1", "000000000000"), false, null);
}