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

@@ -0,0 +1,314 @@
package com.floci.test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.CreateServiceSpecificCredentialRequest;
import software.amazon.awssdk.services.iam.model.CreateServiceSpecificCredentialResponse;
import software.amazon.awssdk.services.iam.model.CreateUserRequest;
import software.amazon.awssdk.services.iam.model.DeleteConflictException;
import software.amazon.awssdk.services.iam.model.DeleteServiceSpecificCredentialRequest;
import software.amazon.awssdk.services.iam.model.DeleteUserRequest;
import software.amazon.awssdk.services.iam.model.LimitExceededException;
import software.amazon.awssdk.services.iam.model.ListServiceSpecificCredentialsRequest;
import software.amazon.awssdk.services.iam.model.ListServiceSpecificCredentialsResponse;
import software.amazon.awssdk.services.iam.model.NoSuchEntityException;
import software.amazon.awssdk.services.iam.model.ResetServiceSpecificCredentialRequest;
import software.amazon.awssdk.services.iam.model.ResetServiceSpecificCredentialResponse;
import software.amazon.awssdk.services.iam.model.ServiceNotSupportedException;
import software.amazon.awssdk.services.iam.model.ServiceSpecificCredential;
import software.amazon.awssdk.services.iam.model.ServiceSpecificCredentialMetadata;
import software.amazon.awssdk.services.iam.model.StatusType;
import software.amazon.awssdk.services.iam.model.UpdateServiceSpecificCredentialRequest;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* Service-specific credentials driven through the AWS SDK rather than hand-written requests.
*
* <p>This is the check the handcrafted XML assertions cannot make: the SDK parses the response
* against its own model, so a missing required member, a mis-named element or a timestamp in the
* wrong format fails here even though the raw XML looked right. The shape marks CreateDate,
* ServiceName, ServiceSpecificCredentialId, UserName and Status required.
*
* <p>It is also where the error types are really checked, which matters most for the unsupported
* service: the model declares {@code ServiceNotSupportedException} on this operation and AWS sends
* {@code NoSuchEntity} instead, so the test asserts the type AWS actually sends and that it is not
* the modelled one.
*/
@DisplayName("IAM Service-Specific Credentials")
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class IamServiceSpecificCredentialTest {
private static final String USER_NAME = "sdk-test-service-credential-user";
private static final String CODECOMMIT = "codecommit.amazonaws.com";
private static final String BEDROCK = "bedrock.amazonaws.com";
/** The services whose credential is a long-term API key rather than a 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 IamClient iam;
private static String credentialId;
@BeforeAll
static void setup() {
iam = TestFixtures.iamClient();
cleanupUser();
iam.createUser(CreateUserRequest.builder().userName(USER_NAME).build());
}
@AfterAll
static void cleanup() {
cleanupUser();
}
private static void cleanupUser() {
if (iam == null) {
return;
}
try {
ListServiceSpecificCredentialsResponse existing = iam.listServiceSpecificCredentials(
ListServiceSpecificCredentialsRequest.builder().userName(USER_NAME).build());
for (ServiceSpecificCredentialMetadata credential
: existing.serviceSpecificCredentials()) {
deleteCredential(credential.serviceSpecificCredentialId());
}
iam.deleteUser(DeleteUserRequest.builder().userName(USER_NAME).build());
} catch (NoSuchEntityException expected) {
// Nothing left over from an earlier run, which is the normal case.
}
}
private static ServiceSpecificCredential create(String serviceName) {
return iam.createServiceSpecificCredential(CreateServiceSpecificCredentialRequest.builder()
.userName(USER_NAME)
.serviceName(serviceName)
.build())
.serviceSpecificCredential();
}
private static void deleteCredential(String id) {
iam.deleteServiceSpecificCredential(DeleteServiceSpecificCredentialRequest.builder()
.userName(USER_NAME)
.serviceSpecificCredentialId(id)
.build());
}
@Test
@Order(1)
@DisplayName("CreateServiceSpecificCredential returns a parseable credential with a password")
void create() {
CreateServiceSpecificCredentialResponse response = iam.createServiceSpecificCredential(
CreateServiceSpecificCredentialRequest.builder()
.userName(USER_NAME)
.serviceName(CODECOMMIT)
.build());
ServiceSpecificCredential credential = response.serviceSpecificCredential();
assertThat(credential).as("the response must carry the credential").isNotNull();
assertThat(credential.userName()).isEqualTo(USER_NAME);
assertThat(credential.serviceName()).isEqualTo(CODECOMMIT);
assertThat(credential.status()).isEqualTo(StatusType.ACTIVE);
assertThat(credential.createDate()).as("CreateDate must parse as a timestamp").isNotNull();
assertThat(credential.servicePassword())
.as("the password is disclosed only here").isNotNull();
assertThat(credential.serviceUserName())
.as("the generated user name combines the IAM user and the account")
.startsWith(USER_NAME + "-at-");
// serviceSpecificCredentialId is 20 to 128 word characters, and the prefix table gives ACCA.
assertThat(credential.serviceSpecificCredentialId())
.startsWith("ACCA")
.matches("\\w{20,128}");
// The password shape and the API-key shape are exclusive.
assertThat(credential.serviceCredentialSecret()).isNull();
assertThat(credential.expirationDate()).isNull();
credentialId = credential.serviceSpecificCredentialId();
}
@Test
@Order(2)
@DisplayName("ListServiceSpecificCredentials returns metadata without the password")
void list() {
ListServiceSpecificCredentialsResponse response = iam.listServiceSpecificCredentials(
ListServiceSpecificCredentialsRequest.builder().userName(USER_NAME).build());
assertThat(response.serviceSpecificCredentials()).hasSize(1);
ServiceSpecificCredentialMetadata credential = response.serviceSpecificCredentials().get(0);
assertThat(credential.serviceSpecificCredentialId()).isEqualTo(credentialId);
assertThat(credential.userName()).isEqualTo(USER_NAME);
assertThat(credential.serviceName()).isEqualTo(CODECOMMIT);
assertThat(credential.createDate()).isNotNull();
assertThat(credential.serviceUserName()).isNotNull();
assertThat(response.isTruncated()).isNotEqualTo(true);
// ServiceSpecificCredentialMetadata has no accessor for either secret at all, which is the
// model's own way of saying the list never carries one.
}
/**
* Each of the four is an alias and a secret rather than a user name and a password, and each
* takes CredentialAgeDays, which the model allows only for a long-term API key service.
*/
@Test
@Order(3)
@DisplayName("Every long-term API key service gives an alias, a secret and an expiry")
void longTermApiKeyShape() {
for (String service : LONG_TERM_KEY_SERVICES) {
ServiceSpecificCredential credential = iam.createServiceSpecificCredential(
CreateServiceSpecificCredentialRequest.builder()
.userName(USER_NAME)
.serviceName(service)
.credentialAgeDays(30)
.build())
.serviceSpecificCredential();
assertThat(credential.serviceName()).isEqualTo(service);
assertThat(credential.serviceCredentialAlias())
.as("the alias includes the IAM user name and a version suffix")
.startsWith(USER_NAME + "+v1-");
assertThat(credential.serviceCredentialSecret())
.as("the secret is returned only on the create").isNotNull();
assertThat(credential.expirationDate())
.as("CredentialAgeDays must come back as a parseable ExpirationDate")
.isNotNull()
.isAfter(credential.createDate());
assertThat(credential.servicePassword()).as("not the password shape").isNull();
assertThat(credential.serviceUserName()).isNull();
deleteCredential(credential.serviceSpecificCredentialId());
}
}
@Test
@Order(4)
@DisplayName("CredentialAgeDays is rejected for a service without long-term API keys")
void credentialAgeDaysIsOnlyForLongTermKeyServices() {
assertThatThrownBy(() -> iam.createServiceSpecificCredential(
CreateServiceSpecificCredentialRequest.builder()
.userName(USER_NAME)
.serviceName(CODECOMMIT)
.credentialAgeDays(30)
.build()))
.hasMessageContaining("long-term API");
}
@Test
@Order(5)
@DisplayName("UpdateServiceSpecificCredential sets the status and the SDK reads it back")
void updateStatus() {
iam.updateServiceSpecificCredential(UpdateServiceSpecificCredentialRequest.builder()
.userName(USER_NAME)
.serviceSpecificCredentialId(credentialId)
.status(StatusType.INACTIVE)
.build());
ListServiceSpecificCredentialsResponse response = iam.listServiceSpecificCredentials(
ListServiceSpecificCredentialsRequest.builder().userName(USER_NAME).build());
assertThat(response.serviceSpecificCredentials().get(0).status())
.as("the status must come back as a value the SDK model knows")
.isEqualTo(StatusType.INACTIVE);
iam.updateServiceSpecificCredential(UpdateServiceSpecificCredentialRequest.builder()
.userName(USER_NAME)
.serviceSpecificCredentialId(credentialId)
.status(StatusType.ACTIVE)
.build());
}
@Test
@Order(6)
@DisplayName("ResetServiceSpecificCredential returns a new password and keeps the identity")
void reset() {
ResetServiceSpecificCredentialResponse response = iam.resetServiceSpecificCredential(
ResetServiceSpecificCredentialRequest.builder()
.userName(USER_NAME)
.serviceSpecificCredentialId(credentialId)
.build());
ServiceSpecificCredential credential = response.serviceSpecificCredential();
assertThat(credential.serviceSpecificCredentialId()).isEqualTo(credentialId);
assertThat(credential.serviceName()).isEqualTo(CODECOMMIT);
assertThat(credential.servicePassword())
.as("the reset discloses the new password").isNotNull();
}
/**
* The quota is per service, so filling CodeCommit's two must leave Bedrock's own two
* available. A count taken over the user rather than the service would fail the second half.
*/
@Test
@Order(7)
@DisplayName("Two credentials per service, and each service has its own allowance")
void quotaIsPerService() {
ServiceSpecificCredential second = create(CODECOMMIT);
assertThat(second.serviceSpecificCredentialId()).isNotEqualTo(credentialId);
assertThat(second.serviceUserName())
.as("two credentials for one service cannot share a user name")
.startsWith(USER_NAME + "+1-at-");
assertThatThrownBy(() -> create(CODECOMMIT)).isInstanceOf(LimitExceededException.class);
ServiceSpecificCredential otherService = create(BEDROCK);
deleteCredential(otherService.serviceSpecificCredentialId());
deleteCredential(second.serviceSpecificCredentialId());
}
/**
* An unsupported service is {@code NoSuchEntity}, not the {@code NotSupportedService} the
* model declares on this operation. AWS never raises the modelled one, so a client written
* against the model and catching {@link ServiceNotSupportedException} catches nothing: the
* assertion here is that the typed exception is the one AWS actually sends.
*/
@Test
@Order(8)
@DisplayName("An unsupported service is NoSuchEntity, not the modelled ServiceNotSupported")
void unsupportedService() {
assertThatThrownBy(() -> create("lambda.amazonaws.com"))
.isInstanceOf(NoSuchEntityException.class)
.isNotInstanceOf(ServiceNotSupportedException.class)
.hasMessageContaining("No such service lambda.amazonaws.com is supported for "
+ "Service Specific Credentials");
}
@Test
@Order(9)
@DisplayName("A credential blocks DeleteUser until it is deleted")
void blocksDeleteUser() {
assertThatThrownBy(() ->
iam.deleteUser(DeleteUserRequest.builder().userName(USER_NAME).build()))
.isInstanceOf(DeleteConflictException.class);
deleteCredential(credentialId);
ListServiceSpecificCredentialsResponse response = iam.listServiceSpecificCredentials(
ListServiceSpecificCredentialsRequest.builder().userName(USER_NAME).build());
assertThat(response.serviceSpecificCredentials()).isEmpty();
assertThatThrownBy(() -> deleteCredential(credentialId))
.isInstanceOf(NoSuchEntityException.class);
}
@Test
@Order(10)
@DisplayName("UserName is optional on the list: it resolves from the signing credentials")
void userNameIsOptionalOnTheList() {
// Omitting UserName must reach the implied-caller resolution rather than fail for a
// missing parameter. The fixture signs with an access key that belongs to no stored IAM
// user, which that resolution reports as NoSuchEntity, so this is the error that proves
// the path ran: were UserName required, it would be a ValidationError instead.
assertThatThrownBy(() -> iam.listServiceSpecificCredentials(
ListServiceSpecificCredentialsRequest.builder().build()))
.isInstanceOf(NoSuchEntityException.class)
.as("the failure must come from resolving the key, not a missing parameter")
.hasMessageContaining("Access Key");
}
}
+116 -7
View File
@@ -304,13 +304,14 @@ also checked against that policy's length and character-class requirements, with
echoed back by any of these actions, matching AWS.
`DeleteUser` returns `DeleteConflict`, as on AWS, while the user still has a login profile, access
keys, inline policies, attached managed policies, group memberships, or an
[enabled MFA device](#multi-factor-authentication): remove those first. Floci has no actions that
create signing certificates, SSH public keys, or Git credentials, so there is nothing of those
kinds to block on. Renaming a user with `UpdateUser` carries its login
profile, access keys, and group membership to the new name. Unlike AWS, Floci does not rewrite
policy documents that name the user's ARN, so a resource or trust policy that referred to the old
name still refers to it after a rename.
keys, inline policies, attached managed policies, group memberships, an
[enabled MFA device](#multi-factor-authentication), a
[signing certificate](#signing-certificates), an [SSH public key](#ssh-public-keys) or a
[service-specific credential](#service-specific-credentials): remove those first. That is every
item on AWS's own list of what to delete before deleting a user programmatically. Renaming a user
with `UpdateUser` carries all of them to the new name, along with its login profile, access keys and
group membership. Unlike AWS, Floci does not rewrite policy documents that name the user's ARN, so a
resource or trust policy that referred to the old name still refers to it after a rename.
### Policy Simulation
@@ -676,6 +677,114 @@ owning user's ARN, along with every other IAM action except the server-certifica
is the general gap tracked in [#4979](https://github.com/floci-io/floci/issues/4979), not something
specific to signing certificates.
### Service-Specific Credentials
| Action | Description |
|--------|-------------|
| CreateServiceSpecificCredential | Generates a credential for one service against an IAM user and returns its generated `ServiceSpecificCredentialId`. |
| ListServiceSpecificCredentials | Lists a user's credentials, or every user's with `AllUsers`, optionally filtered by `ServiceName`. |
| UpdateServiceSpecificCredential | Sets a credential's status to `Active`, `Inactive` or `Expired`. |
| ResetServiceSpecificCredential | Replaces the secret half of a credential and returns the new one. |
| DeleteServiceSpecificCredential | Deletes one of a user's service-specific credentials. |
These are what AWS calls Git credentials when they are used with CodeCommit. A service that does not
support them is `NoSuchEntity` with status 404 and the message "No such service `<name>` is
supported for Service Specific Credentials".
That is not what the wire model would suggest. The model declares `ServiceNotSupportedException`,
code `NotSupportedService`, on both `CreateServiceSpecificCredential` and
`ListServiceSpecificCredentials`, and AWS never raises it: recordings validated against AWS answer
`NoSuchEntity` for a nonexistent service, for a name that is not a service principal at all, and for
a real service that simply does not support these credentials. A client written against the model,
catching the modelled exception, would catch nothing.
**A credential has one of two shapes, decided by the service:**
| Service | Shape |
|---------|-------|
| `codecommit.amazonaws.com` | `ServiceUserName` + `ServicePassword` |
| `cassandra.amazonaws.com` | `ServiceUserName` + `ServicePassword` |
| `bedrock.amazonaws.com` | long-term API key: `ServiceCredentialAlias` + `ServiceCredentialSecret` |
| `aws-external-anthropic.amazonaws.com` | long-term API key |
| `cloudwatch.amazonaws.com` | long-term API key |
| `logs.amazonaws.com` | long-term API key |
That list is the subset AWS's documentation actually names. The User Guide's own enumeration falls
on a page boundary and is absent from the published PDF, so these come from two other passages: the
`iam:ServiceSpecificCredentialServiceName` condition-key section, which gives CodeCommit,
Keyspaces and Bedrock "with their
exact value formatting", and the worked `create-service-specific-credential` CLI block, which
creates the four long-term API key services. A service AWS supports that neither passage names would
be refused here. A legacy per-partition form of a supported principal is accepted and folded to the
universal one, so `bedrock.amazonaws.com.cn` works and comes back as `bedrock.amazonaws.com`; a bare
`codecommit` does not, because AWS documents these with their exact formatting.
Only the long-term API key services accept `CredentialAgeDays`, which the model restricts to
"services that support long-term API keys" and which sets the `ExpirationDate`. It is 1 to 36600
days. Without it the credential does not expire and no expiry is reported. A present but
unparseable value is a validation error rather than a silent absence, since answering it with a
credential that never expires is the opposite of what was asked for.
**A key past its `ExpirationDate` reports `Expired`.** The status is derived when it is read rather
than written back, so the value a caller set is left alone and an `UpdateServiceSpecificCredential`
to `Active` cannot make an expired key report as usable. Expiry outranks `Inactive` as well, since a
key past its expiry is finished either way and `Expired` says more.
This one is a judgement call rather than a sourced behaviour, and worth knowing about. AWS does not
document the transition: `Expired` is in the `statusType` enum, but that enum is shared with access
keys, SSH public keys and signing certificates, most of which have no expiry at all, and the API
Reference's prose describes only `Active` and `Inactive`. Of the two available guesses, reporting an
expired key as `Active` is the worse one, because it tells a caller the key works while the same
response carries the date saying it does not. Nothing authenticates with these credentials in Floci
either way, so the status is the only place the expiry can show.
The secret half, whichever shape it takes, is disclosed by `CreateServiceSpecificCredential` and
`ResetServiceSpecificCredential` and never again: `ListServiceSpecificCredentials` returns
`ServiceSpecificCredentialMetadata`, which the model defines without either secret. A reset keeps
the id, the service and the service user name or alias: only what authenticates with the credential
changes. Note that the User Guide calls the long-term key's secret `ServiceApiKeyValue` in prose;
that is not a wire name, and both the API Reference and the model call it
`ServiceCredentialSecret`.
`ServiceUserName` is derived the way AWS derives it, as the IAM user name, the account, and a `+n`
between them for the second credential: `anika-at-123456789012` and then
`anika+1-at-123456789012`, which are the API Reference's own examples. `ServiceCredentialAlias`
plays the same role for a long-term key, and AWS documents it only as including "the IAM user name
and a suffix containing version and creation information" without publishing a format, so the one
here is Floci's: `anika+v1-20261004`.
In both cases the version is the lowest one not currently in use rather than a count of what
exists, because a count repeats a name as soon as a credential is deleted out of order. Holding
only `anika+1`, a count of one would mint `anika+1` again and two live credentials would share the
name the caller authenticates with. It is taken inside the same lock as the write, so two
concurrent creates cannot both claim the same version.
**The quota is two per service, not two per user**: the User Guide gives "a maximum of two sets of
service-specific credentials for each supported service per IAM user", so a user may hold two for
each of the six while a third for any one of them is `LimitExceeded`. Unlike the SSH public key
limit, this one has no row in the IAM service quotas table, matching the User Guide's framing of it
as a fixed design limit rather than an adjustable quota.
`AllUsers` cannot be given together with `UserName`, which the model says in as many words, so
naming both is a validation error rather than one quietly winning.
`UserName` is required on `CreateServiceSpecificCredential` and optional on the other four, where it
resolves from the access key that signed the request. That is a third pattern again: the
signing-certificate operations take it optionally throughout, and the SSH key operations require it
everywhere but the list.
A service-specific credential blocks `DeleteUser` until it is removed, the last of the items AWS
lists as a prerequisite for deleting a user programmatically, and it follows the user across an
`UpdateUser` rename: left behind, a credential would be stranded on a name that no longer exists,
invisible to its owner because listing goes through the user. The `ServiceUserName` is left as it
was minted rather than re-derived from the new name, because it is what the caller authenticates
with and rewriting it would break a working credential; AWS does not document which way it goes, so
this is a choice rather than a sourced behaviour.
Under [enforcement](#iam-enforcement-mode) these actions are evaluated against `*` rather than the
owning user's ARN, as the general gap in
[#4979](https://github.com/floci-io/floci/issues/4979) describes.
## AWS Managed Policies
Floci seeds a catalog of commonly-used AWS managed policies at startup. These are attachable immediately without any setup:
+1 -1
View File
@@ -22,7 +22,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [Lambda MicroVMs](lambda-microvms.md) | `/2025-09-09/...` + `/2026-04-04/...` | REST JSON | 22 |
| [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 79 |
| [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 53 + data-plane |
| [IAM](iam.md) | `POST /` with `Action=` param | Query | 153 |
| [IAM](iam.md) | `POST /` with `Action=` param | Query | 158 |
| [STS](sts.md) | `POST /` with `Action=` param | Query | 7 |
| [AWS Sign-In](iam.md#aws-sign-in-login-credentials) | `/v1/authorize`, `/v1/token` | REST JSON | 2 |
| [Organizations](organizations.md) | `POST /` + `X-Amz-Target: AWSOrganizationsV20161128.*` | JSON 1.1 | 56 |
@@ -119,6 +119,9 @@ public class AwsQueryController {
"CreateVirtualMFADevice", "DeleteVirtualMFADevice", "ListVirtualMFADevices",
"EnableMFADevice", "DeactivateMFADevice", "ResyncMFADevice", "ListMFADevices",
"TagMFADevice", "UntagMFADevice", "ListMFADeviceTags",
"CreateServiceSpecificCredential", "ListServiceSpecificCredentials",
"UpdateServiceSpecificCredential", "ResetServiceSpecificCredential",
"DeleteServiceSpecificCredential",
"UploadSSHPublicKey", "GetSSHPublicKey", "ListSSHPublicKeys",
"UpdateSSHPublicKey", "DeleteSSHPublicKey",
"UploadSigningCertificate", "ListSigningCertificates",
@@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.iam.model.OpenIDConnectProvider;
import io.github.hectorvent.floci.services.iam.model.PolicyVersion;
import io.github.hectorvent.floci.services.iam.model.SAMLProvider;
import io.github.hectorvent.floci.services.iam.model.ServerCertificate;
import io.github.hectorvent.floci.services.iam.model.ServiceSpecificCredential;
import io.github.hectorvent.floci.services.iam.model.ServiceLastAccessedEntity;
import io.github.hectorvent.floci.services.iam.model.ServiceLastAccessedJob;
import io.github.hectorvent.floci.services.iam.model.SigningCertificate;
@@ -97,6 +98,11 @@ public class IamQueryHandler {
case "DeleteUser" -> handleDeleteUser(params);
case "ListUsers" -> handleListUsers(params);
case "UpdateUser" -> handleUpdateUser(params);
case "CreateServiceSpecificCredential" -> handleCreateServiceSpecificCredential(params);
case "ListServiceSpecificCredentials" -> handleListServiceSpecificCredentials(params, authorization);
case "UpdateServiceSpecificCredential" -> handleUpdateServiceSpecificCredential(params, authorization);
case "ResetServiceSpecificCredential" -> handleResetServiceSpecificCredential(params, authorization);
case "DeleteServiceSpecificCredential" -> handleDeleteServiceSpecificCredential(params, authorization);
case "UploadSSHPublicKey" -> handleUploadSshPublicKey(params);
case "GetSSHPublicKey" -> handleGetSshPublicKey(params);
case "ListSSHPublicKeys" -> handleListSshPublicKeys(params, authorization);
@@ -767,6 +773,131 @@ public class IamQueryHandler {
return Response.ok(AwsQueryResponse.envelope("ListServerCertificates", AwsNamespaces.IAM, xml.build())).build();
}
/**
* UserName is required here and optional on the other four, which is a third pattern again:
* the signing-certificate operations take it optionally throughout and the SSH ones require it
* everywhere but the list.
*/
private Response handleCreateServiceSpecificCredential(
MultivaluedMap<String, String> params) {
ServiceSpecificCredential credential = iamService.createServiceSpecificCredential(
requireParam(params, "UserName"), requireParam(params, "ServiceName"),
optionalInt(params, "CredentialAgeDays"));
XmlBuilder xml = new XmlBuilder().start("ServiceSpecificCredential")
.raw(serviceCredentialXml(credential, true)).end("ServiceSpecificCredential");
return Response.ok(AwsQueryResponse.envelope("CreateServiceSpecificCredential",
AwsNamespaces.IAM, xml.build())).build();
}
/**
* The metadata list, which the model defines without either secret. {@code AllUsers} cannot be
* given together with {@code UserName}, so naming both is a validation error rather than one
* quietly winning.
*/
private Response handleListServiceSpecificCredentials(
MultivaluedMap<String, String> params, String authorization) {
boolean allUsers = "true".equalsIgnoreCase(getParam(params, "AllUsers"));
if (allUsers && getParam(params, "UserName") != null) {
throw new AwsException("ValidationError",
"AllUsers cannot be specified together with UserName.", 400);
}
String userName = allUsers ? null : resolveUserName(params, authorization);
Page<ServiceSpecificCredential> page = paginate(
iamService.listServiceSpecificCredentials(
userName, getParam(params, "ServiceName"), allUsers), params);
XmlBuilder xml = new XmlBuilder().start("ServiceSpecificCredentials");
for (ServiceSpecificCredential credential : page.items()) {
xml.start("member").raw(serviceCredentialXml(credential, false)).end("member");
}
xml.end("ServiceSpecificCredentials").elem("IsTruncated", page.truncated());
if (page.marker() != null) {
xml.elem("Marker", page.marker());
}
return Response.ok(AwsQueryResponse.envelope("ListServiceSpecificCredentials",
AwsNamespaces.IAM, xml.build())).build();
}
private Response handleUpdateServiceSpecificCredential(
MultivaluedMap<String, String> params, String authorization) {
iamService.updateServiceSpecificCredential(resolveUserName(params, authorization),
requireParam(params, "ServiceSpecificCredentialId"), getParam(params, "Status"));
return Response.ok(AwsQueryResponse.envelopeNoResult("UpdateServiceSpecificCredential",
AwsNamespaces.IAM)).build();
}
/** The reset is the only operation besides the create that returns the secret half. */
private Response handleResetServiceSpecificCredential(
MultivaluedMap<String, String> params, String authorization) {
ServiceSpecificCredential credential = iamService.resetServiceSpecificCredential(
resolveUserName(params, authorization),
requireParam(params, "ServiceSpecificCredentialId"));
XmlBuilder xml = new XmlBuilder().start("ServiceSpecificCredential")
.raw(serviceCredentialXml(credential, true)).end("ServiceSpecificCredential");
return Response.ok(AwsQueryResponse.envelope("ResetServiceSpecificCredential",
AwsNamespaces.IAM, xml.build())).build();
}
private Response handleDeleteServiceSpecificCredential(
MultivaluedMap<String, String> params, String authorization) {
iamService.deleteServiceSpecificCredential(resolveUserName(params, authorization),
requireParam(params, "ServiceSpecificCredentialId"));
return Response.ok(AwsQueryResponse.envelopeNoResult("DeleteServiceSpecificCredential",
AwsNamespaces.IAM)).build();
}
/**
* A credential, with the secret half only when the operation is one that discloses it. The
* metadata shape the list uses is defined without {@code ServicePassword} or
* {@code ServiceCredentialSecret}, so omitting them is the shape rather than a precaution.
*/
private String serviceCredentialXml(ServiceSpecificCredential credential, boolean withSecret) {
XmlBuilder xml = new XmlBuilder()
.elem("UserName", credential.getUserName())
.elem("ServiceName", credential.getServiceName())
.elem("ServiceSpecificCredentialId", credential.getServiceSpecificCredentialId())
.elem("Status", iamService.reportedStatus(credential))
.elem("CreateDate", isoDate(credential.getCreateDate()));
if (credential.getServiceUserName() != null) {
xml.elem("ServiceUserName", credential.getServiceUserName());
}
if (credential.getServiceCredentialAlias() != null) {
xml.elem("ServiceCredentialAlias", credential.getServiceCredentialAlias());
}
if (credential.getExpirationDate() != null) {
xml.elem("ExpirationDate", isoDate(credential.getExpirationDate()));
}
if (withSecret) {
if (credential.getServicePassword() != null) {
xml.elem("ServicePassword", credential.getServicePassword());
}
if (credential.getServiceCredentialSecret() != null) {
xml.elem("ServiceCredentialSecret", credential.getServiceCredentialSecret());
}
}
return xml.build();
}
/** An optional integer parameter that AWS documents as having to be positive. */
/**
* An optional integer parameter. Absent means absent, but present and unparseable is a
* validation error rather than a silent absence: {@code CredentialAgeDays=} would otherwise
* create a credential that never expires, which is the opposite of what the caller asked for.
*/
private Integer optionalInt(MultivaluedMap<String, String> params, String name) {
String raw = getParam(params, name);
if (raw == null) {
return null;
}
try {
return Integer.valueOf(raw.trim());
} catch (NumberFormatException e) {
throw new AwsException("ValidationError",
"Value '" + raw + "' at '" + Character.toLowerCase(name.charAt(0))
+ name.substring(1) + "' failed to satisfy constraint: Member must be "
+ "an integer", 400);
}
}
/**
* UserName is required on every SSH public key operation but the list, which is the opposite
* of the signing-certificate operations: there the model marks it optional throughout.
@@ -39,6 +39,7 @@ import io.github.hectorvent.floci.services.iam.model.OpenIDConnectProvider;
import io.github.hectorvent.floci.services.iam.model.OrganizationRootFeatures;
import io.github.hectorvent.floci.services.iam.model.PolicyVersion;
import io.github.hectorvent.floci.services.iam.model.ServerCertificate;
import io.github.hectorvent.floci.services.iam.model.ServiceSpecificCredential;
import io.github.hectorvent.floci.services.iam.model.SessionCredential;
import io.github.hectorvent.floci.services.iam.model.SigningCertificate;
import io.github.hectorvent.floci.services.iam.model.SshPublicKey;
@@ -58,6 +59,7 @@ import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPublicKey;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
@@ -69,6 +71,7 @@ import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
@@ -76,6 +79,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
@@ -168,6 +172,53 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
private static final int MAX_SERVER_CERTIFICATES = 20;
/** IAM User Guide quota table, and GetAccountSummary's SigningCertificatesPerUserQuota. */
private static final int MAX_SIGNING_CERTIFICATES_PER_USER = 2;
/**
* IAM User Guide: "a maximum of two sets of service-specific credentials for each supported
* service per IAM user". Per service, so a user may hold two for each of them.
*/
private static final int MAX_SERVICE_CREDENTIALS_PER_SERVICE = 2;
/** The unique-ID prefix table gives ACCA for a context-specific credential. */
private static final int SERVICE_CREDENTIAL_ID_SUFFIX_LENGTH = 16;
/**
* The services whose credential is a long-term API key, an alias and a secret rather than a
* user name and a password. CredentialAgeDays, and so an expiry, is only valid for these.
*
* <p>Sourced from the User Guide's worked {@code create-service-specific-credential} block,
* which creates exactly these four with {@code --credential-age-days}; the API Reference
* corroborates two of them by naming "Bedrock API keys and CloudWatch Logs API keys" on
* ServiceCredentialAlias, ServiceCredentialSecret and ExpirationDate.
*/
private static final Set<String> LONG_TERM_API_KEY_SERVICES = Set.of(
ServicePrincipals.of("bedrock"),
ServicePrincipals.of("aws-external-anthropic"),
ServicePrincipals.of("cloudwatch"),
ServicePrincipals.of("logs"));
/**
* The services that support service-specific credentials. Anything else is {@code NoSuchEntity}
* with status 404, which is not what the model would suggest: it declares
* {@code ServiceNotSupportedException} (wire code {@code NotSupportedService}) on both Create
* and List, and AWS does not raise it. LocalStack's AWS-validated IAM snapshots record
* {@code NoSuchEntity} for a nonexistent service, a malformed name and an existing but
* unsupported service alike, all with the message this throws.
*
* <p>This is the sourced subset, not a claim of completeness. The User Guide's own
* enumeration ("AWS currently supports service-specific credentials for the following
* services:") falls on a page boundary and renders as nothing in the published PDF, so these
* come from two other passages: CodeCommit and Keyspaces from the
* {@code iam:ServiceSpecificCredentialServiceName}
* condition-key list, which gives them "with their exact value formatting", and the four
* long-term API key services from the CLI block above.
*/
private static final Set<String> SERVICE_CREDENTIAL_SERVICES = Stream.concat(
LONG_TERM_API_KEY_SERVICES.stream(),
Stream.of(ServicePrincipals.of("codecommit"), ServicePrincipals.of("cassandra")))
.collect(Collectors.toUnmodifiableSet());
/** credentialAgeDays is 1 to 36600, in the model and in the User Guide's own prose. */
private static final int MIN_CREDENTIAL_AGE_DAYS = 1;
private static final int MAX_CREDENTIAL_AGE_DAYS = 36600;
/** The creation half of a long-term API key's alias. */
private static final DateTimeFormatter CREDENTIAL_ALIAS_DATE =
DateTimeFormatter.ofPattern("yyyyMMdd").withZone(ZoneOffset.UTC);
/** AWS General Reference, IAM service quotas: "SSH Public keys per user", not adjustable. */
private static final int MAX_SSH_PUBLIC_KEYS_PER_USER = 5;
/** publicKeyIdType is 20 to 128 of [\w]+, and AWS's own examples use the APKA prefix. */
@@ -179,13 +230,14 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
/** certificateIdType is 24 to 128 of [\w]+, so a 32-character id sits inside that. */
private static final int SIGNING_CERTIFICATE_ID_LENGTH = 32;
private static final String CREDENTIAL_STATUS_ACTIVE = "Active";
private static final String CREDENTIAL_STATUS_EXPIRED = "Expired";
/**
* statusType's values, shared by signing certificates and SSH public keys: Active, Inactive
* and Expired. Each operation's prose explains only the first two, so the third is easy to
* reject by mistake, while the API Reference lists all three as valid.
*/
private static final Set<String> CREDENTIAL_STATUSES =
Set.of(CREDENTIAL_STATUS_ACTIVE, "Inactive", "Expired");
Set.of(CREDENTIAL_STATUS_ACTIVE, "Inactive", CREDENTIAL_STATUS_EXPIRED);
/** {@code certificateBodyType} and {@code privateKeyType} are both 1 to 16384 characters. */
private static final int MAX_CERTIFICATE_BODY_LENGTH = 16384;
/** {@code certificateChainType} is far larger, at 1 to 2097152. */
@@ -262,6 +314,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
private final StorageBackend<String, ServerCertificate> serverCertificates;
private final StorageBackend<String, SigningCertificate> signingCertificates;
private final StorageBackend<String, SshPublicKey> sshPublicKeys;
private final StorageBackend<String, ServiceSpecificCredential> serviceCredentials;
/**
* Guards the check-then-write on a server certificate. Upload checks the name is free before
* storing, and UpdateServerCertificate checks a new name is free before moving to it, so two
@@ -270,6 +323,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
private final Object serverCertificateLock = new Object();
private final Object signingCertificateLock = new Object();
private final Object sshPublicKeyLock = new Object();
private final Object serviceCredentialLock = new Object();
/**
* Guards every check-then-write on an MFA device. Assignment is the reason it has to exist:
* EnableMFADevice reads the device to confirm it is unassigned and reads the user's device
@@ -313,6 +367,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
storageFactory.create("iam", "iam-server-certificates.json", new TypeReference<>() {}),
storageFactory.create("iam", "iam-signing-certificates.json", new TypeReference<>() {}),
storageFactory.create("iam", "iam-ssh-public-keys.json", new TypeReference<>() {}),
storageFactory.create("iam", "iam-service-specific-credentials.json", new TypeReference<>() {}),
regionResolver,
config.services().iam().seedDeployerPrincipal(),
config.services().iam().accountAlias().orElse(null)
@@ -345,6 +400,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
regionResolver, seedDeployerPrincipal, null);
}
@@ -369,6 +425,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
serviceLinkedRoleDeletions, new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
regionResolver, seedDeployerPrincipal, seededAccountAlias);
}
@@ -391,6 +448,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
regionResolver, seedDeployerPrincipal, null);
}
@@ -412,6 +470,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
StorageBackend<String, ServerCertificate> serverCertificates,
StorageBackend<String, SigningCertificate> signingCertificates,
StorageBackend<String, SshPublicKey> sshPublicKeys,
StorageBackend<String, ServiceSpecificCredential> serviceCredentials,
RegionResolver regionResolver,
boolean seedDeployerPrincipal,
String seededAccountAlias) {
@@ -433,6 +492,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
this.serverCertificates = serverCertificates;
this.signingCertificates = signingCertificates;
this.sshPublicKeys = sshPublicKeys;
this.serviceCredentials = serviceCredentials;
this.regionResolver = regionResolver;
this.seedDeployerPrincipal = seedDeployerPrincipal;
this.seededAccountAlias = seededAccountAlias;
@@ -611,22 +671,31 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
// UploadSigningCertificate and EnableMFADevice confirm the user under their own lock, so
// none of them can interleave into a credential owned by a deleted user. Taken in this
// order here and in UpdateUser, and nowhere else in more than one, so it cannot deadlock.
synchronized (sshPublicKeyLock) {
if (!userSshPublicKeys(userName).isEmpty()) {
synchronized (serviceCredentialLock) {
// AWS lists these among the items to remove first, under their CodeCommit
// name: "Git credentials (DeleteServiceSpecificCredential)".
if (!userServiceCredentials(userName).isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must delete SSH public keys first.", 409);
"Cannot delete entity, must delete service-specific credentials "
+ "first.", 409);
}
synchronized (signingCertificateLock) {
if (!userSigningCertificates(userName).isEmpty()) {
synchronized (sshPublicKeyLock) {
if (!userSshPublicKeys(userName).isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must delete signing certificates first.", 409);
"Cannot delete entity, must delete SSH public keys first.", 409);
}
synchronized (mfaDeviceLock) {
if (!mfaDevicesForUser(userName).isEmpty()) {
synchronized (signingCertificateLock) {
if (!userSigningCertificates(userName).isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must deactivate MFA device first.", 409);
"Cannot delete entity, must delete signing certificates first.", 409);
}
synchronized (mfaDeviceLock) {
if (!mfaDevicesForUser(userName).isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must deactivate MFA device first.", 409);
}
users.delete(userName);
}
users.delete(userName);
}
}
}
@@ -673,31 +742,40 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
// published but before the credential follows, see none, and delete a user whose
// credential is about to be reassigned to it. The two locks are taken in the same
// order DeleteUser takes them, so the nesting cannot deadlock.
synchronized (sshPublicKeyLock) {
List<SshPublicKey> sshKeysToMove = userSshPublicKeys(userName);
synchronized (signingCertificateLock) {
List<SigningCertificate> certificatesToMove = userSigningCertificates(userName);
synchronized (mfaDeviceLock) {
users.delete(userName);
user.setUserName(newUserName);
if (newPath != null) {
user.setPath(normalizePath(newPath));
synchronized (serviceCredentialLock) {
List<ServiceSpecificCredential> credentialsToMove =
userServiceCredentials(userName);
synchronized (sshPublicKeyLock) {
List<SshPublicKey> sshKeysToMove = userSshPublicKeys(userName);
synchronized (signingCertificateLock) {
List<SigningCertificate> certificatesToMove = userSigningCertificates(userName);
synchronized (mfaDeviceLock) {
users.delete(userName);
user.setUserName(newUserName);
if (newPath != null) {
user.setPath(normalizePath(newPath));
}
user.setArn(iamArnBeside(user.getArn(), "user", user.getPath(), newUserName));
users.put(newUserName, user);
for (VirtualMfaDevice device : mfaDevicesForUser(userName)) {
device.setUserName(newUserName);
virtualMfaDevices.put(device.getSerialNumber(), device);
}
}
user.setArn(iamArnBeside(user.getArn(), "user", user.getPath(), newUserName));
users.put(newUserName, user);
for (VirtualMfaDevice device : mfaDevicesForUser(userName)) {
device.setUserName(newUserName);
virtualMfaDevices.put(device.getSerialNumber(), device);
for (SigningCertificate certificate : certificatesToMove) {
certificate.setUserName(newUserName);
signingCertificates.put(certificate.getCertificateId(), certificate);
}
}
for (SigningCertificate certificate : certificatesToMove) {
certificate.setUserName(newUserName);
signingCertificates.put(certificate.getCertificateId(), certificate);
for (SshPublicKey key : sshKeysToMove) {
key.setUserName(newUserName);
sshPublicKeys.put(key.getSshPublicKeyId(), key);
}
}
for (SshPublicKey key : sshKeysToMove) {
key.setUserName(newUserName);
sshPublicKeys.put(key.getSshPublicKeyId(), key);
for (ServiceSpecificCredential credential : credentialsToMove) {
credential.setUserName(newUserName);
serviceCredentials.put(
credential.getServiceSpecificCredentialId(), credential);
}
}
loginProfiles.get(userName).ifPresent(profile -> {
@@ -2729,6 +2807,261 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
.toList();
}
// Service-specific credentials
// =========================================================================
/**
* Creates a credential scoped to one service. The shape depends on the service: a long-term
* API key service gets an alias and a secret, everything else a user name and a password.
*
* <p>The secret half is returned here and by the reset, and nowhere else: there is no get
* operation, and the list is defined without it.
*/
public ServiceSpecificCredential createServiceSpecificCredential(
String userName, String requestedServiceName, Integer credentialAgeDays) {
String serviceName = supportedServiceName(requestedServiceName);
boolean longTermKey = LONG_TERM_API_KEY_SERVICES.contains(serviceName);
if (credentialAgeDays != null) {
if (!longTermKey) {
throw new AwsException("ValidationError",
"CredentialAgeDays is only valid for services that support long-term API "
+ "keys.", 400);
}
if (credentialAgeDays < MIN_CREDENTIAL_AGE_DAYS
|| credentialAgeDays > MAX_CREDENTIAL_AGE_DAYS) {
throw new AwsException("ValidationError",
"Value '" + credentialAgeDays + "' at 'credentialAgeDays' failed to "
+ "satisfy constraint: Member must be between "
+ MIN_CREDENTIAL_AGE_DAYS + " and " + MAX_CREDENTIAL_AGE_DAYS,
400);
}
}
synchronized (serviceCredentialLock) {
// Confirmed under the lock, as the other per-user credentials are: DeleteUser checks
// for these holding the same lock.
getUser(userName);
// One scan serves both checks: the quota counts this user's credentials for this
// service, the name search needs every name in the account, and no write can land
// between them while this holds the lock.
List<ServiceSpecificCredential> all = serviceCredentials.scan(key -> true);
List<ServiceSpecificCredential> existing = all.stream()
.filter(c -> userName.equals(c.getUserName()))
.filter(c -> serviceName.equals(c.getServiceName()))
.toList();
if (existing.size() >= MAX_SERVICE_CREDENTIALS_PER_SERVICE) {
throw new AwsException("LimitExceeded",
"Cannot exceed quota for ServiceSpecificCredentialsPerUser: "
+ MAX_SERVICE_CREDENTIALS_PER_SERVICE, 409);
}
ServiceSpecificCredential credential = new ServiceSpecificCredential();
credential.setUserName(userName);
credential.setServiceName(serviceName);
credential.setServiceSpecificCredentialId(
"ACCA" + randomId(SERVICE_CREDENTIAL_ID_SUFFIX_LENGTH));
credential.setStatus(CREDENTIAL_STATUS_ACTIVE);
credential.setCreateDate(Instant.now());
int version = freeCredentialVersion(
all, userName, longTermKey, credential.getCreateDate());
if (longTermKey) {
credential.setServiceCredentialAlias(
credentialAliasFor(userName, version, credential.getCreateDate()));
credential.setServiceCredentialSecret(randomSecret(40));
if (credentialAgeDays != null) {
credential.setExpirationDate(
credential.getCreateDate().plus(Duration.ofDays(credentialAgeDays)));
}
} else {
credential.setServiceUserName(serviceUserNameFor(userName, version));
credential.setServicePassword(randomSecret(40));
}
serviceCredentials.put(credential.getServiceSpecificCredentialId(), credential);
LOG.infov("Created a {0} service-specific credential for user {1}",
serviceName, userName);
return credential;
}
}
/**
* The service as the allowlist holds it, or {@code NoSuchEntity}. A legacy per-partition form
* folds to the universal one first, so a China-partition caller naming
* {@code bedrock.amazonaws.com.cn} is not refused for a service that is supported; a bare
* {@code codecommit} still is, because AWS documents these values with their exact formatting.
*/
private String supportedServiceName(String requestedServiceName) {
String canonical = ServicePrincipals.canonical(requestedServiceName);
if (canonical == null || !SERVICE_CREDENTIAL_SERVICES.contains(canonical)) {
// The name as asked for, not the canonical form: AWS echoes what the caller sent.
throw new AwsException("NoSuchEntity",
"No such service " + requestedServiceName
+ " is supported for Service Specific Credentials", 404);
}
return canonical;
}
/**
* The lowest version whose name is not already in use anywhere in the account, which is what
* keeps two live credentials from sharing the name or alias the caller authenticates with.
*
* <p>The comparison has to span the whole store rather than the user's credentials for this
* service, because three different routes reach the same name otherwise. Taking a count
* collides as soon as one is deleted out of order: holding only {@code anika+1}, a count of one
* mints {@code anika+1} again. Scoping to one service lets two services collide, since an alias
* carries no service and two created on the same day would both be {@code anika+v1-<date>}.
* Scoping to one user lets a rename collide, because a credential keeps the name it was minted
* with, so a new user taking the freed IAM name would mint it a second time.
*
* <p>Bounded by the names in use, so one of the first {@code taken + 1} candidates is always
* free. The caller passes the account's credentials rather than this reading them itself,
* because the quota check needs the same snapshot and one scan under the lock serves both.
*/
private int freeCredentialVersion(List<ServiceSpecificCredential> accountCredentials,
String userName,
boolean longTermKey,
Instant createDate) {
Set<String> taken = accountCredentials.stream()
.map(longTermKey
? ServiceSpecificCredential::getServiceCredentialAlias
: ServiceSpecificCredential::getServiceUserName)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
for (int version = 0; version <= taken.size(); version++) {
String candidate = longTermKey
? credentialAliasFor(userName, version, createDate)
: serviceUserNameFor(userName, version);
if (!taken.contains(candidate)) {
return version;
}
}
throw new IllegalStateException("no free service-credential version for " + userName);
}
/**
* The service user name AWS derives for a credential: the IAM user name, the account, and a
* {@code +n} before the account for the second one, which is how two credentials for the same
* service tell themselves apart. The API Reference's examples show {@code anika-at-<account>}
* and {@code anika+1-at-<account>}.
*/
private String serviceUserNameFor(String userName, int version) {
String suffix = version == 0 ? "" : "+" + version;
return userName + suffix + "-at-" + regionResolver.getAccountId();
}
/**
* The public half of a long-term API key, which the API Reference describes as including "the
* IAM user name and a suffix containing version and creation information". The exact format
* AWS produces is not published, so this is ours: the user name, the version that tells two
* credentials for one service apart, and the creation date.
*/
private String credentialAliasFor(String userName, int version, Instant createDate) {
return userName + "+v" + (version + 1) + "-"
+ CREDENTIAL_ALIAS_DATE.format(createDate);
}
/**
* The status to report for a credential: {@code Expired} once its {@code ExpirationDate} has
* passed, and the stored status otherwise.
*
* <p>Derived on read rather than written back, so the status a caller set is never overwritten
* and an {@code UpdateServiceSpecificCredential} to {@code Active} cannot make an expired key
* look usable. Expiry wins over {@code Inactive} too: a key past its expiry is finished either
* way, and {@code Expired} is the more specific answer.
*
* <p>AWS does not document this transition. {@code Expired} is in {@code statusType}, but that
* enum is shared with access keys, SSH public keys and signing certificates, most of which
* have no expiry, and the API Reference's prose describes only the other two values. Reporting
* an expired key as {@code Active} is the worse of the two guesses: it tells a caller a key
* works when the same response carries the date saying it does not.
*/
public String reportedStatus(ServiceSpecificCredential credential) {
Instant expiry = credential.getExpirationDate();
if (expiry != null && !expiry.isAfter(Instant.now())) {
return CREDENTIAL_STATUS_EXPIRED;
}
return credential.getStatus();
}
/** Every credential of a user, or of every user when the caller asked for all of them. */
public List<ServiceSpecificCredential> listServiceSpecificCredentials(
String userName, String requestedServiceName, boolean allUsers) {
String serviceName = requestedServiceName == null
? null : supportedServiceName(requestedServiceName);
List<ServiceSpecificCredential> found;
if (allUsers) {
found = serviceCredentials.scan(key -> true);
} else {
getUser(userName); // validates existence
found = userServiceCredentials(userName);
}
return found.stream()
.filter(c -> serviceName == null || serviceName.equals(c.getServiceName()))
.sorted(Comparator.comparing(
ServiceSpecificCredential::getServiceSpecificCredentialId))
.toList();
}
public void updateServiceSpecificCredential(String userName, String credentialId,
String status) {
if (status == null || !CREDENTIAL_STATUSES.contains(status)) {
throw new AwsException("ValidationError",
"Value '" + status + "' at 'status' failed to satisfy constraint: Member must "
+ "satisfy enum value set: [" + String.join(", ",
CREDENTIAL_STATUSES) + "]", 400);
}
synchronized (serviceCredentialLock) {
ServiceSpecificCredential credential = userServiceCredential(userName, credentialId);
credential.setStatus(status);
serviceCredentials.put(credential.getServiceSpecificCredentialId(), credential);
}
}
/**
* Replaces the secret half and returns the new one. The credential keeps its id, its service
* and its service user name or alias: only what authenticates with it changes.
*/
public ServiceSpecificCredential resetServiceSpecificCredential(String userName,
String credentialId) {
synchronized (serviceCredentialLock) {
ServiceSpecificCredential credential = userServiceCredential(userName, credentialId);
if (LONG_TERM_API_KEY_SERVICES.contains(credential.getServiceName())) {
credential.setServiceCredentialSecret(randomSecret(40));
} else {
credential.setServicePassword(randomSecret(40));
}
serviceCredentials.put(credential.getServiceSpecificCredentialId(), credential);
return credential;
}
}
public void deleteServiceSpecificCredential(String userName, String credentialId) {
synchronized (serviceCredentialLock) {
ServiceSpecificCredential credential = userServiceCredential(userName, credentialId);
serviceCredentials.delete(credential.getServiceSpecificCredentialId());
}
}
/** A credential of that id belonging to that user, reported missing when it belongs elsewhere. */
private ServiceSpecificCredential userServiceCredential(String userName, String credentialId) {
getUser(userName); // validates existence
ServiceSpecificCredential credential = serviceCredentials.get(credentialId)
.orElseThrow(() -> new AwsException("NoSuchEntity",
"The Service Specific Credential with id " + credentialId
+ " cannot be found.", 404));
if (!userName.equals(credential.getUserName())) {
throw new AwsException("NoSuchEntity",
"The Service Specific Credential with id " + credentialId
+ " cannot be found.", 404);
}
return credential;
}
private List<ServiceSpecificCredential> userServiceCredentials(String userName) {
return serviceCredentials.scan(key -> true).stream()
.filter(c -> userName.equals(c.getUserName()))
.sorted(Comparator.comparing(
ServiceSpecificCredential::getServiceSpecificCredentialId))
.toList();
}
// Virtual MFA devices
// =========================================================================
@@ -0,0 +1,77 @@
package io.github.hectorvent.floci.services.iam.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
/**
* A credential scoped to one AWS service, owned by one IAM user. The service named at creation is
* "the only service that can be accessed using these credentials".
*
* <p>The model carries two different credential shapes and a credential has one of them, which is
* why neither pair is required on the shape. A service taking a user name and password, such as
* CodeCommit, gets {@code serviceUserName} and {@code servicePassword}. A service taking a
* long-term API key gets {@code serviceCredentialAlias} and {@code serviceCredentialSecret}, and
* only that kind can carry an {@code expirationDate}, since {@code CredentialAgeDays} "is only
* valid for services that support long-term API keys".
*
* <p>The secret half, whichever it is, is returned only by the create and the reset. There is no
* get operation, and the list returns metadata that the model defines without either secret, so
* nothing else can hand it back.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class ServiceSpecificCredential {
private String userName;
private String serviceName;
private String serviceSpecificCredentialId;
private String status = "Active";
private Instant createDate = Instant.now();
/** The user-name-and-password shape. Never echoed back after the create or a reset. */
private String serviceUserName;
private String servicePassword;
/** The long-term API key shape. The secret is never echoed back either. */
private String serviceCredentialAlias;
private String serviceCredentialSecret;
/** Only ever set for a long-term API key, and only when CredentialAgeDays was given. */
private Instant expirationDate;
public ServiceSpecificCredential() {}
public String getUserName() { return userName; }
public void setUserName(String userName) { this.userName = userName; }
public String getServiceName() { return serviceName; }
public void setServiceName(String serviceName) { this.serviceName = serviceName; }
public String getServiceSpecificCredentialId() { return serviceSpecificCredentialId; }
public void setServiceSpecificCredentialId(String serviceSpecificCredentialId) {
this.serviceSpecificCredentialId = serviceSpecificCredentialId;
}
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public Instant getCreateDate() { return createDate; }
public void setCreateDate(Instant createDate) { this.createDate = createDate; }
public String getServiceUserName() { return serviceUserName; }
public void setServiceUserName(String serviceUserName) {
this.serviceUserName = serviceUserName;
}
public String getServicePassword() { return servicePassword; }
public void setServicePassword(String servicePassword) {
this.servicePassword = servicePassword;
}
public String getServiceCredentialAlias() { return serviceCredentialAlias; }
public void setServiceCredentialAlias(String serviceCredentialAlias) {
this.serviceCredentialAlias = serviceCredentialAlias;
}
public String getServiceCredentialSecret() { return serviceCredentialSecret; }
public void setServiceCredentialSecret(String serviceCredentialSecret) {
this.serviceCredentialSecret = serviceCredentialSecret;
}
public Instant getExpirationDate() { return expirationDate; }
public void setExpirationDate(Instant expirationDate) {
this.expirationDate = expirationDate;
}
}
@@ -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);
}