Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(iam): add GenerateCredentialReport and GetCredentialReport (#4298)

Priamo Germosen910f0922c906
diff --git a/docs/services/iam.md b/docs/services/iam.md
index 6a2530e711..ebc2241fc0 100644
--- a/docs/services/iam.md
+++ b/docs/services/iam.md
@@ -327,6 +327,8 @@ read; the comparison is driven entirely by the policy's own condition operator (
|--------|-------------|
| GetAccountSummary | Returns entity counts (users, groups, roles, customer-managed policies, instance profiles) and IAM quota values. `Providers` counts OIDC providers only; SAML providers are not included. Resources Floci does not track (MFA devices, server certificates) are reported as zero rather than omitted. |
| GetAccountAuthorizationDetails | Returns every user, group and role in the account, and the policies relevant to them: every local (customer-managed) policy, and every AWS-managed policy actually attached to or used as a permissions boundary by something in the account. |
+| GenerateCredentialReport | Generates (or, within 4 hours of the last one, reuses) the account's credential report. |
+| GetCredentialReport | Returns the most recently generated credential report as Base64-encoded CSV. |
`Filter`, `MaxItems` and `Marker` are not honored: the response always includes everything, with
`IsTruncated` always `false`. `AttachmentCount` and `PermissionsBoundaryUsageCount` are computed by
@@ -337,6 +339,22 @@ returned as plain JSON, not URL-encoded as AWS documents them; this matches ever
that returns a policy document (`GetPolicyVersion`, `GetRolePolicy`, and so on), none of which
URL-encode either.
+The credential report holds the 23 columns AWS documents, always led by a `<root_account>` row.
+Floci does not model root account credentials at all (`GetAccountSummary`'s
+`AccountPasswordPresent`/`AccountAccessKeysPresent` are always zero for the same reason), so that
+row is placeholder values throughout. MFA devices and X.509 signing certificates are not modeled
+for IAM users either, so `mfa_active` and every `cert_*` column are always `FALSE`/`N/A`; access
+key last-used tracking (date, region, service) is not modeled, so those three columns are always
+`N/A` too. `password_last_used` is likewise not tracked, so it is always `no_information`.
+`password_last_changed` reflects an `UpdateLoginProfile` password change, not just
+`CreateLoginProfile`. `additional_credentials_info` is Floci's own wording, since AWS does not
+document the exact text; in practice it is unreachable, since `CreateAccessKey` already enforces
+the real 2-key-per-user quota. Generating a report is effectively instant, so `GenerateCredentialReport` never actually
+returns `INPROGRESS`, and a `GetCredentialReport` call right after it always finds the report
+ready. `GenerateCredentialReport`'s `State`/`Description` for the no-report-exists case match AWS's
+own documented example response (`STARTED` / "No report exists. Starting a new report generation
+task"); the wording for the report-expired case is Floci's own, since AWS does not document it.
+
### Organizations Root Access
| Action | Description |
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java
index 1e65d8f1b1..46eae3d474 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java
@@ -134,6 +134,8 @@ public class IamQueryHandler {
case "ListEntitiesForPolicy" -> handleListEntitiesForPolicy(params);
case "GetAccountSummary" -> handleGetAccountSummary(params);
case "GetAccountAuthorizationDetails" -> handleGetAccountAuthorizationDetails(params);
+ case "GenerateCredentialReport" -> handleGenerateCredentialReport(params);
+ case "GetCredentialReport" -> handleGetCredentialReport(params);
case "CreatePolicyVersion" -> handleCreatePolicyVersion(params);
case "GetPolicyVersion" -> handleGetPolicyVersion(params);
case "DeletePolicyVersion" -> handleDeletePolicyVersion(params);
@@ -855,6 +857,25 @@ public class IamQueryHandler {
return Response.ok(AwsQueryResponse.envelope("GetAccountSummary", AwsNamespaces.IAM, xml.build())).build();
}
+ private Response handleGenerateCredentialReport(MultivaluedMap<String, String> params) {
+ IamService.CredentialReportGeneration generation = iamService.generateCredentialReport();
+ String result = new XmlBuilder()
+ .elem("Description", generation.description())
+ .elem("State", generation.state())
+ .build();
+ return Response.ok(AwsQueryResponse.envelope("GenerateCredentialReport", AwsNamespaces.IAM, result)).build();
+ }
+
+ private Response handleGetCredentialReport(MultivaluedMap<String, String> params) {
+ IamService.CredentialReportContent content = iamService.getCredentialReport();
+ String result = new XmlBuilder()
+ .elem("Content", content.base64Content())
+ .elem("ReportFormat", content.reportFormat())
+ .elem("GeneratedTime", isoDate(content.generatedTime()))
+ .build();
+ return Response.ok(AwsQueryResponse.envelope("GetCredentialReport", AwsNamespaces.IAM, result)).build();
+ }
+
// Filter, MaxItems and Marker are not honored: every user, group, role and relevant policy
// is always returned in one response, matching this handler's general convention elsewhere
// (ListInstanceProfiles, SimulatePrincipalPolicy, ...) of not implementing pagination.
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
index 40e21d2e5e..5b2e8b362e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.iam.model.AccessKey;
import io.github.hectorvent.floci.services.iam.model.AccountPasswordPolicy;
+import io.github.hectorvent.floci.services.iam.model.CredentialReport;
import io.github.hectorvent.floci.services.iam.model.IamGroup;
import io.github.hectorvent.floci.services.iam.model.IamPolicy;
import io.github.hectorvent.floci.services.iam.model.IamRole;
@@ -35,7 +36,10 @@ import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
+import java.time.Duration;
import java.time.Instant;
+import java.time.format.DateTimeFormatter;
+import java.util.Base64;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
@@ -118,6 +122,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
/** {@code tagListType} / {@code tagKeyListType} are both {@code max: 50}. */
private static final int MAX_TAGS_PER_INSTANCE_PROFILE = 50;
private static final String ROOT_FEATURES_KEY = "org-root-features";
+ private static final String CREDENTIAL_REPORT_KEY = "credential-report";
+ /** AWS generates a fresh report only if the most recent one is older than this. */
+ private static final Duration CREDENTIAL_REPORT_MAX_AGE = Duration.ofHours(4);
public static final String FEATURE_ROOT_CREDENTIALS = "RootCredentialsManagement";
public static final String FEATURE_ROOT_SESSIONS = "RootSessions";
@@ -150,6 +157,11 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
/** Deletion is synchronous, so an issued task id is a completed one; the value is its role. */
private final StorageBackend<String, String> serviceLinkedRoleDeletions;
private final StorageBackend<String, OrganizationRootFeatures> orgRootFeatures;
+ /**
+ * Holds at most one entry per account under {@link #CREDENTIAL_REPORT_KEY}: the same
+ * single-value-per-account shape as {@link #accountAliases}.
+ */
+ private final StorageBackend<String, CredentialReport> credentialReports;
private final RegionResolver regionResolver;
private final boolean seedDeployerPrincipal;
private final String seededAccountAlias;
@@ -179,6 +191,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
storageFactory.create("iam", "iam-oidc-providers.json", new TypeReference<>() {}),
storageFactory.create("iam", "iam-slr-deletions.json", new TypeReference<>() {}),
storageFactory.create("iam", "iam-org-root-features.json", new TypeReference<>() {}),
+ storageFactory.create("iam", "iam-credential-reports.json", new TypeReference<>() {}),
regionResolver,
config.services().iam().seedDeployerPrincipal(),
config.services().iam().accountAlias().orElse(null)
@@ -208,7 +221,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions,
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
- regionResolver, seedDeployerPrincipal, null);
+ new InMemoryStorage<>(), regionResolver, seedDeployerPrincipal, null);
}
// 8-backend constructor (no org-root-features): kept for existing callers/tests;
@@ -229,8 +242,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
String seededAccountAlias) {
this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions,
accountAliases, passwordPolicies, new InMemoryStorage<>(), oidcProviders,
- serviceLinkedRoleDeletions, new InMemoryStorage<>(), regionResolver,
- seedDeployerPrincipal, seededAccountAlias);
+ serviceLinkedRoleDeletions, new InMemoryStorage<>(), new InMemoryStorage<>(),
+ regionResolver, seedDeployerPrincipal, seededAccountAlias);
}
// 9-backend constructor (no alias/OIDC/SLR backends): kept for existing callers/tests;
@@ -248,8 +261,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
boolean seedDeployerPrincipal) {
this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions,
new InMemoryStorage<>(), passwordPolicies, new InMemoryStorage<>(),
- new InMemoryStorage<>(), new InMemoryStorage<>(), orgRootFeatures, regionResolver,
- seedDeployerPrincipal, null);
+ new InMemoryStorage<>(), new InMemoryStorage<>(), orgRootFeatures,
+ new InMemoryStorage<>(), regionResolver, seedDeployerPrincipal, null);
}
IamService(StorageBackend<String, IamUser> users,
@@ -265,6 +278,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
StorageBackend<String, OpenIDConnectProvider> oidcProviders,
StorageBackend<String, String> serviceLinkedRoleDeletions,
StorageBackend<String, OrganizationRootFeatures> orgRootFeatures,
+ StorageBackend<String, CredentialReport> credentialReports,
RegionResolver regionResolver,
boolean seedDeployerPrincipal,
String seededAccountAlias) {
@@ -281,6 +295,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
this.oidcProviders = oidcProviders;
this.serviceLinkedRoleDeletions = serviceLinkedRoleDeletions;
this.orgRootFeatures = orgRootFeatures;
+ this.credentialReports = credentialReports;
this.regionResolver = regionResolver;
this.seedDeployerPrincipal = seedDeployerPrincipal;
this.seededAccountAlias = seededAccountAlias;
@@ -1811,6 +1826,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
if (password != null) {
validateLoginProfilePassword(password);
profile.setPassword(password);
+ profile.setPasswordLastChanged(Instant.now());
}
if (passwordResetRequired != null) {
profile.setPasswordResetRequired(passwordResetRequired);
@@ -2872,4 +2888,152 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
Map<String, Integer> attachmentCounts,
Map<String, Integer> permissionsBoundaryUsageCounts) {
}
+
+ // =========================================================================
+ // Credential Report
+ // =========================================================================
+
+ public record CredentialReportGeneration(String state, String description) {}
+
+ public record CredentialReportContent(String base64Content, String reportFormat, Instant generatedTime) {}
+
+ /**
+ * AWS generates a fresh report only if the most recent one is older than
+ * {@link #CREDENTIAL_REPORT_MAX_AGE}; otherwise it downloads the existing one. Building the
+ * CSV here is effectively instant, so unlike real AWS this never actually returns
+ * {@code INPROGRESS}: a caller polling {@code GetCredentialReport} after this finds the
+ * report ready immediately. The {@code STARTED} state and its description text still match
+ * AWS's own documented example response for the no-report-exists case.
+ */
+ public CredentialReportGeneration generateCredentialReport() {
+ Instant now = Instant.now();
+ Optional<CredentialReport> existing = credentialReports.get(CREDENTIAL_REPORT_KEY);
+ if (existing.isPresent() && now.isBefore(existing.get().getGeneratedTime().plus(CREDENTIAL_REPORT_MAX_AGE))) {
+ return new CredentialReportGeneration("COMPLETE",
+ "Current report has already been generated within the past 4 hours.");
+ }
+ String csv = buildCredentialReportCsv();
+ String base64Content = Base64.getEncoder().encodeToString(csv.getBytes(StandardCharsets.UTF_8));
+ credentialReports.put(CREDENTIAL_REPORT_KEY, new CredentialReport(base64Content, now));
+ String description = existing.isEmpty()
+ ? "No report exists. Starting a new report generation task"
+ : "The previous report has expired. Starting a new report generation task";
+ return new CredentialReportGeneration("STARTED", description);
+ }
+
+ public CredentialReportContent getCredentialReport() {
+ CredentialReport report = credentialReports.get(CREDENTIAL_REPORT_KEY)
+ .orElseThrow(() -> new AwsException("ReportNotPresent",
+ "The request was rejected because the credential report does not exist. "
+ + "To generate a credential report, use GenerateCredentialReport.", 410));
+ if (Instant.now().isAfter(report.getGeneratedTime().plus(CREDENTIAL_REPORT_MAX_AGE))) {
+ throw new AwsException("ReportExpired",
+ "The request was rejected because the most recent credential report has expired. "
+ + "To generate a new credential report, use GenerateCredentialReport.", 410);
+ }
+ return new CredentialReportContent(report.getBase64Content(), "text/csv", report.getGeneratedTime());
+ }
+
+ /**
+ * The 23 columns AWS documents for the credential report, in order, always led by the
+ * {@code <root_account>} row. Floci does not model root account credentials at all (see
+ * {@code GetAccountSummary}'s {@code AccountPasswordPresent}/{@code AccountAccessKeysPresent},
+ * always zero), so that row is always unused/not-present placeholders. MFA devices and X.509
+ * signing certificates are not modeled for IAM users either, so those columns are always
+ * {@code FALSE}/{@code N/A} for every row; access key last-used tracking (date, region,
+ * service) is not modeled, so those three columns are always {@code N/A} too.
+ */
+ private String buildCredentialReportCsv() {
+ StringBuilder csv = new StringBuilder(
+ "user,arn,user_creation_time,password_enabled,password_last_used,password_last_changed,"
+ + "password_next_rotation,mfa_active,access_key_1_active,access_key_1_last_rotated,"
+ + "access_key_1_last_used_date,access_key_1_last_used_region,access_key_1_last_used_service,"
+ + "access_key_2_active,access_key_2_last_rotated,access_key_2_last_used_date,"
+ + "access_key_2_last_used_region,access_key_2_last_used_service,cert_1_active,"
+ + "cert_1_last_rotated,cert_2_active,cert_2_last_rotated,additional_credentials_info\n");
+ csv.append(rootAccountReportRow()).append('\n');
+ for (IamUser user : listUsers(null)) {
+ csv.append(userReportRow(user)).append('\n');
+ }
+ return csv.toString();
+ }
+
+ private String rootAccountReportRow() {
+ String arn = "arn:aws:iam::" + regionResolver.getAccountId() + ":root";
+ return String.join(",",
+ "<root_account>", arn, "N/A",
+ "FALSE", "N/A", "N/A", "not_supported",
+ "FALSE",
+ "FALSE", "N/A", "N/A", "N/A", "N/A",
+ "FALSE", "N/A", "N/A", "N/A", "N/A",
+ "FALSE", "N/A", "FALSE", "N/A", "");
+ }
+
+ private String userReportRow(IamUser user) {
+ List<AccessKey> keys = userAccessKeys(user.getUserName());
+ AccessKey key1 = keys.size() > 0 ? keys.get(0) : null;
+ AccessKey key2 = keys.size() > 1 ? keys.get(1) : null;
+ Optional<LoginProfile> loginProfile = loginProfiles.get(user.getUserName());
+ boolean passwordEnabled = loginProfile.isPresent();
+
+ return String.join(",",
+ user.getUserName(),
+ user.getArn(),
+ isoDate(user.getCreateDate()),
+ passwordEnabled ? "TRUE" : "FALSE",
+ passwordLastUsedField(user, passwordEnabled),
+ passwordEnabled ? isoDate(passwordLastChanged(loginProfile.get())) : "N/A",
+ passwordNextRotationField(loginProfile, passwordEnabled),
+ "FALSE",
+ accessKeyActiveField(key1), accessKeyRotatedField(key1), "N/A", "N/A", "N/A",
+ accessKeyActiveField(key2), accessKeyRotatedField(key2), "N/A", "N/A", "N/A",
+ "FALSE", "N/A", "FALSE", "N/A",
+ additionalCredentialsInfoField(keys));
+ }
+
+ /**
+ * AWS documents this as naming the count of extra access keys or certificates and the
+ * actions to list them, but not the exact wording, so this is Floci's own text, not a
+ * verified match. In practice this branch is unreachable through the API: {@link
+ * #createAccessKey} already enforces the real 2-key-per-user quota, so more than two keys
+ * can only happen through directly-edited persisted state, not anything a caller can do.
+ */
+ private String additionalCredentialsInfoField(List<AccessKey> keys) {
+ return keys.size() > 2 ? (keys.size() - 2) + " additional access key(s)" : "";
+ }
+
+ private String passwordLastUsedField(IamUser user, boolean passwordEnabled) {
+ if (!passwordEnabled) {
+ return "N/A";
+ }
+ return user.getPasswordLastUsed() != null ? isoDate(user.getPasswordLastUsed()) : "no_information";
+ }
+
+ /** AWS documents this as always {@code not_supported} for root; blank when no rotation policy is set. */
+ private String passwordNextRotationField(Optional<LoginProfile> loginProfile, boolean passwordEnabled) {
+ if (!passwordEnabled) {
+ return "N/A";
+ }
+ return getAccountPasswordPolicy()
+ .map(AccountPasswordPolicy::getMaxPasswordAge)
+ .map(maxAge -> isoDate(passwordLastChanged(loginProfile.get()).plus(Duration.ofDays(maxAge))))
+ .orElse("");
+ }
+
+ /** Falls back to createDate for a profile persisted before passwordLastChanged existed. */
+ private Instant passwordLastChanged(LoginProfile profile) {
+ return profile.getPasswordLastChanged() != null ? profile.getPasswordLastChanged() : profile.getCreateDate();
+ }
+
+ private String accessKeyActiveField(AccessKey key) {
+ return key != null && "Active".equals(key.getStatus()) ? "TRUE" : "FALSE";
+ }
+
+ private String accessKeyRotatedField(AccessKey key) {
+ return key != null ? isoDate(key.getCreateDate()) : "N/A";
+ }
+
+ private String isoDate(Instant instant) {
+ return instant == null ? "" : DateTimeFormatter.ISO_INSTANT.format(instant);
+ }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/CredentialReport.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/CredentialReport.java
new file mode 100644
index 0000000000..ec871a031d
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/CredentialReport.java
@@ -0,0 +1,33 @@
+package io.github.hectorvent.floci.services.iam.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+
+/**
+ * The account's single stored credential report, Base64-encoded CSV content plus the time it
+ * was generated. AWS stores at most one per account: generating a new one overwrites the
+ * previous one, matching {@link io.github.hectorvent.floci.services.iam.IamService}'s other
+ * single-value-per-account stores ({@code accountAliases}, {@code passwordPolicies}).
+ */
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class CredentialReport {
+
+ private String base64Content;
+ private Instant generatedTime;
+
+ public CredentialReport() {}
+
+ public CredentialReport(String base64Content, Instant generatedTime) {
+ this.base64Content = base64Content;
+ this.generatedTime = generatedTime;
+ }
+
+ public String getBase64Content() { return base64Content; }
+ public void setBase64Content(String base64Content) { this.base64Content = base64Content; }
+
+ public Instant getGeneratedTime() { return generatedTime; }
+ public void setGeneratedTime(Instant generatedTime) { this.generatedTime = generatedTime; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/LoginProfile.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/LoginProfile.java
index dd9eb761a6..284423b9b4 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/model/LoginProfile.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/LoginProfile.java
@@ -20,6 +20,13 @@ public class LoginProfile {
private String password;
private boolean passwordResetRequired;
private Instant createDate;
+ /**
+ * When the password was last set: the credential report's {@code password_last_changed}.
+ * Set alongside {@code createDate} initially, and again whenever {@code UpdateLoginProfile}
+ * actually changes the password (not merely {@code passwordResetRequired}). {@code null} for
+ * a profile persisted before this field existed; callers fall back to {@link #createDate}.
+ */
+ private Instant passwordLastChanged;
public LoginProfile() {}
@@ -28,6 +35,7 @@ public class LoginProfile {
this.password = password;
this.passwordResetRequired = passwordResetRequired;
this.createDate = Instant.now();
+ this.passwordLastChanged = this.createDate;
}
public String getUserName() { return userName; }
@@ -43,4 +51,7 @@ public class LoginProfile {
public Instant getCreateDate() { return createDate; }
public void setCreateDate(Instant createDate) { this.createDate = createDate; }
+
+ public Instant getPasswordLastChanged() { return passwordLastChanged; }
+ public void setPasswordLastChanged(Instant passwordLastChanged) { this.passwordLastChanged = passwordLastChanged; }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/CredentialReportIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/CredentialReportIntegrationTest.java
new file mode 100644
index 0000000000..bbc0cf1342
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/CredentialReportIntegrationTest.java
@@ -0,0 +1,86 @@
+package io.github.hectorvent.floci.services.iam;
+
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.Test;
+
+import java.util.Base64;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.anyOf;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Verifies GenerateCredentialReport and GetCredentialReport against the real wire shape.
+ * IAM state, including the one stored credential report, is shared across the whole test
+ * suite, so a report may already exist for this account by the time these tests run: none of
+ * them assume a specific prior State, only that a Generate/Get pair always succeeds and that
+ * the CSV content is well-formed.
+ */
+@QuarkusTest
+class CredentialReportIntegrationTest {
+
+ private static final String IAM_AUTH =
+ "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request";
+
+ private static io.restassured.specification.RequestSpecification iam(String action) {
+ return given().header("Authorization", IAM_AUTH).formParam("Action", action);
+ }
+
+ @Test
+ void generateCredentialReportReturnsAValidState() {
+ iam("GenerateCredentialReport")
+ .when().post("/").then()
+ .statusCode(200)
+ .contentType("application/xml")
+ .body("GenerateCredentialReportResponse.GenerateCredentialReportResult.State",
+ anyOf(equalTo("STARTED"), equalTo("COMPLETE")));
+ }
+
+ @Test
+ void getCredentialReportAfterGenerateReturnsWellFormedCsv() {
+ iam("GenerateCredentialReport")
+ .when().post("/").then().statusCode(200);
+
+ String content = iam("GetCredentialReport")
+ .when().post("/").then()
+ .statusCode(200)
+ .contentType("application/xml")
+ .body("GetCredentialReportResponse.GetCredentialReportResult.ReportFormat", equalTo("text/csv"))
+ .extract().path("GetCredentialReportResponse.GetCredentialReportResult.Content");
+
+ String csv = new String(Base64.getDecoder().decode(content));
+ assertTrue(csv.startsWith("user,arn,user_creation_time,password_enabled,password_last_used,"
+ + "password_last_changed,password_next_rotation,mfa_active,"),
+ "expected the documented column header, got: " + csv);
+ assertTrue(csv.contains("<root_account>,arn:aws:iam::"), "expected a root account row, got: " + csv);
+ }
+
+ @Test
+ void getCredentialReportIncludesAUserCreatedAfterTheLastGenerate() {
+ String user = "cred-report-it-user-" + Long.toString(System.nanoTime(), 36);
+ iam("CreateUser").formParam("UserName", user)
+ .when().post("/").then().statusCode(200);
+ iam("GenerateCredentialReport")
+ .when().post("/").then().statusCode(200);
+
+ String content = iam("GetCredentialReport")
+ .when().post("/").then().statusCode(200)
+ .extract().path("GetCredentialReportResponse.GetCredentialReportResult.Content");
+ String csv = new String(Base64.getDecoder().decode(content));
+
+ assertTrue(csv.lines().anyMatch(line -> line.startsWith(user + ",")),
+ "expected a row for " + user + ", got: " + csv);
+ }
+
+ @Test
+ void generateCredentialReportResponseHasNoOtherUnexpectedElements() {
+ iam("GenerateCredentialReport")
+ .when().post("/").then()
+ .statusCode(200)
+ .body(containsString("<GenerateCredentialReportResponse"))
+ .body(containsString("<State>"))
+ .body(containsString("<Description>"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
index 9b109e5dfb..c5321f69a1 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
@@ -9,19 +9,23 @@ import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.iam.model.AccessKey;
import io.github.hectorvent.floci.services.iam.model.AccountPasswordPolicy;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
+import io.github.hectorvent.floci.services.iam.model.CredentialReport;
import io.github.hectorvent.floci.services.iam.model.IamGroup;
import io.github.hectorvent.floci.services.iam.model.IamPolicy;
import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.services.iam.model.IamUser;
import io.github.hectorvent.floci.services.iam.model.LoginProfile;
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.InstanceProfile;
import io.github.hectorvent.floci.services.iam.model.PolicyVersion;
import io.github.hectorvent.floci.services.iam.model.SessionCredential;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import java.time.Duration;
import java.time.Instant;
+import java.util.Base64;
import java.util.List;
import java.util.Map;
@@ -2055,4 +2059,130 @@ class IamServiceTest {
assertTrue(details.groups().stream().anyMatch(g -> g.getGroupName().equals("aad-list-group")));
assertTrue(details.roles().stream().anyMatch(r -> r.getRoleName().equals("aad-list-role")));
}
+
+ // =========================================================================
+ // Credential Report
+ // =========================================================================
+
+ @Test
+ void getCredentialReportBeforeAnyGenerateReturnsReportNotPresent() {
+ AwsException ex = assertThrows(AwsException.class, () -> iamService.getCredentialReport());
+ assertEquals("ReportNotPresent", ex.getErrorCode());
+ }
+
+ @Test
+ void generateCredentialReportReturnsStartedWhenNoneExists() {
+ IamService.CredentialReportGeneration generation = iamService.generateCredentialReport();
+
+ assertEquals("STARTED", generation.state());
+ assertEquals("No report exists. Starting a new report generation task", generation.description());
+ }
+
+ @Test
+ void generateCredentialReportReturnsCompleteWithinFourHoursOfAnExistingReport() {
+ iamService.generateCredentialReport();
+
+ IamService.CredentialReportGeneration second = iamService.generateCredentialReport();
+
+ assertEquals("COMPLETE", second.state());
+ }
+
+ @Test
+ void getCredentialReportAfterGenerateReturnsDecodableCsvWithTheHeaderAndRootRow() {
+ iamService.generateCredentialReport();
+
+ IamService.CredentialReportContent content = iamService.getCredentialReport();
+
+ assertEquals("text/csv", content.reportFormat());
+ String csv = new String(Base64.getDecoder().decode(content.base64Content()));
+ assertTrue(csv.startsWith("user,arn,user_creation_time,password_enabled,"),
+ "expected the documented column header, got: " + csv);
+ assertTrue(csv.contains("<root_account>,arn:aws:iam::"), "expected a root account row, got: " + csv);
+ }
+
+ @Test
+ void getCredentialReportIncludesEveryUserWithPasswordAndAccessKeyState() {
+ iamService.createUser("cred-report-user", "/");
+ iamService.createLoginProfile("cred-report-user", "Sup3r-Secret!", false);
+ iamService.createAccessKey("cred-report-user");
+ iamService.generateCredentialReport();
+
+ String csv = new String(Base64.getDecoder().decode(iamService.getCredentialReport().base64Content()));
+ String row = csv.lines().filter(line -> line.startsWith("cred-report-user,")).findFirst()
+ .orElseThrow(() -> new AssertionError("no row for cred-report-user in: " + csv));
+ String[] fields = row.split(",", -1);
+
+ assertEquals("TRUE", fields[3], "password_enabled");
+ assertEquals("TRUE", fields[8], "access_key_1_active");
+ assertEquals("FALSE", fields[7], "mfa_active is never modeled");
+ }
+
+ /**
+ * UpdateLoginProfile changes the password without touching LoginProfile's own createDate
+ * (its meaning stays "profile created"), so the credential report's password_last_changed
+ * column has to be backed by a separate field, updated whenever the password itself
+ * changes: otherwise a changed password would still report the original creation time.
+ */
+ @Test
+ void updateLoginProfilePasswordChangeMovesPasswordLastChanged() {
+ iamService.createUser("cred-report-changed-user", "/");
+ iamService.createLoginProfile("cred-report-changed-user", "Original-P4ss!", false);
+ Instant createdAt = iamService.getLoginProfile("cred-report-changed-user").getPasswordLastChanged();
+
+ iamService.updateLoginProfile("cred-report-changed-user", "Updated-P4ss!", null);
+ Instant changedAt = iamService.getLoginProfile("cred-report-changed-user").getPasswordLastChanged();
+
+ assertTrue(changedAt.isAfter(createdAt),
+ "expected password_last_changed to move: created=" + createdAt + " changed=" + changedAt);
+ }
+
+ /** Toggling only passwordResetRequired is not a password change, so the timestamp must not move. */
+ @Test
+ void updateLoginProfileWithoutAPasswordChangeLeavesPasswordLastChangedAlone() {
+ iamService.createUser("cred-report-unchanged-user", "/");
+ iamService.createLoginProfile("cred-report-unchanged-user", "Original-P4ss!", false);
+ Instant createdAt = iamService.getLoginProfile("cred-report-unchanged-user").getPasswordLastChanged();
+
+ iamService.updateLoginProfile("cred-report-unchanged-user", null, true);
+
+ assertEquals(createdAt, iamService.getLoginProfile("cred-report-unchanged-user").getPasswordLastChanged());
+ }
+
+ @Test
+ void getCredentialReportOnAnExpiredReportThrowsReportExpired() {
+ StorageBackend<String, CredentialReport> credentialReports = new InMemoryStorage<>();
+ credentialReports.put("credential-report",
+ new CredentialReport("dGVzdA==", Instant.now().minus(Duration.ofHours(5))));
+ IamService withExpiredReport = 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<>(), credentialReports,
+ new RegionResolver("us-east-1", "000000000000"), false, null);
+
+ AwsException ex = assertThrows(AwsException.class, withExpiredReport::getCredentialReport);
+ assertEquals("ReportExpired", ex.getErrorCode());
+ }
+
+ @Test
+ void generateCredentialReportOnAnExpiredReportStartsANewOne() {
+ StorageBackend<String, CredentialReport> credentialReports = new InMemoryStorage<>();
+ credentialReports.put("credential-report",
+ new CredentialReport("dGVzdA==", Instant.now().minus(Duration.ofHours(5))));
+ IamService withExpiredReport = 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<>(), credentialReports,
+ new RegionResolver("us-east-1", "000000000000"), false, null);
+
+ IamService.CredentialReportGeneration generation = withExpiredReport.generateCredentialReport();
+
+ assertEquals("STARTED", generation.state());
+ assertEquals("The previous report has expired. Starting a new report generation task",
+ generation.description());
+ assertDoesNotThrow(withExpiredReport::getCredentialReport);
+ }
}