Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(servicequotas,ram): add Service Quotas and AWS RAM resource sharing (#2579)

Sam Fakhreddinef912c3b717ac
diff --git a/README.md b/README.md
index b596d7a8b7..bc6fe97e92 100644
--- a/README.md
+++ b/README.md
@@ -178,7 +178,7 @@ LocalStack's community edition [sunset in March 2026](https://blog.localstack.cl
| CodeBuild | Real Docker execution | No |
| Native binary | ~40 MB | No |
-**76 AWS services. Broad coverage. Free forever.**
+**78 AWS services. Broad coverage. Free forever.**
## Architecture Overview
@@ -226,7 +226,7 @@ Floci supports local emulation for application services, data services, eventing
| Data, analytics, and AI | Athena, Glue, EMR, Firehose, Managed Service for Apache Flink, OpenSearch, S3 Tables, S3 Vectors, Textract, Transcribe, 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 |
-| Security and governance | WAF v2, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations |
+| Security and governance | AWS RAM, Service Quotas, WAF v2, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations |
| 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 |
@@ -291,6 +291,8 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/
| CodeBuild | In-process with real Docker | Real buildspec execution, CloudWatch logs, S3 artifacts |
| CodeDeploy | In-process with Lambda traffic shifting | Deployment groups, configs, lifecycle hooks, auto-rollback |
| CodePipeline | In-process orchestration | Pipelines, executions, S3 artifacts, approvals, local providers, custom workers |
+| Service Quotas | In-process | Generated quota catalog with generous static values; real quota codes for CodeBuild and Lambda concurrency |
+| AWS RAM | In-process | EnableSharingWithAwsOrganization opt-in |
| AWS Batch | In-process | Compute environments, job queues, job definitions, job submission and lifecycle |
| Auto Scaling | In-process with reconciler | Launch configs, ASGs, desired capacity reconciliation, lifecycle hooks |
| Application Auto Scaling | In-process | Scalable targets, target-tracking and step scaling policies, CloudWatch alarm creation, tagging (policies are stored but inert) |
diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.md
index a3d94387c4..b41c122386 100644
--- a/docs/configuration/advanced/application-yml.md
+++ b/docs/configuration/advanced/application-yml.md
@@ -155,6 +155,13 @@ floci:
enforcement-enabled: false # Set to true to enforce IAM policies on all requests
seed-deployer-principal: false # Set to true to create a local floci-deployer admin principal
+ servicequotas:
+ enabled: true
+
+ ram:
+ enabled: true
+
+
elasticache:
enabled: true
proxy-base-port: 6379
diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md
index 2ff3c6e231..72bdf2cebb 100644
--- a/docs/configuration/environment-variables.md
+++ b/docs/configuration/environment-variables.md
@@ -457,6 +457,8 @@ These services spawn Docker containers. They require access to the Docker socket
| `FLOCI_SERVICES_CODEBUILD_ENABLED` | `true` | Enable the CodeBuild service |
| `FLOCI_SERVICES_CODEBUILD_DOCKER_NETWORK` | _(none)_ | Docker network for CodeBuild build containers |
| `FLOCI_SERVICES_CODEDEPLOY_ENABLED` | `true` | Enable the CodeDeploy service |
+| `FLOCI_SERVICES_SERVICEQUOTAS_ENABLED` | `true` | Enable the Service Quotas service |
+| `FLOCI_SERVICES_RAM_ENABLED` | `true` | Enable the AWS RAM service |
| `FLOCI_SERVICES_BACKUP_ENABLED` | `true` | Enable the AWS Backup service |
| `FLOCI_SERVICES_BACKUP_JOB_COMPLETION_DELAY_SECONDS` | `3` | Simulated delay before backup jobs transition to `COMPLETED` |
| `FLOCI_SERVICES_FIS_ENABLED` | `true` | Enable the AWS Fault Injection Service management API |
diff --git a/docs/index.md b/docs/index.md
index 816cad8925..9af7ce3b23 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -12,7 +12,7 @@ Floci is a fast, free, and open-source local AWS service emulator built for deve
## Supported Services
-Floci emulates 73 AWS services. See the [Services Overview](services/index.md) for per-service operation counts, endpoints, and full protocol details.
+Floci emulates 78 AWS services. See the [Services Overview](services/index.md) for per-service operation counts, endpoints, and full protocol details.
| Service | Protocol |
|---|---|
@@ -80,6 +80,8 @@ Floci emulates 73 AWS services. See the [Services Overview](services/index.md) f
| Cost and Usage Reports | JSON 1.1 |
| BCM Data Exports | JSON 1.1 |
| Transfer Family | JSON 1.1 |
+| AWS RAM | REST JSON |
+| Service Quotas | JSON 1.1 |
## Why Floci?
@@ -115,7 +117,7 @@ docker compose up -d
aws --endpoint-url http://localhost:4566 s3 mb s3://my-bucket
```
-All 73 AWS services are immediately available at `http://localhost:4566`.
+All 78 AWS services are immediately available at `http://localhost:4566`.
[Get started →](getting-started/quick-start.md){ .md-button .md-button--primary }
[View services →](services/index.md){ .md-button }
diff --git a/docs/services/index.md b/docs/services/index.md
index 5b27619fc5..469f6b30a5 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -1,6 +1,6 @@
# Services Overview
-Floci emulates 76 AWS services on a single port (`4566`). All services use the real AWS wire protocol, your existing AWS CLI commands and SDK clients work without modification.
+Floci emulates 78 AWS services on a single port (`4566`). All services use the real AWS wire protocol, your existing AWS CLI commands and SDK clients work without modification.
This page is the canonical reference for supported service and operation counts. Some services expose separate control-plane and data-plane rows below. Other docs (and the README) should link here rather than duplicating the table.
@@ -85,6 +85,8 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [AWS Batch](batch.md) | `/v1/...` | REST JSON | 10 |
| [CodeDeploy](codedeploy.md) | `POST /` + `X-Amz-Target: CodeDeploy_20141006.*` | JSON 1.1 | 30 |
| [CodePipeline](codepipeline.md) | `POST /` + `X-Amz-Target: CodePipeline_20150709.*` | JSON 1.1 | 44 |
+| [Service Quotas](servicequotas.md) | `POST /` + `X-Amz-Target: ServiceQuotasV20190624.*` | JSON 1.1 | 5 |
+| [AWS RAM](ram.md) | `POST /{operationname}` (lowercase), `DELETE /deleteresourceshare` | REST JSON | 12 |
| [Control Tower](controltower.md) | `/list-landingzones`, `/get-landingzone`, `/create-landingzone`, `/*-baseline*` | REST JSON | 15 |
| [AWS Backup](backup.md) | `/backup-vaults/*`, `/backup/plans/*`, `/backup-jobs/*`, `/supported-resource-types` | REST JSON | 20 |
| [AWS FIS](fis.md) | `/experimentTemplates/*`, `/experiments/*`, `/actions/*`, `/targetResourceTypes/*`, `/safetyLevers/*`, `/tags/*` | REST JSON | 26 |
diff --git a/docs/services/ram.md b/docs/services/ram.md
new file mode 100644
index 0000000000..954b7ee499
--- /dev/null
+++ b/docs/services/ram.md
@@ -0,0 +1,86 @@
+# AWS RAM
+
+**Protocol:** REST JSON
+**Endpoint:** `http://localhost:4566`
+**Signing name:** `ram`
+
+Floci implements the AWS Resource Access Manager calls AWS Landing Zone Accelerator makes
+while bootstrapping shared Transit Gateway attachments and other cross-account resources:
+the organization-sharing opt-in, resource-share CRUD, association management, principal
+listing, and tagging. Sharing is modeled as a flat in-memory store, not full RAM semantics —
+see Current Scope below for what's simplified.
+
+## Supported Actions
+
+<!-- floci:actions:start -->
+| Action | Description |
+| --- | --- |
+| `EnableSharingWithAwsOrganization` | Enables resource sharing within the organization; returns `{"returnValue": true}`. Idempotent, no disable counterpart, matching real AWS (`POST /enablesharingwithawsorganization`) |
+| `CreateResourceShare` | Creates a resource share with the given name, principals, and resource ARNs (`POST /createresourceshare`) |
+| `GetResourceShares` | Lists resource shares visible to the caller, `SELF` owned or `OTHER-ACCOUNTS` shared in (`POST /getresourceshares`) |
+| `DeleteResourceShare` | Marks a share `DELETED`, a soft delete matching real AWS's async-then-terminal status (`DELETE /deleteresourceshare`) |
+| `UpdateResourceShare` | Renames a share and/or toggles `allowExternalPrincipals` (`POST /updateresourceshare`) |
+| `AssociateResourceShare` | Adds resource ARNs and/or principals to an existing share (`POST /associateresourceshare`) |
+| `DisassociateResourceShare` | Removes resource ARNs and/or principals from a share (`POST /disassociateresourceshare`) |
+| `ListPrincipals` | Lists principals associated with visible shares (`POST /listprincipals`) |
+| `TagResource` | Adds/overwrites tags on a resource share (`POST /tagresource`) |
+| `UntagResource` | Removes tags by key from a resource share (`POST /untagresource`) |
+| `GetResourceShareInvitations` | Always returns an empty list — organization sharing auto-accepts, so invitations never exist here (`POST /getresourceshareinvitations`) |
+| `ListResources` | Lists shared resource ARNs, with the RAM resource type derived from the ARN, e.g. `ec2:TransitGateway` (`POST /listresources`) |
+<!-- floci:actions:end -->
+
+## Configuration
+
+| Environment variable | Default | Description |
+| --- | --- | --- |
+| `FLOCI_SERVICES_RAM_ENABLED` | `true` | Enables the service |
+
+## Example
+
+```bash
+aws --endpoint-url http://localhost:4566 ram enable-sharing-with-aws-organization
+
+aws --endpoint-url http://localhost:4566 ram create-resource-share \
+ --name my-share \
+ --resource-arns arn:aws:ec2:us-east-1:000000000000:transit-gateway/tgw-0abc \
+ --principals arn:aws:organizations::000000000000:ou/o-abc/ou-infra
+
+aws --endpoint-url http://localhost:4566 ram delete-resource-share \
+ --resource-share-arn arn:aws:ram:us-east-1:000000000000:resource-share/...
+```
+
+## Current Scope
+
+- Visibility is simplified: `OTHER-ACCOUNTS` shows every non-owned share regardless of
+ principal targeting, since launched-container credentials all resolve to the same default
+ account and a principal-based check would hide shares from consumers that should see them.
+ LZA's `Custom::GetResourceShare` Lambda filters client-side by `owningAccountId` + `name`
+ anyway, so this doesn't affect that flow.
+- Mutations are owner-only: a caller that is not the share's owning account gets
+ `UnknownResourceException`, the same error an unknown ARN gets, since AWS resolves a share
+ ARN within the caller's own account. Visibility above is unaffected.
+- `resourceOwner` is required on `GetResourceShares`, `ListPrincipals` and `ListResources`: a
+ missing or unmodelled value is rejected with `InvalidParameterException` rather than defaulted
+ to `SELF`.
+- `GetResourceShares` applies the `name`, `resourceShareArns` and `resourceShareStatus` filters;
+ `tagFilters`, `permissionArn`, `permissionVersion` and pagination (`nextToken`/`maxResults`)
+ are accepted but ignored — every matching share is returned in one page.
+- Operations outside the table above are not routed. RAM's paths are matched literally, so an
+ unimplemented operation falls through to S3's `/{bucket}` route and comes back as an S3
+ `NoSuchBucket` XML body where the SDK expects JSON — not a modeled `UnknownOperationException`.
+ If a client reports an XML parse error against a RAM call, that is the cause, not credentials.
+ `GetResourceShareAssociations` is the one most likely to be hit: Terraform's
+ `aws_ram_resource_association` and `aws_ram_principal_association` read it on every refresh.
+- `AssociateResourceShare`/`DisassociateResourceShare` responses synthesize one
+ `resourceShareAssociation` row per requested ARN/principal rather than tracking real
+ per-association status transitions (e.g. no `ASSOCIATING`/`DISASSOCIATING` intermediate
+ state — everything completes synchronously).
+- `TagResource`/`UntagResource` only support tagging by `resourceShareArn`; tagging an
+ individual shared resource via `resourceArn` is not modeled (RAM's `TagResource` accepts
+ either, but LZA only tags shares).
+- Permission-related operations are not implemented: `CreatePermission`,
+ `AssociateResourceSharePermission`, `ListPermissions`, and the rest of the permission-version
+ family. Shares created here always use RAM's default managed permission implicitly — there
+ is no explicit permission model to associate or version.
+- `AcceptResourceShareInvitation` / `RejectResourceShareInvitation` are not implemented —
+ moot under organization sharing, which never produces invitations to begin with.
diff --git a/docs/services/servicequotas.md b/docs/services/servicequotas.md
new file mode 100644
index 0000000000..37c7ef4d55
--- /dev/null
+++ b/docs/services/servicequotas.md
@@ -0,0 +1,67 @@
+# Service Quotas
+
+**Protocol:** JSON 1.1 (`X-Amz-Target: ServiceQuotasV20190624.*`)
+**Endpoint:** `POST http://localhost:4566/`
+**Signing name:** `servicequotas`
+
+Floci answers Service Quotas lookups from a generated in-memory catalog. Every service code
+resolves to a quota list: a curated set with real AWS quota codes where tooling depends on
+them — CodeBuild's `L-2DC20C30` ("Concurrently running builds") and Lambda's `L-B99A9384`
+("Concurrent executions") — plus a deterministic generic set for any other service code. All
+values are deliberately generous (5000) so local pipelines that gate on quota headroom, such
+as AWS Landing Zone Accelerator, never stall on a limit the emulator does not enforce.
+
+Applied quotas and AWS default quotas return the same data, and quota values are static.
+`RequestServiceQuotaIncrease` is accepted and validated but does not change any quota value —
+see Limitations.
+
+## Supported Actions
+
+<!-- floci:actions:start -->
+| Action | Description |
+| --- | --- |
+| `ListServiceQuotas` | Lists the quotas for a service code; generated quotas for unknown codes |
+| `GetServiceQuota` | Returns one quota by service and quota code, else `NoSuchResourceException` |
+| `GetAWSDefaultServiceQuota` | Same as GetServiceQuota; defaults equal applied values |
+| `ListAWSDefaultServiceQuotas` | Same as ListServiceQuotas; defaults equal applied values |
+| `RequestServiceQuotaIncrease` | Validates and echoes an increase request as `PENDING`; not persisted, quota unchanged |
+<!-- floci:actions:end -->
+
+## Limitations
+
+- **Quota increase requests are not persisted.** `RequestServiceQuotaIncrease` validates its
+ input, resolves the quota, and returns a well-formed `RequestedQuota`, but keeps no state.
+ The request is observable only in the response that creates it.
+- **`Status` is always `PENDING` and never advances.** Nothing processes requests, so no
+ request ever reaches `APPROVED`, `CASE_OPENED`, or `DENIED`. `PENDING` is what real AWS
+ returns on creation, so a caller that only reads the creation response sees faithful data;
+ a caller that polls for completion will wait forever.
+- **Unknown service codes generate a quota catalog rather than failing.** This is deliberate, so
+ the code has to be well-formed to be trusted: `ServiceCode` is validated against the modeled
+ `[a-zA-Z][a-zA-Z0-9-]{1,63}` (max 63 characters) and a malformed one is rejected with
+ `IllegalArgumentException` instead of returning invented quotas.
+- **A requested increase does not change the quota.** `GetServiceQuota` continues to return
+ the catalog value after a successful increase request. Quota values remain static by design
+ so pipelines never stall on an unenforced limit.
+- `GetRequestedServiceQuotaChange` and `ListRequestedServiceQuotaChangeHistory` are not
+ implemented — there is no request store for them to read.
+- `CaseId` is never returned; no support case is opened. `SupportCaseAllowed` in the request is
+ accepted and ignored, as the emulator has no case-opening path either way.
+- The quota-increase template operations (`PutServiceQuotaIncreaseRequestIntoTemplate` and
+ related) are not implemented.
+
+## Configuration
+
+| Environment variable | Default | Description |
+| --- | --- | --- |
+| `FLOCI_SERVICES_SERVICEQUOTAS_ENABLED` | `true` | Enables the service |
+
+## Example
+
+```bash
+aws --endpoint-url http://localhost:4566 service-quotas list-service-quotas \
+ --service-code codebuild
+
+aws --endpoint-url http://localhost:4566 service-quotas get-service-quota \
+ --service-code codebuild --quota-code L-2DC20C30
+```
diff --git a/mkdocs.yml b/mkdocs.yml
index 2198742f13..594261d641 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -137,6 +137,8 @@ nav:
- AWS Batch: services/batch.md
- CodeDeploy: services/codedeploy.md
- CodePipeline: services/codepipeline.md
+ - Service Quotas: services/servicequotas.md
+ - AWS RAM: services/ram.md
- AWS Backup: services/backup.md
- AWS FIS: services/fis.md
- CloudTrail: services/cloudtrail.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 8507f2ca55..b278677272 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -672,9 +672,9 @@ public interface EmulatorConfig {
RumServiceConfig rum();
GuardDutyServiceConfig guardduty();
EmrServerlessServiceConfig emrserverless();
-
+ ServiceQuotasServiceConfig servicequotas();
+ RamServiceConfig ram();
ControlTowerServiceConfig controltower();
-
LakeFormationServiceConfig lakeformation();
EfsServiceConfig efs();
}
@@ -725,6 +725,16 @@ public interface EmulatorConfig {
boolean enabled();
}
+ interface ServiceQuotasServiceConfig {
+ @WithDefault("true")
+ boolean enabled();
+ }
+
+ interface RamServiceConfig {
+ @WithDefault("true")
+ boolean enabled();
+ }
+
interface LakeFormationServiceConfig {
@WithDefault("true")
boolean enabled();
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java
index 3d368eccf9..5a75eed20f 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java
@@ -41,6 +41,7 @@ import io.github.hectorvent.floci.services.kinesisanalytics.KinesisAnalyticsV2Js
import io.github.hectorvent.floci.services.kms.KmsJsonHandler;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerJsonHandler;
import io.github.hectorvent.floci.services.organizations.OrganizationsJsonHandler;
+import io.github.hectorvent.floci.services.servicequotas.ServiceQuotasJsonHandler;
import io.github.hectorvent.floci.services.ssm.Ec2MessagesJsonHandler;
import io.github.hectorvent.floci.services.ssm.SsmJsonHandler;
import jakarta.inject.Inject;
@@ -107,6 +108,7 @@ public class AwsJson11Controller {
private final ApplicationAutoScalingJsonHandler applicationAutoScalingJsonHandler;
private final CloudHsmV2JsonHandler cloudHsmV2JsonHandler;
private final OrganizationsJsonHandler organizationsJsonHandler;
+ private final ServiceQuotasJsonHandler serviceQuotasJsonHandler;
@Inject
public AwsJson11Controller(ObjectMapper objectMapper, ResolvedServiceCatalog catalog,
@@ -144,7 +146,8 @@ public class AwsJson11Controller {
CloudControlJsonHandler cloudControlJsonHandler,
ApplicationAutoScalingJsonHandler applicationAutoScalingJsonHandler,
CloudHsmV2JsonHandler cloudHsmV2JsonHandler,
- OrganizationsJsonHandler organizationsJsonHandler){
+ OrganizationsJsonHandler organizationsJsonHandler,
+ ServiceQuotasJsonHandler serviceQuotasJsonHandler) {
this.objectMapper = objectMapper;
this.strictBodyReader = objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
this.catalog = catalog;
@@ -187,6 +190,7 @@ public class AwsJson11Controller {
this.applicationAutoScalingJsonHandler = applicationAutoScalingJsonHandler;
this.cloudHsmV2JsonHandler = cloudHsmV2JsonHandler;
this.organizationsJsonHandler = organizationsJsonHandler;
+ this.serviceQuotasJsonHandler = serviceQuotasJsonHandler;
}
@POST
@@ -263,6 +267,8 @@ public class AwsJson11Controller {
// action is authorized against the calling account, so pass that instead of region.
case "organizations" ->
organizationsJsonHandler.handle(action, request, regionResolver.getAccountId());
+ case "servicequotas" -> serviceQuotasJsonHandler.handle(
+ action, request, region, regionResolver.getAccountId());
default -> null;
};
// catalog.matchTarget is protocol-agnostic: a JSON 1.0 target
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 76aa972b70..7e73adb2d9 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
@@ -355,6 +355,15 @@ public class ResolvedServiceCatalog {
config.storage().services().codepipeline().flushIntervalMs(), null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
Set.of("CodePipeline_20150709."), Set.of("codepipeline"), Set.of(), Set.of()),
+ descriptor("servicequotas", "servicequotas", config.services().servicequotas().enabled(), true,
+ null, null, 5000L, null, ServiceProtocol.JSON,
+ protocols(ServiceProtocol.JSON),
+ Set.of("ServiceQuotasV20190624."), Set.of("servicequotas"), Set.of(), Set.of()),
+ descriptor("ram", "ram", config.services().ram().enabled(), true,
+ null, null, 5000L, null, ServiceProtocol.REST_JSON,
+ protocols(ServiceProtocol.REST_JSON),
+ Set.of(), Set.of("ram"), Set.of(),
+ Set.of(io.github.hectorvent.floci.services.ram.RamController.class)),
descriptor("config", "configservice", config.services().configservice().enabled(), true,
"config", storageMode(config.storage().services().config().mode(), config.storage().mode()),
config.storage().services().config().flushIntervalMs(), null, ServiceProtocol.JSON,
diff --git a/src/main/java/io/github/hectorvent/floci/services/ram/RamController.java b/src/main/java/io/github/hectorvent/floci/services/ram/RamController.java
new file mode 100644
index 0000000000..493a6b48f3
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ram/RamController.java
@@ -0,0 +1,336 @@
+package io.github.hectorvent.floci.services.ram;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.ObjectReader;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.services.ram.model.PrincipalAssociation;
+import io.github.hectorvent.floci.services.ram.model.ResourceShare;
+import io.github.hectorvent.floci.services.ram.model.SharedResource;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Consumes;
+import jakarta.ws.rs.DELETE;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.QueryParam;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * AWS Resource Access Manager (Smithy restJson1).
+ *
+ * <p>Serves the RAM calls AWS Landing Zone Accelerator makes: the organization-sharing opt-in
+ * plus the share reads of the Custom::GetResourceShare / Custom::GetResourceShareItem Lambdas.
+ * The literal paths take JAX-RS precedence over S3's {@code /{bucket}} template route, so no
+ * extra routing wiring is needed — but any RAM path missing here falls through to S3 and
+ * produces an XML error a restJson1 client cannot parse.
+ */
+@Path("/")
+@Produces(MediaType.APPLICATION_JSON)
+@Consumes(MediaType.APPLICATION_JSON)
+public class RamController {
+
+ private final RamService service;
+ private final ObjectMapper objectMapper;
+ private final ObjectReader requestReader;
+ private final RegionResolver regionResolver;
+
+ @Inject
+ public RamController(RamService service, ObjectMapper objectMapper, RegionResolver regionResolver) {
+ this.service = service;
+ this.objectMapper = objectMapper;
+ this.requestReader = objectMapper.reader()
+ .with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
+ this.regionResolver = regionResolver;
+ }
+
+ @POST
+ @Path("/enablesharingwithawsorganization")
+ @Consumes(MediaType.WILDCARD)
+ public Response enableSharingWithAwsOrganization() {
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("returnValue", service.enableSharingWithAwsOrganization());
+ return Response.ok(response).build();
+ }
+
+ @POST
+ @Path("/createresourceshare")
+ @Consumes(MediaType.WILDCARD)
+ public Response createResourceShare(@Context HttpHeaders headers, String body) {
+ JsonNode request = readTree(body);
+ String name = request.path("name").asText();
+ boolean allowExternalPrincipals = request.path("allowExternalPrincipals").asBoolean(false);
+ ResourceShare share = service.createResourceShare(
+ name,
+ stringList(request.path("principals")),
+ stringList(request.path("resourceArns")),
+ allowExternalPrincipals,
+ regionResolver.resolveRegion(headers),
+ regionResolver.getAccountId());
+
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("resourceShare", shareNode(share));
+ return Response.ok(response).build();
+ }
+
+ @POST
+ @Path("/getresourceshares")
+ @Consumes(MediaType.WILDCARD)
+ public Response getResourceShares(String body) {
+ JsonNode request = readTree(body);
+ String resourceOwner = request.hasNonNull("resourceOwner")
+ ? request.path("resourceOwner").asText() : null;
+ List<ResourceShare> shares = service.getResourceShares(
+ regionResolver.getAccountId(),
+ resourceOwner,
+ request.hasNonNull("name") ? request.path("name").asText() : null,
+ stringList(request.path("resourceShareArns")),
+ request.hasNonNull("resourceShareStatus")
+ ? request.path("resourceShareStatus").asText() : null);
+
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode array = objectMapper.createArrayNode();
+ shares.forEach(share -> array.add(shareNode(share)));
+ response.set("resourceShares", array);
+ return Response.ok(response).build();
+ }
+
+ @DELETE
+ @Path("/deleteresourceshare")
+ @Consumes(MediaType.WILDCARD)
+ public Response deleteResourceShare(@QueryParam("resourceShareArn") String resourceShareArn,
+ @QueryParam("clientToken") String clientToken) {
+ service.deleteResourceShare(resourceShareArn, regionResolver.getAccountId());
+
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("returnValue", true);
+ // The response models clientToken; AWS echoes what the caller sent so a retry can be
+ // correlated with the original request.
+ if (clientToken != null) {
+ response.put("clientToken", clientToken);
+ }
+ return Response.ok(response).build();
+ }
+
+ @POST
+ @Path("/updateresourceshare")
+ @Consumes(MediaType.WILDCARD)
+ public Response updateResourceShare(String body) {
+ JsonNode request = readTree(body);
+ ResourceShare updated = service.updateResourceShare(
+ request.path("resourceShareArn").asText(),
+ request.hasNonNull("name") ? request.path("name").asText() : null,
+ request.hasNonNull("allowExternalPrincipals")
+ ? request.path("allowExternalPrincipals").asBoolean() : null,
+ regionResolver.getAccountId());
+
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("resourceShare", shareNode(updated));
+ return Response.ok(response).build();
+ }
+
+ @POST
+ @Path("/associateresourceshare")
+ @Consumes(MediaType.WILDCARD)
+ public Response associateResourceShare(String body) {
+ JsonNode request = readTree(body);
+ String resourceShareArn = request.path("resourceShareArn").asText();
+ List<String> resourceArns = stringList(request.path("resourceArns"));
+ List<String> principals = stringList(request.path("principals"));
+ ResourceShare updated = service.associateResourceShare(
+ resourceShareArn, resourceArns, principals, regionResolver.getAccountId());
+
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("resourceShareAssociations",
+ associationArray(updated, resourceArns, principals, "ASSOCIATED"));
+ return Response.ok(response).build();
+ }
+
+ @POST
+ @Path("/disassociateresourceshare")
+ @Consumes(MediaType.WILDCARD)
+ public Response disassociateResourceShare(String body) {
+ JsonNode request = readTree(body);
+ String resourceShareArn = request.path("resourceShareArn").asText();
+ List<String> resourceArns = stringList(request.path("resourceArns"));
+ List<String> principals = stringList(request.path("principals"));
+ ResourceShare updated = service.disassociateResourceShare(
+ resourceShareArn, resourceArns, principals, regionResolver.getAccountId());
+
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("resourceShareAssociations",
+ associationArray(updated, resourceArns, principals, "DISASSOCIATED"));
+ return Response.ok(response).build();
+ }
+
+ @POST
+ @Path("/listprincipals")
+ @Consumes(MediaType.WILDCARD)
+ public Response listPrincipals(String body) {
+ JsonNode request = readTree(body);
+ String resourceOwner = request.hasNonNull("resourceOwner")
+ ? request.path("resourceOwner").asText() : null;
+ List<PrincipalAssociation> principals = service.listPrincipals(
+ regionResolver.getAccountId(), resourceOwner, stringList(request.path("resourceShareArns")));
+
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode array = objectMapper.createArrayNode();
+ for (PrincipalAssociation principal : principals) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("id", principal.id());
+ node.put("resourceShareArn", principal.resourceShareArn());
+ node.put("creationTime", principal.creationTime().toEpochMilli() / 1000.0);
+ node.put("lastUpdatedTime", principal.lastUpdatedTime().toEpochMilli() / 1000.0);
+ node.put("external", principal.external());
+ array.add(node);
+ }
+ response.set("principals", array);
+ return Response.ok(response).build();
+ }
+
+ @POST
+ @Path("/tagresource")
+ @Consumes(MediaType.WILDCARD)
+ public Response tagResource(String body) {
+ JsonNode request = readTree(body);
+ Map<String, String> tags = new LinkedHashMap<>();
+ request.path("tags").forEach(tag -> tags.put(tag.path("key").asText(), tag.path("value").asText()));
+ service.tagResource(request.path("resourceShareArn").asText(), tags,
+ regionResolver.getAccountId());
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ @POST
+ @Path("/untagresource")
+ @Consumes(MediaType.WILDCARD)
+ public Response untagResource(String body) {
+ JsonNode request = readTree(body);
+ service.untagResource(request.path("resourceShareArn").asText(),
+ stringList(request.path("tagKeys")), regionResolver.getAccountId());
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ @POST
+ @Path("/getresourceshareinvitations")
+ @Consumes(MediaType.WILDCARD)
+ public Response getResourceShareInvitations(String body) {
+ // The body is semantically ignored (invitations are always empty under
+ // organization sharing) but malformed JSON is still a client error.
+ readTree(body);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("resourceShareInvitations", objectMapper.createArrayNode());
+ return Response.ok(response).build();
+ }
+
+ @POST
+ @Path("/listresources")
+ @Consumes(MediaType.WILDCARD)
+ public Response listResources(String body) {
+ JsonNode request = readTree(body);
+ String resourceOwner = request.hasNonNull("resourceOwner")
+ ? request.path("resourceOwner").asText() : null;
+ List<SharedResource> resources = service.listResources(
+ regionResolver.getAccountId(), resourceOwner, stringList(request.path("resourceShareArns")));
+
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode array = objectMapper.createArrayNode();
+ for (SharedResource resource : resources) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("arn", resource.arn());
+ node.put("type", resource.type());
+ node.put("resourceShareArn", resource.resourceShareArn());
+ node.put("status", resource.status());
+ array.add(node);
+ }
+ response.set("resources", array);
+ return Response.ok(response).build();
+ }
+
+ private ObjectNode shareNode(ResourceShare share) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("resourceShareArn", share.getResourceShareArn());
+ node.put("name", share.getName());
+ node.put("owningAccountId", share.getOwningAccountId());
+ node.put("allowExternalPrincipals", share.isAllowExternalPrincipals());
+ node.put("status", share.getStatus());
+ // Shares created through the API are STANDARD; CREATED_FROM_POLICY covers shares RAM
+ // derives from a resource policy, which floci has no path to produce.
+ node.put("featureSet", "STANDARD");
+ node.put("creationTime", share.getCreationTime().toEpochMilli() / 1000.0);
+ node.put("lastUpdatedTime", share.getLastUpdatedTime().toEpochMilli() / 1000.0);
+ ArrayNode tags = objectMapper.createArrayNode();
+ share.getTags().forEach((key, value) -> {
+ ObjectNode tag = objectMapper.createObjectNode();
+ tag.put("key", key);
+ tag.put("value", value);
+ tags.add(tag);
+ });
+ node.set("tags", tags);
+ return node;
+ }
+
+ /** One row per associated/disassociated resourceArn and principal, per the real RAM shape. */
+ private ArrayNode associationArray(ResourceShare share, List<String> resourceArns,
+ List<String> principals, String status) {
+ ArrayNode array = objectMapper.createArrayNode();
+ double now = share.getLastUpdatedTime().toEpochMilli() / 1000.0;
+ for (String resourceArn : resourceArns) {
+ array.add(associationNode(share, resourceArn, "RESOURCE", status, now));
+ }
+ for (String principal : principals) {
+ array.add(associationNode(share, principal, "PRINCIPAL", status, now));
+ }
+ return array;
+ }
+
+ private ObjectNode associationNode(ResourceShare share, String associatedEntity,
+ String associationType, String status, double time) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("resourceShareArn", share.getResourceShareArn());
+ node.put("resourceShareName", share.getName());
+ node.put("associatedEntity", associatedEntity);
+ node.put("associationType", associationType);
+ node.put("status", status);
+ node.put("creationTime", time);
+ node.put("lastUpdatedTime", time);
+ node.put("external", false);
+ return node;
+ }
+
+ /**
+ * A body that is not valid JSON is a client error: restJson1 rejects it with 400
+ * SerializationException. Left as an UncheckedIOException it escapes to Quarkus'
+ * generic handler and the SDK sees a 500 InternalFailure instead.
+ */
+ private JsonNode readTree(String body) {
+ try {
+ return (body == null || body.isBlank())
+ ? objectMapper.createObjectNode()
+ // Strict: Jackson's default stops at the first complete value, so
+ // "{} not-json" would parse as an empty object and the request would run.
+ : requestReader.readTree(body);
+ } catch (IOException e) {
+ throw new AwsException("SerializationException",
+ "The request could not be parsed as valid JSON.", 400);
+ }
+ }
+
+ private static List<String> stringList(JsonNode node) {
+ List<String> values = new ArrayList<>();
+ node.forEach(n -> values.add(n.asText()));
+ return values;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ram/RamService.java b/src/main/java/io/github/hectorvent/floci/services/ram/RamService.java
new file mode 100644
index 0000000000..965e8e79aa
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ram/RamService.java
@@ -0,0 +1,343 @@
+package io.github.hectorvent.floci.services.ram;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.ram.model.PrincipalAssociation;
+import io.github.hectorvent.floci.services.ram.model.ResourceShare;
+import io.github.hectorvent.floci.services.ram.model.SharedResource;
+import jakarta.annotation.PostConstruct;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+
+/**
+ * AWS Resource Access Manager (RAM) business logic.
+ *
+ * <p>Covers {@code EnableSharingWithAwsOrganization} plus the resource-share reads LZA's
+ * TGW share flow performs: the owning account registers a share (from the
+ * {@code AWS::RAM::ResourceShare} CFN provisioner), and accepting accounts page
+ * GetResourceShareInvitations (always empty here — organization sharing auto-accepts, matching
+ * real AWS), find the share via GetResourceShares(OTHER-ACCOUNTS), and read the shared ARNs via
+ * ListResources.
+ *
+ * <p>Principals are stored but not enforced for visibility: floci's org is the only org, and
+ * launched containers call in with placeholder credentials that resolve to the default account,
+ * so OTHER-ACCOUNTS simply means "every share the caller does not own". Mutations are the
+ * opposite: they are owner-only, and a non-owner gets the same UnknownResourceException a
+ * never-created ARN gets.
+ */
+@ApplicationScoped
+public class RamService {
+
+ private static final String ORGANIZATION_SHARING_KEY = "sharing-with-organization-enabled";
+ /** The modeled ResourceShareStatus enum. */
+ private static final List<String> SHARE_STATUSES =
+ List.of("PENDING", "ACTIVE", "FAILED", "DELETING", "DELETED");
+
+ private final StorageFactory storageFactory;
+ private StorageBackend<String, ResourceShare> shares;
+ private StorageBackend<String, Boolean> settings;
+
+ @Inject
+ public RamService(StorageFactory storageFactory) {
+ this.storageFactory = storageFactory;
+ }
+
+ @PostConstruct
+ void initializeStorage() {
+ shares = storageFactory.create("ram", "ram-resource-shares.json",
+ new TypeReference<Map<String, ResourceShare>>() {});
+ settings = storageFactory.create("ram", "ram-settings.json",
+ new TypeReference<Map<String, Boolean>>() {});
+ }
+
+ public boolean enableSharingWithAwsOrganization() {
+ settings.put(ORGANIZATION_SHARING_KEY, true);
+ return true;
+ }
+
+ public boolean isSharingWithOrganizationEnabled() {
+ return settings.get(ORGANIZATION_SHARING_KEY).orElse(false);
+ }
+
+ public ResourceShare createResourceShare(String name, List<String> principals,
+ List<String> resourceArns, boolean allowExternalPrincipals,
+ String region, String owningAccountId) {
+ String arn = "arn:aws:ram:" + region + ":" + owningAccountId
+ + ":resource-share/" + UUID.randomUUID();
+ ResourceShare share = new ResourceShare(
+ arn, name, owningAccountId, principals, resourceArns, allowExternalPrincipals);
+ return putForOwner(share);
+ }
+
+ /** The unfiltered read: every share visible to the caller under {@code resourceOwner}. */
+ public List<ResourceShare> getResourceShares(String callerAccountId, String resourceOwner) {
+ return getResourceShares(callerAccountId, resourceOwner, null, List.of(), null);
+ }
+
+ /**
+ * @param resourceOwner {@code SELF} (shares the caller owns) or {@code OTHER-ACCOUNTS}
+ * (shares other accounts made visible to the caller)
+ * @param name exact share name to match, or null for any
+ * @param resourceShareArns share ARNs to restrict the result to, or empty for any
+ * @param resourceShareStatus one {@code ResourceShareStatus} value to match, or null for any
+ */
+ public List<ResourceShare> getResourceShares(String callerAccountId, String resourceOwner,
+ String name, List<String> resourceShareArns,
+ String resourceShareStatus) {
+ requireResourceOwner(resourceOwner);
+ requireResourceShareStatus(resourceShareStatus);
+ List<ResourceShare> result = new ArrayList<>();
+ for (ResourceShare share : allShares()) {
+ if (!isVisible(share, callerAccountId, resourceOwner)) {
+ continue;
+ }
+ if (name != null && !name.equals(share.getName())) {
+ continue;
+ }
+ if (!resourceShareArns.isEmpty() && !resourceShareArns.contains(share.getResourceShareArn())) {
+ continue;
+ }
+ if (resourceShareStatus != null && !resourceShareStatus.equals(share.getStatus())) {
+ continue;
+ }
+ result.add(share);
+ }
+ return result;
+ }
+
+ /** Organization sharing never creates invitations — resources become visible directly. */
+ public List<Object> getResourceShareInvitations(String callerAccountId) {
+ return List.of();
+ }
+
+ public List<SharedResource> listResources(String callerAccountId, String resourceOwner,
+ List<String> resourceShareArns) {
+ requireResourceOwner(resourceOwner);
+ List<SharedResource> result = new ArrayList<>();
+ for (ResourceShare share : allShares()) {
+ if (!isVisible(share, callerAccountId, resourceOwner)) {
+ continue;
+ }
+ // A deleted share stays readable via GetResourceShares (status DELETED)
+ // but its contents stop being consumable.
+ if ("DELETED".equals(share.getStatus())) {
+ continue;
+ }
+ if (!resourceShareArns.isEmpty() && !resourceShareArns.contains(share.getResourceShareArn())) {
+ continue;
+ }
+ for (String resourceArn : share.getResourceArns()) {
+ result.add(new SharedResource(resourceArn, ramResourceType(resourceArn),
+ share.getResourceShareArn(), "AVAILABLE"));
+ }
+ }
+ return result;
+ }
+
+ public ResourceShare deleteResourceShare(String resourceShareArn, String callerAccountId) {
+ return putForOwner(
+ requireOwnedShare(resourceShareArn, callerAccountId).withStatus("DELETED"));
+ }
+
+ public ResourceShare updateResourceShare(String resourceShareArn, String name,
+ Boolean allowExternalPrincipals, String callerAccountId) {
+ ResourceShare share = requireOwnedShare(resourceShareArn, callerAccountId);
+ if (name != null) {
+ share = share.withName(name);
+ }
+ if (allowExternalPrincipals != null) {
+ share = share.withAllowExternalPrincipals(allowExternalPrincipals);
+ }
+ return putForOwner(share);
+ }
+
+ public ResourceShare associateResourceShare(String resourceShareArn, List<String> resourceArns,
+ List<String> principals, String callerAccountId) {
+ ResourceShare share = requireOwnedShare(resourceShareArn, callerAccountId);
+ ResourceShare updated = share.withPrincipalsAndResources(
+ mergeDistinct(share.getPrincipals(), principals),
+ mergeDistinct(share.getResourceArns(), resourceArns));
+ return putForOwner(updated);
+ }
+
+ public ResourceShare disassociateResourceShare(String resourceShareArn, List<String> resourceArns,
+ List<String> principals, String callerAccountId) {
+ ResourceShare share = requireOwnedShare(resourceShareArn, callerAccountId);
+ ResourceShare updated = share.withPrincipalsAndResources(
+ withoutAll(share.getPrincipals(), principals),
+ withoutAll(share.getResourceArns(), resourceArns));
+ return putForOwner(updated);
+ }
+
+ /**
+ * @param resourceOwner {@code SELF} or {@code OTHER-ACCOUNTS}, same visibility rule as
+ * {@link #getResourceShares}
+ */
+ public List<PrincipalAssociation> listPrincipals(String callerAccountId, String resourceOwner,
+ List<String> resourceShareArns) {
+ requireResourceOwner(resourceOwner);
+ List<PrincipalAssociation> result = new ArrayList<>();
+ for (ResourceShare share : allShares()) {
+ if (!isVisible(share, callerAccountId, resourceOwner)) {
+ continue;
+ }
+ // A deleted share stays readable via GetResourceShares (status DELETED)
+ // but its contents stop being consumable.
+ if ("DELETED".equals(share.getStatus())) {
+ continue;
+ }
+ if (!resourceShareArns.isEmpty() && !resourceShareArns.contains(share.getResourceShareArn())) {
+ continue;
+ }
+ for (String principal : share.getPrincipals()) {
+ result.add(new PrincipalAssociation(principal, share.getResourceShareArn(),
+ share.getCreationTime(), share.getLastUpdatedTime(), false));
+ }
+ }
+ return result;
+ }
+
+ public void tagResource(String resourceShareArn, Map<String, String> newTags, String callerAccountId) {
+ ResourceShare share = requireOwnedShare(resourceShareArn, callerAccountId);
+ Map<String, String> merged = new LinkedHashMap<>(share.getTags());
+ merged.putAll(newTags);
+ putForOwner(share.withTags(merged));
+ }
+
+ public void untagResource(String resourceShareArn, List<String> tagKeys, String callerAccountId) {
+ ResourceShare share = requireOwnedShare(resourceShareArn, callerAccountId);
+ Map<String, String> remaining = new LinkedHashMap<>(share.getTags());
+ tagKeys.forEach(remaining::remove);
+ putForOwner(share.withTags(remaining));
+ }
+
+ /**
+ * Resolves a share the caller may mutate. A share owned by another account gets the same
+ * UnknownResourceException as one that was never created: AWS resolves a share ARN within
+ * the caller's own account, so a non-owner must not learn that the ARN exists — let alone
+ * be able to rename, retag, or delete it.
+ */
+ private ResourceShare requireOwnedShare(String resourceShareArn, String callerAccountId) {
+ return findOwnedShare(resourceShareArn, callerAccountId)
+ .orElseThrow(() -> new AwsException("UnknownResourceException",
+ "ResourceShare " + resourceShareArn + " does not exist.", 400));
+ }
+
+ private Optional<ResourceShare> findOwnedShare(String resourceShareArn, String callerAccountId) {
+ return allShares().stream()
+ .filter(share -> share.getResourceShareArn().equals(resourceShareArn))
+ .filter(share -> share.getOwningAccountId().equals(callerAccountId))
+ // DELETED is terminal: the share stays readable via GetResourceShares for the
+ // retention window, but mutations resolve it like an ARN that never existed.
+ .filter(share -> !"DELETED".equals(share.getStatus()))
+ .findFirst();
+ }
+
+ private static List<String> mergeDistinct(List<String> existing, List<String> additions) {
+ Set<String> merged = new LinkedHashSet<>(existing);
+ merged.addAll(additions);
+ return List.copyOf(merged);
+ }
+
+ private static List<String> withoutAll(List<String> existing, List<String> removals) {
+ List<String> remaining = new ArrayList<>(existing);
+ remaining.removeAll(removals);
+ return List.copyOf(remaining);
+ }
+
+ /**
+ * The single write seam: every create and every mutation lands here, so stamping
+ * lastUpdatedTime once at this point keeps it advancing without six call sites having to
+ * remember to do it. Returns the stamped share so callers respond with what was stored.
+ */
+ private ResourceShare putForOwner(ResourceShare share) {
+ ResourceShare stamped = share.withLastUpdatedTime(Instant.now());
+ if (shares instanceof AccountAwareStorageBackend<ResourceShare> accountAware) {
+ accountAware.putForAccount(
+ stamped.getOwningAccountId(), stamped.getResourceShareArn(), stamped);
+ return stamped;
+ }
+ shares.put(stamped.getResourceShareArn(), stamped);
+ return stamped;
+ }
+
+ private List<ResourceShare> allShares() {
+ if (shares instanceof AccountAwareStorageBackend<ResourceShare> accountAware) {
+ return accountAware.scanAllAccounts();
+ }
+ return shares.scan(key -> true);
+ }
+
+ /**
+ * The model enumerates {@code resourceOwner} as {@code SELF} or {@code OTHER-ACCOUNTS} on every
+ * read operation that takes it. The visibility fork below is a two-way branch, so an unmodelled
+ * value silently means OTHER-ACCOUNTS — a caller who sent {@code "self"} would be handed every
+ * share they do NOT own. AWS answers InvalidParameterException, which all three operations list.
+ *
+ * <p>It is also a required member, so a null one is rejected rather than defaulted: guessing
+ * SELF answers a question the caller never asked, with the caller's own shares.
+ */
+ /** {@code ResourceShareStatus} is optional on GetResourceShares, but enumerated when sent. */
+ private static void requireResourceShareStatus(String resourceShareStatus) {
+ if (resourceShareStatus != null && !SHARE_STATUSES.contains(resourceShareStatus)) {
+ throw new AwsException("InvalidParameterException",
+ "resourceShareStatus must be one of " + SHARE_STATUSES + ".", 400);
+ }
+ }
+
+ private static void requireResourceOwner(String resourceOwner) {
+ if (resourceOwner == null) {
+ throw new AwsException("InvalidParameterException",
+ "resourceOwner is required and must be one of [SELF, OTHER-ACCOUNTS].", 400);
+ }
+ if (!"SELF".equals(resourceOwner) && !"OTHER-ACCOUNTS".equals(resourceOwner)) {
+ throw new AwsException("InvalidParameterException",
+ "resourceOwner must be one of [SELF, OTHER-ACCOUNTS].", 400);
+ }
+ }
+
+ private boolean isVisible(ResourceShare share, String callerAccountId, String resourceOwner) {
+ boolean owned = share.getOwningAccountId().equals(callerAccountId);
+ if ("SELF".equals(resourceOwner)) {
+ return owned;
+ }
+ // OTHER-ACCOUNTS: every non-owned share is visible, regardless of principals.
+ // Launched-container credentials resolve to the emulator default account, so a
+ // principal-based check would hide account-principal shares from the very Lambda
+ // they were shared with (LZA's Custom::GetResourceShare filters client-side by
+ // owningAccountId + name anyway).
+ return !owned;
+ }
+
+ /** {@code arn:aws:ec2:...:transit-gateway/tgw-1} → {@code ec2:TransitGateway}. */
+ private static String ramResourceType(String resourceArn) {
+ String[] parts = resourceArn.split(":", 6);
+ if (parts.length < 6) {
+ return "";
+ }
+ String service = parts[2];
+ String resource = parts[5];
+ int slash = resource.indexOf('/');
+ String typeSegment = slash >= 0 ? resource.substring(0, slash) : resource;
+ StringBuilder camel = new StringBuilder();
+ for (String word : typeSegment.split("-")) {
+ if (!word.isEmpty()) {
+ camel.append(Character.toUpperCase(word.charAt(0))).append(word.substring(1));
+ }
+ }
+ return service + ":" + camel;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ram/model/PrincipalAssociation.java b/src/main/java/io/github/hectorvent/floci/services/ram/model/PrincipalAssociation.java
new file mode 100644
index 0000000000..f152e57019
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ram/model/PrincipalAssociation.java
@@ -0,0 +1,15 @@
+package io.github.hectorvent.floci.services.ram.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+
+/** One row of a {@code ListPrincipals} response: a principal associated with a resource share. */
+@RegisterForReflection
+public record PrincipalAssociation(
+ String id,
+ String resourceShareArn,
+ Instant creationTime,
+ Instant lastUpdatedTime,
+ boolean external) {
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ram/model/ResourceShare.java b/src/main/java/io/github/hectorvent/floci/services/ram/model/ResourceShare.java
new file mode 100644
index 0000000000..febd7726a0
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ram/model/ResourceShare.java
@@ -0,0 +1,98 @@
+package io.github.hectorvent.floci.services.ram.model;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+import java.util.List;
+import java.util.Map;
+
+@RegisterForReflection
+public class ResourceShare {
+
+ private final String resourceShareArn;
+ private final String name;
+ private final String owningAccountId;
+ private final List<String> principals;
+ private final List<String> resourceArns;
+ private final boolean allowExternalPrincipals;
+ private final String status;
+ private final Instant creationTime;
+ private final Instant lastUpdatedTime;
+ private final Map<String, String> tags;
+
+ public ResourceShare(String resourceShareArn, String name, String owningAccountId,
+ List<String> principals, List<String> resourceArns,
+ boolean allowExternalPrincipals) {
+ this(resourceShareArn, name, owningAccountId, principals, resourceArns,
+ allowExternalPrincipals, "ACTIVE", Instant.now(), null, Map.of());
+ }
+
+ @JsonCreator
+ public ResourceShare(
+ @JsonProperty("resourceShareArn") String resourceShareArn,
+ @JsonProperty("name") String name,
+ @JsonProperty("owningAccountId") String owningAccountId,
+ @JsonProperty("principals") List<String> principals,
+ @JsonProperty("resourceArns") List<String> resourceArns,
+ @JsonProperty("allowExternalPrincipals") boolean allowExternalPrincipals,
+ @JsonProperty("status") String status,
+ @JsonProperty("creationTime") Instant creationTime,
+ @JsonProperty("lastUpdatedTime") Instant lastUpdatedTime,
+ @JsonProperty("tags") Map<String, String> tags) {
+ this.resourceShareArn = resourceShareArn;
+ this.name = name;
+ this.owningAccountId = owningAccountId;
+ this.principals = List.copyOf(principals);
+ this.resourceArns = List.copyOf(resourceArns);
+ this.allowExternalPrincipals = allowExternalPrincipals;
+ this.status = status;
+ this.creationTime = creationTime;
+ // State persisted before lastUpdatedTime existed has never been mutated since it was
+ // written, so creation time is its correct last-updated value.
+ this.lastUpdatedTime = lastUpdatedTime == null ? creationTime : lastUpdatedTime;
+ this.tags = tags == null ? Map.of() : Map.copyOf(tags);
+ }
+
+ public String getResourceShareArn() { return resourceShareArn; }
+ public String getName() { return name; }
+ public String getOwningAccountId() { return owningAccountId; }
+ public List<String> getPrincipals() { return principals; }
+ public List<String> getResourceArns() { return resourceArns; }
+ public boolean isAllowExternalPrincipals() { return allowExternalPrincipals; }
+ public String getStatus() { return status; }
+ public Instant getCreationTime() { return creationTime; }
+ public Instant getLastUpdatedTime() { return lastUpdatedTime; }
+ public Map<String, String> getTags() { return tags; }
+
+ public ResourceShare withName(String newName) {
+ return new ResourceShare(resourceShareArn, newName, owningAccountId, principals, resourceArns,
+ allowExternalPrincipals, status, creationTime, lastUpdatedTime, tags);
+ }
+
+ public ResourceShare withAllowExternalPrincipals(boolean value) {
+ return new ResourceShare(resourceShareArn, name, owningAccountId, principals, resourceArns,
+ value, status, creationTime, lastUpdatedTime, tags);
+ }
+
+ public ResourceShare withStatus(String newStatus) {
+ return new ResourceShare(resourceShareArn, name, owningAccountId, principals, resourceArns,
+ allowExternalPrincipals, newStatus, creationTime, lastUpdatedTime, tags);
+ }
+
+ public ResourceShare withPrincipalsAndResources(List<String> newPrincipals, List<String> newResourceArns) {
+ return new ResourceShare(resourceShareArn, name, owningAccountId, newPrincipals, newResourceArns,
+ allowExternalPrincipals, status, creationTime, lastUpdatedTime, tags);
+ }
+
+ public ResourceShare withLastUpdatedTime(Instant stamp) {
+ return new ResourceShare(resourceShareArn, name, owningAccountId, principals, resourceArns,
+ allowExternalPrincipals, status, creationTime, stamp, tags);
+ }
+
+ public ResourceShare withTags(Map<String, String> newTags) {
+ return new ResourceShare(resourceShareArn, name, owningAccountId, principals, resourceArns,
+ allowExternalPrincipals, status, creationTime, lastUpdatedTime, newTags);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ram/model/SharedResource.java b/src/main/java/io/github/hectorvent/floci/services/ram/model/SharedResource.java
new file mode 100644
index 0000000000..7bacf543ec
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ram/model/SharedResource.java
@@ -0,0 +1,11 @@
+package io.github.hectorvent.floci.services.ram.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+/**
+ * One entry of a RAM ListResources response: a resource ARN belonging to a share, with the
+ * RAM resource type ({@code service:CamelCasedResource}, e.g. {@code ec2:TransitGateway}).
+ */
+@RegisterForReflection
+public record SharedResource(String arn, String type, String resourceShareArn, String status) {
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasJsonHandler.java
new file mode 100644
index 0000000000..f95e53fdfb
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasJsonHandler.java
@@ -0,0 +1,82 @@
+package io.github.hectorvent.floci.services.servicequotas;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.core.common.AwsErrorResponse;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.core.Response;
+import org.jboss.logging.Logger;
+
+/**
+ * JSON 1.1 handler for Service Quotas operations.
+ * Dispatches {@code X-Amz-Target: ServiceQuotasV20190624.*} actions to {@link ServiceQuotasService}.
+ *
+ * @see <a href="https://docs.aws.amazon.com/servicequotas/2019-06-24/apireference/Welcome.html">Service Quotas API</a>
+ */
+@ApplicationScoped
+public class ServiceQuotasJsonHandler {
+
+ private static final Logger LOG = Logger.getLogger(ServiceQuotasJsonHandler.class);
+
+ private final ServiceQuotasService service;
+
+ @Inject
+ public ServiceQuotasJsonHandler(ServiceQuotasService service) {
+ this.service = service;
+ }
+
+ public Response handle(String action, JsonNode request, String region, String accountId) {
+ LOG.debugv("ServiceQuotas action: {0}", action);
+ return switch (action) {
+ case "ListServiceQuotas" -> handleListServiceQuotas(request, region, accountId);
+ case "GetServiceQuota" -> handleGetServiceQuota(request, region, accountId);
+ case "GetAWSDefaultServiceQuota" -> handleGetServiceQuota(request, region, accountId);
+ case "ListAWSDefaultServiceQuotas" -> handleListServiceQuotas(request, region, accountId);
+ case "RequestServiceQuotaIncrease" -> handleRequestServiceQuotaIncrease(request, region, accountId);
+ default -> Response.status(400)
+ .entity(new AwsErrorResponse("UnknownOperationException",
+ "Unknown operation: ServiceQuotasV20190624." + action))
+ .build();
+ };
+ }
+
+ private Response handleListServiceQuotas(JsonNode request, String region, String accountId) {
+ return Response.ok(service.listServiceQuotas(
+ stringOrNull(request, "ServiceCode"),
+ stringOrNull(request, "QuotaCode"),
+ stringOrNull(request, "NextToken"),
+ integerOrNull(request, "MaxResults"),
+ region, accountId)).build();
+ }
+
+ private Response handleGetServiceQuota(JsonNode request, String region, String accountId) {
+ return Response.ok(service.getServiceQuota(
+ stringOrNull(request, "ServiceCode"),
+ stringOrNull(request, "QuotaCode"),
+ region, accountId)).build();
+ }
+
+ private static String stringOrNull(JsonNode node, String field) {
+ JsonNode value = node == null ? null : node.get(field);
+ return (value != null && !value.isNull()) ? value.asText() : null;
+ }
+
+ private static Integer integerOrNull(JsonNode node, String field) {
+ JsonNode value = node == null ? null : node.get(field);
+ return (value != null && value.isNumber()) ? value.asInt() : null;
+ }
+
+ private Response handleRequestServiceQuotaIncrease(JsonNode request, String region, String accountId) {
+ return Response.ok(service.requestServiceQuotaIncrease(
+ stringOrNull(request, "ServiceCode"),
+ stringOrNull(request, "QuotaCode"),
+ doubleOrNull(request, "DesiredValue"),
+ stringOrNull(request, "ContextId"),
+ region, accountId)).build();
+ }
+
+ private static Double doubleOrNull(JsonNode node, String field) {
+ JsonNode value = node == null ? null : node.get(field);
+ return (value != null && value.isNumber()) ? value.asDouble() : null;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasService.java b/src/main/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasService.java
new file mode 100644
index 0000000000..045b467f07
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasService.java
@@ -0,0 +1,253 @@
+package io.github.hectorvent.floci.services.servicequotas;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Pattern;
+import java.util.zip.CRC32;
+import java.time.Instant;
+
+/**
+ * Service Quotas emulation backed by a generated in-memory catalog.
+ *
+ * <p>Every service code resolves to a quota list: a curated set with real AWS
+ * quota codes where tooling depends on them (CodeBuild's {@code L-2DC20C30}
+ * "Concurrently running builds", Lambda's {@code L-B99A9384} "Concurrent
+ * executions"), plus a deterministic generic set for any other service code.
+ * All values are deliberately generous so local pipelines that gate on quota
+ * headroom (for example Landing Zone Accelerator) never stall on a limit the
+ * emulator does not enforce. Applied and default quotas return the same data.
+ *
+ * @see <a href="https://docs.aws.amazon.com/servicequotas/2019-06-24/apireference/Welcome.html">Service Quotas API</a>
+ */
+@ApplicationScoped
+public class ServiceQuotasService {
+
+ private static final double GENERIC_QUOTA_VALUE = 5000.0;
+ private static final Pattern SERVICE_CODE_PATTERN =
+ Pattern.compile("[a-zA-Z][a-zA-Z0-9-]{1,63}");
+
+ private static final Map<String, String> SERVICE_NAMES = Map.ofEntries(
+ Map.entry("codebuild", "AWS CodeBuild"),
+ Map.entry("codepipeline", "AWS CodePipeline"),
+ Map.entry("lambda", "AWS Lambda"),
+ Map.entry("cloudformation", "AWS CloudFormation"),
+ Map.entry("organizations", "AWS Organizations"),
+ Map.entry("iam", "AWS Identity and Access Management (IAM)"),
+ Map.entry("kms", "AWS Key Management Service (AWS KMS)"),
+ Map.entry("s3", "Amazon Simple Storage Service (Amazon S3)"),
+ Map.entry("sns", "Amazon Simple Notification Service (Amazon SNS)"),
+ Map.entry("sqs", "Amazon Simple Queue Service (Amazon SQS)"),
+ Map.entry("ec2", "Amazon Elastic Compute Cloud (Amazon EC2)"),
+ Map.entry("dynamodb", "Amazon DynamoDB"),
+ Map.entry("logs", "Amazon CloudWatch Logs"),
+ Map.entry("events", "Amazon EventBridge (CloudWatch Events)"));
+
+ private static final Map<String, List<QuotaDefinition>> CURATED_QUOTAS = Map.of(
+ "codebuild", List.of(
+ new QuotaDefinition("L-2DC20C30", "Concurrently running builds", GENERIC_QUOTA_VALUE)),
+ "lambda", List.of(
+ new QuotaDefinition("L-B99A9384", "Concurrent executions", GENERIC_QUOTA_VALUE)));
+
+ private static final List<String> GENERIC_QUOTA_NAMES = List.of(
+ "Resources per Region",
+ "Rate of requests per second",
+ "Concurrent operations");
+
+ private final ObjectMapper objectMapper;
+
+ @Inject
+ public ServiceQuotasService(ObjectMapper objectMapper) {
+ this.objectMapper = objectMapper;
+ }
+
+ public ObjectNode listServiceQuotas(String serviceCode, String quotaCodeFilter, String nextToken,
+ Integer maxResults, String region, String accountId) {
+ requireServiceCode(serviceCode);
+ List<QuotaDefinition> quotas = quotasFor(serviceCode);
+ if (quotaCodeFilter != null && !quotaCodeFilter.isEmpty()) {
+ quotas = quotas.stream().filter(q -> q.quotaCode().equals(quotaCodeFilter)).toList();
+ }
+ Page page = paginate(quotas, nextToken, maxResults);
+
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode array = response.putArray("Quotas");
+ for (QuotaDefinition quota : page.items()) {
+ array.add(quotaNode(serviceCode, quota, region, accountId));
+ }
+ if (page.nextToken() != null) {
+ response.put("NextToken", page.nextToken());
+ }
+ return response;
+ }
+
+ public ObjectNode getServiceQuota(String serviceCode, String quotaCode, String region, String accountId) {
+ requireServiceCode(serviceCode);
+ if (quotaCode == null || quotaCode.isEmpty()) {
+ throw new AwsException("IllegalArgumentException",
+ "Invalid input: QuotaCode must not be empty.", 400);
+ }
+ QuotaDefinition quota = quotasFor(serviceCode).stream()
+ .filter(q -> q.quotaCode().equals(quotaCode))
+ .findFirst()
+ .orElseThrow(() -> new AwsException("NoSuchResourceException",
+ "The request failed because the specified service quota does not exist.", 400));
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("Quota", quotaNode(serviceCode, quota, region, accountId));
+ return response;
+ }
+
+ List<QuotaDefinition> quotasFor(String serviceCode) {
+ List<QuotaDefinition> quotas = new ArrayList<>(CURATED_QUOTAS.getOrDefault(serviceCode, List.of()));
+ for (String name : GENERIC_QUOTA_NAMES) {
+ quotas.add(new QuotaDefinition(syntheticQuotaCode(serviceCode, name), name, GENERIC_QUOTA_VALUE));
+ }
+ return quotas;
+ }
+
+ /**
+ * Deterministic {@code L-XXXXXXXX} code for generated quotas so that a code
+ * observed in {@code ListServiceQuotas} always resolves in {@code GetServiceQuota}.
+ */
+ static String syntheticQuotaCode(String serviceCode, String quotaName) {
+ CRC32 crc = new CRC32();
+ crc.update((serviceCode + "/" + quotaName).getBytes(StandardCharsets.UTF_8));
+ return "L-%08X".formatted(crc.getValue());
+ }
+
+ private ObjectNode quotaNode(String serviceCode, QuotaDefinition quota, String region, String accountId) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("ServiceCode", serviceCode);
+ node.put("ServiceName", SERVICE_NAMES.getOrDefault(serviceCode, serviceCode));
+ node.put("QuotaArn", "arn:aws:servicequotas:" + region + ":" + accountId + ":"
+ + serviceCode + "/" + quota.quotaCode());
+ node.put("QuotaCode", quota.quotaCode());
+ node.put("QuotaName", quota.quotaName());
+ node.put("Value", quota.value());
+ node.put("Unit", "None");
+ node.put("Adjustable", true);
+ node.put("GlobalQuota", false);
+ node.put("QuotaAppliedAtLevel", "ACCOUNT");
+ return node;
+ }
+
+ /**
+ * Unknown-but-well-formed service codes deliberately generate a quota catalog, which makes the
+ * shape check load-bearing: without it a code that cannot name any service — {@code "!!!"} —
+ * comes back with invented quotas instead of an error. The model constrains ServiceCode to at
+ * most 63 characters matching {@code [a-zA-Z][a-zA-Z0-9-]{1,63}} (the pattern's own minimum of
+ * two characters is the binding one, the shape's {@code min: 1} notwithstanding).
+ */
+ private static void requireServiceCode(String serviceCode) {
+ if (serviceCode == null || serviceCode.isEmpty()) {
+ throw new AwsException("IllegalArgumentException",
+ "Invalid input: ServiceCode must not be empty.", 400);
+ }
+ if (serviceCode.length() > 63 || !SERVICE_CODE_PATTERN.matcher(serviceCode).matches()) {
+ throw new AwsException("IllegalArgumentException",
+ "Invalid input: ServiceCode must match [a-zA-Z][a-zA-Z0-9-]{1,63} "
+ + "and be at most 63 characters.", 400);
+ }
+ }
+
+ private static Page paginate(List<QuotaDefinition> items, String nextToken, Integer maxResults) {
+ if (maxResults != null && (maxResults < 1 || maxResults > 100)) {
+ throw new AwsException("IllegalArgumentException",
+ "Invalid input: MaxResults must be between 1 and 100.", 400);
+ }
+ int start = decodeToken(nextToken);
+ if (start < 0 || start > items.size()) {
+ throw new AwsException("InvalidPaginationTokenException", "Invalid NextToken.", 400);
+ }
+ int end = (maxResults == null) ? items.size() : Math.min(items.size(), start + maxResults);
+ String next = (end < items.size()) ? encodeToken(end) : null;
+ return new Page(items.subList(start, end), next);
+ }
+
+ private static String encodeToken(int offset) {
+ return Base64.getUrlEncoder().withoutPadding()
+ .encodeToString(Integer.toString(offset).getBytes(StandardCharsets.UTF_8));
+ }
+
+ private static int decodeToken(String token) {
+ if (token == null || token.isEmpty()) {
+ return 0;
+ }
+ try {
+ byte[] decoded = Base64.getUrlDecoder().decode(token);
+ return Integer.parseInt(new String(decoded, StandardCharsets.UTF_8));
+ } catch (IllegalArgumentException e) {
+ return -1;
+ }
+ }
+
+ record QuotaDefinition(String quotaCode, String quotaName, double value) {
+ }
+
+ private record Page(List<QuotaDefinition> items, String nextToken) {
+ }
+
+ public ObjectNode requestServiceQuotaIncrease(String serviceCode, String quotaCode, Double desiredValue,
+ String contextId, String region, String accountId) {
+ requireServiceCode(serviceCode);
+ if (quotaCode == null || quotaCode.isEmpty()) {
+ throw new AwsException("IllegalArgumentException",
+ "Invalid input: QuotaCode must not be empty.", 400);
+ }
+ if (desiredValue == null) {
+ throw new AwsException("IllegalArgumentException",
+ "Invalid input: DesiredValue must not be null.", 400);
+ }
+ if (desiredValue < 0 || desiredValue > 10000000000.0) {
+ throw new AwsException("IllegalArgumentException",
+ "Invalid input: DesiredValue must be between 0 and 10000000000.", 400);
+ }
+ QuotaDefinition quota = quotasFor(serviceCode).stream()
+ .filter(q -> q.quotaCode().equals(quotaCode))
+ .findFirst()
+ .orElseThrow(() -> new AwsException("NoSuchResourceException",
+ "The request failed because the specified service quota does not exist.", 400));
+
+ CRC32 crc = new CRC32();
+ crc.update((serviceCode + "/" + quotaCode).getBytes(StandardCharsets.UTF_8));
+ String id = "%08X".formatted(crc.getValue());
+
+ long now = Instant.now().getEpochSecond();
+
+ ObjectNode requestedQuota = objectMapper.createObjectNode();
+ requestedQuota.put("Id", id);
+ requestedQuota.put("ServiceCode", serviceCode);
+ requestedQuota.put("ServiceName", SERVICE_NAMES.getOrDefault(serviceCode, serviceCode));
+ requestedQuota.put("QuotaCode", quotaCode);
+ requestedQuota.put("QuotaName", quota.quotaName());
+ requestedQuota.put("QuotaArn", "arn:aws:servicequotas:" + region + ":" + accountId + ":"
+ + serviceCode + "/" + quotaCode);
+ requestedQuota.put("DesiredValue", desiredValue);
+ requestedQuota.put("Status", "PENDING");
+ requestedQuota.put("Requester", "floci-emulator");
+ requestedQuota.put("Unit", "None");
+ requestedQuota.put("GlobalQuota", false);
+ requestedQuota.put("QuotaRequestedAtLevel", "ACCOUNT");
+ requestedQuota.put("Created", now);
+ requestedQuota.put("LastUpdated", now);
+ if (contextId != null) {
+ ObjectNode context = objectMapper.createObjectNode();
+ context.put("ContextId", contextId);
+ context.put("ContextScope", "RESOURCE");
+ requestedQuota.set("QuotaContext", context);
+ }
+
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("RequestedQuota", requestedQuota);
+ return response;
+ }
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 8e22dccd34..65ea0d49a8 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -567,3 +567,7 @@ floci:
# validate-runtime-exists: false # true = reject unknown runtime ARNs
bedrock-agent-core-control:
enabled: true
+ servicequotas:
+ enabled: true
+ ram:
+ enabled: true
diff --git a/src/test/java/io/github/hectorvent/floci/services/ram/RamIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ram/RamIntegrationTest.java
new file mode 100644
index 0000000000..ed85860805
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ram/RamIntegrationTest.java
@@ -0,0 +1,349 @@
+package io.github.hectorvent.floci.services.ram;
+
+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;
+
+/**
+ * Verifies the RAM restJson1 organization-sharing opt-in:
+ * {@code POST /enablesharingwithawsorganization} succeeds with or without a request body.
+ */
+@QuarkusTest
+class RamIntegrationTest {
+
+ private static final String AUTH_HEADER =
+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ram/aws4_request";
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void enableSharingWithAwsOrganization_returnsTrue() {
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("{}")
+ .when()
+ .post("/enablesharingwithawsorganization")
+ .then()
+ .statusCode(200)
+ .body("returnValue", equalTo(true));
+ }
+
+ @Test
+ void enableSharingWithAwsOrganization_withoutBody_returnsTrue() {
+ given()
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/enablesharingwithawsorganization")
+ .then()
+ .statusCode(200)
+ .body("returnValue", equalTo(true));
+ }
+
+ @Test
+ void getResourceShareInvitations_returnsEmptyJson() {
+ // LZA's Custom::GetResourceShare Lambda pages this first; under organization
+ // sharing there are never invitations. The response must be JSON (restJson1) —
+ // an XML fallthrough here is exactly the SyntaxError seen in run b81f0999.
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("{}")
+ .when()
+ .post("/getresourceshareinvitations")
+ .then()
+ .statusCode(200)
+ .contentType("application/json")
+ .body("resourceShareInvitations.size()", equalTo(0));
+ }
+
+ @Test
+ void ownerCanTagAndDeleteItsOwnShareOverHttp() {
+ // Mutations resolve the share within the caller's account, so the identity stamped at
+ // create time has to be the identity resolved at tag/delete time — otherwise LZA's
+ // AWS::RAM::ResourceShare teardown would fail against a share it had just created.
+ String shareArn =
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ {
+ "name": "owner-mutation-share",
+ "principals": ["arn:aws:organizations::000000000000:ou/o-abc/ou-infra"],
+ "resourceArns": ["arn:aws:ec2:us-east-1:000000000000:transit-gateway/tgw-0own"]
+ }
+ """)
+ .when()
+ .post("/createresourceshare")
+ .then()
+ .statusCode(200)
+ .extract().path("resourceShare.resourceShareArn");
+
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ { "resourceShareArn": "%s", "tags": [{"key": "Owner", "value": "network"}] }
+ """.formatted(shareArn))
+ .when()
+ .post("/tagresource")
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .delete("/deleteresourceshare?resourceShareArn=" + shareArn)
+ .then()
+ .statusCode(200)
+ .body("returnValue", equalTo(true));
+ }
+
+ @Test
+ void getResourceSharesHonoursTheNameFilterOverHttp() {
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ {
+ "name": "http-filtered-share",
+ "resourceArns": ["arn:aws:ec2:us-east-1:000000000000:transit-gateway/tgw-0flt"]
+ }
+ """)
+ .when()
+ .post("/createresourceshare")
+ .then()
+ .statusCode(200);
+
+ // The filter has to be read off the body, not ignored: without it this returns every
+ // share the other tests in this class created.
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ { "resourceOwner": "SELF", "name": "http-filtered-share" }
+ """)
+ .when()
+ .post("/getresourceshares")
+ .then()
+ .statusCode(200)
+ .body("resourceShares.size()", equalTo(1))
+ .body("resourceShares[0].name", equalTo("http-filtered-share"));
+ }
+
+ @Test
+ void deleteEchoesTheClientTokenAndSharesReportFeatureSet() {
+ String shareArn =
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ {
+ "name": "token-echo-share",
+ "resourceArns": ["arn:aws:ec2:us-east-1:000000000000:transit-gateway/tgw-0tok"]
+ }
+ """)
+ .when()
+ .post("/createresourceshare")
+ .then()
+ .statusCode(200)
+ // Shares created through the API are STANDARD, not policy-derived.
+ .body("resourceShare.featureSet", equalTo("STANDARD"))
+ .extract().path("resourceShare.resourceShareArn");
+
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .delete("/deleteresourceshare?resourceShareArn=" + shareArn + "&clientToken=idem-1")
+ .then()
+ .statusCode(200)
+ .body("returnValue", equalTo(true))
+ .body("clientToken", equalTo("idem-1"));
+ }
+
+ /**
+ * Jackson's default readTree stops at the first complete value, so a body like
+ * {@code {} not-json} parsed as an empty object and the request executed. The JSON 1.0/1.1
+ * controllers and the FIS REST controller all read with FAIL_ON_TRAILING_TOKENS; RAM was the
+ * outlier.
+ */
+ @Test
+ void trailingContentAfterValidJsonIsSerializationException() {
+ for (String body : new String[] {
+ "{} not-json",
+ "{\"resourceOwner\":\"SELF\"}{\"second\":\"document\"}"}) {
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body(body)
+ .when()
+ .post("/getresourceshares")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("SerializationException"));
+ }
+ }
+
+ @Test
+ void malformedBodyIsRejectedAsSerializationException() {
+ // A body that is not JSON is a client error; without an explicit rejection the parse
+ // failure escapes as UncheckedIOException and the SDK sees a 500 InternalFailure.
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("not json at all")
+ .when()
+ .post("/getresourceshares")
+ .then()
+ .statusCode(400)
+ .contentType("application/json")
+ .body("__type", equalTo("SerializationException"));
+ }
+
+ @Test
+ void malformedInvitationsBodyIsRejectedAsSerializationException() {
+ // GetResourceShareInvitations ignores its body semantically (invitations are
+ // always empty under organization sharing), but a malformed body is still a
+ // client error, not a 200.
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("not json at all")
+ .when()
+ .post("/getresourceshareinvitations")
+ .then()
+ .statusCode(400)
+ .contentType("application/json")
+ .body("__type", equalTo("SerializationException"));
+ }
+
+ /**
+ * A present-but-unmodelled resourceOwner — including a non-string that {@code asText}
+ * coerces — has to reach the service check and come back as InvalidParameterException on the
+ * wire, which is the path LZA actually takes.
+ */
+ @Test
+ void unmodelledResourceOwnerIsRejectedOnTheWire() {
+ for (String path : new String[] {"/getresourceshares", "/listprincipals", "/listresources"}) {
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ { "resourceOwner": "self" }
+ """)
+ .when()
+ .post(path)
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("InvalidParameterException"));
+ }
+
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ { "resourceOwner": 5 }
+ """)
+ .when()
+ .post("/getresourceshares")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("InvalidParameterException"));
+
+ }
+
+ /**
+ * resourceOwner is a required member on all three read operations. Substituting SELF for an
+ * absent one answered a question the caller never asked — and answered it with the caller's
+ * own shares, which is the more dangerous of the two branches to guess at.
+ */
+ @Test
+ void missingResourceOwnerIsRejectedOnEveryReadPath() {
+ for (String path : new String[] {"/getresourceshares", "/listprincipals", "/listresources"}) {
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("{}")
+ .when()
+ .post(path)
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("InvalidParameterException"));
+ }
+
+ // An explicit null is absent too, not a third state.
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ { "resourceOwner": null }
+ """)
+ .when()
+ .post("/getresourceshares")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("InvalidParameterException"));
+ }
+
+ @Test
+ void createThenGetResourceSharesAndListResources() {
+ String tgwArn = "arn:aws:ec2:us-east-1:000000000000:transit-gateway/tgw-0abc";
+ String shareArn =
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ {
+ "name": "us-east-1-tgw-share",
+ "principals": ["arn:aws:organizations::000000000000:ou/o-abc/ou-infra"],
+ "resourceArns": ["%s"]
+ }
+ """.formatted(tgwArn))
+ .when()
+ .post("/createresourceshare")
+ .then()
+ .statusCode(200)
+ .body("resourceShare.name", equalTo("us-east-1-tgw-share"))
+ .body("resourceShare.status", equalTo("ACTIVE"))
+ .extract().path("resourceShare.resourceShareArn");
+
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ { "resourceOwner": "SELF" }
+ """)
+ .when()
+ .post("/getresourceshares")
+ .then()
+ .statusCode(200)
+ // Selected by name: the store is shared across the tests in this class.
+ .body("resourceShares.findAll { it.name == 'us-east-1-tgw-share' }.size()", equalTo(1))
+ .body("resourceShares.find { it.name == 'us-east-1-tgw-share' }.owningAccountId",
+ equalTo("000000000000"));
+
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ { "resourceOwner": "SELF", "resourceShareArns": ["%s"] }
+ """.formatted(shareArn))
+ .when()
+ .post("/listresources")
+ .then()
+ .statusCode(200)
+ .body("resources.size()", equalTo(1))
+ .body("resources[0].arn", equalTo(tgwArn))
+ .body("resources[0].type", equalTo("ec2:TransitGateway"))
+ .body("resources[0].resourceShareArn", equalTo(shareArn));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ram/RamResourceShareLifecycleConsumerTest.java b/src/test/java/io/github/hectorvent/floci/services/ram/RamResourceShareLifecycleConsumerTest.java
new file mode 100644
index 0000000000..cbbce72cec
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ram/RamResourceShareLifecycleConsumerTest.java
@@ -0,0 +1,214 @@
+package io.github.hectorvent.floci.services.ram;
+
+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;
+import static org.hamcrest.Matchers.hasItem;
+import static org.hamcrest.Matchers.not;
+
+/**
+ * Wire-level tests for the RAM lifecycle operations LZA's TGW share flow needs beyond
+ * CreateResourceShare/GetResourceShares/ListResources: UpdateResourceShare, DeleteResourceShare,
+ * AssociateResourceShare, DisassociateResourceShare, ListPrincipals, TagResource, UntagResource.
+ *
+ * <p>New class, not appended to {@code RamIntegrationTest} (CS-001), so falsifiability isolates
+ * per operation.
+ */
+@QuarkusTest
+class RamResourceShareLifecycleConsumerTest {
+
+ private static final String AUTH_HEADER =
+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ram/aws4_request";
+ private static final String TGW_ARN = "arn:aws:ec2:us-east-1:000000000000:transit-gateway/tgw-0lifecycle";
+ private static final String OU_PRINCIPAL = "arn:aws:organizations::000000000000:ou/o-abc/ou-lifecycle";
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ private String createShare(String name) {
+ return given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ { "name": "%s", "resourceArns": ["%s"] }
+ """.formatted(name, TGW_ARN))
+ .when()
+ .post("/createresourceshare")
+ .then()
+ .statusCode(200)
+ .extract().path("resourceShare.resourceShareArn");
+ }
+
+ @Test
+ void updateResourceShare_renamesAndTogglesAllowExternalPrincipals() {
+ String arn = createShare("lifecycle-update");
+
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ { "resourceShareArn": "%s", "name": "renamed-share", "allowExternalPrincipals": true }
+ """.formatted(arn))
+ .when()
+ .post("/updateresourceshare")
+ .then()
+ .statusCode(200)
+ .body("resourceShare.name", equalTo("renamed-share"))
+ .body("resourceShare.allowExternalPrincipals", equalTo(true));
+ }
+
+ @Test
+ void updateResourceShare_unknownArn_returns400() {
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ { "resourceShareArn": "arn:aws:ram:us-east-1:000000000000:resource-share/does-not-exist" }
+ """)
+ .when()
+ .post("/updateresourceshare")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("UnknownResourceException"));
+ }
+
+ @Test
+ void deleteResourceShare_marksStatusDeleted() {
+ String arn = createShare("lifecycle-delete");
+
+ given()
+ .header("Authorization", AUTH_HEADER)
+ .queryParam("resourceShareArn", arn)
+ .when()
+ .delete("/deleteresourceshare")
+ .then()
+ .statusCode(200)
+ .body("returnValue", equalTo(true));
+
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ { "resourceOwner": "SELF" }
+ """)
+ .when()
+ .post("/getresourceshares")
+ .then()
+ .statusCode(200)
+ .body("resourceShares.find { it.resourceShareArn == '%s' }.status".formatted(arn), equalTo("DELETED"));
+ }
+
+ @Test
+ void associateThenDisassociateResourceShare_addsAndRemovesPrincipal() {
+ String arn = createShare("lifecycle-associate");
+
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ { "resourceShareArn": "%s", "principals": ["%s"] }
+ """.formatted(arn, OU_PRINCIPAL))
+ .when()
+ .post("/associateresourceshare")
+ .then()
+ .statusCode(200)
+ .body("resourceShareAssociations.size()", equalTo(1))
+ .body("resourceShareAssociations[0].associatedEntity", equalTo(OU_PRINCIPAL))
+ .body("resourceShareAssociations[0].associationType", equalTo("PRINCIPAL"))
+ .body("resourceShareAssociations[0].status", equalTo("ASSOCIATED"));
+
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ { "resourceOwner": "SELF" }
+ """)
+ .when()
+ .post("/listprincipals")
+ .then()
+ .statusCode(200)
+ .body("principals.id", hasItem(OU_PRINCIPAL));
+
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ { "resourceShareArn": "%s", "principals": ["%s"] }
+ """.formatted(arn, OU_PRINCIPAL))
+ .when()
+ .post("/disassociateresourceshare")
+ .then()
+ .statusCode(200)
+ .body("resourceShareAssociations[0].status", equalTo("DISASSOCIATED"));
+
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ { "resourceOwner": "SELF" }
+ """)
+ .when()
+ .post("/listprincipals")
+ .then()
+ .statusCode(200)
+ .body("principals.id", not(hasItem(OU_PRINCIPAL)));
+ }
+
+ @Test
+ void tagThenUntagResource_addsAndRemovesTag() {
+ String arn = createShare("lifecycle-tags");
+
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ { "resourceShareArn": "%s", "tags": [{ "key": "env", "value": "prod" }] }
+ """.formatted(arn))
+ .when()
+ .post("/tagresource")
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ { "resourceOwner": "SELF" }
+ """)
+ .when()
+ .post("/getresourceshares")
+ .then()
+ .statusCode(200)
+ .body("resourceShares.find { it.resourceShareArn == '%s' }.tags[0].key".formatted(arn), equalTo("env"))
+ .body("resourceShares.find { it.resourceShareArn == '%s' }.tags[0].value".formatted(arn), equalTo("prod"));
+
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ { "resourceShareArn": "%s", "tagKeys": ["env"] }
+ """.formatted(arn))
+ .when()
+ .post("/untagresource")
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ { "resourceOwner": "SELF" }
+ """)
+ .when()
+ .post("/getresourceshares")
+ .then()
+ .statusCode(200)
+ .body("resourceShares.find { it.resourceShareArn == '%s' }.tags.size()".formatted(arn), equalTo(0));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ram/RamServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/ram/RamServicePersistenceTest.java
new file mode 100644
index 0000000000..0181ec93f4
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ram/RamServicePersistenceTest.java
@@ -0,0 +1,75 @@
+package io.github.hectorvent.floci.services.ram;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.ram.model.ResourceShare;
+import io.github.hectorvent.floci.services.ram.model.SharedResource;
+import org.junit.jupiter.api.Test;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** Verifies RAM organization settings and cross-account resource shares survive a restart. */
+class RamServicePersistenceTest {
+
+ private static final String OWNER = "111111111111";
+ private static final String ACCEPTER = "222222222222";
+ private static final String TGW_ARN =
+ "arn:aws:ec2:us-east-1:111111111111:transit-gateway/tgw-0abc";
+
+ @Test
+ void resourceSharesAndOrganizationSettingSurviveRestart() {
+ SharedStorageFactory storage = new SharedStorageFactory();
+ RamService first = serviceWithStorage(storage);
+ first.enableSharingWithAwsOrganization();
+ ResourceShare created = first.createResourceShare(
+ "us-east-1-tgw-share",
+ List.of("arn:aws:organizations::000000000000:ou/o-abc/ou-infra"),
+ List.of(TGW_ARN), false, "us-east-1", OWNER);
+
+ RamService reloaded = serviceWithStorage(storage);
+
+ assertTrue(reloaded.isSharingWithOrganizationEnabled());
+ List<ResourceShare> owned = reloaded.getResourceShares(OWNER, "SELF");
+ assertEquals(1, owned.size());
+ assertEquals(created.getResourceShareArn(), owned.getFirst().getResourceShareArn());
+ assertEquals(created.getCreationTime(), owned.getFirst().getCreationTime());
+
+ List<ResourceShare> shared = reloaded.getResourceShares(ACCEPTER, "OTHER-ACCOUNTS");
+ assertEquals(1, shared.size());
+ List<SharedResource> resources = reloaded.listResources(
+ ACCEPTER, "OTHER-ACCOUNTS", List.of(created.getResourceShareArn()));
+ assertEquals(1, resources.size());
+ assertEquals(TGW_ARN, resources.getFirst().arn());
+ }
+
+ private static RamService serviceWithStorage(StorageFactory storage) {
+ RamService service = new RamService(storage);
+ service.initializeStorage();
+ return service;
+ }
+
+ private static final class SharedStorageFactory extends StorageFactory {
+ private final Map<String, StorageBackend<String, ?>> stores = new HashMap<>();
+
+ private SharedStorageFactory() {
+ super(null, null);
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public <V> AccountAwareStorageBackend<V> create(String serviceName,
+ String fileName,
+ TypeReference<Map<String, V>> typeReference) {
+ return (AccountAwareStorageBackend<V>) stores.computeIfAbsent(
+ fileName, ignored -> AccountAwareStorageBackend.inMemory("000000000000"));
+ }
+ }
+}
+
diff --git a/src/test/java/io/github/hectorvent/floci/services/ram/RamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ram/RamServiceTest.java
new file mode 100644
index 0000000000..51199f20c8
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ram/RamServiceTest.java
@@ -0,0 +1,324 @@
+package io.github.hectorvent.floci.services.ram;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.ram.model.ResourceShare;
+import io.github.hectorvent.floci.services.ram.model.SharedResource;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.function.Executable;
+
+import java.util.List;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * Resource-share semantics behind LZA's TGW share flow: the owning account creates a share
+ * (via {@code AWS::RAM::ResourceShare}), and the accepting account's Custom::GetResourceShare
+ * Lambda pages GetResourceShareInvitations (empty under organization sharing) then
+ * GetResourceShares(resourceOwner=OTHER-ACCOUNTS) filtering by owner + name, and finally
+ * Custom::GetResourceShareItem lists the shared resource ARNs via ListResources.
+ */
+class RamServiceTest {
+
+ private static final String OWNER = "111111111111";
+ private static final String ACCEPTER = "222222222222";
+ private static final String OU_ARN = "arn:aws:organizations::000000000000:ou/o-abc123/ou-root-infra";
+ private static final String TGW_ARN = "arn:aws:ec2:us-east-1:111111111111:transit-gateway/tgw-0abc";
+
+ private RamService service;
+
+ @BeforeEach
+ void setUp() {
+ service = new RamService(new SharedStorageFactory());
+ service.initializeStorage();
+ }
+
+ @Test
+ void deletedShareStopsExposingItsResourcesAndPrincipals() {
+ // Real RAM keeps a deleted share visible (status DELETED) for a retention
+ // window, but its resources and principals stop being consumable: a
+ // non-owning consumer must not discover AVAILABLE resources of a deleted
+ // share through ListResources or ListPrincipals.
+ ResourceShare share = service.createResourceShare(
+ "delete-me", List.of(OU_ARN), List.of(TGW_ARN), false, "us-east-1", OWNER);
+ service.deleteResourceShare(share.getResourceShareArn(), OWNER);
+
+ assertTrue(service.listResources(ACCEPTER, "OTHER-ACCOUNTS", List.of()).isEmpty());
+ assertTrue(service.listPrincipals(ACCEPTER, "OTHER-ACCOUNTS", List.of()).isEmpty());
+ assertTrue(service.listResources(OWNER, "SELF", List.of()).isEmpty());
+
+ // The share itself remains readable with DELETED status.
+ List<ResourceShare> own = service.getResourceShares(OWNER, "SELF");
+ assertEquals(1, own.size());
+ assertEquals("DELETED", own.get(0).getStatus());
+ }
+
+ @Test
+ void createResourceShareIsVisibleToOwnerAsSelf() {
+ ResourceShare share = service.createResourceShare(
+ "us-east-1-tgw-share", List.of(OU_ARN), List.of(TGW_ARN), false, "us-east-1", OWNER);
+
+ assertNotNull(share.getResourceShareArn());
+ assertTrue(share.getResourceShareArn().startsWith("arn:aws:ram:us-east-1:" + OWNER + ":resource-share/"));
+ assertEquals("ACTIVE", share.getStatus());
+
+ List<ResourceShare> own = service.getResourceShares(OWNER, "SELF");
+ assertEquals(1, own.size());
+ assertEquals("us-east-1-tgw-share", own.get(0).getName());
+ assertEquals(OWNER, own.get(0).getOwningAccountId());
+ }
+
+ @Test
+ void shareWithOuPrincipalIsVisibleToOrgAccountsAsOtherAccounts() {
+ service.createResourceShare(
+ "us-east-1-tgw-share", List.of(OU_ARN), List.of(TGW_ARN), false, "us-east-1", OWNER);
+
+ List<ResourceShare> visible = service.getResourceShares(ACCEPTER, "OTHER-ACCOUNTS");
+ assertEquals(1, visible.size());
+ assertEquals(OWNER, visible.get(0).getOwningAccountId());
+ }
+
+ @Test
+ void ownShareIsNotListedUnderOtherAccounts() {
+ service.createResourceShare(
+ "us-east-1-tgw-share", List.of(OU_ARN), List.of(TGW_ARN), false, "us-east-1", OWNER);
+
+ assertTrue(service.getResourceShares(OWNER, "OTHER-ACCOUNTS").isEmpty());
+ assertTrue(service.getResourceShares(ACCEPTER, "SELF").isEmpty());
+ }
+
+ @Test
+ void directAccountPrincipalIsVisibleToTheSharedAccount() {
+ service.createResourceShare(
+ "direct-share", List.of(ACCEPTER), List.of(TGW_ARN), false, "us-east-1", OWNER);
+
+ assertEquals(1, service.getResourceShares(ACCEPTER, "OTHER-ACCOUNTS").size());
+ }
+
+ @Test
+ void accountPrincipalShareIsVisibleToAnyNonOwningCaller() {
+ // LZA's Custom::GetResourceShare Lambda runs on launched-container placeholder
+ // credentials, so its caller resolves to the emulator default account rather than
+ // the function's account. OTHER-ACCOUNTS must therefore return every non-owned
+ // share and leave the narrowing to the Lambda's own owningAccountId+name filter.
+ service.createResourceShare(
+ "ipam-pool-share", List.of(ACCEPTER), List.of(TGW_ARN), false, "us-east-1", OWNER);
+
+ assertEquals(1, service.getResourceShares("000000000000", "OTHER-ACCOUNTS").size());
+ }
+
+ @Test
+ void invitationsAreAlwaysEmptyUnderOrganizationSharing() {
+ service.createResourceShare(
+ "us-east-1-tgw-share", List.of(OU_ARN), List.of(TGW_ARN), false, "us-east-1", OWNER);
+
+ assertTrue(service.getResourceShareInvitations(ACCEPTER).isEmpty());
+ }
+
+ @Test
+ void listResourcesReturnsSharedArnsWithTypeAndShareArn() {
+ ResourceShare share = service.createResourceShare(
+ "us-east-1-tgw-share", List.of(OU_ARN), List.of(TGW_ARN), false, "us-east-1", OWNER);
+
+ List<SharedResource> resources =
+ service.listResources(ACCEPTER, "OTHER-ACCOUNTS", List.of(share.getResourceShareArn()));
+ assertEquals(1, resources.size());
+ assertEquals(TGW_ARN, resources.get(0).arn());
+ assertEquals("ec2:TransitGateway", resources.get(0).type());
+ assertEquals(share.getResourceShareArn(), resources.get(0).resourceShareArn());
+ }
+
+ @Test
+ void listResourcesFiltersByShareArn() {
+ service.createResourceShare(
+ "share-a", List.of(OU_ARN), List.of(TGW_ARN), false, "us-east-1", OWNER);
+ ResourceShare other = service.createResourceShare(
+ "share-b", List.of(OU_ARN),
+ List.of("arn:aws:ec2:us-east-1:111111111111:subnet/subnet-1"), false, "us-east-1", OWNER);
+
+ List<SharedResource> resources =
+ service.listResources(ACCEPTER, "OTHER-ACCOUNTS", List.of(other.getResourceShareArn()));
+ assertEquals(1, resources.size());
+ assertEquals("ec2:Subnet", resources.get(0).type());
+ }
+
+ @Test
+ void nonOwnerCannotMutateAnotherAccountsShare() {
+ // A share is visible to every other account under OTHER-ACCOUNTS, but visibility is not
+ // a licence to mutate: AWS resolves a share ARN within the caller's account, so to a
+ // non-owner the share does not exist as a mutable target.
+ ResourceShare share = service.createResourceShare(
+ "us-east-1-tgw-share", List.of(OU_ARN), List.of(TGW_ARN), false, "us-east-1", OWNER);
+ String arn = share.getResourceShareArn();
+
+ assertUnknownResource(() -> service.deleteResourceShare(arn, ACCEPTER));
+ assertUnknownResource(() -> service.updateResourceShare(arn, "hijacked", null, ACCEPTER));
+ assertUnknownResource(() -> service.associateResourceShare(arn, List.of(TGW_ARN), List.of(), ACCEPTER));
+ assertUnknownResource(() -> service.disassociateResourceShare(arn, List.of(TGW_ARN), List.of(), ACCEPTER));
+ assertUnknownResource(() -> service.tagResource(arn, Map.of("Owner", "attacker"), ACCEPTER));
+ assertUnknownResource(() -> service.untagResource(arn, List.of("Owner"), ACCEPTER));
+
+ ResourceShare untouched = service.getResourceShares(OWNER, "SELF").get(0);
+ assertEquals("us-east-1-tgw-share", untouched.getName());
+ assertEquals("ACTIVE", untouched.getStatus());
+ assertEquals(List.of(TGW_ARN), untouched.getResourceArns());
+ assertTrue(untouched.getTags().isEmpty());
+ }
+
+ @Test
+ void ownerCanMutateOwnShare() {
+ ResourceShare share = service.createResourceShare(
+ "us-east-1-tgw-share", List.of(OU_ARN), List.of(TGW_ARN), false, "us-east-1", OWNER);
+ String arn = share.getResourceShareArn();
+
+ assertEquals("renamed", service.updateResourceShare(arn, "renamed", null, OWNER).getName());
+ service.tagResource(arn, Map.of("Owner", "network"), OWNER);
+ assertEquals("network", service.getResourceShares(OWNER, "SELF").get(0).getTags().get("Owner"));
+ assertEquals("DELETED", service.deleteResourceShare(arn, OWNER).getStatus());
+ }
+
+ /**
+ * The model enumerates resourceOwner as SELF or OTHER-ACCOUNTS on GetResourceShares,
+ * ListPrincipals and ListResources. Anything else used to fall through the "not SELF" branch
+ * and silently return other accounts' shares — the opposite of what a caller who typo'd
+ * "self" expected.
+ */
+ @Test
+ void unmodelledResourceOwnerIsRejectedOnEveryReadPath() {
+ service.createResourceShare(
+ "us-east-1-tgw-share", List.of(OU_ARN), List.of(TGW_ARN), false, "us-east-1", OWNER);
+
+ assertInvalidParameter(() -> service.getResourceShares(ACCEPTER, "self"));
+ assertInvalidParameter(() -> service.listPrincipals(ACCEPTER, "EVERYTHING", List.of()));
+ assertInvalidParameter(() -> service.listResources(ACCEPTER, "OTHER_ACCOUNTS", List.of()));
+
+ assertEquals(1, service.getResourceShares(ACCEPTER, "OTHER-ACCOUNTS").size());
+ assertEquals(0, service.getResourceShares(ACCEPTER, "SELF").size());
+ }
+
+ @Test
+ void mutatingADeletedShareRaisesUnknownResource() {
+ // DELETED is terminal: the share stays readable for the retention window,
+ // but every mutation resolves it the same as an ARN that never existed.
+ ResourceShare share = service.createResourceShare(
+ "gone", List.of(OU_ARN), List.of(TGW_ARN), false, "us-east-1", OWNER);
+ String arn = share.getResourceShareArn();
+ service.deleteResourceShare(arn, OWNER);
+
+ assertUnknownResource(() -> service.updateResourceShare(arn, "renamed", null, OWNER));
+ assertUnknownResource(() -> service.associateResourceShare(arn, List.of(TGW_ARN), List.of(), OWNER));
+ assertUnknownResource(() -> service.disassociateResourceShare(arn, List.of(TGW_ARN), List.of(), OWNER));
+ assertUnknownResource(() -> service.tagResource(arn, Map.of("k", "v"), OWNER));
+ assertUnknownResource(() -> service.untagResource(arn, List.of("k"), OWNER));
+ assertUnknownResource(() -> service.deleteResourceShare(arn, OWNER));
+
+ // Still readable with DELETED status — mutation rejection must not hide it from reads.
+ assertEquals("DELETED", service.getResourceShares(OWNER, "SELF").get(0).getStatus());
+ }
+
+ @Test
+ void getResourceSharesAppliesTheNameFilter() {
+ service.createResourceShare("tgw-share", List.of(OU_ARN), List.of(TGW_ARN), false, "us-east-1", OWNER);
+ service.createResourceShare("ipam-share", List.of(OU_ARN), List.of(TGW_ARN), false, "us-east-1", OWNER);
+
+ List<ResourceShare> matched =
+ service.getResourceShares(OWNER, "SELF", "ipam-share", List.of(), null);
+ assertEquals(1, matched.size());
+ assertEquals("ipam-share", matched.get(0).getName());
+
+ assertTrue(service.getResourceShares(OWNER, "SELF", "no-such-share", List.of(), null).isEmpty());
+ }
+
+ @Test
+ void getResourceSharesAppliesTheResourceShareArnsFilter() {
+ ResourceShare wanted = service.createResourceShare(
+ "tgw-share", List.of(OU_ARN), List.of(TGW_ARN), false, "us-east-1", OWNER);
+ service.createResourceShare("ipam-share", List.of(OU_ARN), List.of(TGW_ARN), false, "us-east-1", OWNER);
+
+ List<ResourceShare> matched = service.getResourceShares(
+ OWNER, "SELF", null, List.of(wanted.getResourceShareArn()), null);
+ assertEquals(1, matched.size());
+ assertEquals(wanted.getResourceShareArn(), matched.get(0).getResourceShareArn());
+ }
+
+ @Test
+ void getResourceSharesAppliesTheStatusFilter() {
+ // LZA polls for ACTIVE shares; a share left in the DELETED retention window must not
+ // come back from that poll, but must still be findable by an explicit DELETED filter.
+ service.createResourceShare("live", List.of(OU_ARN), List.of(TGW_ARN), false, "us-east-1", OWNER);
+ ResourceShare doomed = service.createResourceShare(
+ "gone", List.of(OU_ARN), List.of(TGW_ARN), false, "us-east-1", OWNER);
+ service.deleteResourceShare(doomed.getResourceShareArn(), OWNER);
+
+ List<ResourceShare> active = service.getResourceShares(OWNER, "SELF", null, List.of(), "ACTIVE");
+ assertEquals(1, active.size());
+ assertEquals("live", active.get(0).getName());
+
+ List<ResourceShare> deleted = service.getResourceShares(OWNER, "SELF", null, List.of(), "DELETED");
+ assertEquals(1, deleted.size());
+ assertEquals("gone", deleted.get(0).getName());
+
+ // No status filter still returns both, as it does today.
+ assertEquals(2, service.getResourceShares(OWNER, "SELF").size());
+ }
+
+ @Test
+ void unmodelledResourceShareStatusIsRejected() {
+ assertInvalidParameter(() -> service.getResourceShares(OWNER, "SELF", null, List.of(), "active"));
+ assertInvalidParameter(() -> service.getResourceShares(OWNER, "SELF", null, List.of(), "GONE"));
+ }
+
+ @Test
+ void lastUpdatedTimeAdvancesOnMutationButCreationTimeDoesNot() {
+ ResourceShare created = service.createResourceShare(
+ "tgw-share", List.of(OU_ARN), List.of(TGW_ARN), false, "us-east-1", OWNER);
+ String arn = created.getResourceShareArn();
+ assertFalse(created.getLastUpdatedTime().isBefore(created.getCreationTime()));
+
+ ResourceShare renamed = service.updateResourceShare(arn, "renamed", null, OWNER);
+ assertTrue(renamed.getLastUpdatedTime().isAfter(created.getLastUpdatedTime()));
+ assertEquals(created.getCreationTime(), renamed.getCreationTime());
+
+ service.tagResource(arn, Map.of("Owner", "network"), OWNER);
+ ResourceShare tagged = service.getResourceShares(OWNER, "SELF").get(0);
+ assertTrue(tagged.getLastUpdatedTime().isAfter(renamed.getLastUpdatedTime()));
+ assertEquals(created.getCreationTime(), tagged.getCreationTime());
+ }
+
+ private static void assertInvalidParameter(Executable read) {
+ AwsException error = assertThrows(AwsException.class, read);
+ assertEquals("InvalidParameterException", error.getErrorCode());
+ assertEquals(400, error.getHttpStatus());
+ }
+
+ private static void assertUnknownResource(Executable mutation) {
+ AwsException error = assertThrows(AwsException.class, mutation);
+ assertEquals("UnknownResourceException", error.getErrorCode());
+ assertEquals(400, error.getHttpStatus());
+ // Same message an unknown ARN gets — a non-owner must not learn the share exists.
+ assertTrue(error.getMessage().endsWith(" does not exist."));
+ }
+
+ private static final class SharedStorageFactory extends StorageFactory {
+ private final Map<String, StorageBackend<String, ?>> stores = new HashMap<>();
+
+ private SharedStorageFactory() {
+ super(null, null);
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public <V> AccountAwareStorageBackend<V> create(String serviceName,
+ String fileName,
+ TypeReference<Map<String, V>> typeReference) {
+ return (AccountAwareStorageBackend<V>) stores.computeIfAbsent(
+ fileName, ignored -> AccountAwareStorageBackend.inMemory("000000000000"));
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/servicequotas/RequestServiceQuotaIncreaseConsumerTest.java b/src/test/java/io/github/hectorvent/floci/services/servicequotas/RequestServiceQuotaIncreaseConsumerTest.java
new file mode 100644
index 0000000000..9435403de4
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/servicequotas/RequestServiceQuotaIncreaseConsumerTest.java
@@ -0,0 +1,172 @@
+package io.github.hectorvent.floci.services.servicequotas;
+
+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;
+import static org.hamcrest.Matchers.matchesRegex;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.hamcrest.Matchers.nullValue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * Wire-level tests for {@code ServiceQuotasV20190624.RequestServiceQuotaIncrease}.
+ *
+ * <p>These drive the real HTTP route with the real {@code X-Amz-Target} header, so the
+ * dispatch case itself is under test: remove the case from
+ * {@link ServiceQuotasJsonHandler} and every test here fails on
+ * {@code UnknownOperationException}. A green run therefore proves the operation is
+ * reachable by name, which a service-level test could not (CS-001).
+ *
+ * <p><strong>Known limitation asserted here deliberately:</strong> the emulator does not
+ * persist increase requests. {@code GetRequestedServiceQuotaChange} and
+ * {@code ListRequestedServiceQuotaChangeHistory} are unsupported, so a request is
+ * observable only in the response that creates it. {@code Status} is therefore always
+ * {@code PENDING} and never advances. Documented in {@code docs/services/servicequotas.md}
+ * per CS-021.
+ */
+@QuarkusTest
+class RequestServiceQuotaIncreaseConsumerTest {
+
+ private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
+ private static final String AUTH_HEADER =
+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/servicequotas/aws4_request";
+ private static final String TARGET = "ServiceQuotasV20190624.RequestServiceQuotaIncrease";
+ private static final String CONCURRENT_BUILDS_QUOTA = "L-2DC20C30";
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ private static io.restassured.response.Response request(String body) {
+ return given()
+ .contentType(CONTENT_TYPE)
+ .header("X-Amz-Target", TARGET)
+ .header("Authorization", AUTH_HEADER)
+ .body(body)
+ .when()
+ .post("/");
+ }
+
+ @Test
+ void requestIncrease_curatedQuota_returnsFullyPopulatedPendingRequest() {
+ request("{\"ServiceCode\":\"codebuild\",\"QuotaCode\":\"" + CONCURRENT_BUILDS_QUOTA
+ + "\",\"DesiredValue\":9000}")
+ .then()
+ .statusCode(200)
+ .body("RequestedQuota.Id", matchesRegex("[0-9A-F]{8}"))
+ .body("RequestedQuota.ServiceCode", equalTo("codebuild"))
+ .body("RequestedQuota.ServiceName", equalTo("AWS CodeBuild"))
+ .body("RequestedQuota.QuotaCode", equalTo(CONCURRENT_BUILDS_QUOTA))
+ .body("RequestedQuota.QuotaName", equalTo("Concurrently running builds"))
+ .body("RequestedQuota.QuotaArn", equalTo(
+ "arn:aws:servicequotas:us-east-1:000000000000:codebuild/" + CONCURRENT_BUILDS_QUOTA))
+ .body("RequestedQuota.DesiredValue", equalTo(9000.0f))
+ .body("RequestedQuota.Status", equalTo("PENDING"))
+ .body("RequestedQuota.Unit", equalTo("None"))
+ .body("RequestedQuota.GlobalQuota", equalTo(false))
+ .body("RequestedQuota.QuotaRequestedAtLevel", equalTo("ACCOUNT"))
+ .body("RequestedQuota.Requester", notNullValue())
+ .body("RequestedQuota.Created", notNullValue())
+ .body("RequestedQuota.LastUpdated", notNullValue());
+ }
+
+ @Test
+ void requestIncrease_generatedQuotaOnUnknownService_resolves() {
+ String quotaCode = ServiceQuotasService.syntheticQuotaCode("widgetfactory", "Resources per Region");
+ request("{\"ServiceCode\":\"widgetfactory\",\"QuotaCode\":\"" + quotaCode
+ + "\",\"DesiredValue\":1}")
+ .then()
+ .statusCode(200)
+ .body("RequestedQuota.QuotaCode", equalTo(quotaCode))
+ .body("RequestedQuota.QuotaName", equalTo("Resources per Region"))
+ .body("RequestedQuota.ServiceCode", equalTo("widgetfactory"));
+ }
+
+ /** The id must be stable so a caller can correlate a repeated request. */
+ @Test
+ void requestIncrease_sameQuotaTwice_returnsSameId() {
+ String body = "{\"ServiceCode\":\"lambda\",\"QuotaCode\":\"L-B99A9384\",\"DesiredValue\":2000}";
+ String first = request(body).then().statusCode(200)
+ .extract().path("RequestedQuota.Id");
+ String second = request(body).then().statusCode(200)
+ .extract().path("RequestedQuota.Id");
+ assertEquals(first, second);
+ }
+
+ @Test
+ void requestIncrease_withContextId_emitsQuotaContext() {
+ request("{\"ServiceCode\":\"lambda\",\"QuotaCode\":\"L-B99A9384\",\"DesiredValue\":10,"
+ + "\"ContextId\":\"arn:aws:lambda:us-east-1:000000000000:function:fn\"}")
+ .then()
+ .statusCode(200)
+ .body("RequestedQuota.QuotaContext.ContextId",
+ equalTo("arn:aws:lambda:us-east-1:000000000000:function:fn"))
+ .body("RequestedQuota.QuotaContext.ContextScope", equalTo("RESOURCE"));
+ }
+
+ /** An unmodelled-by-the-emulator field must be absent, not null-valued or invented. */
+ @Test
+ void requestIncrease_withoutContextId_omitsQuotaContextAndCaseId() {
+ request("{\"ServiceCode\":\"lambda\",\"QuotaCode\":\"L-B99A9384\",\"DesiredValue\":10}")
+ .then()
+ .statusCode(200)
+ .body("RequestedQuota.QuotaContext", nullValue())
+ .body("RequestedQuota.CaseId", nullValue());
+ }
+
+ @Test
+ void requestIncrease_unknownQuotaCode_returnsNoSuchResource() {
+ request("{\"ServiceCode\":\"codebuild\",\"QuotaCode\":\"L-DEADBEEF\",\"DesiredValue\":1}")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("NoSuchResourceException"));
+ }
+
+ @Test
+ void requestIncrease_missingQuotaCode_returnsIllegalArgument() {
+ request("{\"ServiceCode\":\"codebuild\",\"DesiredValue\":1}")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("IllegalArgumentException"));
+ }
+
+ @Test
+ void requestIncrease_missingServiceCode_returnsIllegalArgument() {
+ request("{\"QuotaCode\":\"" + CONCURRENT_BUILDS_QUOTA + "\",\"DesiredValue\":1}")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("IllegalArgumentException"));
+ }
+
+ @Test
+ void requestIncrease_missingDesiredValue_returnsIllegalArgument() {
+ request("{\"ServiceCode\":\"codebuild\",\"QuotaCode\":\"" + CONCURRENT_BUILDS_QUOTA + "\"}")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("IllegalArgumentException"));
+ }
+
+ @Test
+ void requestIncrease_negativeDesiredValue_returnsIllegalArgument() {
+ request("{\"ServiceCode\":\"codebuild\",\"QuotaCode\":\"" + CONCURRENT_BUILDS_QUOTA
+ + "\",\"DesiredValue\":-1}")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("IllegalArgumentException"));
+ }
+
+ /** Packet bounds are min=0 max=10000000000; one past the top must be rejected. */
+ @Test
+ void requestIncrease_desiredValueAboveModelledMaximum_returnsIllegalArgument() {
+ request("{\"ServiceCode\":\"codebuild\",\"QuotaCode\":\"" + CONCURRENT_BUILDS_QUOTA
+ + "\",\"DesiredValue\":10000000001}")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("IllegalArgumentException"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasIntegrationTest.java
new file mode 100644
index 0000000000..a5f6cebe12
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasIntegrationTest.java
@@ -0,0 +1,237 @@
+package io.github.hectorvent.floci.services.servicequotas;
+
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.Response;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.greaterThanOrEqualTo;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.hamcrest.Matchers.startsWith;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+/**
+ * Integration tests for the Service Quotas service.
+ * Protocol: JSON 1.1 — Content-Type: application/x-amz-json-1.1,
+ * X-Amz-Target: ServiceQuotasV20190624.&lt;Action&gt;
+ */
+@QuarkusTest
+class ServiceQuotasIntegrationTest {
+
+ private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
+ private static final String AUTH_HEADER =
+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/servicequotas/aws4_request";
+ private static final String CONCURRENT_BUILDS_QUOTA = "L-2DC20C30";
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void listServiceQuotas_codebuild_includesConcurrentlyRunningBuilds() {
+ String quotaPath = "Quotas.find { it.QuotaCode == '" + CONCURRENT_BUILDS_QUOTA + "' }";
+ given()
+ .contentType(CONTENT_TYPE)
+ .header("X-Amz-Target", "ServiceQuotasV20190624.ListServiceQuotas")
+ .header("Authorization", AUTH_HEADER)
+ .body("{\"ServiceCode\":\"codebuild\"}")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(quotaPath + ".QuotaName", equalTo("Concurrently running builds"))
+ .body(quotaPath + ".ServiceCode", equalTo("codebuild"))
+ .body(quotaPath + ".ServiceName", equalTo("AWS CodeBuild"))
+ .body(quotaPath + ".QuotaArn", equalTo(
+ "arn:aws:servicequotas:us-east-1:000000000000:codebuild/" + CONCURRENT_BUILDS_QUOTA))
+ .body(quotaPath + ".Value", greaterThanOrEqualTo(60.0f))
+ .body(quotaPath + ".Unit", equalTo("None"))
+ .body(quotaPath + ".Adjustable", equalTo(true))
+ .body(quotaPath + ".GlobalQuota", equalTo(false))
+ .body(quotaPath + ".QuotaAppliedAtLevel", equalTo("ACCOUNT"));
+ }
+
+ @Test
+ void listServiceQuotas_unknownServiceCode_returnsGeneratedQuotas() {
+ given()
+ .contentType(CONTENT_TYPE)
+ .header("X-Amz-Target", "ServiceQuotasV20190624.ListServiceQuotas")
+ .header("Authorization", AUTH_HEADER)
+ .body("{\"ServiceCode\":\"widgetfactory\"}")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Quotas.size()", equalTo(3))
+ .body("Quotas[0].ServiceCode", equalTo("widgetfactory"))
+ .body("Quotas[0].QuotaCode", startsWith("L-"))
+ .body("Quotas[0].Value", equalTo(5000.0f))
+ .body("Quotas[0].Unit", equalTo("None"));
+ }
+
+ @Test
+ void listServiceQuotas_missingServiceCode_returnsIllegalArgument() {
+ given()
+ .contentType(CONTENT_TYPE)
+ .header("X-Amz-Target", "ServiceQuotasV20190624.ListServiceQuotas")
+ .header("Authorization", AUTH_HEADER)
+ .body("{}")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("IllegalArgumentException"));
+ }
+
+ @Test
+ void listServiceQuotas_paginatesDeterministically() {
+ Response first = given()
+ .contentType(CONTENT_TYPE)
+ .header("X-Amz-Target", "ServiceQuotasV20190624.ListServiceQuotas")
+ .header("Authorization", AUTH_HEADER)
+ .body("{\"ServiceCode\":\"codebuild\",\"MaxResults\":1}")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Quotas.size()", equalTo(1))
+ .body("NextToken", notNullValue())
+ .extract().response();
+ String firstCode = first.path("Quotas[0].QuotaCode");
+ String nextToken = first.path("NextToken");
+ assertEquals(CONCURRENT_BUILDS_QUOTA, firstCode);
+ assertNotNull(nextToken);
+
+ Response second = given()
+ .contentType(CONTENT_TYPE)
+ .header("X-Amz-Target", "ServiceQuotasV20190624.ListServiceQuotas")
+ .header("Authorization", AUTH_HEADER)
+ .body("{\"ServiceCode\":\"codebuild\",\"NextToken\":\"" + nextToken + "\"}")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Quotas.size()", equalTo(3))
+ .extract().response();
+ List<String> remainingCodes = second.path("Quotas.QuotaCode");
+ assertEquals(3, remainingCodes.size());
+ assertNull(second.path("NextToken"));
+ }
+
+ @Test
+ void listServiceQuotas_invalidNextToken_returnsInvalidPaginationToken() {
+ given()
+ .contentType(CONTENT_TYPE)
+ .header("X-Amz-Target", "ServiceQuotasV20190624.ListServiceQuotas")
+ .header("Authorization", AUTH_HEADER)
+ .body("{\"ServiceCode\":\"codebuild\",\"NextToken\":\"not_a_token!\"}")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("InvalidPaginationTokenException"));
+ }
+
+ @Test
+ void getServiceQuota_returnsConcurrentlyRunningBuilds() {
+ given()
+ .contentType(CONTENT_TYPE)
+ .header("X-Amz-Target", "ServiceQuotasV20190624.GetServiceQuota")
+ .header("Authorization", AUTH_HEADER)
+ .body("{\"ServiceCode\":\"codebuild\",\"QuotaCode\":\"" + CONCURRENT_BUILDS_QUOTA + "\"}")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Quota.QuotaCode", equalTo(CONCURRENT_BUILDS_QUOTA))
+ .body("Quota.QuotaName", equalTo("Concurrently running builds"))
+ .body("Quota.Value", greaterThanOrEqualTo(60.0f))
+ .body("Quota.Adjustable", equalTo(true))
+ .body("Quota.GlobalQuota", equalTo(false));
+ }
+
+ @Test
+ void getServiceQuota_unknownQuotaCode_returnsNoSuchResource() {
+ given()
+ .contentType(CONTENT_TYPE)
+ .header("X-Amz-Target", "ServiceQuotasV20190624.GetServiceQuota")
+ .header("Authorization", AUTH_HEADER)
+ .body("{\"ServiceCode\":\"codebuild\",\"QuotaCode\":\"L-DOESNOTEX\"}")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("NoSuchResourceException"));
+ }
+
+ @Test
+ void getAwsDefaultServiceQuota_matchesAppliedQuota() {
+ given()
+ .contentType(CONTENT_TYPE)
+ .header("X-Amz-Target", "ServiceQuotasV20190624.GetAWSDefaultServiceQuota")
+ .header("Authorization", AUTH_HEADER)
+ .body("{\"ServiceCode\":\"codebuild\",\"QuotaCode\":\"" + CONCURRENT_BUILDS_QUOTA + "\"}")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Quota.QuotaCode", equalTo(CONCURRENT_BUILDS_QUOTA))
+ .body("Quota.QuotaName", equalTo("Concurrently running builds"));
+ }
+
+ @Test
+ void listAwsDefaultServiceQuotas_matchesAppliedQuotas() {
+ Response applied = given()
+ .contentType(CONTENT_TYPE)
+ .header("X-Amz-Target", "ServiceQuotasV20190624.ListServiceQuotas")
+ .header("Authorization", AUTH_HEADER)
+ .body("{\"ServiceCode\":\"lambda\"}")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().response();
+
+ Response defaults = given()
+ .contentType(CONTENT_TYPE)
+ .header("X-Amz-Target", "ServiceQuotasV20190624.ListAWSDefaultServiceQuotas")
+ .header("Authorization", AUTH_HEADER)
+ .body("{\"ServiceCode\":\"lambda\"}")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().response();
+
+ List<String> appliedCodes = applied.path("Quotas.QuotaCode");
+ List<String> defaultCodes = defaults.path("Quotas.QuotaCode");
+ assertEquals(appliedCodes, defaultCodes);
+ assertEquals("L-B99A9384", appliedCodes.getFirst());
+ }
+
+ @Test
+ void unknownAction_returnsUnknownOperation() {
+ // Deliberately a name AWS will never define. This test previously used
+ // RequestServiceQuotaIncrease, which then became supported and silently
+ // inverted the test's premise. A synthetic name keeps the assertion honest
+ // no matter which real operations get implemented later.
+ given()
+ .contentType(CONTENT_TYPE)
+ .header("X-Amz-Target", "ServiceQuotasV20190624.ThisOperationDoesNotExist")
+ .header("Authorization", AUTH_HEADER)
+ .body("{}")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("UnknownOperationException"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasServiceTest.java
new file mode 100644
index 0000000000..80d9dccee7
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasServiceTest.java
@@ -0,0 +1,82 @@
+package io.github.hectorvent.floci.services.servicequotas;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class ServiceQuotasServiceTest {
+
+ private final ServiceQuotasService service = new ServiceQuotasService(new ObjectMapper());
+
+ @Test
+ void syntheticQuotaCodesAreStableAndWellFormed() {
+ String code = ServiceQuotasService.syntheticQuotaCode("widgetfactory", "Resources per Region");
+ assertEquals(code, ServiceQuotasService.syntheticQuotaCode("widgetfactory", "Resources per Region"));
+ assertTrue(code.matches("L-[0-9A-F]{8}"), code);
+ }
+
+ @Test
+ void everyListedQuotaResolvesThroughGetServiceQuota() {
+ for (String serviceCode : List.of("codebuild", "lambda", "widgetfactory")) {
+ for (ServiceQuotasService.QuotaDefinition quota : service.quotasFor(serviceCode)) {
+ ObjectNode response = service.getServiceQuota(
+ serviceCode, quota.quotaCode(), "us-east-1", "000000000000");
+ assertEquals(quota.quotaCode(), response.path("Quota").path("QuotaCode").asText());
+ assertTrue(response.path("Quota").path("Value").asDouble() >= 60.0);
+ }
+ }
+ }
+
+ @Test
+ void codebuildIncludesConcurrentlyRunningBuilds() {
+ List<String> codes = service.quotasFor("codebuild").stream()
+ .map(ServiceQuotasService.QuotaDefinition::quotaCode)
+ .toList();
+ assertTrue(codes.contains("L-2DC20C30"), codes.toString());
+ }
+
+ @Test
+ void getServiceQuota_unknownCode_throwsNoSuchResource() {
+ AwsException e = assertThrows(AwsException.class,
+ () -> service.getServiceQuota("codebuild", "L-DOESNOTEX", "us-east-1", "000000000000"));
+ assertEquals("NoSuchResourceException", e.getErrorCode());
+ }
+
+ /**
+ * Unknown-but-well-formed service codes deliberately generate a quota catalog, so a code that
+ * cannot name a service at all has to be rejected up front — otherwise "!!!" comes back with
+ * three invented quotas instead of an error. The model constrains ServiceCode to at most 63
+ * characters matching {@code [a-zA-Z][a-zA-Z0-9-]{1,63}}.
+ */
+ @Test
+ void malformedServiceCodeIsRejected() {
+ for (String bad : List.of("!!!", "1codebuild", "-codebuild", "code build", "c", "a".repeat(64))) {
+ AwsException listing = assertThrows(AwsException.class,
+ () -> service.listServiceQuotas(bad, null, null, null, "us-east-1", "000000000000"),
+ "expected ListServiceQuotas to reject " + bad);
+ assertEquals("IllegalArgumentException", listing.getErrorCode(), bad);
+ assertEquals(400, listing.getHttpStatus(), bad);
+
+ AwsException get = assertThrows(AwsException.class,
+ () -> service.getServiceQuota(bad, "L-2DC20C30", "us-east-1", "000000000000"),
+ "expected GetServiceQuota to reject " + bad);
+ assertEquals("IllegalArgumentException", get.getErrorCode(), bad);
+ }
+ }
+
+ @Test
+ void wellFormedServiceCodesAreStillAccepted() {
+ // Including an unknown-but-valid code: generating a catalog for those is deliberate.
+ for (String good : List.of("codebuild", "widgetfactory", "elasticloadbalancing", "AWS-Thing", "ec")) {
+ assertTrue(service.listServiceQuotas(good, null, null, null, "us-east-1", "000000000000")
+ .withArray("Quotas").size() > 0, good);
+ }
+ }
+}
diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml
index 509295b21a..f6fe88402d 100644
--- a/src/test/resources/application.yml
+++ b/src/test/resources/application.yml
@@ -359,3 +359,7 @@ floci:
enabled: true
bedrock-agent-core-control:
enabled: true
+ servicequotas:
+ enabled: true
+ ram:
+ enabled: true
diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml
index 6f38a046cc..3531e3b8f1 100644
--- a/tools/docs/services.yaml
+++ b/tools/docs/services.yaml
@@ -108,6 +108,10 @@ services:
doc: docs/services/neptune.md
sources:
- { path: src/main/java/io/github/hectorvent/floci/services/neptune/NeptuneQueryHandler.java, mode: switch }
+ - service: ram
+ doc: docs/services/ram.md
+ sources:
+ - { path: src/main/java/io/github/hectorvent/floci/services/ram/RamController.java, mode: rest }
- service: rds
doc: docs/services/rds.md
sources:
@@ -117,6 +121,10 @@ services:
doc: docs/services/secrets-manager.md
sources:
- { path: src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerJsonHandler.java, mode: switch }
+ - service: servicequotas
+ doc: docs/services/servicequotas.md
+ sources:
+ - { path: src/main/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasJsonHandler.java, mode: switch }
- service: sqs
doc: docs/services/sqs.md
sources: