Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(account): add alternate contact operations (#3118)

Franklin G. Mendozad80734e6de0c
diff --git a/README.md b/README.md
index 697ab4f70b..5e6f9f2b73 100644
--- a/README.md
+++ b/README.md
@@ -238,7 +238,7 @@ Floci supports local emulation for application services, data services, eventing
| Data, analytics, and AI | Athena, Glue, Lake Formation, EMR, EMR Serverless, Redshift, Firehose, Managed Service for Apache Flink, OpenSearch, S3 Tables, S3 Vectors, Textract, Transcribe, Comprehend, Rekognition, Translate, Bedrock Runtime, Bedrock AgentCore |
| Databases and caching | RDS, RDS Data API, Neptune, DocumentDB, MemoryDB, ElastiCache |
| Messaging and transfer | SES, Kinesis, MSK, Amazon MQ, Transfer Family, IoT Core, Amazon Connect |
-| Security and governance | AWS Network Firewall, AWS RAM, Service Quotas, WAF v2, GuardDuty, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations, IAM Access Analyzer, IAM Identity Center (SSO Admin), Amazon Macie, Control Tower, Service Catalog |
+| Security and governance | AWS Network Firewall, AWS RAM, Service Quotas, WAF v2, GuardDuty, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations, AWS Account Management, IAM Access Analyzer, IAM Identity Center (SSO Admin), Amazon Macie, Control Tower, Service Catalog |
| Cost and billing | Pricing, Cost Explorer, Cost and Usage Reports, BCM Data Exports |
| Resilience, backup, and config | AWS FIS, AWS Backup, AWS Config, AppConfig, AppConfigData, CloudFormation, Cloud Control API |
diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml
index 3738cd6a27..1c9be54002 100644
--- a/compatibility-tests/sdk-test-java/pom.xml
+++ b/compatibility-tests/sdk-test-java/pom.xml
@@ -244,6 +244,11 @@
<groupId>software.amazon.awssdk</groupId>
<artifactId>macie2</artifactId>
</dependency>
+ <!-- AWS Account Management client -->
+ <dependency>
+ <groupId>software.amazon.awssdk</groupId>
+ <artifactId>account</artifactId>
+ </dependency>
<!-- IAM Access Analyzer client -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
index 64a6e0f4d3..40928290af 100644
--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
@@ -3,6 +3,7 @@ package com.floci.test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.account.AccountClient;
import software.amazon.awssdk.services.accessanalyzer.AccessAnalyzerClient;
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
import software.amazon.awssdk.services.cloudhsmv2.CloudHsmV2Client;
@@ -278,6 +279,14 @@ public final class TestFixtures {
.build();
}
+ public static AccountClient accountClient() {
+ return AccountClient.builder()
+ .endpointOverride(ENDPOINT)
+ .region(REGION)
+ .credentialsProvider(CREDENTIALS)
+ .build();
+ }
+
public static AccessAnalyzerClient accessAnalyzerClient() {
return AccessAnalyzerClient.builder()
.endpointOverride(ENDPOINT)
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AccountAlternateContactTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AccountAlternateContactTest.java
new file mode 100644
index 0000000000..8b207636c9
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AccountAlternateContactTest.java
@@ -0,0 +1,33 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.services.account.AccountClient;
+import software.amazon.awssdk.services.account.model.AlternateContactType;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assumptions.assumeFalse;
+
+@DisplayName("AWS Account Management alternate contacts")
+class AccountAlternateContactTest {
+
+ @Test
+ void putAndGetAlternateContactUseAwsSdk() {
+ assumeFalse(TestFixtures.isRealAws(), "Writes emulator account contact state");
+
+ try (AccountClient account = TestFixtures.accountClient()) {
+ account.putAlternateContact(request -> request
+ .alternateContactType(AlternateContactType.SECURITY)
+ .emailAddress("[email protected]")
+ .name("Security Team")
+ .phoneNumber("+1 555 0100")
+ .title("Security"));
+
+ var response = account.getAlternateContact(request -> request
+ .alternateContactType(AlternateContactType.SECURITY));
+ assertThat(response.alternateContact()).isNotNull();
+ assertThat(response.alternateContact().emailAddress()).isEqualTo("[email protected]");
+ assertThat(response.alternateContact().alternateContactType()).isEqualTo(AlternateContactType.SECURITY);
+ }
+ }
+}
diff --git a/docs/services/account.md b/docs/services/account.md
new file mode 100644
index 0000000000..ecc1974a46
--- /dev/null
+++ b/docs/services/account.md
@@ -0,0 +1,32 @@
+# AWS Account Management
+
+**Protocol:** REST JSON
+
+**Endpoint:** `http://localhost:4566`
+
+Floci supports alternate-contact management over the AWS REST JSON protocol.
+
+## Supported Actions
+
+<!-- floci:actions:start -->
+| Action | Description |
+| --- | --- |
+| `PutAlternateContact` | - |
+| `GetAlternateContact` | - |
+<!-- floci:actions:end -->
+
+Alternate contacts are isolated by caller account and stored through `StorageFactory`.
+
+## AWS-compatible failures
+
+`PutAlternateContact` validates the contact type, name, title, email address, phone number, and optional target account ID. `GetAlternateContact` returns `ResourceNotFoundException` when the requested contact has not been configured. Invalid request data uses `ValidationException` and unsupported cross-account access uses `AccessDeniedException`.
+
+AWS models provider-side `InternalServerException` and `TooManyRequestsException`; Floci does not synthesize those failures without an actual triggering condition.
+
+See the [AWS Account Management API Reference](https://docs.aws.amazon.com/accounts/latest/reference/API_Operations.html).
+
+## Configuration
+
+| Variable | Default | Description |
+|---|---|---|
+| `FLOCI_SERVICES_ACCOUNT_ENABLED` | `true` | Enable or disable AWS Account Management |
diff --git a/docs/services/index.md b/docs/services/index.md
index 5b6e6227e3..7aaf8fb88d 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -44,6 +44,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [CloudWatch Metrics](cloudwatch.md#metrics) | `POST /` with `Action=` or JSON 1.1 | Query / JSON | 11 |
| [CloudWatch RUM](rum.md) | `/appmonitor`, `/appmonitor/{name}`, `/appmonitors` | REST JSON | 5 |
| [GuardDuty](guardduty.md) | `/detector`, `/detector/{detectorId}`, `/detector/{detectorId}/admin`, `/admin/*`, `/tags/*` | REST JSON | 13 |
+| [AWS Account Management](account.md) | `/putAlternateContact`, `/getAlternateContact` | REST JSON | 2 |
| [IAM Access Analyzer](access-analyzer.md) | `/analyzer`, `/analyzer/{name}` | REST JSON | 3 |
| [IAM Identity Center (SSO Admin)](ssoadmin.md) | `POST /` + `X-Amz-Target: SWBExternalService.*` | JSON 1.1 | 13 |
| [Amazon Macie](macie2.md) | `/admin`, `/macie`, `/admin/configuration` | REST JSON | 6 |
diff --git a/mkdocs.yml b/mkdocs.yml
index 994dfc7c25..5aed3823df 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -119,6 +119,7 @@ nav:
- IAM: services/iam.md
- STS: services/sts.md
- Organizations: services/organizations.md
+ - AWS Account Management: services/account.md
- IAM Access Analyzer: services/access-analyzer.md
- IAM Identity Center (SSO Admin): services/ssoadmin.md
- Amazon Macie: services/macie2.md
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index b79cedbd19..0c1515f390 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -711,6 +711,7 @@ public interface EmulatorConfig {
ServiceCatalogServiceConfig servicecatalog();
SsoAdminServiceConfig ssoadmin();
Macie2ServiceConfig macie2();
+ AccountServiceConfig account();
AccessAnalyzerServiceConfig accessanalyzer();
ServiceQuotasServiceConfig servicequotas();
RamServiceConfig ram();
@@ -745,6 +746,11 @@ public interface EmulatorConfig {
boolean enabled();
}
+ interface AccountServiceConfig {
+ @WithDefault("true")
+ boolean enabled();
+ }
+
interface AccessAnalyzerServiceConfig {
@WithDefault("true")
boolean enabled();
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
index aa6fe742e1..b9e1121134 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
@@ -33,6 +33,7 @@ import io.github.hectorvent.floci.services.appsync.AppSyncController;
import io.github.hectorvent.floci.services.rdsdata.RdsDataController;
import io.github.hectorvent.floci.services.guardduty.GuardDutyController;
import io.github.hectorvent.floci.services.macie2.MacieController;
+import io.github.hectorvent.floci.services.account.AccountController;
import io.github.hectorvent.floci.services.accessanalyzer.AccessAnalyzerController;
import io.github.hectorvent.floci.services.aps.ApsController;
import io.github.hectorvent.floci.services.controltower.ControlTowerControlController;
@@ -413,6 +414,9 @@ public class ResolvedServiceCatalog {
descriptor("macie2", "macie2", config.services().macie2().enabled(), true,
"macie2", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON), Set.of(), Set.of("macie2"), Set.of(), Set.of(MacieController.class)),
+ descriptor("account", "account", config.services().account().enabled(), true,
+ "account", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
+ protocols(ServiceProtocol.REST_JSON), Set.of(), Set.of("account"), Set.of(), Set.of(AccountController.class)),
descriptor("access-analyzer", "accessanalyzer", config.services().accessanalyzer().enabled(), true,
"accessanalyzer", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON), Set.of(), Set.of("access-analyzer"), Set.of(), Set.of(AccessAnalyzerController.class)),
diff --git a/src/main/java/io/github/hectorvent/floci/services/account/AccountController.java b/src/main/java/io/github/hectorvent/floci/services/account/AccountController.java
new file mode 100644
index 0000000000..0eabfd3d87
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/account/AccountController.java
@@ -0,0 +1,59 @@
+package io.github.hectorvent.floci.services.account;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.JsonErrorResponseUtils;
+import io.github.hectorvent.floci.core.common.RequestContext;
+import io.github.hectorvent.floci.services.account.model.AlternateContact;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Consumes;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.WebApplicationException;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+
+@Path("/")
+@Produces(MediaType.APPLICATION_JSON)
+@Consumes(MediaType.APPLICATION_JSON)
+public class AccountController {
+ private final AccountService accountService;
+ private final ObjectMapper objectMapper;
+ private final RequestContext requestContext;
+
+ @Inject
+ public AccountController(AccountService accountService, ObjectMapper objectMapper, RequestContext requestContext) {
+ this.accountService = accountService;
+ this.objectMapper = objectMapper;
+ this.requestContext = requestContext;
+ }
+
+ @POST
+ @Path("/putAlternateContact")
+ public Response putAlternateContact(String body) {
+ accountService.putAlternateContact(requestContext.getAccountId(), readTree(body));
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ @POST
+ @Path("/getAlternateContact")
+ public Response getAlternateContact(String body) {
+ AlternateContact contact = accountService.getAlternateContact(requestContext.getAccountId(), readTree(body));
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("AlternateContact", objectMapper.valueToTree(contact));
+ return Response.ok(response).build();
+ }
+
+ private JsonNode readTree(String body) {
+ try {
+ return objectMapper.reader()
+ .with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .readTree(body == null || body.isBlank() ? "{}" : body);
+ } catch (Exception e) {
+ throw new WebApplicationException(JsonErrorResponseUtils.createSerializationErrorResponse());
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/account/AccountService.java b/src/main/java/io/github/hectorvent/floci/services/account/AccountService.java
new file mode 100644
index 0000000000..445781c6a7
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/account/AccountService.java
@@ -0,0 +1,142 @@
+package io.github.hectorvent.floci.services.account;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.Resettable;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.account.model.AlternateContact;
+import io.github.hectorvent.floci.services.organizations.OrganizationsService;
+import io.github.hectorvent.floci.services.organizations.model.Organization;
+import io.github.hectorvent.floci.services.organizations.model.OrganizationAccount;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Pattern;
+
+@ApplicationScoped
+public class AccountService implements Resettable {
+ private static final String ACCOUNT_MANAGEMENT_SERVICE_PRINCIPAL = "account.amazonaws.com";
+ private static final Pattern ACCOUNT_ID = Pattern.compile("\\d{12}");
+ private static final Pattern EMAIL = Pattern.compile("\\s*[\\w+=.#|!&-]+@[\\w.-]+\\.[\\w]+\\s*");
+ private static final Pattern PHONE = Pattern.compile("[\\s0-9()+-]+");
+ private static final Set<String> CONTACT_TYPES = Set.of("BILLING", "OPERATIONS", "SECURITY");
+
+ private final AccountAwareStorageBackend<AlternateContact> contacts;
+ private final OrganizationsService organizationsService;
+
+ @Inject
+ public AccountService(StorageFactory storageFactory, OrganizationsService organizationsService) {
+ this.contacts = storageFactory.create("account", "account-alternate-contacts.json",
+ new TypeReference<Map<String, AlternateContact>>() {});
+ this.organizationsService = organizationsService;
+ }
+
+ public void putAlternateContact(String callerAccountId, JsonNode request) {
+ String targetAccountId = resolveTargetAccount(callerAccountId, request);
+ String type = requireContactType(request);
+ AlternateContact contact = new AlternateContact(
+ type,
+ requirePattern(request, "EmailAddress", 1, 254, EMAIL),
+ requireLength(request, "Name", 1, 64),
+ requirePattern(request, "PhoneNumber", 1, 25, PHONE),
+ requireLength(request, "Title", 1, 50));
+ contacts.putForAccount(targetAccountId, type, contact);
+ }
+
+ public AlternateContact getAlternateContact(String callerAccountId, JsonNode request) {
+ String targetAccountId = resolveTargetAccount(callerAccountId, request);
+ String type = requireContactType(request);
+ return contacts.getForAccount(targetAccountId, type)
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",
+ "The alternate contact does not exist for the specified account and contact type.", 404));
+ }
+
+ private String resolveTargetAccount(String callerAccountId, JsonNode request) {
+ JsonNode accountIdNode = request == null ? null : request.get("AccountId");
+ if (accountIdNode == null || accountIdNode.isNull()) {
+ return callerAccountId;
+ }
+ if (!accountIdNode.isTextual()) {
+ throw new AwsException("SerializationException",
+ "AccountId must be a string.", 400);
+ }
+ String requestedAccountId = accountIdNode.textValue();
+ if (!ACCOUNT_ID.matcher(requestedAccountId).matches()) {
+ throw validation("AccountId must be a 12 digit account ID.");
+ }
+
+ Organization organization;
+ OrganizationAccount caller;
+ try {
+ organization = organizationsService.describeOrganization(callerAccountId);
+ caller = organizationsService.describeAccount(callerAccountId, callerAccountId);
+ organizationsService.describeAccount(callerAccountId, requestedAccountId);
+ } catch (AwsException e) {
+ throw new AwsException("AccessDeniedException",
+ "The specified account cannot be accessed by the calling account.", 403);
+ }
+
+ if (!"ALL".equals(organization.getFeatureSet())) {
+ throw new AwsException("AccessDeniedException",
+ "The organization must have all features enabled.", 403);
+ }
+ if (!organization.getEnabledServicePrincipals().containsKey(ACCOUNT_MANAGEMENT_SERVICE_PRINCIPAL)) {
+ throw new AwsException("AccessDeniedException",
+ "Trusted access for AWS Account Management is not enabled for the organization.", 403);
+ }
+
+ boolean managementAccount = callerAccountId.equals(organization.getMasterAccountId());
+ boolean delegatedAdministrator = caller.getDelegatedServices()
+ .containsKey(ACCOUNT_MANAGEMENT_SERVICE_PRINCIPAL);
+ if (!managementAccount && !delegatedAdministrator) {
+ throw new AwsException("AccessDeniedException",
+ "The calling account is not the management account or a delegated administrator.", 403);
+ }
+ if (managementAccount && requestedAccountId.equals(callerAccountId)) {
+ throw validation("The management account cannot specify its own AccountId.");
+ }
+ return requestedAccountId;
+ }
+
+ @Override
+ public void clear() {
+ contacts.clear();
+ }
+
+ private static String requireContactType(JsonNode request) {
+ String value = requireLength(request, "AlternateContactType", 1, 32);
+ if (!CONTACT_TYPES.contains(value)) {
+ throw validation("AlternateContactType must be BILLING, OPERATIONS, or SECURITY.");
+ }
+ return value;
+ }
+
+ private static String requirePattern(JsonNode request, String field, int min, int max, Pattern pattern) {
+ String value = requireLength(request, field, min, max);
+ if (!pattern.matcher(value).matches()) {
+ throw validation(field + " does not satisfy the required pattern.");
+ }
+ return value;
+ }
+
+ private static String requireLength(JsonNode request, String field, int min, int max) {
+ String value = text(request, field);
+ if (value == null || value.length() < min || value.length() > max) {
+ throw validation(field + " must be between " + min + " and " + max + " characters.");
+ }
+ return value;
+ }
+
+ private static String text(JsonNode request, String field) {
+ JsonNode value = request == null ? null : request.get(field);
+ return value != null && value.isTextual() ? value.textValue() : null;
+ }
+
+ private static AwsException validation(String message) {
+ return new AwsException("ValidationException", message, 400);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/account/model/AlternateContact.java b/src/main/java/io/github/hectorvent/floci/services/account/model/AlternateContact.java
new file mode 100644
index 0000000000..46a5c670fd
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/account/model/AlternateContact.java
@@ -0,0 +1,72 @@
+package io.github.hectorvent.floci.services.account.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class AlternateContact {
+ @JsonProperty("AlternateContactType")
+ private String alternateContactType;
+ @JsonProperty("EmailAddress")
+ private String emailAddress;
+ @JsonProperty("Name")
+ private String name;
+ @JsonProperty("PhoneNumber")
+ private String phoneNumber;
+ @JsonProperty("Title")
+ private String title;
+
+ public AlternateContact() {
+ }
+
+ public AlternateContact(String alternateContactType, String emailAddress, String name,
+ String phoneNumber, String title) {
+ this.alternateContactType = alternateContactType;
+ this.emailAddress = emailAddress;
+ this.name = name;
+ this.phoneNumber = phoneNumber;
+ this.title = title;
+ }
+
+ public String getAlternateContactType() {
+ return alternateContactType;
+ }
+
+ public void setAlternateContactType(String alternateContactType) {
+ this.alternateContactType = alternateContactType;
+ }
+
+ public String getEmailAddress() {
+ return emailAddress;
+ }
+
+ public void setEmailAddress(String emailAddress) {
+ this.emailAddress = emailAddress;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getPhoneNumber() {
+ return phoneNumber;
+ }
+
+ public void setPhoneNumber(String phoneNumber) {
+ this.phoneNumber = phoneNumber;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index d80ca3d539..0cd7c50535 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -614,6 +614,8 @@ floci:
enabled: true
macie2:
enabled: true
+ account:
+ enabled: true
accessanalyzer:
enabled: true
controltower:
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/UnknownServiceScopeGuardIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/UnknownServiceScopeGuardIntegrationTest.java
index 8df629b875..a573ca51f4 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/UnknownServiceScopeGuardIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/UnknownServiceScopeGuardIntegrationTest.java
@@ -23,9 +23,9 @@ class UnknownServiceScopeGuardIntegrationTest {
}
@Test
- void accountScopedRestRequestGetsUnknownOperation() {
+ void unsupportedRestServiceScopeGetsUnknownOperation() {
given()
- .header("Authorization", authorization("account"))
+ .header("Authorization", authorization("support"))
.contentType("application/json")
.body("{}")
.when()
diff --git a/src/test/java/io/github/hectorvent/floci/services/account/AccountAlternateContactIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/account/AccountAlternateContactIntegrationTest.java
new file mode 100644
index 0000000000..0a1fd3f22d
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/account/AccountAlternateContactIntegrationTest.java
@@ -0,0 +1,58 @@
+package io.github.hectorvent.floci.services.account;
+
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+
+@QuarkusTest
+class AccountAlternateContactIntegrationTest {
+ private static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260904/us-east-1/account/aws4_request";
+
+ @BeforeAll
+ static void configureRestAssured() { RestAssuredJsonUtils.configureAwsContentTypes(); }
+
+ @Test
+ void createsUpdatesReadsAndDeletesAlternateContact() {
+ put("[email protected]").statusCode(200);
+ get().statusCode(200).body("AlternateContact.EmailAddress", equalTo("[email protected]"));
+ put("[email protected]").statusCode(200);
+ get().statusCode(200).body("AlternateContact.EmailAddress", equalTo("[email protected]"));
+ }
+
+ @Test
+ void rejectsInvalidContactType() {
+ given().contentType("application/json").header("Authorization", AUTH)
+ .body("{\"AlternateContactType\":\"OTHER\"}")
+ .post("/getAlternateContact").then().statusCode(400).body("__type", equalTo("ValidationException"));
+ }
+
+ @Test
+ void rejectsNonStringAccountIdInsteadOfFallingBackToCaller() {
+ given().contentType("application/json").header("Authorization", AUTH)
+ .body("{\"AccountId\":123456789012,\"AlternateContactType\":\"SECURITY\",\"Name\":\"Security\",\"Title\":\"Owner\",\"EmailAddress\":\"[email protected]\",\"PhoneNumber\":\"+12025550123\"}")
+ .post("/putAlternateContact").then().statusCode(400).body("__type", equalTo("SerializationException"));
+ }
+
+ @Test
+ void trailingJsonReturnsSerializationException() {
+ given().contentType("application/json").header("Authorization", AUTH)
+ .body("{\"AlternateContactType\":\"SECURITY\"} {}")
+ .post("/getAlternateContact").then().statusCode(400).body("__type", equalTo("SerializationException"));
+ }
+
+ private static io.restassured.response.ValidatableResponse put(String email) {
+ return given().contentType("application/json").header("Authorization", AUTH)
+ .body("{\"AlternateContactType\":\"SECURITY\",\"Name\":\"Security\",\"Title\":\"Owner\",\"EmailAddress\":\"" + email + "\",\"PhoneNumber\":\"+12025550123\"}")
+ .post("/putAlternateContact").then();
+ }
+
+ private static io.restassured.response.ValidatableResponse get() {
+ return given().contentType("application/json").header("Authorization", AUTH)
+ .body("{\"AlternateContactType\":\"SECURITY\"}")
+ .post("/getAlternateContact").then();
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/account/AccountServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/account/AccountServiceTest.java
new file mode 100644
index 0000000000..a3a38b8394
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/account/AccountServiceTest.java
@@ -0,0 +1,76 @@
+package io.github.hectorvent.floci.services.account;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.account.model.AlternateContact;
+import io.github.hectorvent.floci.services.organizations.OrganizationsService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+class AccountServiceTest {
+ private static final String ACCOUNT_ID = "123456789012";
+ private final ObjectMapper mapper = new ObjectMapper();
+ private AccountService service;
+
+ @BeforeEach
+ @SuppressWarnings({"unchecked", "rawtypes"})
+ void setUp() {
+ StorageFactory storageFactory = mock(StorageFactory.class);
+ AccountAwareStorageBackend<AlternateContact> store = AccountAwareStorageBackend.inMemory(ACCOUNT_ID);
+ when(storageFactory.create(eq("account"), eq("account-alternate-contacts.json"), any(TypeReference.class)))
+ .thenReturn((AccountAwareStorageBackend) store);
+ service = new AccountService(storageFactory, mock(OrganizationsService.class));
+ }
+
+ @Test
+ void ownAccountPutAndGetRoundTrip() {
+ ObjectNode request = contactRequest();
+ service.putAlternateContact(ACCOUNT_ID, request);
+ AlternateContact contact = service.getAlternateContact(ACCOUNT_ID, request);
+ assertEquals("[email protected]", contact.getEmailAddress());
+ assertEquals("SECURITY", contact.getAlternateContactType());
+ }
+
+ @Test
+ void nonStringAccountIdReturnsSerializationException() {
+ ObjectNode request = contactRequest();
+ request.put("AccountId", 123456789012L);
+ AwsException error = assertThrows(AwsException.class,
+ () -> service.putAlternateContact(ACCOUNT_ID, request));
+ assertEquals("SerializationException", error.getErrorCode());
+ }
+
+ @Test
+ void clearRemovesContacts() {
+ ObjectNode request = contactRequest();
+ service.putAlternateContact(ACCOUNT_ID, request);
+ service.clear();
+ AwsException error = assertThrows(AwsException.class,
+ () -> service.getAlternateContact(ACCOUNT_ID, request));
+ assertEquals("ResourceNotFoundException", error.getErrorCode());
+ }
+
+ private ObjectNode contactRequest() {
+ ObjectNode request = mapper.createObjectNode();
+ request.put("AlternateContactType", "SECURITY");
+ request.put("EmailAddress", "[email protected]");
+ request.put("Name", "Security Team");
+ request.put("PhoneNumber", "+1 555 0100");
+ request.put("Title", "Security");
+ return request;
+ }
+}
diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml
index 89bc79b569..4ff6210d39 100644
--- a/src/test/resources/application.yml
+++ b/src/test/resources/application.yml
@@ -376,6 +376,8 @@ floci:
enabled: true
macie2:
enabled: true
+ account:
+ enabled: true
accessanalyzer:
enabled: true
controltower:
diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml
index 616e614cff..d7aaaaef6c 100644
--- a/tools/docs/services.yaml
+++ b/tools/docs/services.yaml
@@ -10,6 +10,10 @@
# the new-service sentinel only fires on genuinely unregistered handlers.
services:
+ - service: account
+ doc: docs/services/account.md
+ sources:
+ - { path: src/main/java/io/github/hectorvent/floci/services/account/AccountController.java, mode: rest }
- service: accessanalyzer
doc: docs/services/access-analyzer.md
sources: