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:
Sam Fakhreddine authored and GitHub committed 2026-08-26 21:04:30 -04:00
1 parent 94795dd67b
commit f912c3b717
28 files changed
+2810 -8

No files matched your search

@@ -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));
}
}
@@ -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));
}
}
@@ -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"));
}
}
}
@@ -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"));
}
}
}
@@ -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"));
}
}
@@ -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"));
}
}
@@ -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);
}
}
}