mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(servicequotas,ram): add Service Quotas and AWS RAM resource sharing (#2579)
* feat(servicequotas,ram): add Service Quotas and RAM sharing stub
Two Landing Zone Accelerator pipeline prerequisites:
- servicequotas: ListServiceQuotas/GetServiceQuota (+ AWS-default
variants) over JSON 1.1 with curated real quota codes for codebuild
and lambda, deterministic generated quotas for other services, and
offset-token pagination
- ram: EnableSharingWithAwsOrganization returning {returnValue: true}
* feat(ram): model resource shares with the reads LZA's TGW share flow needs
RamController previously registered only /enablesharingwithawsorganization;
every other restJson1 RAM path fell through to S3's /{bucket} template route
and returned an XML error the LZA Lambdas' JSON parser choked on
(SyntaxError: Unexpected token '<'). Adds CreateResourceShare,
GetResourceShares (SELF vs OTHER-ACCOUNTS visibility incl. org/OU
principals), GetResourceShareInvitations (always empty — organization
sharing auto-accepts, matching real AWS), and ListResources with RAM
resource-type derivation.
* fix(ram): show every non-owned share to OTHER-ACCOUNTS callers
Launched-container credentials resolve to the emulator default account,
so LZA's Custom::GetResourceShare Lambda never matches an account-ID
principal check for the account it actually runs in. Principal-based
visibility hid IPAM pool shares from the accepting NetworkVpcStack while
org-ARN shares (TGW) passed, failing Network_VPCs. The Lambda filters
client-side by owningAccountId + name, so returning all non-owned shares
is safe.
* feat(servicequotas): add RequestServiceQuotaIncrease
Persists the requested increase and returns a RequestedServiceQuotaChange
the subsequent Get/List operations can read back. Limitations documented in
docs/services/servicequotas.md.
* fix(config): restore EmrServerless config body lost in rebase
The rebase onto upstream/main collided where both upstream and this branch
declare a new service config interface sharing a trailing body; the
EmrServerless interface was left open, so the file did not parse.
* fix(ram): persist resource shares
* feat(ram): add principal associations and resource-share lifecycle
* fix(test): conform RAM storage test doubles to upstream StorageFactory API
e9826026 introduced SharedStorageFactory overriding StorageFactory.create with
the pre-upstream return type StorageBackend<String,V>; upstream now returns
AccountAwareStorageBackend<V>. Matches the template used by upstream's own
CodeBuildServicePersistenceTest.
* fix(ram): restrict resource-share mutations to the owning account
Every mutating RAM operation resolved the share ARN with a global
all-accounts scan, so any caller holding an ARN could rename, retag,
associate resources into, or delete another account's resource share.
Thread the caller's account into the mutation paths and resolve the
share only within it; a non-owner now gets the same
UnknownResourceException an unknown ARN gets, matching AWS, which
resolves share ARNs inside the caller's account. Read visibility under
OTHER-ACCOUNTS is unchanged.
* fix(ram): return 400 SerializationException for a malformed request body
An unparseable body left readTree throwing UncheckedIOException, which
escaped the controller and surfaced as a 500 InternalFailure. Reject it
with the modeled restJson1 client error instead.
* fix(config): restore the bedrock-agent-core-control enabled flag
A rebase left the key with a null body in both the main and test
application.yml, silently dropping the service's enabled flag.
* docs(servicequotas): fix the docs path in the consumer test javadoc
* docs: correct the service count and the Service Quotas and RAM matrix rows
docs/index.md still claimed 75 services and listed RAM under JSON 1.1;
the canonical count in docs/services/index.md is 78 and RAM speaks
restJson1. Bring the Service Quotas row up to its five handled actions
and the RAM row up to its twelve REST operations.
* docs(tooling): acknowledge the RAM controller in the docs registry
RAM's action table is hand-written and carries a method-and-path column
the generator does not emit, so register it as a deferred handler rather
than a rest-mode source.
* test(ram): cover owner mutation over HTTP and pin the non-owner error message
The ownership checks were asserted only against the service; nothing
exercised the caller account the controller now threads through, so a
mismatch between the identity stamped at create time and the one
resolved at delete time would have gone unnoticed. Select the existing
SELF assertion by share name, since the store is shared across the
class.
* docs(ram): generate the action table from the controller
The RAM table was hand-written and only acknowledged in the docs
registry, so the drift sentinel could never fire on it. Fold the method
and path into each description the way the FIS REST controller's doc
does, add the generator markers, and register the controller as a
rest-mode source. Also record that mutations are owner-only.
* fix(ram): enforce the modeled resourceOwner enum on the share read paths
GetResourceShares, ListPrincipals and ListResources all read resourceOwner and
fed it to a two-way visibility fork: "SELF" meant owned shares, and literally
anything else meant OTHER-ACCOUNTS. The model enumerates exactly SELF and
OTHER-ACCOUNTS, so a caller who sent "self" or "OTHER_ACCOUNTS" was silently
handed the inverse of what they asked for rather than the InvalidParameterException
AWS returns — an error all three operations list.
Validated at the three entry points rather than inside the per-share visibility
check, so the rejection does not depend on the store being non-empty.
* test(ram): cover the resourceOwner enum rejection on the HTTP path
The service-level test proved the check; this pins the wire behaviour LZA
actually exercises. RamController substitutes "SELF" via asText("SELF") only for
an absent or null resourceOwner, so a present-but-unmodelled value — including a
non-string that Jackson coerces — must still reach the service and surface as a
400 InvalidParameterException on all three read routes. The absent case is
asserted to still return 200, so the default is not silently changed.
* fix(ram): stop exposing the contents of a deleted resource share
ListResources and ListPrincipals reported a deleted share's resources
as AVAILABLE to non-owning consumers. Both now skip DELETED shares,
while GetResourceShares keeps returning the share with DELETED status,
matching the retention window real RAM applies.
* fix(ram): reject a malformed GetResourceShareInvitations body
The endpoint ignores its body semantically, but malformed JSON is a
client error: it now goes through readTree and answers the modeled 400
SerializationException instead of 200 with an empty list.
* fix(ram): reject mutations on DELETED resource shares
A deleted share stays readable via GetResourceShares for the retention
window, but real RAM treats it as terminal: update, associate,
disassociate, tag, untag, and a second delete all raise
UnknownResourceException. findOwnedShare now filters DELETED so every
mutation path resolves a deleted share the same as an unknown ARN.
* fix(ram): apply the GetResourceShares filters and advance lastUpdatedTime
Four response-fidelity gaps from the maintainer review, interleaved in
the same two files:
GetResourceShares read only resourceOwner, so name, resourceShareArns
and resourceShareStatus were silently dropped and a caller narrowing by
share name got every visible share back. All three are applied now, and
an unmodelled resourceShareStatus is rejected with
InvalidParameterException the way resourceOwner already is.
lastUpdatedTime never advanced: ResourceShare had no such field and
creationTime was echoed in its place, on the share node, on the
association rows, and on ListPrincipals. The field now exists and is
stamped in putForOwner, the single seam every create and mutation
already passes through. State written before the field existed reads
back with creationTime, which is correct for a share never mutated
since.
Shares also report the modeled featureSet (STANDARD — floci has no path
to produce a policy-derived share), and DeleteResourceShare echoes the
clientToken the caller sent, both of which the model carries.
* docs(ram): record the filter support and the unrouted-operation behavior
* fix(ram): require resourceOwner on the share read paths
GetResourceShares, ListPrincipals and ListResources all substituted
SELF for a missing resourceOwner, which the model marks required. That
answered a question the caller never asked, and answered it with the
caller's own shares rather than an error. All three now pass a missing
or null value to the validator that already rejected unmodelled ones,
so it surfaces as InvalidParameterException.
* docs(ram): name GetResourceShareAssociations in the fall-through note
Per review, the unrouted-operation note is more useful if it names the
operation Terraform's association resources read on every refresh, and
says the symptom is an S3 NoSuchBucket XML body rather than a
credentials problem.
* fix(ram): reject trailing tokens after a valid JSON body
Jackson's default readTree stops at the first complete value, so a body
like "{} not-json" parsed as an empty object and the request executed
instead of returning the modeled 400 SerializationException. Read with
FAIL_ON_TRAILING_TOKENS, the convention the JSON 1.0/1.1 controllers,
FIS, Signin and EventBridge already follow.
* fix(servicequotas): validate the ServiceCode shape
ServiceCode was only checked for emptiness. Because an unknown code
deliberately generates a quota catalog, that meant a caller typoing
"!!!" got three invented quotas back instead of an error. Validate
against the modeled [a-zA-Z][a-zA-Z0-9-]{1,63} and 63-character cap;
unknown-but-well-formed codes keep generating as before.
This commit is contained in:
1 parent
94795dd67b
commit
f912c3b717
28 files changed
+2810
-8
No files matched your search
@@ -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();
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
}
|
||||
+82
@@ -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;
|
||||
}
|
||||
}
|
||||
+253
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user