diff --git a/.github/ci/compat-timing-report.py b/.github/ci/compat-timing-report.py new file mode 100755 index 0000000000..068fa8a762 --- /dev/null +++ b/.github/ci/compat-timing-report.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +"""Print per-class timings from junit XMLs, slowest first. + +Usage: compat-timing-report.py +Also appends the table to GITHUB_STEP_SUMMARY when set. Never fails the job: +bad or absent XMLs produce an empty report, not an error. +""" +import glob +import os +import sys +import xml.etree.ElementTree as ET + +def main(): + d = sys.argv[1] if len(sys.argv) > 1 else 'test-results' + rows = [] + for f in glob.glob(os.path.join(d, '*.xml')): + try: + root = ET.parse(f).getroot() + except (ET.ParseError, OSError) as exc: + print(f'warning: skipping unreadable JUnit XML {f}: {exc}', file=sys.stderr) + continue + suites = root.iter('testsuite') if root.tag != 'testsuite' else [root] + for ts in suites: + try: + rows.append((float(ts.get('time') or 0), int(ts.get('tests') or 0), + ts.get('name') or os.path.basename(f))) + except ValueError as exc: + print(f'warning: skipping suite with non-numeric attributes in {f}: {exc}', + file=sys.stderr) + rows.sort(reverse=True) + total_t = sum(r[0] for r in rows) + total_n = sum(r[1] for r in rows) + lines = [f'== {len(rows)} suites, {total_n} tests, {total_t / 60:.1f} min total test time', + '== slowest 25 classes:'] + lines += [f'{t:8.1f}s {n:5d} tests {name}' for t, n, name in rows[:25]] + report = '\n'.join(lines) + print(report) + summary = os.environ.get('GITHUB_STEP_SUMMARY') + if summary: + with open(summary, 'a') as fh: + fh.write('```\n' + report + '\n```\n') + +if __name__ == '__main__': + main() diff --git a/.github/workflows/compatibility.yml b/.github/workflows/compatibility.yml index f6941934ee..f07a8e7417 100644 --- a/.github/workflows/compatibility.yml +++ b/.github/workflows/compatibility.yml @@ -10,6 +10,7 @@ on: - 'docker/entrypoint.sh' - 'docker/localstack-parity.sh' - 'compatibility-tests/**' + - '.github/ci/compat-timing-report.py' - '.github/workflows/compatibility.yml' permissions: @@ -179,7 +180,9 @@ jobs: - name: Checkout repository uses: actions/checkout@v7.0.1 with: - sparse-checkout: compatibility-tests + sparse-checkout: | + compatibility-tests + .github/ci - uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0 @@ -230,6 +233,25 @@ jobs: with: paths: test-results/*.xml + # The test body inside the container runs its build tool quietly, so the + # job log carries no per-class timings and the slow legs (sdk-test-java, + # ~10 min) are a black box. Surface the timings from the junit XMLs the + # suites already export, and upload the raw XMLs so the numbers are + # machine-readable across runs. + - name: Report slowest test classes + if: always() && steps.tests.outcome != 'skipped' + # Measurement-only: a reporting bug must never fail an otherwise-green leg. + continue-on-error: true + run: python3 .github/ci/compat-timing-report.py test-results + + - name: Upload test results + if: always() && steps.tests.outcome != 'skipped' + uses: actions/upload-artifact@v7 + with: + name: compat-results-${{ matrix.test }} + path: test-results/ + if-no-files-found: warn + - name: Dump floci logs if: failure() run: docker logs floci diff --git a/README.md b/README.md index b596d7a8b7..bc6fe97e92 100644 --- a/README.md +++ b/README.md @@ -178,7 +178,7 @@ LocalStack's community edition [sunset in March 2026](https://blog.localstack.cl | CodeBuild | Real Docker execution | No | | Native binary | ~40 MB | No | -**76 AWS services. Broad coverage. Free forever.** +**78 AWS services. Broad coverage. Free forever.** ## Architecture Overview @@ -226,7 +226,7 @@ Floci supports local emulation for application services, data services, eventing | Data, analytics, and AI | Athena, Glue, EMR, Firehose, Managed Service for Apache Flink, OpenSearch, S3 Tables, S3 Vectors, Textract, Transcribe, Bedrock Runtime, Bedrock AgentCore | | Databases and caching | RDS, RDS Data API, Neptune, DocumentDB, MemoryDB, ElastiCache | | Messaging and transfer | SES, Kinesis, MSK, Amazon MQ, Transfer Family, IoT Core | -| Security and governance | WAF v2, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations | +| Security and governance | AWS RAM, Service Quotas, WAF v2, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations | | Cost and billing | Pricing, Cost Explorer, Cost and Usage Reports, BCM Data Exports | | Resilience, backup, and config | AWS FIS, AWS Backup, AWS Config, AppConfig, AppConfigData, CloudFormation, Cloud Control API | @@ -291,6 +291,8 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/ | CodeBuild | In-process with real Docker | Real buildspec execution, CloudWatch logs, S3 artifacts | | CodeDeploy | In-process with Lambda traffic shifting | Deployment groups, configs, lifecycle hooks, auto-rollback | | CodePipeline | In-process orchestration | Pipelines, executions, S3 artifacts, approvals, local providers, custom workers | +| Service Quotas | In-process | Generated quota catalog with generous static values; real quota codes for CodeBuild and Lambda concurrency | +| AWS RAM | In-process | EnableSharingWithAwsOrganization opt-in | | AWS Batch | In-process | Compute environments, job queues, job definitions, job submission and lifecycle | | Auto Scaling | In-process with reconciler | Launch configs, ASGs, desired capacity reconciliation, lifecycle hooks | | Application Auto Scaling | In-process | Scalable targets, target-tracking and step scaling policies, CloudWatch alarm creation, tagging (policies are stored but inert) | diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesTagResourceTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesTagResourceTest.java index e068d88607..9d4c610b8c 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesTagResourceTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesTagResourceTest.java @@ -10,12 +10,20 @@ import org.junit.jupiter.api.TestMethodOrder; import software.amazon.awssdk.services.sesv2.SesV2Client; import software.amazon.awssdk.services.sesv2.model.CreateConfigurationSetRequest; +import software.amazon.awssdk.services.sesv2.model.CreateContactListRequest; +import software.amazon.awssdk.services.sesv2.model.CreateCustomVerificationEmailTemplateRequest; +import software.amazon.awssdk.services.sesv2.model.CreateDedicatedIpPoolRequest; import software.amazon.awssdk.services.sesv2.model.CreateEmailIdentityRequest; import software.amazon.awssdk.services.sesv2.model.CreateEmailTemplateRequest; import software.amazon.awssdk.services.sesv2.model.DeleteConfigurationSetRequest; +import software.amazon.awssdk.services.sesv2.model.DeleteContactListRequest; +import software.amazon.awssdk.services.sesv2.model.DeleteCustomVerificationEmailTemplateRequest; +import software.amazon.awssdk.services.sesv2.model.DeleteDedicatedIpPoolRequest; import software.amazon.awssdk.services.sesv2.model.DeleteEmailIdentityRequest; import software.amazon.awssdk.services.sesv2.model.DeleteEmailTemplateRequest; import software.amazon.awssdk.services.sesv2.model.EmailTemplateContent; +import software.amazon.awssdk.services.sesv2.model.GetContactListRequest; +import software.amazon.awssdk.services.sesv2.model.GetContactListResponse; import software.amazon.awssdk.services.sesv2.model.GetEmailIdentityRequest; import software.amazon.awssdk.services.sesv2.model.GetEmailIdentityResponse; import software.amazon.awssdk.services.sesv2.model.GetEmailTemplateRequest; @@ -43,6 +51,13 @@ class SesTagResourceTest { private static String templateArn; private static String identityValue; private static String identityArn; + private static String contactListName; + private static String contactListArn; + private static String cvetFrom; + private static String cvetName; + private static String cvetArn; + private static String poolName; + private static String poolArn; @BeforeAll static void setup() { @@ -54,6 +69,13 @@ class SesTagResourceTest { templateArn = "arn:aws:ses:us-east-1:000000000000:template/" + templateName; identityValue = "sdk-tag-id-" + suffix + "@example.com"; identityArn = "arn:aws:ses:us-east-1:000000000000:identity/" + identityValue; + contactListName = "sdk-tag-cl-" + suffix; + contactListArn = "arn:aws:ses:us-east-1:000000000000:contact-list/" + contactListName; + cvetFrom = "sdk-tag-cvet-sender-" + suffix + "@example.com"; + cvetName = "sdk-tag-cvet-" + suffix; + cvetArn = "arn:aws:ses:us-east-1:000000000000:custom-verification-email-template/" + cvetName; + poolName = "sdk-tag-pool-" + suffix; + poolArn = "arn:aws:ses:us-east-1:000000000000:dedicated-ip-pool/" + poolName; sesV2.createConfigurationSet(CreateConfigurationSetRequest.builder() .configurationSetName(configSetName) @@ -75,6 +97,32 @@ class SesTagResourceTest { sesV2.deleteEmailIdentity(DeleteEmailIdentityRequest.builder() .emailIdentity(identityValue).build()); } catch (Exception ignored) {} + // Freeing the one-contact-list-per-account slot matters for later test classes; the + // others are best-effort tidiness. Log failures so a real problem is diagnosable. + try { + sesV2.deleteContactList(DeleteContactListRequest.builder() + .contactListName(contactListName).build()); + } catch (Exception e) { + System.out.println("Cleanup: failed to delete contact list " + contactListName + ": " + e.getMessage()); + } + try { + sesV2.deleteCustomVerificationEmailTemplate(DeleteCustomVerificationEmailTemplateRequest.builder() + .templateName(cvetName).build()); + } catch (Exception e) { + System.out.println("Cleanup: failed to delete template " + cvetName + ": " + e.getMessage()); + } + try { + sesV2.deleteEmailIdentity(DeleteEmailIdentityRequest.builder() + .emailIdentity(cvetFrom).build()); + } catch (Exception e) { + System.out.println("Cleanup: failed to delete identity " + cvetFrom + ": " + e.getMessage()); + } + try { + sesV2.deleteDedicatedIpPool(DeleteDedicatedIpPoolRequest.builder() + .poolName(poolName).build()); + } catch (Exception e) { + System.out.println("Cleanup: failed to delete pool " + poolName + ": " + e.getMessage()); + } sesV2.close(); } } @@ -245,4 +293,114 @@ class SesTagResourceTest { assertThat(afterUntag.tags()).hasSize(1); assertThat(afterUntag.tags().get(0).key()).isEqualTo("owner"); } + + @Test + @Order(30) + void contactList_createWithTags_visibleViaListTagsAndGet() { + sesV2.createContactList(CreateContactListRequest.builder() + .contactListName(contactListName) + .tags( + Tag.builder().key("env").value("dev").build(), + Tag.builder().key("team").value("platform").build()) + .build()); + + ListTagsForResourceResponse listed = sesV2.listTagsForResource(ListTagsForResourceRequest.builder() + .resourceArn(contactListArn).build()); + assertThat(listed.tags()).hasSize(2); + + GetContactListResponse got = sesV2.getContactList(GetContactListRequest.builder() + .contactListName(contactListName).build()); + assertThat(got.tags()) + .extracting(Tag::key) + .containsExactlyInAnyOrder("env", "team"); + } + + @Test + @Order(31) + void contactList_tagAndUntag_lifecycle() { + sesV2.tagResource(TagResourceRequest.builder() + .resourceArn(contactListArn) + .tags(Tag.builder().key("owner").value("alice").build()) + .build()); + + ListTagsForResourceResponse afterTag = sesV2.listTagsForResource(ListTagsForResourceRequest.builder() + .resourceArn(contactListArn).build()); + assertThat(afterTag.tags()).hasSize(3); + + sesV2.untagResource(UntagResourceRequest.builder() + .resourceArn(contactListArn) + .tagKeys("env", "team") + .build()); + + ListTagsForResourceResponse afterUntag = sesV2.listTagsForResource(ListTagsForResourceRequest.builder() + .resourceArn(contactListArn).build()); + assertThat(afterUntag.tags()).hasSize(1); + assertThat(afterUntag.tags().get(0).key()).isEqualTo("owner"); + } + + @Test + @Order(40) + void customVerificationEmailTemplate_createWithTags_tagAndUntag_lifecycle() { + // CVET creation requires the From address to be a verified identity. The v2 create API + // accepts inline Tags; the update API has no Tags member. + sesV2.createEmailIdentity(CreateEmailIdentityRequest.builder().emailIdentity(cvetFrom).build()); + sesV2.createCustomVerificationEmailTemplate(CreateCustomVerificationEmailTemplateRequest.builder() + .templateName(cvetName) + .fromEmailAddress(cvetFrom) + .templateSubject("Verify") + .templateContent("verify") + .successRedirectionURL("https://example.com/ok") + .failureRedirectionURL("https://example.com/no") + .tags(Tag.builder().key("env").value("dev").build()) + .build()); + + ListTagsForResourceResponse initial = sesV2.listTagsForResource(ListTagsForResourceRequest.builder() + .resourceArn(cvetArn).build()); + assertThat(initial.tags()).hasSize(1); + assertThat(initial.tags().get(0).key()).isEqualTo("env"); + + sesV2.tagResource(TagResourceRequest.builder() + .resourceArn(cvetArn) + .tags(Tag.builder().key("owner").value("alice").build()) + .build()); + + sesV2.untagResource(UntagResourceRequest.builder() + .resourceArn(cvetArn) + .tagKeys("env") + .build()); + + ListTagsForResourceResponse afterUntag = sesV2.listTagsForResource(ListTagsForResourceRequest.builder() + .resourceArn(cvetArn).build()); + assertThat(afterUntag.tags()).hasSize(1); + assertThat(afterUntag.tags().get(0).key()).isEqualTo("owner"); + } + + @Test + @Order(50) + void dedicatedIpPool_createWithTags_tagAndUntag_lifecycle() { + sesV2.createDedicatedIpPool(CreateDedicatedIpPoolRequest.builder() + .poolName(poolName) + .tags(Tag.builder().key("env").value("dev").build()) + .build()); + + ListTagsForResourceResponse listed = sesV2.listTagsForResource(ListTagsForResourceRequest.builder() + .resourceArn(poolArn).build()); + assertThat(listed.tags()).hasSize(1); + assertThat(listed.tags().get(0).key()).isEqualTo("env"); + + sesV2.tagResource(TagResourceRequest.builder() + .resourceArn(poolArn) + .tags(Tag.builder().key("owner").value("alice").build()) + .build()); + + sesV2.untagResource(UntagResourceRequest.builder() + .resourceArn(poolArn) + .tagKeys("env") + .build()); + + ListTagsForResourceResponse afterUntag = sesV2.listTagsForResource(ListTagsForResourceRequest.builder() + .resourceArn(poolArn).build()); + assertThat(afterUntag.tags()).hasSize(1); + assertThat(afterUntag.tags().get(0).key()).isEqualTo("owner"); + } } diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.md index a3d94387c4..b41c122386 100644 --- a/docs/configuration/advanced/application-yml.md +++ b/docs/configuration/advanced/application-yml.md @@ -155,6 +155,13 @@ floci: enforcement-enabled: false # Set to true to enforce IAM policies on all requests seed-deployer-principal: false # Set to true to create a local floci-deployer admin principal + servicequotas: + enabled: true + + ram: + enabled: true + + elasticache: enabled: true proxy-base-port: 6379 diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index 2ff3c6e231..72bdf2cebb 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -457,6 +457,8 @@ These services spawn Docker containers. They require access to the Docker socket | `FLOCI_SERVICES_CODEBUILD_ENABLED` | `true` | Enable the CodeBuild service | | `FLOCI_SERVICES_CODEBUILD_DOCKER_NETWORK` | _(none)_ | Docker network for CodeBuild build containers | | `FLOCI_SERVICES_CODEDEPLOY_ENABLED` | `true` | Enable the CodeDeploy service | +| `FLOCI_SERVICES_SERVICEQUOTAS_ENABLED` | `true` | Enable the Service Quotas service | +| `FLOCI_SERVICES_RAM_ENABLED` | `true` | Enable the AWS RAM service | | `FLOCI_SERVICES_BACKUP_ENABLED` | `true` | Enable the AWS Backup service | | `FLOCI_SERVICES_BACKUP_JOB_COMPLETION_DELAY_SECONDS` | `3` | Simulated delay before backup jobs transition to `COMPLETED` | | `FLOCI_SERVICES_FIS_ENABLED` | `true` | Enable the AWS Fault Injection Service management API | diff --git a/docs/index.md b/docs/index.md index 816cad8925..9af7ce3b23 100644 --- a/docs/index.md +++ b/docs/index.md @@ -12,7 +12,7 @@ Floci is a fast, free, and open-source local AWS service emulator built for deve ## Supported Services -Floci emulates 73 AWS services. See the [Services Overview](services/index.md) for per-service operation counts, endpoints, and full protocol details. +Floci emulates 78 AWS services. See the [Services Overview](services/index.md) for per-service operation counts, endpoints, and full protocol details. | Service | Protocol | |---|---| @@ -80,6 +80,8 @@ Floci emulates 73 AWS services. See the [Services Overview](services/index.md) f | Cost and Usage Reports | JSON 1.1 | | BCM Data Exports | JSON 1.1 | | Transfer Family | JSON 1.1 | +| AWS RAM | REST JSON | +| Service Quotas | JSON 1.1 | ## Why Floci? @@ -115,7 +117,7 @@ docker compose up -d aws --endpoint-url http://localhost:4566 s3 mb s3://my-bucket ``` -All 73 AWS services are immediately available at `http://localhost:4566`. +All 78 AWS services are immediately available at `http://localhost:4566`. [Get started →](getting-started/quick-start.md){ .md-button .md-button--primary } [View services →](services/index.md){ .md-button } diff --git a/docs/services/index.md b/docs/services/index.md index 4db8d0f694..ca8e2ee15f 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -1,6 +1,6 @@ # Services Overview -Floci emulates 76 AWS services on a single port (`4566`). All services use the real AWS wire protocol, your existing AWS CLI commands and SDK clients work without modification. +Floci emulates 78 AWS services on a single port (`4566`). All services use the real AWS wire protocol, your existing AWS CLI commands and SDK clients work without modification. This page is the canonical reference for supported service and operation counts. Some services expose separate control-plane and data-plane rows below. Other docs (and the README) should link here rather than duplicating the table. @@ -85,6 +85,8 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [AWS Batch](batch.md) | `/v1/...` | REST JSON | 10 | | [CodeDeploy](codedeploy.md) | `POST /` + `X-Amz-Target: CodeDeploy_20141006.*` | JSON 1.1 | 30 | | [CodePipeline](codepipeline.md) | `POST /` + `X-Amz-Target: CodePipeline_20150709.*` | JSON 1.1 | 44 | +| [Service Quotas](servicequotas.md) | `POST /` + `X-Amz-Target: ServiceQuotasV20190624.*` | JSON 1.1 | 5 | +| [AWS RAM](ram.md) | `POST /{operationname}` (lowercase), `DELETE /deleteresourceshare` | REST JSON | 12 | | [Control Tower](controltower.md) | `/list-landingzones`, `/get-landingzone`, `/create-landingzone`, `/*-baseline*` | REST JSON | 15 | | [AWS Backup](backup.md) | `/backup-vaults/*`, `/backup/plans/*`, `/backup-jobs/*`, `/supported-resource-types` | REST JSON | 20 | | [AWS FIS](fis.md) | `/experimentTemplates/*`, `/experiments/*`, `/actions/*`, `/targetResourceTypes/*`, `/safetyLevers/*`, `/tags/*` | REST JSON | 26 | diff --git a/docs/services/lambda.md b/docs/services/lambda.md index 045612cb8f..754d0e2d8d 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -446,6 +446,44 @@ No extra configuration or `cap_add` is needed because Docker containers have `CAP_NET_BIND_SERVICE` in their default capability set, so Floci (running as a non-root user) can bind UDP/53 without any changes to your Compose file. +### VpcConfig, SnapStart and LoggingConfig + +All three round-trip through `CreateFunction`, `UpdateFunctionConfiguration`, +`GetFunctionConfiguration`, `GetFunction`, `ListFunctions` and `PublishVersion`. + +The response shapes are **not** the request shapes, and Floci follows the AWS model +rather than echoing the request back: + +| Field | Request shape | Response shape | Extra members Floci fills in | +|---|---|---|---| +| `VpcConfig` | `VpcConfig` | `VpcConfigResponse` | `VpcId`, resolved from the first subnet via EC2 | +| `SnapStart` | `SnapStart` | `SnapStartResponse` | `OptimizationStatus` — `On` only for a published version with `ApplyOn=PublishedVersions`, `Off` for `$LATEST` | +| `LoggingConfig` | `LoggingConfig` | `LoggingConfig` | — | + +`SnapStart` and `LoggingConfig` are always present in a response, as on AWS: an +unset function reads back `SnapStart={ApplyOn: None, OptimizationStatus: Off}` and +`LoggingConfig={LogFormat: Text, LogGroup: /aws/lambda/}`. With +`LogFormat=JSON`, `ApplicationLogLevel` and `SystemLogLevel` are also returned, +defaulting to `INFO`. Terraform treats these as `Computed` blocks, so a missing one +is a permanent diff rather than a cosmetic omission. + +`LoggingConfig` is replaced wholesale on update, not merged — an update naming only +`LogFormat` resets `LogGroup` to the default. + +`LogGroup` is validated against AWS's documented constraint: 1-512 characters matching +`[.\-_/#A-Za-z0-9]+`. `ApplicationLogLevel` and `SystemLogLevel` are accepted with any +`LogFormat` but are only ever stored — and therefore only ever returned — when the +resolved format is `JSON`; supplying them with `LogFormat=Text` is not an error, it is +simply a no-op, matching the fact that the response never surfaces them for Text. + +`VpcConfig` is omitted entirely while the function is not attached to a VPC. +Subnets that EC2 does not know about are still accepted and returned; only `VpcId` +is left off in that case. + +`RuntimeVersionConfig.RuntimeVersionArn` is returned for managed (non-image) +runtimes. Its value is derived from the runtime name, so it is stable across +restarts. + ### File system configs `FileSystemConfigs` accepts one EFS access point and mounts it under the diff --git a/docs/services/ram.md b/docs/services/ram.md new file mode 100644 index 0000000000..954b7ee499 --- /dev/null +++ b/docs/services/ram.md @@ -0,0 +1,86 @@ +# AWS RAM + +**Protocol:** REST JSON +**Endpoint:** `http://localhost:4566` +**Signing name:** `ram` + +Floci implements the AWS Resource Access Manager calls AWS Landing Zone Accelerator makes +while bootstrapping shared Transit Gateway attachments and other cross-account resources: +the organization-sharing opt-in, resource-share CRUD, association management, principal +listing, and tagging. Sharing is modeled as a flat in-memory store, not full RAM semantics — +see Current Scope below for what's simplified. + +## Supported Actions + + +| Action | Description | +| --- | --- | +| `EnableSharingWithAwsOrganization` | Enables resource sharing within the organization; returns `{"returnValue": true}`. Idempotent, no disable counterpart, matching real AWS (`POST /enablesharingwithawsorganization`) | +| `CreateResourceShare` | Creates a resource share with the given name, principals, and resource ARNs (`POST /createresourceshare`) | +| `GetResourceShares` | Lists resource shares visible to the caller, `SELF` owned or `OTHER-ACCOUNTS` shared in (`POST /getresourceshares`) | +| `DeleteResourceShare` | Marks a share `DELETED`, a soft delete matching real AWS's async-then-terminal status (`DELETE /deleteresourceshare`) | +| `UpdateResourceShare` | Renames a share and/or toggles `allowExternalPrincipals` (`POST /updateresourceshare`) | +| `AssociateResourceShare` | Adds resource ARNs and/or principals to an existing share (`POST /associateresourceshare`) | +| `DisassociateResourceShare` | Removes resource ARNs and/or principals from a share (`POST /disassociateresourceshare`) | +| `ListPrincipals` | Lists principals associated with visible shares (`POST /listprincipals`) | +| `TagResource` | Adds/overwrites tags on a resource share (`POST /tagresource`) | +| `UntagResource` | Removes tags by key from a resource share (`POST /untagresource`) | +| `GetResourceShareInvitations` | Always returns an empty list — organization sharing auto-accepts, so invitations never exist here (`POST /getresourceshareinvitations`) | +| `ListResources` | Lists shared resource ARNs, with the RAM resource type derived from the ARN, e.g. `ec2:TransitGateway` (`POST /listresources`) | + + +## Configuration + +| Environment variable | Default | Description | +| --- | --- | --- | +| `FLOCI_SERVICES_RAM_ENABLED` | `true` | Enables the service | + +## Example + +```bash +aws --endpoint-url http://localhost:4566 ram enable-sharing-with-aws-organization + +aws --endpoint-url http://localhost:4566 ram create-resource-share \ + --name my-share \ + --resource-arns arn:aws:ec2:us-east-1:000000000000:transit-gateway/tgw-0abc \ + --principals arn:aws:organizations::000000000000:ou/o-abc/ou-infra + +aws --endpoint-url http://localhost:4566 ram delete-resource-share \ + --resource-share-arn arn:aws:ram:us-east-1:000000000000:resource-share/... +``` + +## Current Scope + +- Visibility is simplified: `OTHER-ACCOUNTS` shows every non-owned share regardless of + principal targeting, since launched-container credentials all resolve to the same default + account and a principal-based check would hide shares from consumers that should see them. + LZA's `Custom::GetResourceShare` Lambda filters client-side by `owningAccountId` + `name` + anyway, so this doesn't affect that flow. +- Mutations are owner-only: a caller that is not the share's owning account gets + `UnknownResourceException`, the same error an unknown ARN gets, since AWS resolves a share + ARN within the caller's own account. Visibility above is unaffected. +- `resourceOwner` is required on `GetResourceShares`, `ListPrincipals` and `ListResources`: a + missing or unmodelled value is rejected with `InvalidParameterException` rather than defaulted + to `SELF`. +- `GetResourceShares` applies the `name`, `resourceShareArns` and `resourceShareStatus` filters; + `tagFilters`, `permissionArn`, `permissionVersion` and pagination (`nextToken`/`maxResults`) + are accepted but ignored — every matching share is returned in one page. +- Operations outside the table above are not routed. RAM's paths are matched literally, so an + unimplemented operation falls through to S3's `/{bucket}` route and comes back as an S3 + `NoSuchBucket` XML body where the SDK expects JSON — not a modeled `UnknownOperationException`. + If a client reports an XML parse error against a RAM call, that is the cause, not credentials. + `GetResourceShareAssociations` is the one most likely to be hit: Terraform's + `aws_ram_resource_association` and `aws_ram_principal_association` read it on every refresh. +- `AssociateResourceShare`/`DisassociateResourceShare` responses synthesize one + `resourceShareAssociation` row per requested ARN/principal rather than tracking real + per-association status transitions (e.g. no `ASSOCIATING`/`DISASSOCIATING` intermediate + state — everything completes synchronously). +- `TagResource`/`UntagResource` only support tagging by `resourceShareArn`; tagging an + individual shared resource via `resourceArn` is not modeled (RAM's `TagResource` accepts + either, but LZA only tags shares). +- Permission-related operations are not implemented: `CreatePermission`, + `AssociateResourceSharePermission`, `ListPermissions`, and the rest of the permission-version + family. Shares created here always use RAM's default managed permission implicitly — there + is no explicit permission model to associate or version. +- `AcceptResourceShareInvitation` / `RejectResourceShareInvitation` are not implemented — + moot under organization sharing, which never produces invitations to begin with. diff --git a/docs/services/servicequotas.md b/docs/services/servicequotas.md new file mode 100644 index 0000000000..37c7ef4d55 --- /dev/null +++ b/docs/services/servicequotas.md @@ -0,0 +1,67 @@ +# Service Quotas + +**Protocol:** JSON 1.1 (`X-Amz-Target: ServiceQuotasV20190624.*`) +**Endpoint:** `POST http://localhost:4566/` +**Signing name:** `servicequotas` + +Floci answers Service Quotas lookups from a generated in-memory catalog. Every service code +resolves to a quota list: a curated set with real AWS quota codes where tooling depends on +them — CodeBuild's `L-2DC20C30` ("Concurrently running builds") and Lambda's `L-B99A9384` +("Concurrent executions") — plus a deterministic generic set for any other service code. All +values are deliberately generous (5000) so local pipelines that gate on quota headroom, such +as AWS Landing Zone Accelerator, never stall on a limit the emulator does not enforce. + +Applied quotas and AWS default quotas return the same data, and quota values are static. +`RequestServiceQuotaIncrease` is accepted and validated but does not change any quota value — +see Limitations. + +## Supported Actions + + +| Action | Description | +| --- | --- | +| `ListServiceQuotas` | Lists the quotas for a service code; generated quotas for unknown codes | +| `GetServiceQuota` | Returns one quota by service and quota code, else `NoSuchResourceException` | +| `GetAWSDefaultServiceQuota` | Same as GetServiceQuota; defaults equal applied values | +| `ListAWSDefaultServiceQuotas` | Same as ListServiceQuotas; defaults equal applied values | +| `RequestServiceQuotaIncrease` | Validates and echoes an increase request as `PENDING`; not persisted, quota unchanged | + + +## Limitations + +- **Quota increase requests are not persisted.** `RequestServiceQuotaIncrease` validates its + input, resolves the quota, and returns a well-formed `RequestedQuota`, but keeps no state. + The request is observable only in the response that creates it. +- **`Status` is always `PENDING` and never advances.** Nothing processes requests, so no + request ever reaches `APPROVED`, `CASE_OPENED`, or `DENIED`. `PENDING` is what real AWS + returns on creation, so a caller that only reads the creation response sees faithful data; + a caller that polls for completion will wait forever. +- **Unknown service codes generate a quota catalog rather than failing.** This is deliberate, so + the code has to be well-formed to be trusted: `ServiceCode` is validated against the modeled + `[a-zA-Z][a-zA-Z0-9-]{1,63}` (max 63 characters) and a malformed one is rejected with + `IllegalArgumentException` instead of returning invented quotas. +- **A requested increase does not change the quota.** `GetServiceQuota` continues to return + the catalog value after a successful increase request. Quota values remain static by design + so pipelines never stall on an unenforced limit. +- `GetRequestedServiceQuotaChange` and `ListRequestedServiceQuotaChangeHistory` are not + implemented — there is no request store for them to read. +- `CaseId` is never returned; no support case is opened. `SupportCaseAllowed` in the request is + accepted and ignored, as the emulator has no case-opening path either way. +- The quota-increase template operations (`PutServiceQuotaIncreaseRequestIntoTemplate` and + related) are not implemented. + +## Configuration + +| Environment variable | Default | Description | +| --- | --- | --- | +| `FLOCI_SERVICES_SERVICEQUOTAS_ENABLED` | `true` | Enables the service | + +## Example + +```bash +aws --endpoint-url http://localhost:4566 service-quotas list-service-quotas \ + --service-code codebuild + +aws --endpoint-url http://localhost:4566 service-quotas get-service-quota \ + --service-code codebuild --quota-code L-2DC20C30 +``` diff --git a/docs/services/ses.md b/docs/services/ses.md index 77cdf8a424..f792ee3c4d 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -288,7 +288,9 @@ Suppressed recipients are filtered out of the SMTP relay step (non-suppressed re For a **single-recipient** list-managed send, Floci injects a functional unsubscribe link (matching AWS, which only does this for one recipient): the `{{amazonSESUnsubscribeUrl}}` body placeholder is replaced (up to twice) and a `List-Unsubscribe` header plus `List-Unsubscribe-Post: List-Unsubscribe=One-Click` are added (applied to the relayed message and shown under `Headers` at `GET /_aws/ses`; a caller-supplied `List-Unsubscribe` is overridden, matching AWS). The `{{amazonSESUnsubscribeUrl}}` placeholder is also preserved through template rendering so a templated body can carry it. On a send without `ListManagementOptions`, the placeholder is left in the body verbatim (neither replaced nor stripped) — this specific behavior is Floci's choice and is not verified against real SES. Unlike AWS's opaque hosted URL, the link points at Floci's own `/_aws/ses/unsubscribe?region=…&contactList=…&address=…&topic=…` endpoint. `GET` (a browser click) only renders a confirmation page and changes nothing — matching AWS's landing-page behavior and avoiding the RFC 8058 hazard where a client or bot that prefetches the link would silently unsubscribe the contact — while `POST` (the one-click request the confirmation form submits) applies the opt-out (a topic → `OPT_OUT` for that topic; no topic → `UnsubscribeAll`), auto-creating the contact if needed. Two deviations from AWS here: the link is carried as readable query parameters rather than an opaque token (so, like the rest of Floci, the endpoint is unauthenticated and only safe on a trusted dev/test network — a `POST` can opt out any contact), and only the one-click URL entry is emitted — its scheme follows Floci's base URL (`http` unless TLS is enabled) — whereas AWS also includes a `mailto:` entry, which Floci can't service since it has no inbound mail endpoint. Raw (MIME) sends do not get link injection yet. -Tag operations support these ARN forms: `arn:aws:ses:::configuration-set/`, `arn:aws:ses:::template/`, and `arn:aws:ses:::identity/`. Tags supplied to `CreateConfigurationSet`, `CreateEmailTemplate`, and `CreateEmailIdentity` are reachable through `ListTagsForResource`; `UpdateEmailTemplate` does not modify tags. Other resource types return `NotFoundException`. A non-string tag `Key` or `Value` (number, boolean, object, array), or a `Tags` element that is not an object, is rejected with `SerializationException` rather than being coerced, matching AWS's restJson1 deserializer. +Tag operations accept `arn:aws:ses:::/` ARNs for six resource types — `configuration-set`, `template`, `identity`, `contact-list`, `custom-verification-email-template`, and `dedicated-ip-pool`; other types return `NotFoundException`. Tags supplied to `CreateConfigurationSet`, `CreateEmailTemplate`, `CreateEmailIdentity`, `CreateContactList`, `CreateCustomVerificationEmailTemplate`, and `CreateDedicatedIpPool` are reachable through `ListTagsForResource`; `UpdateEmailTemplate` and `UpdateCustomVerificationEmailTemplate` do not modify tags. + +ARN handling is uniform across the six types (probe-confirmed against real AWS). A foreign account id fails first with `BadRequestException` ("Operations on a resource created in a different account is not allowed"). A region differing from the signing region fails `TagResource` / `UntagResource` with `BadRequestException` ("Failed to tag resource" / "Failed to untag resource"); `ListTagsForResource` instead checks existence in the signing region (`NotFoundException`, "No \ present with name: \") and keys tags by the literal ARN, so a mismatched-region ARN returns `200` with an empty tag set. An empty `Tags` array on `TagResource` is not an error — the account, region, and existence checks still run, then the empty merge no-ops — while a missing/empty `TagKeys` on `UntagResource` fails with a message-less `ValidationException` (AWS sends only the error-type header with an empty body; Floci's standard error body carries `"message": null`). A non-string tag `Key`/`Value` or a non-object `Tags` element is rejected with `SerializationException` rather than coerced, matching AWS's restJson1 deserializer. The same AWS-compatible validation applies wherever tags are set (including `CreateContactList` and `TagResource`): at most 50 tags, unique keys, keys 1–128 / values 0–256 code points, characters limited to letters, numbers, Unicode whitespace and `_ . : / = + - @`, and the reserved `aws:` key prefix. `TagResource` applies the 50-tag limit to the merged (existing + incoming) set. Violations return `BadRequestException` with AWS's messages. diff --git a/mkdocs.yml b/mkdocs.yml index 2198742f13..594261d641 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -137,6 +137,8 @@ nav: - AWS Batch: services/batch.md - CodeDeploy: services/codedeploy.md - CodePipeline: services/codepipeline.md + - Service Quotas: services/servicequotas.md + - AWS RAM: services/ram.md - AWS Backup: services/backup.md - AWS FIS: services/fis.md - CloudTrail: services/cloudtrail.md diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index d775f32847..ecc84f86ff 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -672,8 +672,9 @@ public interface EmulatorConfig { RumServiceConfig rum(); GuardDutyServiceConfig guardduty(); EmrServerlessServiceConfig emrserverless(); - Route53ResolverServiceConfig route53resolver(); + ServiceQuotasServiceConfig servicequotas(); + RamServiceConfig ram(); ControlTowerServiceConfig controltower(); LakeFormationServiceConfig lakeformation(); EfsServiceConfig efs(); @@ -730,6 +731,16 @@ public interface EmulatorConfig { boolean enabled(); } + interface ServiceQuotasServiceConfig { + @WithDefault("true") + boolean enabled(); + } + + interface RamServiceConfig { + @WithDefault("true") + boolean enabled(); + } + interface LakeFormationServiceConfig { @WithDefault("true") boolean enabled(); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java index 0f10805f55..0db80ebe5c 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java @@ -42,6 +42,7 @@ 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.route53resolver.Route53ResolverJsonHandler; +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; @@ -109,6 +110,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, @@ -147,7 +149,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; @@ -191,6 +194,7 @@ public class AwsJson11Controller { this.applicationAutoScalingJsonHandler = applicationAutoScalingJsonHandler; this.cloudHsmV2JsonHandler = cloudHsmV2JsonHandler; this.organizationsJsonHandler = organizationsJsonHandler; + this.serviceQuotasJsonHandler = serviceQuotasJsonHandler; } @POST @@ -268,6 +272,8 @@ public class AwsJson11Controller { // action is authorized against the calling account, so pass that instead of region. case "organizations" -> organizationsJsonHandler.handle(action, request, regionResolver.getAccountId()); + case "servicequotas" -> serviceQuotasJsonHandler.handle( + action, request, region, regionResolver.getAccountId()); default -> null; }; // catalog.matchTarget is protocol-agnostic: a JSON 1.0 target diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java index c14e5de1df..6af5d4057c 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java @@ -355,6 +355,15 @@ public class ResolvedServiceCatalog { config.storage().services().codepipeline().flushIntervalMs(), null, ServiceProtocol.JSON, protocols(ServiceProtocol.JSON), Set.of("CodePipeline_20150709."), Set.of("codepipeline"), Set.of(), Set.of()), + descriptor("servicequotas", "servicequotas", config.services().servicequotas().enabled(), true, + null, null, 5000L, null, ServiceProtocol.JSON, + protocols(ServiceProtocol.JSON), + Set.of("ServiceQuotasV20190624."), Set.of("servicequotas"), Set.of(), Set.of()), + descriptor("ram", "ram", config.services().ram().enabled(), true, + null, null, 5000L, null, ServiceProtocol.REST_JSON, + protocols(ServiceProtocol.REST_JSON), + Set.of(), Set.of("ram"), Set.of(), + Set.of(io.github.hectorvent.floci.services.ram.RamController.class)), descriptor("config", "configservice", config.services().configservice().enabled(), true, "config", storageMode(config.storage().services().config().mode(), config.storage().mode()), config.storage().services().config().flushIntervalMs(), null, ServiceProtocol.JSON, diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java index 8d94b30a83..d0b73ee7ec 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java @@ -4673,6 +4673,18 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider { synchronized (lockFor(key(region, routeTableId))) { RouteTable current = getRequiredRouteTable(region, routeTableId); List next = new ArrayList<>(current.getRoutes()); + // A destination identifies a route: ReplaceRoute matches the first copy and DeleteRoute + // removes every copy, so a table holding two routes with the same destination has no + // well-defined behaviour for either. AWS rejects the second CreateRoute instead, and it + // makes no exception for the local route seeded by CreateRouteTable. + if (next.stream().anyMatch(r -> matchesDestination(r, destinationCidrBlock, + destinationIpv6CidrBlock, destinationPrefixListId))) { + throw new AwsException("RouteAlreadyExists", + "The route identified by " + + destinationLabel(destinationCidrBlock, destinationIpv6CidrBlock, + destinationPrefixListId) + + " already exists", 400); + } Route route = new Route(destinationCidrBlock, gatewayId, "CreateRoute"); route.setDestinationIpv6CidrBlock(destinationIpv6CidrBlock); route.setDestinationPrefixListId(destinationPrefixListId); diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java index a344eefd2a..b1bc49bf24 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java @@ -28,9 +28,13 @@ import jakarta.ws.rs.core.UriBuilder; import jakarta.ws.rs.core.UriInfo; import org.jboss.logging.Logger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; +import java.util.HexFormat; import java.util.List; import java.util.Map; @@ -660,8 +664,109 @@ public class LambdaController { fn.getEnvironment().forEach(vars::put); } + putVpcConfig(node, fn); + putSnapStart(node, fn); + putLoggingConfig(node, fn); + putRuntimeVersionConfig(node, fn); + @SuppressWarnings("unchecked") Map result = objectMapper.convertValue(node, Map.class); return result; } + + /** + * VpcConfigResponse, not VpcConfig: the response shape adds VpcId, which the request shape + * has no member for. Emitted only while the function is actually attached to a VPC — AWS + * omits the block entirely once the last subnet and security group are removed. + */ + private void putVpcConfig(ObjectNode node, LambdaFunction fn) { + Map vpcConfig = fn.getVpcConfig(); + List subnetIds = stringList(vpcConfig, "SubnetIds"); + List securityGroupIds = stringList(vpcConfig, "SecurityGroupIds"); + if (subnetIds.isEmpty() && securityGroupIds.isEmpty()) { + return; + } + ObjectNode vpcNode = node.putObject("VpcConfig"); + ArrayNode subnetNode = vpcNode.putArray("SubnetIds"); + subnetIds.forEach(subnetNode::add); + ArrayNode securityGroupNode = vpcNode.putArray("SecurityGroupIds"); + securityGroupIds.forEach(securityGroupNode::add); + if (fn.getVpcId() != null) { + vpcNode.put("VpcId", fn.getVpcId()); + } + vpcNode.put("Ipv6AllowedForDualStack", + Boolean.TRUE.equals(vpcConfig.get("Ipv6AllowedForDualStack"))); + } + + /** + * SnapStartResponse, not SnapStart: the response adds OptimizationStatus, which the request + * shape has no member for. AWS only reports {@code On} for a published version whose snapshot + * has been optimized; {@code $LATEST} is always {@code Off} even with ApplyOn set. + */ + private void putSnapStart(ObjectNode node, LambdaFunction fn) { + String applyOn = fn.getSnapStartApplyOn() != null ? fn.getSnapStartApplyOn() : "None"; + boolean optimized = "PublishedVersions".equals(applyOn) && !"$LATEST".equals(fn.getVersion()); + node.putObject("SnapStart") + .put("ApplyOn", applyOn) + .put("OptimizationStatus", optimized ? "On" : "Off"); + } + + /** + * Always present, as on AWS: an unset LoggingConfig still reads back as Text plus the default + * {@code /aws/lambda/} log group. The two log levels are JSON-format-only. + */ + private void putLoggingConfig(ObjectNode node, LambdaFunction fn) { + String logFormat = fn.getLogFormat() != null ? fn.getLogFormat() : "Text"; + ObjectNode logging = node.putObject("LoggingConfig"); + logging.put("LogFormat", logFormat); + if ("JSON".equals(logFormat)) { + logging.put("ApplicationLogLevel", + fn.getApplicationLogLevel() != null ? fn.getApplicationLogLevel() : "INFO"); + logging.put("SystemLogLevel", + fn.getSystemLogLevel() != null ? fn.getSystemLogLevel() : "INFO"); + } + logging.put("LogGroup", fn.getLogGroup() != null && !fn.getLogGroup().isBlank() + ? fn.getLogGroup() + : "/aws/lambda/" + fn.getFunctionName()); + } + + /** Managed-runtime only: AWS omits it for container images, which pin their own runtime. */ + private void putRuntimeVersionConfig(ObjectNode node, LambdaFunction fn) { + if ("Image".equals(fn.getPackageType()) || fn.getRuntime() == null || fn.getRuntime().isBlank()) { + return; + } + node.putObject("RuntimeVersionConfig") + .put("RuntimeVersionArn", runtimeVersionArn(fn)); + } + + private static String runtimeVersionArn(LambdaFunction fn) { + String region = "us-east-1"; + String[] arnParts = fn.getFunctionArn() != null ? fn.getFunctionArn().split(":") : new String[0]; + if (arnParts.length > 3 && !arnParts[3].isBlank()) { + region = arnParts[3]; + } + return "arn:aws:lambda:" + region + "::runtime:" + runtimeVersionId(fn.getRuntime()); + } + + /** + * AWS identifies a runtime version by a 64-hex digest. Derived from the runtime name so the + * same runtime keeps the same id across restarts — a value that churned would show up as a + * perpetual diff in anything that records it. + */ + private static String runtimeVersionId(String runtime) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256") + .digest(runtime.getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(digest); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 unavailable", e); + } + } + + private static List stringList(Map config, String key) { + if (config == null || !(config.get(key) instanceof List values)) { + return List.of(); + } + return values.stream().filter(java.util.Objects::nonNull).map(Object::toString).toList(); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java index 2a5de66562..5e686e66f2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java @@ -10,6 +10,8 @@ import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.core.resource.ExplorerResource; import io.github.hectorvent.floci.core.resource.ResourceProvider; import io.github.hectorvent.floci.core.resource.SupportedResourceType; +import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.ec2.model.Subnet; import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping; import io.github.hectorvent.floci.services.lambda.model.FunctionEventInvokeConfig; import io.github.hectorvent.floci.services.lambda.model.InvocationType; @@ -59,6 +61,7 @@ public class LambdaService implements ResourceProvider { + "(?:(?:-gov)|(?:-iso(?:b)?))?-[a-z]+-\\d:" + "\\d{12}:access-point/fsap-[a-f0-9]{17}$"); private static final Pattern FILE_SYSTEM_LOCAL_MOUNT_PATH = Pattern.compile("^/mnt/[A-Za-z0-9._-]+$"); + private static final Pattern LOG_GROUP_PATTERN = Pattern.compile("[.\\-_/#A-Za-z0-9]+"); private final LambdaFunctionStore functionStore; private final LambdaExecutorService executorService; @@ -77,6 +80,7 @@ public class LambdaService implements ResourceProvider { private final DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller; private final StorageFactory storageFactory; private final LambdaLayerService layerService; + private final Ec2Service ec2Service; private Map versionCounters = new ConcurrentHashMap<>(); private Map eventInvokeConfigs = new ConcurrentHashMap<>(); /** @@ -146,6 +150,7 @@ public class LambdaService implements ResourceProvider { this.dynamodbStreamsPoller = null; this.storageFactory = storageFactory; this.layerService = null; + this.ec2Service = null; } @Inject @@ -165,7 +170,8 @@ public class LambdaService implements ResourceProvider { KinesisEventSourcePoller kinesisPoller, DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller, StorageFactory storageFactory, - LambdaLayerService layerService) { + LambdaLayerService layerService, + Ec2Service ec2Service) { this.functionStore = functionStore; this.executorService = executorService; this.concurrencyLimiter = concurrencyLimiter; @@ -183,6 +189,7 @@ public class LambdaService implements ResourceProvider { this.dynamodbStreamsPoller = dynamodbStreamsPoller; this.storageFactory = storageFactory; this.layerService = layerService; + this.ec2Service = ec2Service; } // Real AWS validates a function's Layers eagerly at CreateFunction/UpdateFunctionConfiguration @@ -384,8 +391,12 @@ public class LambdaService implements ResourceProvider { @SuppressWarnings("unchecked") Map vpc = (Map) request.get("VpcConfig"); fn.setVpcConfig(vpc); + fn.setVpcId(resolveVpcId(region, vpc)); } + applySnapStart(fn, request.get("SnapStart")); + applyLoggingConfig(fn, request.get("LoggingConfig")); + List fileSystemConfigs = parseFileSystemConfigs(request.get("FileSystemConfigs")); validateFileSystemVpcConfig(fileSystemConfigs, fn.getVpcConfig()); @@ -526,6 +537,12 @@ public class LambdaService implements ResourceProvider { if (request.containsKey("Layers")) { validateLayersResolvable(layerList); } + if (request.containsKey("SnapStart")) { + validateSnapStart(request.get("SnapStart")); + } + if (request.containsKey("LoggingConfig")) { + validateLoggingConfig(request.get("LoggingConfig")); + } Map requestedVpcConfig = fn.getVpcConfig(); if (request.get("VpcConfig") instanceof Map) { @@ -619,9 +636,18 @@ public class LambdaService implements ResourceProvider { if (request.containsKey("VpcConfig")) { if (request.get("VpcConfig") instanceof Map) { fn.setVpcConfig(requestedVpcConfig); + fn.setVpcId(resolveVpcId(region, requestedVpcConfig)); } } + if (request.containsKey("SnapStart")) { + applySnapStart(fn, request.get("SnapStart")); + } + + if (request.containsKey("LoggingConfig")) { + applyLoggingConfig(fn, request.get("LoggingConfig")); + } + if (request.containsKey("FileSystemConfigs")) { fn.setFileSystemConfigs(requestedFileSystemConfigs); } @@ -1137,6 +1163,12 @@ public class LambdaService implements ResourceProvider { snapshot.setVpcConfig(fn.getVpcConfig() == null ? null : new java.util.HashMap<>(fn.getVpcConfig())); + snapshot.setVpcId(fn.getVpcId()); + snapshot.setSnapStartApplyOn(fn.getSnapStartApplyOn()); + snapshot.setLogFormat(fn.getLogFormat()); + snapshot.setApplicationLogLevel(fn.getApplicationLogLevel()); + snapshot.setSystemLogLevel(fn.getSystemLogLevel()); + snapshot.setLogGroup(fn.getLogGroup()); snapshot.setFileSystemConfigs(new ArrayList<>(fn.getFileSystemConfigs())); snapshot.setLastModified(System.currentTimeMillis()); snapshot.setRevisionId(UUID.randomUUID().toString()); @@ -1219,6 +1251,118 @@ public class LambdaService implements ResourceProvider { } } + /** + * The VpcConfig request shape carries no VpcId; VpcConfigResponse does. AWS derives it from + * the subnets the function is attached to, so resolve it once at attach time and store it. + * A subnet EC2 has never heard of resolves to null rather than failing the call - Floci's + * Lambda accepts unmanaged subnet ids, and CreateFunction must not start rejecting them. + */ + private String resolveVpcId(String region, Map vpcConfig) { + if (ec2Service == null || !hasValues(vpcConfig, "SubnetIds")) { + return null; + } + for (Object subnetId : (List) vpcConfig.get("SubnetIds")) { + if (subnetId == null) { + continue; + } + try { + List found = ec2Service.describeSubnets(region, List.of(subnetId.toString()), Map.of()); + if (!found.isEmpty() && found.get(0).getVpcId() != null) { + return found.get(0).getVpcId(); + } + } catch (RuntimeException e) { + LOG.debugv(e, "Could not resolve VpcId for subnet {0} in {1}", subnetId, region); + } + } + return null; + } + + private static void validateSnapStart(Object value) { + if (!(value instanceof Map snapStart)) { + return; + } + Object applyOn = snapStart.get("ApplyOn"); + if (applyOn != null && !"None".equals(applyOn) && !"PublishedVersions".equals(applyOn)) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + applyOn + "' at 'snapStart.applyOn' failed to " + + "satisfy constraint: Member must satisfy enum value set: " + + "[PublishedVersions, None]", 400); + } + } + + private static void applySnapStart(LambdaFunction fn, Object value) { + if (!(value instanceof Map snapStart)) { + return; + } + validateSnapStart(value); + Object applyOn = snapStart.get("ApplyOn"); + fn.setSnapStartApplyOn(applyOn instanceof String s && !s.isBlank() ? s : "None"); + } + + private static void validateLoggingConfig(Object value) { + if (!(value instanceof Map logging)) { + return; + } + validateEnum(logging.get("LogFormat"), "loggingConfig.logFormat", List.of("JSON", "Text")); + validateEnum(logging.get("ApplicationLogLevel"), "loggingConfig.applicationLogLevel", + List.of("TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL")); + validateEnum(logging.get("SystemLogLevel"), "loggingConfig.systemLogLevel", + List.of("DEBUG", "INFO", "WARN")); + validateLogGroup(logging.get("LogGroup")); + } + + private static void validateEnum(Object value, String field, List allowed) { + if (value == null || allowed.contains(value)) { + return; + } + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + value + "' at '" + field + "' failed to satisfy " + + "constraint: Member must satisfy enum value set: [" + + String.join(", ", allowed) + "]", 400); + } + + /** + * LogGroup is the one LoggingConfig member with a documented length and character + * constraint rather than an enum: 1-512 characters, {@code [.\-_/#A-Za-z0-9]+}. + */ + private static void validateLogGroup(Object value) { + if (!(value instanceof String group) || group.isBlank()) { + return; + } + if (group.length() > 512 || !LOG_GROUP_PATTERN.matcher(group).matches()) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + group + "' at 'loggingConfig.logGroup' failed to " + + "satisfy constraint: Member must satisfy regular expression pattern: " + + "[.\\-_/#A-Za-z0-9]+ or member must have length less than or equal to 512", 400); + } + } + + /** + * LoggingConfig is replaced wholesale, not merged: AWS resets any member the request omits + * back to its default, so an update that names only LogFormat drops a previously set LogGroup. + * + *

ApplicationLogLevel and SystemLogLevel are JSON-format-only: {@link #putLoggingConfig} + * never surfaces them for a Text-format function. Storing them anyway would leave state + * that is accepted, persisted and then never observable through any read path — the same + * accepted-then-forgotten shape this fix removes elsewhere — so they are only kept when the + * resolved format is JSON. + */ + private static void applyLoggingConfig(LambdaFunction fn, Object value) { + if (!(value instanceof Map logging)) { + return; + } + validateLoggingConfig(value); + String format = logging.get("LogFormat") instanceof String f && !f.isBlank() ? f : "Text"; + boolean json = "JSON".equals(format); + fn.setLogFormat(format); + fn.setApplicationLogLevel(json && logging.get("ApplicationLogLevel") instanceof String level + && !level.isBlank() ? level : null); + fn.setSystemLogLevel(json && logging.get("SystemLogLevel") instanceof String level + && !level.isBlank() ? level : null); + fn.setLogGroup(logging.get("LogGroup") instanceof String group && !group.isBlank() + ? group : null); + } + private static boolean hasValues(Map config, String key) { return config != null && config.get(key) instanceof List values diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaFunction.java b/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaFunction.java index 2de33e447e..11e0707b16 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaFunction.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaFunction.java @@ -49,6 +49,16 @@ public class LambdaFunction { private List layers = new ArrayList<>(); private String kmsKeyArn; private Map vpcConfig; + /** + * Resolved at attach time from the first VpcConfig subnet. Response-only: the AWS model's + * VpcConfigResponse carries VpcId, while the VpcConfig request shape does not. + */ + private String vpcId; + private String snapStartApplyOn = "None"; + private String logFormat = "Text"; + private String applicationLogLevel; + private String systemLogLevel; + private String logGroup; private List fileSystemConfigs = new ArrayList<>(); private String codeSha256; @@ -169,6 +179,24 @@ public class LambdaFunction { public Map getVpcConfig() { return vpcConfig; } public void setVpcConfig(Map vpcConfig) { this.vpcConfig = vpcConfig; } + public String getVpcId() { return vpcId; } + public void setVpcId(String vpcId) { this.vpcId = vpcId; } + + public String getSnapStartApplyOn() { return snapStartApplyOn; } + public void setSnapStartApplyOn(String snapStartApplyOn) { this.snapStartApplyOn = snapStartApplyOn; } + + public String getLogFormat() { return logFormat; } + public void setLogFormat(String logFormat) { this.logFormat = logFormat; } + + public String getApplicationLogLevel() { return applicationLogLevel; } + public void setApplicationLogLevel(String applicationLogLevel) { this.applicationLogLevel = applicationLogLevel; } + + public String getSystemLogLevel() { return systemLogLevel; } + public void setSystemLogLevel(String systemLogLevel) { this.systemLogLevel = systemLogLevel; } + + public String getLogGroup() { return logGroup; } + public void setLogGroup(String logGroup) { this.logGroup = logGroup; } + public List getFileSystemConfigs() { return fileSystemConfigs; } public void setFileSystemConfigs(List fileSystemConfigs) { this.fileSystemConfigs = fileSystemConfigs == null ? new ArrayList<>() : new ArrayList<>(fileSystemConfigs); diff --git a/src/main/java/io/github/hectorvent/floci/services/ram/RamController.java b/src/main/java/io/github/hectorvent/floci/services/ram/RamController.java new file mode 100644 index 0000000000..493a6b48f3 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ram/RamController.java @@ -0,0 +1,336 @@ +package io.github.hectorvent.floci.services.ram; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.ram.model.PrincipalAssociation; +import io.github.hectorvent.floci.services.ram.model.ResourceShare; +import io.github.hectorvent.floci.services.ram.model.SharedResource; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * AWS Resource Access Manager (Smithy restJson1). + * + *

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 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 resourceArns = stringList(request.path("resourceArns")); + List 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 resourceArns = stringList(request.path("resourceArns")); + List 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 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 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 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 resourceArns, + List 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 stringList(JsonNode node) { + List values = new ArrayList<>(); + node.forEach(n -> values.add(n.asText())); + return values; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ram/RamService.java b/src/main/java/io/github/hectorvent/floci/services/ram/RamService.java new file mode 100644 index 0000000000..965e8e79aa --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ram/RamService.java @@ -0,0 +1,343 @@ +package io.github.hectorvent.floci.services.ram; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.ram.model.PrincipalAssociation; +import io.github.hectorvent.floci.services.ram.model.ResourceShare; +import io.github.hectorvent.floci.services.ram.model.SharedResource; +import jakarta.annotation.PostConstruct; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; + +/** + * AWS Resource Access Manager (RAM) business logic. + * + *

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. + * + *

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 SHARE_STATUSES = + List.of("PENDING", "ACTIVE", "FAILED", "DELETING", "DELETED"); + + private final StorageFactory storageFactory; + private StorageBackend shares; + private StorageBackend settings; + + @Inject + public RamService(StorageFactory storageFactory) { + this.storageFactory = storageFactory; + } + + @PostConstruct + void initializeStorage() { + shares = storageFactory.create("ram", "ram-resource-shares.json", + new TypeReference>() {}); + settings = storageFactory.create("ram", "ram-settings.json", + new TypeReference>() {}); + } + + 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 principals, + List 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 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 getResourceShares(String callerAccountId, String resourceOwner, + String name, List resourceShareArns, + String resourceShareStatus) { + requireResourceOwner(resourceOwner); + requireResourceShareStatus(resourceShareStatus); + List 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 getResourceShareInvitations(String callerAccountId) { + return List.of(); + } + + public List listResources(String callerAccountId, String resourceOwner, + List resourceShareArns) { + requireResourceOwner(resourceOwner); + List 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 resourceArns, + List 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 resourceArns, + List 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 listPrincipals(String callerAccountId, String resourceOwner, + List resourceShareArns) { + requireResourceOwner(resourceOwner); + List 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 newTags, String callerAccountId) { + ResourceShare share = requireOwnedShare(resourceShareArn, callerAccountId); + Map merged = new LinkedHashMap<>(share.getTags()); + merged.putAll(newTags); + putForOwner(share.withTags(merged)); + } + + public void untagResource(String resourceShareArn, List tagKeys, String callerAccountId) { + ResourceShare share = requireOwnedShare(resourceShareArn, callerAccountId); + Map 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 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 mergeDistinct(List existing, List additions) { + Set merged = new LinkedHashSet<>(existing); + merged.addAll(additions); + return List.copyOf(merged); + } + + private static List withoutAll(List existing, List removals) { + List 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 accountAware) { + accountAware.putForAccount( + stamped.getOwningAccountId(), stamped.getResourceShareArn(), stamped); + return stamped; + } + shares.put(stamped.getResourceShareArn(), stamped); + return stamped; + } + + private List allShares() { + if (shares instanceof AccountAwareStorageBackend 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. + * + *

It is also a required member, so a null one is rejected rather than defaulted: guessing + * SELF answers a question the caller never asked, with the caller's own shares. + */ + /** {@code ResourceShareStatus} is optional on GetResourceShares, but enumerated when sent. */ + private static void requireResourceShareStatus(String resourceShareStatus) { + if (resourceShareStatus != null && !SHARE_STATUSES.contains(resourceShareStatus)) { + throw new AwsException("InvalidParameterException", + "resourceShareStatus must be one of " + SHARE_STATUSES + ".", 400); + } + } + + private static void requireResourceOwner(String resourceOwner) { + if (resourceOwner == null) { + throw new AwsException("InvalidParameterException", + "resourceOwner is required and must be one of [SELF, OTHER-ACCOUNTS].", 400); + } + if (!"SELF".equals(resourceOwner) && !"OTHER-ACCOUNTS".equals(resourceOwner)) { + throw new AwsException("InvalidParameterException", + "resourceOwner must be one of [SELF, OTHER-ACCOUNTS].", 400); + } + } + + private boolean isVisible(ResourceShare share, String callerAccountId, String resourceOwner) { + boolean owned = share.getOwningAccountId().equals(callerAccountId); + if ("SELF".equals(resourceOwner)) { + return owned; + } + // OTHER-ACCOUNTS: every non-owned share is visible, regardless of principals. + // Launched-container credentials resolve to the emulator default account, so a + // principal-based check would hide account-principal shares from the very Lambda + // they were shared with (LZA's Custom::GetResourceShare filters client-side by + // owningAccountId + name anyway). + return !owned; + } + + /** {@code arn:aws:ec2:...:transit-gateway/tgw-1} → {@code ec2:TransitGateway}. */ + private static String ramResourceType(String resourceArn) { + String[] parts = resourceArn.split(":", 6); + if (parts.length < 6) { + return ""; + } + String service = parts[2]; + String resource = parts[5]; + int slash = resource.indexOf('/'); + String typeSegment = slash >= 0 ? resource.substring(0, slash) : resource; + StringBuilder camel = new StringBuilder(); + for (String word : typeSegment.split("-")) { + if (!word.isEmpty()) { + camel.append(Character.toUpperCase(word.charAt(0))).append(word.substring(1)); + } + } + return service + ":" + camel; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ram/model/PrincipalAssociation.java b/src/main/java/io/github/hectorvent/floci/services/ram/model/PrincipalAssociation.java new file mode 100644 index 0000000000..f152e57019 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ram/model/PrincipalAssociation.java @@ -0,0 +1,15 @@ +package io.github.hectorvent.floci.services.ram.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; + +/** One row of a {@code ListPrincipals} response: a principal associated with a resource share. */ +@RegisterForReflection +public record PrincipalAssociation( + String id, + String resourceShareArn, + Instant creationTime, + Instant lastUpdatedTime, + boolean external) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ram/model/ResourceShare.java b/src/main/java/io/github/hectorvent/floci/services/ram/model/ResourceShare.java new file mode 100644 index 0000000000..febd7726a0 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ram/model/ResourceShare.java @@ -0,0 +1,98 @@ +package io.github.hectorvent.floci.services.ram.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.List; +import java.util.Map; + +@RegisterForReflection +public class ResourceShare { + + private final String resourceShareArn; + private final String name; + private final String owningAccountId; + private final List principals; + private final List resourceArns; + private final boolean allowExternalPrincipals; + private final String status; + private final Instant creationTime; + private final Instant lastUpdatedTime; + private final Map tags; + + public ResourceShare(String resourceShareArn, String name, String owningAccountId, + List principals, List 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 principals, + @JsonProperty("resourceArns") List resourceArns, + @JsonProperty("allowExternalPrincipals") boolean allowExternalPrincipals, + @JsonProperty("status") String status, + @JsonProperty("creationTime") Instant creationTime, + @JsonProperty("lastUpdatedTime") Instant lastUpdatedTime, + @JsonProperty("tags") Map 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 getPrincipals() { return principals; } + public List 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 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 newPrincipals, List 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 newTags) { + return new ResourceShare(resourceShareArn, name, owningAccountId, principals, resourceArns, + allowExternalPrincipals, status, creationTime, lastUpdatedTime, newTags); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ram/model/SharedResource.java b/src/main/java/io/github/hectorvent/floci/services/ram/model/SharedResource.java new file mode 100644 index 0000000000..7bacf543ec --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ram/model/SharedResource.java @@ -0,0 +1,11 @@ +package io.github.hectorvent.floci.services.ram.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * One entry of a RAM ListResources response: a resource ARN belonging to a share, with the + * RAM resource type ({@code service:CamelCasedResource}, e.g. {@code ec2:TransitGateway}). + */ +@RegisterForReflection +public record SharedResource(String arn, String type, String resourceShareArn, String status) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasJsonHandler.java new file mode 100644 index 0000000000..f95e53fdfb --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasJsonHandler.java @@ -0,0 +1,82 @@ +package io.github.hectorvent.floci.services.servicequotas; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.core.common.AwsErrorResponse; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.core.Response; +import org.jboss.logging.Logger; + +/** + * JSON 1.1 handler for Service Quotas operations. + * Dispatches {@code X-Amz-Target: ServiceQuotasV20190624.*} actions to {@link ServiceQuotasService}. + * + * @see Service Quotas API + */ +@ApplicationScoped +public class ServiceQuotasJsonHandler { + + private static final Logger LOG = Logger.getLogger(ServiceQuotasJsonHandler.class); + + private final ServiceQuotasService service; + + @Inject + public ServiceQuotasJsonHandler(ServiceQuotasService service) { + this.service = service; + } + + public Response handle(String action, JsonNode request, String region, String accountId) { + LOG.debugv("ServiceQuotas action: {0}", action); + return switch (action) { + case "ListServiceQuotas" -> handleListServiceQuotas(request, region, accountId); + case "GetServiceQuota" -> handleGetServiceQuota(request, region, accountId); + case "GetAWSDefaultServiceQuota" -> handleGetServiceQuota(request, region, accountId); + case "ListAWSDefaultServiceQuotas" -> handleListServiceQuotas(request, region, accountId); + case "RequestServiceQuotaIncrease" -> handleRequestServiceQuotaIncrease(request, region, accountId); + default -> Response.status(400) + .entity(new AwsErrorResponse("UnknownOperationException", + "Unknown operation: ServiceQuotasV20190624." + action)) + .build(); + }; + } + + private Response handleListServiceQuotas(JsonNode request, String region, String accountId) { + return Response.ok(service.listServiceQuotas( + stringOrNull(request, "ServiceCode"), + stringOrNull(request, "QuotaCode"), + stringOrNull(request, "NextToken"), + integerOrNull(request, "MaxResults"), + region, accountId)).build(); + } + + private Response handleGetServiceQuota(JsonNode request, String region, String accountId) { + return Response.ok(service.getServiceQuota( + stringOrNull(request, "ServiceCode"), + stringOrNull(request, "QuotaCode"), + region, accountId)).build(); + } + + private static String stringOrNull(JsonNode node, String field) { + JsonNode value = node == null ? null : node.get(field); + return (value != null && !value.isNull()) ? value.asText() : null; + } + + private static Integer integerOrNull(JsonNode node, String field) { + JsonNode value = node == null ? null : node.get(field); + return (value != null && value.isNumber()) ? value.asInt() : null; + } + + private Response handleRequestServiceQuotaIncrease(JsonNode request, String region, String accountId) { + return Response.ok(service.requestServiceQuotaIncrease( + stringOrNull(request, "ServiceCode"), + stringOrNull(request, "QuotaCode"), + doubleOrNull(request, "DesiredValue"), + stringOrNull(request, "ContextId"), + region, accountId)).build(); + } + + private static Double doubleOrNull(JsonNode node, String field) { + JsonNode value = node == null ? null : node.get(field); + return (value != null && value.isNumber()) ? value.asDouble() : null; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasService.java b/src/main/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasService.java new file mode 100644 index 0000000000..045b467f07 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasService.java @@ -0,0 +1,253 @@ +package io.github.hectorvent.floci.services.servicequotas; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; +import java.util.zip.CRC32; +import java.time.Instant; + +/** + * Service Quotas emulation backed by a generated in-memory catalog. + * + *

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 Service Quotas API + */ +@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 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> 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 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 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 quotasFor(String serviceCode) { + List 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 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 items, String nextToken) { + } + + public ObjectNode requestServiceQuotaIncrease(String serviceCode, String quotaCode, Double desiredValue, + String contextId, String region, String accountId) { + requireServiceCode(serviceCode); + if (quotaCode == null || quotaCode.isEmpty()) { + throw new AwsException("IllegalArgumentException", + "Invalid input: QuotaCode must not be empty.", 400); + } + if (desiredValue == null) { + throw new AwsException("IllegalArgumentException", + "Invalid input: DesiredValue must not be null.", 400); + } + if (desiredValue < 0 || desiredValue > 10000000000.0) { + throw new AwsException("IllegalArgumentException", + "Invalid input: DesiredValue must be between 0 and 10000000000.", 400); + } + QuotaDefinition quota = quotasFor(serviceCode).stream() + .filter(q -> q.quotaCode().equals(quotaCode)) + .findFirst() + .orElseThrow(() -> new AwsException("NoSuchResourceException", + "The request failed because the specified service quota does not exist.", 400)); + + CRC32 crc = new CRC32(); + crc.update((serviceCode + "/" + quotaCode).getBytes(StandardCharsets.UTF_8)); + String id = "%08X".formatted(crc.getValue()); + + long now = Instant.now().getEpochSecond(); + + ObjectNode requestedQuota = objectMapper.createObjectNode(); + requestedQuota.put("Id", id); + requestedQuota.put("ServiceCode", serviceCode); + requestedQuota.put("ServiceName", SERVICE_NAMES.getOrDefault(serviceCode, serviceCode)); + requestedQuota.put("QuotaCode", quotaCode); + requestedQuota.put("QuotaName", quota.quotaName()); + requestedQuota.put("QuotaArn", "arn:aws:servicequotas:" + region + ":" + accountId + ":" + + serviceCode + "/" + quotaCode); + requestedQuota.put("DesiredValue", desiredValue); + requestedQuota.put("Status", "PENDING"); + requestedQuota.put("Requester", "floci-emulator"); + requestedQuota.put("Unit", "None"); + requestedQuota.put("GlobalQuota", false); + requestedQuota.put("QuotaRequestedAtLevel", "ACCOUNT"); + requestedQuota.put("Created", now); + requestedQuota.put("LastUpdated", now); + if (contextId != null) { + ObjectNode context = objectMapper.createObjectNode(); + context.put("ContextId", contextId); + context.put("ContextScope", "RESOURCE"); + requestedQuota.set("QuotaContext", context); + } + + ObjectNode response = objectMapper.createObjectNode(); + response.set("RequestedQuota", requestedQuota); + return response; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesContactService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesContactService.java index c4f622e01c..fea8d2495e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesContactService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesContactService.java @@ -105,6 +105,48 @@ public class SesContactService { .orElseThrow(() -> contactListNotFound(name)); } + public List listTags(String name, String region) { + ContactList list = contactListStore.get(contactListKey(region, name)) + .orElseThrow(() -> tagTargetNotFound(name)); + return new ArrayList<>(list.getTags()); + } + + /** + * Merges the incoming tags into the stored list. The lookup and write share the mutation lock + * used by deletion, so tagging can't resurrect a concurrently deleted list or overwrite a + * concurrent mutation with a stale object. + */ + public void tag(String name, String region, List newTags) { + String key = contactListKey(region, name); + synchronized (contactMutationLock) { + ContactList list = contactListStore.get(key).orElseThrow(() -> tagTargetNotFound(name)); + list.setTags(SesTags.merge(list.getTags(), newTags)); + contactListStore.put(key, list); + } + LOG.infov("Tagged SES contact list: {0} in region {1} (+{2} tags)", name, region, newTags.size()); + } + + public void untag(String name, String region, List tagKeys) { + String key = contactListKey(region, name); + synchronized (contactMutationLock) { + ContactList list = contactListStore.get(key).orElseThrow(() -> tagTargetNotFound(name)); + Set toRemove = new HashSet<>(tagKeys); + // Copy-on-write: the stored list may be immutable, and unlocked readers iterate it. + List remaining = new ArrayList<>(list.getTags()); + remaining.removeIf(t -> toRemove.contains(t.key())); + list.setTags(remaining); + contactListStore.put(key, list); + } + LOG.infov("Untagged SES contact list: {0} in region {1} (-{2} keys)", name, region, tagKeys.size()); + } + + private static AwsException tagTargetNotFound(String name) { + // The tag endpoints use AWS's "No ContactList present with name" wording + // (probe-confirmed), unlike the CRUD "List with name: X doesn't exist." + return new AwsException("NotFoundException", + "No ContactList present with name: " + name, 404); + } + public List listContactLists(String region) { String prefix = "contactList::" + region + "::"; return contactListStore.scan(k -> k.startsWith(prefix)).stream() diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java index e1b9c3fe98..b2430b2cae 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java @@ -722,7 +722,11 @@ public class SesController { public Response createCustomVerificationEmailTemplate(@Context HttpHeaders headers, String body) { String region = regionResolver.resolveRegion(headers); try { - CustomVerificationEmailTemplate t = parseCvet(objectMapper.readTree(body)); + JsonNode request = objectMapper.readTree(body); + CustomVerificationEmailTemplate t = parseCvet(request); + // Tags exist only on the create request; UpdateCustomVerificationEmailTemplate has no + // Tags member and preserves the stored ones. + t.setTags(parseTagsArray(request.path("Tags"))); sesService.createCustomVerificationEmailTemplate(t, region); return Response.ok(objectMapper.createObjectNode()).build(); } catch (AwsException e) { @@ -1468,7 +1472,8 @@ public class SesController { } else { scalingMode = scalingNode.asText(); } - sesService.createDedicatedIpPool(poolName, scalingMode, region); + List tags = parseTagsArray(request.path("Tags")); + sesService.createDedicatedIpPool(poolName, scalingMode, tags, region); LOG.infov("SES V2 CreateDedicatedIpPool: {0}", poolName); return Response.ok(objectMapper.createObjectNode()).build(); } catch (AwsException e) { @@ -1495,7 +1500,11 @@ public class SesController { String region = regionResolver.resolveRegion(headers); DedicatedIpPool pool = sesService.getDedicatedIpPool(poolName, region); ObjectNode result = objectMapper.createObjectNode(); - result.set("DedicatedIpPool", objectMapper.valueToTree(pool)); + // Built explicitly: the AWS DedicatedIpPool shape carries only PoolName and ScalingMode; + // the model's tags are exposed via ListTagsForResource, not here. + ObjectNode poolNode = result.putObject("DedicatedIpPool"); + poolNode.put("PoolName", pool.getPoolName()); + poolNode.put("ScalingMode", pool.getScalingMode()); return Response.ok(result).build(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesCvetService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesCvetService.java index 76086794b4..be600b591a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesCvetService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesCvetService.java @@ -5,14 +5,18 @@ import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.ses.model.CustomVerificationEmailTemplate; +import io.github.hectorvent.floci.services.ses.model.Tag; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.util.ArrayList; import java.util.Comparator; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Set; /** * Storage for custom verification email templates (the {@code cvetStore}), extracted from @@ -47,6 +51,7 @@ public class SesCvetService { } public void createCustomVerificationEmailTemplate(CustomVerificationEmailTemplate template, String region) { + SesTags.validate(template.getTags()); String key = cvetKey(region, template.getTemplateName()); // Lock only the check-then-put so concurrent creates for the same name can't both observe // the key as absent; the facade's validation and this logging stay outside the lock. @@ -80,9 +85,11 @@ public class SesCvetService { // Guard the existence check and the put together so a concurrent delete can't slip between // them and have the update resurrect the just-deleted template. synchronized (cvetMutationLock) { - if (cvetStore.get(key).isEmpty()) { - throw cvetNotFound(template.getTemplateName()); - } + CustomVerificationEmailTemplate existing = cvetStore.get(key) + .orElseThrow(() -> cvetNotFound(template.getTemplateName())); + // The update request has no Tags member — preserve the stored ones (copied, so the + // two objects never share a list instance). + template.setTags(new ArrayList<>(existing.getTags())); cvetStore.put(key, template); } LOG.infov("Updated custom verification email template {0} in region {1}", @@ -110,6 +117,52 @@ public class SesCvetService { return cvetStore.get(cvetKey(region, templateName)); } + public List listTags(String templateName, String region) { + CustomVerificationEmailTemplate template = cvetStore.get(cvetKey(region, templateName)) + .orElseThrow(() -> tagTargetNotFound(templateName)); + return new ArrayList<>(template.getTags()); + } + + /** + * Merges the incoming tags into the stored template. The lookup and write share the mutation + * lock so a concurrent update can't be overwritten with a stale object and a concurrent delete + * can't be resurrected. + */ + public void tag(String templateName, String region, List newTags) { + String key = cvetKey(region, templateName); + synchronized (cvetMutationLock) { + CustomVerificationEmailTemplate template = cvetStore.get(key) + .orElseThrow(() -> tagTargetNotFound(templateName)); + template.setTags(SesTags.merge(template.getTags(), newTags)); + cvetStore.put(key, template); + } + LOG.infov("Tagged custom verification email template {0} in region {1} (+{2} tags)", + templateName, region, newTags.size()); + } + + public void untag(String templateName, String region, List tagKeys) { + String key = cvetKey(region, templateName); + synchronized (cvetMutationLock) { + CustomVerificationEmailTemplate template = cvetStore.get(key) + .orElseThrow(() -> tagTargetNotFound(templateName)); + Set toRemove = new HashSet<>(tagKeys); + // Copy-on-write: the stored list may be immutable, and unlocked readers iterate it. + List remaining = new ArrayList<>(template.getTags()); + remaining.removeIf(t -> toRemove.contains(t.key())); + template.setTags(remaining); + cvetStore.put(key, template); + } + LOG.infov("Untagged custom verification email template {0} in region {1} (-{2} keys)", + templateName, region, tagKeys.size()); + } + + private static AwsException tagTargetNotFound(String templateName) { + // The v2 tag endpoints use AWS's "No CustomVerificationEmailTemplate present with name" + // wording (probe-confirmed), not the v1-native CRUD message above. + return new AwsException("NotFoundException", + "No CustomVerificationEmailTemplate present with name: " + templateName, 404); + } + private static AwsException cvetNotFound(String templateName) { // v1-native code (verified: CustomVerificationEmailTemplateDoesNotExist / 400). // SesController.remapV1Exception translates it to NotFoundException / 404 for the v2 boundary. diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpService.java index af196dc063..855b56033c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpService.java @@ -5,10 +5,13 @@ import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.ses.model.DedicatedIpPool; +import io.github.hectorvent.floci.services.ses.model.Tag; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.util.ArrayList; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -27,6 +30,9 @@ public class SesDedicatedIpService { private static final Set SCALING_MODES = Set.of("STANDARD", "MANAGED"); private final StorageBackend dedicatedIpPoolStore; + // Serializes pool check-then-write mutations (create/delete/tag) so concurrent creates for the + // same name can't both succeed and tagging can't resurrect a concurrently deleted pool. + private final Object poolMutationLock = new Object(); @Inject public SesDedicatedIpService(StorageFactory storageFactory) { @@ -38,7 +44,8 @@ public class SesDedicatedIpService { this.dedicatedIpPoolStore = dedicatedIpPoolStore; } - public DedicatedIpPool createDedicatedIpPool(String poolName, String scalingMode, String region) { + public DedicatedIpPool createDedicatedIpPool(String poolName, String scalingMode, List tags, + String region) { if (poolName == null || poolName.isBlank()) { throw new AwsException("BadRequestException", "PoolName is required.", 400); } @@ -46,13 +53,17 @@ public class SesDedicatedIpService { if (!SCALING_MODES.contains(effectiveScaling)) { throw new AwsException("BadRequestException", "The ScalingMode parameter is invalid.", 400); } + SesTags.validate(tags); String key = dedicatedIpPoolKey(region, poolName); - if (dedicatedIpPoolStore.get(key).isPresent()) { - throw new AwsException("AlreadyExistsException", - "The pool <" + poolName + "> already exists.", 400); - } DedicatedIpPool pool = new DedicatedIpPool(poolName, effectiveScaling); - dedicatedIpPoolStore.put(key, pool); + pool.setTags(tags); + synchronized (poolMutationLock) { + if (dedicatedIpPoolStore.get(key).isPresent()) { + throw new AwsException("AlreadyExistsException", + "The pool <" + poolName + "> already exists.", 400); + } + dedicatedIpPoolStore.put(key, pool); + } LOG.infov("Created SES dedicated IP pool: {0} in region {1}", poolName, region); return pool; } @@ -77,14 +88,59 @@ public class SesDedicatedIpService { public void deleteDedicatedIpPool(String poolName, String region) { String key = dedicatedIpPoolKey(region, poolName); - if (dedicatedIpPoolStore.get(key).isEmpty()) { - throw new AwsException("NotFoundException", - "The requested pool <" + poolName + "> does not exist.", 404); + synchronized (poolMutationLock) { + if (dedicatedIpPoolStore.get(key).isEmpty()) { + throw new AwsException("NotFoundException", + "The requested pool <" + poolName + "> does not exist.", 404); + } + dedicatedIpPoolStore.delete(key); } - dedicatedIpPoolStore.delete(key); LOG.infov("Deleted SES dedicated IP pool: {0} in region {1}", poolName, region); } + public List listTags(String poolName, String region) { + DedicatedIpPool pool = dedicatedIpPoolStore.get(dedicatedIpPoolKey(region, poolName)) + .orElseThrow(() -> tagTargetNotFound(poolName)); + return new ArrayList<>(pool.getTags()); + } + + /** + * Merges the incoming tags into the stored pool. The lookup and write share the mutation lock + * so tagging can't resurrect a concurrently deleted pool or lose a concurrent tag update. + */ + public void tag(String poolName, String region, List newTags) { + String key = dedicatedIpPoolKey(region, poolName); + synchronized (poolMutationLock) { + DedicatedIpPool pool = dedicatedIpPoolStore.get(key) + .orElseThrow(() -> tagTargetNotFound(poolName)); + pool.setTags(SesTags.merge(pool.getTags(), newTags)); + dedicatedIpPoolStore.put(key, pool); + } + LOG.infov("Tagged SES dedicated IP pool: {0} in region {1} (+{2} tags)", poolName, region, newTags.size()); + } + + public void untag(String poolName, String region, List tagKeys) { + String key = dedicatedIpPoolKey(region, poolName); + synchronized (poolMutationLock) { + DedicatedIpPool pool = dedicatedIpPoolStore.get(key) + .orElseThrow(() -> tagTargetNotFound(poolName)); + Set toRemove = new HashSet<>(tagKeys); + // Copy-on-write: the stored list may be immutable, and unlocked readers iterate it. + List remaining = new ArrayList<>(pool.getTags()); + remaining.removeIf(t -> toRemove.contains(t.key())); + pool.setTags(remaining); + dedicatedIpPoolStore.put(key, pool); + } + LOG.infov("Untagged SES dedicated IP pool: {0} in region {1} (-{2} keys)", poolName, region, tagKeys.size()); + } + + private static AwsException tagTargetNotFound(String poolName) { + // The tag endpoints use AWS's "No DedicatedIpPool present with name" wording + // (probe-confirmed), unlike the CRUD "The requested pool does not exist." + return new AwsException("NotFoundException", + "No DedicatedIpPool present with name: " + poolName, 404); + } + private static String dedicatedIpPoolKey(String region, String name) { return "dedicatedIpPool::" + region + "::" + name; } diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java index 13539a5540..77b1133425 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java @@ -1671,8 +1671,9 @@ public class SesService { // Storage lives in SesDedicatedIpService; the facade forwards. - public DedicatedIpPool createDedicatedIpPool(String poolName, String scalingMode, String region) { - return dedicatedIpService.createDedicatedIpPool(poolName, scalingMode, region); + public DedicatedIpPool createDedicatedIpPool(String poolName, String scalingMode, List tags, + String region) { + return dedicatedIpService.createDedicatedIpPool(poolName, scalingMode, tags, region); } public DedicatedIpPool getDedicatedIpPool(String poolName, String region) { @@ -2040,33 +2041,44 @@ public class SesService { public List listResourceTags(String arn, String region) { ResourceRef ref = parseSesArn(arn); - return switch (ref.type()) { - case "configuration-set" -> listConfigurationSetTags(ref.name(), ref.region()); - // AWS ListTagsForResource on template / identity ARNs uses the signing region - // for lookup (the ARN region is effectively ignored), unlike configuration-set - // which routes by the ARN's region. + requireCallerAccount(ref); + List tags = switch (ref.type()) { + case "configuration-set" -> listConfigurationSetTags(ref.name(), region); case "template" -> listEmailTemplateTags(ref.name(), region); case "identity" -> listIdentityTags(ref.name(), region); + case "contact-list" -> contactService.listTags(ref.name(), region); + case "custom-verification-email-template" -> cvetService.listTags(ref.name(), region); + case "dedicated-ip-pool" -> dedicatedIpService.listTags(ref.name(), region); default -> throw new AwsException("NotFoundException", "Resource " + arn + " was not found.", 404); }; + // AWS checks existence against the signing region but keys the tag store by the literal + // ARN: a mismatched ARN region passes the existence check above yet addresses an ARN + // nothing was ever tagged under, so the result is empty (probe-confirmed across all six + // resource types). + if (!ref.region().equals(region)) { + return List.of(); + } + return tags; } public void tagResource(String arn, String region, List newTags) { ResourceRef ref = parseSesArn(arn); + requireCallerAccount(ref); if (!ref.region().equals(region)) { throw new AwsException("BadRequestException", "Failed to tag resource", 400); } - if (newTags == null || newTags.isEmpty()) { - throw new AwsException("BadRequestException", - "1 validation error detected: Value at 'tags' failed to satisfy constraint: " - + "Member must have length greater than or equal to 1", 400); - } - SesTags.validate(newTags); + // An empty Tags list is not an error: AWS still runs the account, region, and existence + // checks and then applies the empty merge as a no-op (probe-confirmed). + List tags = newTags == null ? List.of() : newTags; + SesTags.validate(tags); switch (ref.type()) { - case "configuration-set" -> tagConfigurationSet(ref.name(), ref.region(), newTags); - case "template" -> tagEmailTemplate(ref.name(), ref.region(), newTags); - case "identity" -> tagIdentity(ref.name(), ref.region(), newTags); + case "configuration-set" -> tagConfigurationSet(ref.name(), region, tags); + case "template" -> tagEmailTemplate(ref.name(), region, tags); + case "identity" -> tagIdentity(ref.name(), region, tags); + case "contact-list" -> contactService.tag(ref.name(), region, tags); + case "custom-verification-email-template" -> cvetService.tag(ref.name(), region, tags); + case "dedicated-ip-pool" -> dedicatedIpService.tag(ref.name(), region, tags); default -> throw new AwsException("NotFoundException", "Resource " + arn + " was not found.", 404); } @@ -2074,29 +2086,25 @@ public class SesService { public void untagResource(String arn, String region, List tagKeys) { ResourceRef ref = parseSesArn(arn); + requireCallerAccount(ref); if (tagKeys == null || tagKeys.isEmpty()) { - throw new AwsException("BadRequestException", - "1 validation error detected: Value at 'tagKeys' failed to satisfy constraint: " - + "Member must have length greater than or equal to 1", 400); + // AWS rejects a missing/empty TagKeys member with a message-less ValidationException + // (probe-confirmed: only the error-type header, empty body), after the account guard + // and before the region guard. The null message is deliberate — it surfaces through + // Floci's standard error body as "message":null, which restJson1 SDKs parse the same + // way as AWS's empty body since they read x-amzn-errortype first. + throw new AwsException("ValidationException", null, 400); + } + if (!ref.region().equals(region)) { + throw new AwsException("BadRequestException", "Failed to untag resource", 400); } switch (ref.type()) { - case "configuration-set" -> untagConfigurationSet(ref.name(), ref.region(), tagKeys); - case "template" -> { - // AWS UntagResource on template / identity ARNs strictly requires the ARN - // region to match the signing region (rejects mismatch with - // BadRequestException), unlike configuration-set which routes the lookup - // to the ARN's region. - if (!ref.region().equals(region)) { - throw new AwsException("BadRequestException", "Failed to untag resource", 400); - } - untagEmailTemplate(ref.name(), region, tagKeys); - } - case "identity" -> { - if (!ref.region().equals(region)) { - throw new AwsException("BadRequestException", "Failed to untag resource", 400); - } - untagIdentity(ref.name(), region, tagKeys); - } + case "configuration-set" -> untagConfigurationSet(ref.name(), region, tagKeys); + case "template" -> untagEmailTemplate(ref.name(), region, tagKeys); + case "identity" -> untagIdentity(ref.name(), region, tagKeys); + case "contact-list" -> contactService.untag(ref.name(), region, tagKeys); + case "custom-verification-email-template" -> cvetService.untag(ref.name(), region, tagKeys); + case "dedicated-ip-pool" -> dedicatedIpService.untag(ref.name(), region, tagKeys); default -> throw new AwsException("NotFoundException", "Resource " + arn + " was not found.", 404); } @@ -2114,7 +2122,7 @@ public class SesService { ConfigurationSet cs = configSetStore.get(key) .orElseThrow(() -> new AwsException("NotFoundException", "No ConfigurationSet present with name: " + name, 404)); - cs.setTags(mergeTags(cs.getTags(), newTags)); + cs.setTags(SesTags.merge(cs.getTags(), newTags)); configSetStore.put(key, cs); LOG.infov("Tagged SES configuration set: {0} (region {1}, +{2} tags)", name, region, newTags.size()); } @@ -2125,7 +2133,10 @@ public class SesService { .orElseThrow(() -> new AwsException("NotFoundException", "No ConfigurationSet present with name: " + name, 404)); Set toRemove = new HashSet<>(tagKeys); - cs.getTags().removeIf(t -> toRemove.contains(t.key())); + // Copy-on-write: the stored list may be immutable, and unlocked readers iterate it. + List remaining = new ArrayList<>(cs.getTags()); + remaining.removeIf(t -> toRemove.contains(t.key())); + cs.setTags(remaining); configSetStore.put(key, cs); LOG.infov("Untagged SES configuration set: {0} (region {1}, -{2} keys)", name, region, tagKeys.size()); } @@ -2141,26 +2152,11 @@ public class SesService { EmailTemplate template = templateService.find(name, region) .orElseThrow(() -> new AwsException("NotFoundException", "No Template present with name: " + name, 404)); - template.setTags(mergeTags(template.getTags(), newTags)); + template.setTags(SesTags.merge(template.getTags(), newTags)); templateService.save(template, region); LOG.infov("Tagged SES template: {0} (region {1}, +{2} tags)", name, region, newTags.size()); } - private static List mergeTags(List existing, - List incoming) { - Map merged = new LinkedHashMap<>(); - for (Tag t : existing) { - merged.put(t.key(), t.value()); - } - for (Tag t : incoming) { - merged.put(t.key(), t.value()); - } - SesTags.validateMergedCount(merged.size()); - List out = new ArrayList<>(); - merged.forEach((k, v) -> out.add(new Tag(k, v))); - return out; - } - private List listIdentityTags(String identityValue, String region) { Identity identity = identityStore.get(identityKey(region, identityValue)) .orElseThrow(() -> new AwsException("NotFoundException", @@ -2173,7 +2169,7 @@ public class SesService { Identity identity = identityStore.get(key) .orElseThrow(() -> new AwsException("NotFoundException", "No EmailIdentity present with name: " + identityValue, 404)); - identity.setTags(mergeTags(identity.getTags(), newTags)); + identity.setTags(SesTags.merge(identity.getTags(), newTags)); identityStore.put(key, identity); LOG.infov("Tagged SES identity: {0} (region {1}, +{2} tags)", identityValue, region, newTags.size()); } @@ -2184,7 +2180,10 @@ public class SesService { .orElseThrow(() -> new AwsException("NotFoundException", "No EmailIdentity present with name: " + identityValue, 404)); Set toRemove = new HashSet<>(tagKeys); - identity.getTags().removeIf(t -> toRemove.contains(t.key())); + // Copy-on-write: the stored list may be immutable, and unlocked readers iterate it. + List remaining = new ArrayList<>(identity.getTags()); + remaining.removeIf(t -> toRemove.contains(t.key())); + identity.setTags(remaining); identityStore.put(key, identity); LOG.infov("Untagged SES identity: {0} (region {1}, -{2} keys)", identityValue, region, tagKeys.size()); } @@ -2204,12 +2203,28 @@ public class SesService { .orElseThrow(() -> new AwsException("NotFoundException", "No Template present with name: " + name, 404)); Set toRemove = new HashSet<>(tagKeys); - template.getTags().removeIf(t -> toRemove.contains(t.key())); + // Copy-on-write: the stored list may be immutable, and unlocked readers iterate it. + List remaining = new ArrayList<>(template.getTags()); + remaining.removeIf(t -> toRemove.contains(t.key())); + template.setTags(remaining); templateService.save(template, region); LOG.infov("Untagged SES template: {0} (region {1}, -{2} keys)", name, region, tagKeys.size()); } - private record ResourceRef(String region, String type, String name) {} + private record ResourceRef(String account, String region, String type, String name) {} + + /** + * AWS rejects a tag operation whose ARN carries a different account id before any region or + * existence check (probe-confirmed): the account error wins even when the region is also + * mismatched or the resource doesn't exist anywhere. + */ + private void requireCallerAccount(ResourceRef ref) { + String callerAccountId = regionResolver != null ? regionResolver.getAccountId() : defaultAccountId; + if (!ref.account().equals(callerAccountId)) { + throw new AwsException("BadRequestException", + "Operations on a resource created in a different account is not allowed", 400); + } + } private static ResourceRef parseSesArn(String arn) { if (arn == null || arn.isBlank()) { @@ -2234,7 +2249,8 @@ public class SesService { if (slash <= 0 || slash == resource.length() - 1) { throw new AwsException("BadRequestException", "Invalid ARN: " + arn, 400); } - return new ResourceRef(parsed.region(), resource.substring(0, slash), resource.substring(slash + 1)); + return new ResourceRef(parsed.accountId(), parsed.region(), + resource.substring(0, slash), resource.substring(slash + 1)); } // ──────────────────── Suppression (account attributes + list) ──────────────────── diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesTags.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesTags.java index ffc592f6ef..e512453f5f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesTags.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesTags.java @@ -5,7 +5,9 @@ import io.github.hectorvent.floci.services.ses.model.Tag; import java.util.ArrayList; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.regex.Pattern; @@ -112,6 +114,24 @@ final class SesTags { } } + /** + * {@code TagResource} merge semantics: incoming keys overwrite existing values, insertion order + * is preserved, and the 50-tag ceiling applies to the merged result. + */ + static List merge(List existing, List incoming) { + Map merged = new LinkedHashMap<>(); + for (Tag t : existing) { + merged.put(t.key(), t.value()); + } + for (Tag t : incoming) { + merged.put(t.key(), t.value()); + } + validateMergedCount(merged.size()); + List out = new ArrayList<>(); + merged.forEach((k, v) -> out.add(new Tag(k, v))); + return out; + } + // A null value counts as a character-set violation (AWS requires a string value; empty is allowed). private static boolean charsetOk(String s) { return s != null && TAG_CHARS.matcher(s).matches(); diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesTemplateService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesTemplateService.java index 27e681f6d8..43e11a0be0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesTemplateService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesTemplateService.java @@ -74,8 +74,9 @@ public class SesTemplateService { "Template " + template.getTemplateName() + " does not exist.", 400)); template.setCreatedTimestamp(existing.getCreatedTimestamp()); template.setLastUpdatedTimestamp(Instant.now()); - // Tags are managed exclusively via Tag/UntagResource — preserve them on update. - template.setTags(existing.getTags()); + // Tags are managed exclusively via Tag/UntagResource — preserve them on update (copied, + // so the two objects never share a list instance). + template.setTags(new ArrayList<>(existing.getTags())); templateStore.put(key, template); LOG.infov("Updated SES template: {0} in region {1}", template.getTemplateName(), region); return template; diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/CustomVerificationEmailTemplate.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/CustomVerificationEmailTemplate.java index 7cde112ca2..2d15989367 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/model/CustomVerificationEmailTemplate.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/CustomVerificationEmailTemplate.java @@ -4,6 +4,9 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import io.quarkus.runtime.annotations.RegisterForReflection; +import java.util.ArrayList; +import java.util.List; + /** * A custom verification email template: the branded email SES sends when verifying a new * sender email address (as opposed to {@link EmailTemplate}, which is for the emails a caller @@ -31,6 +34,9 @@ public class CustomVerificationEmailTemplate { @JsonProperty("FailureRedirectionURL") private String failureRedirectionURL; + @JsonProperty("Tags") + private List tags = new ArrayList<>(); + public CustomVerificationEmailTemplate() {} public String getTemplateName() { return templateName; } @@ -54,4 +60,9 @@ public class CustomVerificationEmailTemplate { public void setFailureRedirectionURL(String failureRedirectionURL) { this.failureRedirectionURL = failureRedirectionURL; } + + public List getTags() { return tags; } + public void setTags(List tags) { + this.tags = tags == null ? new ArrayList<>() : tags; + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/DedicatedIpPool.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/DedicatedIpPool.java index 1de5009453..3859627eb3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/model/DedicatedIpPool.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/DedicatedIpPool.java @@ -5,6 +5,9 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import io.quarkus.runtime.annotations.RegisterForReflection; +import java.util.ArrayList; +import java.util.List; + /** * A SES V2 dedicated IP pool. Mirrors the AWS {@code DedicatedIpPool} shape: * a pool name and its scaling mode ({@code STANDARD} or {@code MANAGED}). @@ -20,6 +23,9 @@ public class DedicatedIpPool { @JsonProperty("ScalingMode") private String scalingMode; + @JsonProperty("Tags") + private List tags = new ArrayList<>(); + public DedicatedIpPool() {} public DedicatedIpPool(String poolName, String scalingMode) { @@ -32,4 +38,9 @@ public class DedicatedIpPool { public String getScalingMode() { return scalingMode; } public void setScalingMode(String scalingMode) { this.scalingMode = scalingMode; } + + public List getTags() { return tags; } + public void setTags(List tags) { + this.tags = tags == null ? new ArrayList<>() : tags; + } } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index ea9cb7e8b9..e24cc30379 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -568,3 +568,7 @@ floci: # validate-runtime-exists: false # true = reject unknown runtime ARNs bedrock-agent-core-control: enabled: true + servicequotas: + enabled: true + ram: + enabled: true diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2DuplicateRouteTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2DuplicateRouteTest.java new file mode 100644 index 0000000000..bad3f30968 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2DuplicateRouteTest.java @@ -0,0 +1,218 @@ +package io.github.hectorvent.floci.services.ec2; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.xml.HasXPath.hasXPath; + +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import io.quarkus.test.junit.QuarkusTest; +import static io.restassured.RestAssured.given; + +/** + * A destination identifies a route, so CreateRoute takes each one at most once per table and + * https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateRoute.html rejects a repeat with + * RouteAlreadyExists. + * + *

Accepting the repeat is worse than untidy, because the two operations that address a route by + * its destination then disagree about which copy they mean: ReplaceRoute matches only the first, so + * the stale copy survives the replace, while DeleteRoute removes every copy, so deleting one of two + * loses both. Neither has a defined result on a table holding duplicates, which is why the last two + * tests here pin the behaviour of all three verbs together rather than only the rejection. + * + *

The local route CreateRouteTable seeds for the VPC CIDR is a route like any other for this + * purpose, and AWS reports it the same way — the error is the one Terraform surfaces as + * "RouteAlreadyExists: The route identified by 10.0.0.0/16 already exists" when a configuration + * tries to add a route over it. + * + *

The XPath assertions use {@code local-name()} because EC2 responses carry a default namespace. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class Ec2DuplicateRouteTest { + + private static final String AUTH_HEADER = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request"; + + private static final String VPC_CIDR = "198.51.100.0/24"; + private static final String IPV4_ROUTE = "0.0.0.0/0"; + private static final String IPV6_ROUTE = "::/0"; + private static final String PREFIX_LIST = "pl-0dup0route0test0"; + private static final String INTERNET_GATEWAY = "igw-0dup0route0test0"; + private static final String OTHER_GATEWAY = "igw-0dup0route0othr0"; + private static final String NAT_GATEWAY = "nat-0dup0route0test0"; + + private static final String ROUTE_COUNT = + "count(//*[local-name()='routeSet']/*[local-name()='item'])"; + + private static String routeTableId; + + private static io.restassured.specification.RequestSpecification ec2() { + return given().header("Authorization", AUTH_HEADER); + } + + private static io.restassured.response.ValidatableResponse describe() { + return ec2() + .formParam("Action", "DescribeRouteTables") + .formParam("RouteTableId.1", routeTableId) + .when() + .post("/") + .then() + .statusCode(200); + } + + /** CreateRoute with one destination and the internet gateway as its target. */ + private static io.restassured.specification.RequestSpecification createRoute( + String destinationParam, String destination) { + return ec2() + .formParam("Action", "CreateRoute") + .formParam("RouteTableId", routeTableId) + .formParam(destinationParam, destination) + .formParam("GatewayId", INTERNET_GATEWAY); + } + + /** Asserts the response is RouteAlreadyExists and names the destination it refused. */ + private static void expectRouteAlreadyExists( + io.restassured.specification.RequestSpecification request, String destination) { + String message = request + .when() + .post("/") + .then() + .statusCode(400) + .body("Response.Errors.Error.Code", equalTo("RouteAlreadyExists")) + .extract().path("Response.Errors.Error.Message"); + + assertThat(message, containsString(destination)); + } + + @Test + @Order(1) + void createARouteTableWithOneRoutePerDestinationKind() { + String vpcId = ec2() + .formParam("Action", "CreateVpc") + .formParam("CidrBlock", VPC_CIDR) + .when() + .post("/") + .then() + .statusCode(200) + .extract().path("CreateVpcResponse.vpc.vpcId"); + + routeTableId = ec2() + .formParam("Action", "CreateRouteTable") + .formParam("VpcId", vpcId) + .when() + .post("/") + .then() + .statusCode(200) + .extract().path("CreateRouteTableResponse.routeTable.routeTableId"); + + createRoute("DestinationCidrBlock", IPV4_ROUTE).when().post("/").then().statusCode(200); + createRoute("DestinationIpv6CidrBlock", IPV6_ROUTE).when().post("/").then().statusCode(200); + createRoute("DestinationPrefixListId", PREFIX_LIST).when().post("/").then().statusCode(200); + + // The seeded local route plus the three just created. + describe().body(hasXPath(ROUTE_COUNT, equalTo("4"))); + } + + @Test + @Order(2) + void aRepeatedIpv4DestinationIsRejected() { + expectRouteAlreadyExists(createRoute("DestinationCidrBlock", IPV4_ROUTE), IPV4_ROUTE); + } + + @Test + @Order(3) + void aRepeatedIpv6DestinationIsRejected() { + expectRouteAlreadyExists(createRoute("DestinationIpv6CidrBlock", IPV6_ROUTE), IPV6_ROUTE); + } + + @Test + @Order(4) + void aRepeatedPrefixListDestinationIsRejected() { + expectRouteAlreadyExists(createRoute("DestinationPrefixListId", PREFIX_LIST), PREFIX_LIST); + } + + /** + * The local route is seeded by CreateRouteTable rather than by a caller, and is still a route + * whose destination is taken. + */ + @Test + @Order(5) + void theSeededLocalRouteCannotBeRoutedOver() { + expectRouteAlreadyExists(createRoute("DestinationCidrBlock", VPC_CIDR), VPC_CIDR); + } + + /** A different target does not make the destination free. */ + @Test + @Order(6) + void aRepeatedDestinationIsRejectedEvenWithADifferentTarget() { + expectRouteAlreadyExists( + ec2() + .formParam("Action", "CreateRoute") + .formParam("RouteTableId", routeTableId) + .formParam("DestinationCidrBlock", IPV4_ROUTE) + .formParam("NatGatewayId", NAT_GATEWAY), + IPV4_ROUTE); + } + + /** Every rejection above left the table exactly as test 1 built it. */ + @Test + @Order(7) + void noRejectedCreateChangedTheTable() { + describe().body(hasXPath(ROUTE_COUNT, equalTo("4"))); + } + + /** + * ReplaceRoute matches the first route with the destination. With duplicates barred there is + * only one, so the replace is unambiguous and leaves no stale copy behind. + */ + @Test + @Order(8) + void replaceRouteRetargetsTheOnlyRouteWithThatDestination() { + ec2() + .formParam("Action", "ReplaceRoute") + .formParam("RouteTableId", routeTableId) + .formParam("DestinationCidrBlock", IPV4_ROUTE) + .formParam("GatewayId", OTHER_GATEWAY) + .when() + .post("/") + .then() + .statusCode(200); + + describe() + .body(hasXPath(ROUTE_COUNT, equalTo("4"))) + .body(hasXPath("count(//*[local-name()='routeSet']/*[local-name()='item']" + + "[*[local-name()='destinationCidrBlock']='" + IPV4_ROUTE + "'])", + equalTo("1"))) + .body("DescribeRouteTablesResponse.routeTableSet.item.routeSet.item" + + ".find { it.destinationCidrBlock == '" + IPV4_ROUTE + "' }.gatewayId", + equalTo(OTHER_GATEWAY)); + } + + /** + * DeleteRoute removes every route matching the destination. With duplicates barred that is + * exactly one, so a delete frees the destination rather than taking an unrelated route with it. + */ + @Test + @Order(9) + void deleteRouteRemovesOneRouteAndFreesTheDestination() { + ec2() + .formParam("Action", "DeleteRoute") + .formParam("RouteTableId", routeTableId) + .formParam("DestinationCidrBlock", IPV4_ROUTE) + .when() + .post("/") + .then() + .statusCode(200); + + describe().body(hasXPath(ROUTE_COUNT, equalTo("3"))); + + // Freed, so the destination can be created again. + createRoute("DestinationCidrBlock", IPV4_ROUTE).when().post("/").then().statusCode(200); + describe().body(hasXPath(ROUTE_COUNT, equalTo("4"))); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnInvocationAccountTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnInvocationAccountTest.java index 0eb0ac3c25..8a5008fc64 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnInvocationAccountTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnInvocationAccountTest.java @@ -66,6 +66,7 @@ class LambdaArnInvocationAccountTest { null, null, null, + null, null); InvokeResult result = service.invokeArn(functionArn, "{}".getBytes(), InvocationType.Event); @@ -125,6 +126,7 @@ class LambdaArnInvocationAccountTest { null, null, null, + null, null); InvokeResult versionResult = service.invokeArn( @@ -262,6 +264,7 @@ class LambdaArnInvocationAccountTest { null, null, null, + null, null); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaVpcSnapStartLoggingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaVpcSnapStartLoggingIntegrationTest.java new file mode 100644 index 0000000000..dd66994ee8 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaVpcSnapStartLoggingIntegrationTest.java @@ -0,0 +1,534 @@ +package io.github.hectorvent.floci.services.lambda; + +import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.ec2.model.Subnet; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.startsWith; + +/** + * VpcConfig, SnapStart and LoggingConfig must survive CreateFunction and + * UpdateFunctionConfiguration and read back from GetFunctionConfiguration / GetFunction. + * Terraform refreshes all three on every plan, so a field accepted and then dropped is a + * permanent non-converging diff rather than a cosmetic omission. + * + *

The request and response shapes deliberately differ: VpcConfigResponse adds VpcId and + * SnapStartResponse adds OptimizationStatus, neither of which the caller can send. + */ +@QuarkusTest +class LambdaVpcSnapStartLoggingIntegrationTest { + + private static final String BASE_PATH = "/2015-03-31"; + private static final String REGION = "us-east-1"; + private static final String SECURITY_GROUP_ID = "sg-0123456789abcdef0"; + + @Inject + Ec2Service ec2Service; + + private String subnetId; + private String expectedVpcId; + + @BeforeEach + void resolveSubnet() { + Subnet subnet = ec2Service.describeSubnets(REGION, List.of(), Map.of()).get(0); + subnetId = subnet.getSubnetId(); + expectedVpcId = subnet.getVpcId(); + } + + private void createFunction(String name, String extraJson) { + createFunction(name, "nodejs20.x", extraJson); + } + + /** + * SnapStart is only available on a subset of managed runtimes (Java 11+, Python 3.12+, + * .NET 8+); {@code nodejs20.x} is not among them. Tests that exercise SnapStart use this + * overload with a supported runtime so they don't lock in a create AWS would reject. + */ + private void createFunction(String name, String runtime, String extraJson) { + given() + .contentType("application/json") + .body(""" + { + "FunctionName": "%s", + "Runtime": "%s", + "Role": "arn:aws:iam::000000000000:role/lambda-role", + "Handler": "index.handler"%s + } + """.formatted(name, runtime, extraJson)) + .when() + .post(BASE_PATH + "/functions") + .then() + .statusCode(201); + } + + private String vpcConfigJson() { + return """ + , + "VpcConfig": { + "SubnetIds": ["%s"], + "SecurityGroupIds": ["%s"] + }""".formatted(subnetId, SECURITY_GROUP_ID); + } + + @Test + void createFunctionReturnsVpcConfigWithResolvedVpcId() { + given() + .contentType("application/json") + .body(""" + { + "FunctionName": "vpc-create-fn", + "Runtime": "nodejs20.x", + "Role": "arn:aws:iam::000000000000:role/lambda-role", + "Handler": "index.handler"%s + } + """.formatted(vpcConfigJson())) + .when() + .post(BASE_PATH + "/functions") + .then() + .statusCode(201) + .body("VpcConfig.SubnetIds", contains(subnetId)) + .body("VpcConfig.SecurityGroupIds", contains(SECURITY_GROUP_ID)) + .body("VpcConfig.VpcId", equalTo(expectedVpcId)) + .body("VpcConfig.Ipv6AllowedForDualStack", equalTo(false)); + } + + @Test + void getFunctionConfigurationReturnsVpcConfig() { + createFunction("vpc-get-config-fn", vpcConfigJson()); + + given() + .when() + .get(BASE_PATH + "/functions/vpc-get-config-fn/configuration") + .then() + .statusCode(200) + .body("VpcConfig.SubnetIds", contains(subnetId)) + .body("VpcConfig.SecurityGroupIds", contains(SECURITY_GROUP_ID)) + .body("VpcConfig.VpcId", equalTo(expectedVpcId)); + } + + @Test + void getFunctionReturnsVpcConfig() { + createFunction("vpc-get-fn", vpcConfigJson()); + + given() + .when() + .get(BASE_PATH + "/functions/vpc-get-fn") + .then() + .statusCode(200) + .body("Configuration.VpcConfig.SubnetIds", contains(subnetId)) + .body("Configuration.VpcConfig.SecurityGroupIds", contains(SECURITY_GROUP_ID)) + .body("Configuration.VpcConfig.VpcId", equalTo(expectedVpcId)); + } + + @Test + void updateFunctionConfigurationAttachesVpcAndRoundTrips() { + createFunction("vpc-update-fn", ""); + + given() + .contentType("application/json") + .body(""" + { + "VpcConfig": { + "SubnetIds": ["%s"], + "SecurityGroupIds": ["%s"] + } + } + """.formatted(subnetId, SECURITY_GROUP_ID)) + .when() + .put(BASE_PATH + "/functions/vpc-update-fn/configuration") + .then() + .statusCode(200) + .body("VpcConfig.SubnetIds", contains(subnetId)) + .body("VpcConfig.VpcId", equalTo(expectedVpcId)); + + given() + .when() + .get(BASE_PATH + "/functions/vpc-update-fn/configuration") + .then() + .statusCode(200) + .body("VpcConfig.SubnetIds", contains(subnetId)) + .body("VpcConfig.SecurityGroupIds", contains(SECURITY_GROUP_ID)) + .body("VpcConfig.VpcId", equalTo(expectedVpcId)); + } + + @Test + void vpcConfigIsAbsentWhenTheFunctionIsNotAttached() { + createFunction("vpc-absent-fn", ""); + + given() + .when() + .get(BASE_PATH + "/functions/vpc-absent-fn/configuration") + .then() + .statusCode(200) + .body("VpcConfig", nullValue()); + } + + @Test + void unknownSubnetStillRoundTripsWithoutVpcId() { + createFunction("vpc-unmanaged-subnet-fn", """ + , + "VpcConfig": { + "SubnetIds": ["subnet-ffffffffffffffff0"], + "SecurityGroupIds": ["%s"] + }""".formatted(SECURITY_GROUP_ID)); + + given() + .when() + .get(BASE_PATH + "/functions/vpc-unmanaged-subnet-fn/configuration") + .then() + .statusCode(200) + .body("VpcConfig.SubnetIds", contains("subnet-ffffffffffffffff0")) + .body("VpcConfig.VpcId", nullValue()); + } + + @Test + void snapStartAndLoggingConfigDefaultsArePopulatedWhenUnset() { + createFunction("defaults-fn", ""); + + given() + .when() + .get(BASE_PATH + "/functions/defaults-fn/configuration") + .then() + .statusCode(200) + .body("SnapStart.ApplyOn", equalTo("None")) + .body("SnapStart.OptimizationStatus", equalTo("Off")) + .body("LoggingConfig.LogFormat", equalTo("Text")) + .body("LoggingConfig.LogGroup", equalTo("/aws/lambda/defaults-fn")) + .body("LoggingConfig.ApplicationLogLevel", nullValue()) + .body("RuntimeVersionConfig.RuntimeVersionArn", startsWith("arn:aws:lambda:us-east-1::runtime:")); + } + + @Test + void snapStartRoundTripsAndOptimizationStatusIsResponseOnly() { + createFunction("snapstart-fn", "java21", """ + , + "SnapStart": {"ApplyOn": "PublishedVersions"}"""); + + given() + .when() + .get(BASE_PATH + "/functions/snapstart-fn/configuration") + .then() + .statusCode(200) + .body("SnapStart.ApplyOn", equalTo("PublishedVersions")) + .body("SnapStart.OptimizationStatus", equalTo("Off")); + + given() + .contentType("application/json") + .body("{}") + .when() + .post(BASE_PATH + "/functions/snapstart-fn/versions") + .then() + .statusCode(201) + .body("SnapStart.ApplyOn", equalTo("PublishedVersions")) + .body("SnapStart.OptimizationStatus", equalTo("On")); + } + + @Test + void updateFunctionConfigurationRoundTripsSnapStart() { + createFunction("snapstart-update-fn", "java21", ""); + + given() + .contentType("application/json") + .body("{\"SnapStart\": {\"ApplyOn\": \"PublishedVersions\"}}") + .when() + .put(BASE_PATH + "/functions/snapstart-update-fn/configuration") + .then() + .statusCode(200) + .body("SnapStart.ApplyOn", equalTo("PublishedVersions")); + + given() + .when() + .get(BASE_PATH + "/functions/snapstart-update-fn/configuration") + .then() + .statusCode(200) + .body("SnapStart.ApplyOn", equalTo("PublishedVersions")); + } + + @Test + void snapStartRejectsValueOutsideTheEnum() { + given() + .contentType("application/json") + .body(""" + { + "FunctionName": "snapstart-invalid-fn", + "Runtime": "nodejs20.x", + "Role": "arn:aws:iam::000000000000:role/lambda-role", + "Handler": "index.handler", + "SnapStart": {"ApplyOn": "Always"} + } + """) + .when() + .post(BASE_PATH + "/functions") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", equalTo("1 validation error detected: Value 'Always' at 'snapStart.applyOn' " + + "failed to satisfy constraint: Member must satisfy enum value set: " + + "[PublishedVersions, None]")); + } + + @Test + void jsonLoggingConfigRoundTripsWithLogLevels() { + createFunction("logging-json-fn", """ + , + "LoggingConfig": { + "LogFormat": "JSON", + "ApplicationLogLevel": "DEBUG", + "SystemLogLevel": "WARN", + "LogGroup": "/custom/log/group" + }"""); + + given() + .when() + .get(BASE_PATH + "/functions/logging-json-fn/configuration") + .then() + .statusCode(200) + .body("LoggingConfig.LogFormat", equalTo("JSON")) + .body("LoggingConfig.ApplicationLogLevel", equalTo("DEBUG")) + .body("LoggingConfig.SystemLogLevel", equalTo("WARN")) + .body("LoggingConfig.LogGroup", equalTo("/custom/log/group")); + } + + @Test + void jsonLoggingConfigDefaultsBothLogLevelsToInfo() { + createFunction("logging-json-default-fn", """ + , + "LoggingConfig": {"LogFormat": "JSON"}"""); + + given() + .when() + .get(BASE_PATH + "/functions/logging-json-default-fn/configuration") + .then() + .statusCode(200) + .body("LoggingConfig.LogFormat", equalTo("JSON")) + .body("LoggingConfig.ApplicationLogLevel", equalTo("INFO")) + .body("LoggingConfig.SystemLogLevel", equalTo("INFO")) + .body("LoggingConfig.LogGroup", equalTo("/aws/lambda/logging-json-default-fn")); + } + + @Test + void updateFunctionConfigurationReplacesLoggingConfigWholesale() { + createFunction("logging-update-fn", """ + , + "LoggingConfig": { + "LogFormat": "JSON", + "ApplicationLogLevel": "DEBUG", + "LogGroup": "/custom/log/group" + }"""); + + given() + .contentType("application/json") + .body("{\"LoggingConfig\": {\"LogFormat\": \"Text\"}}") + .when() + .put(BASE_PATH + "/functions/logging-update-fn/configuration") + .then() + .statusCode(200) + .body("LoggingConfig.LogFormat", equalTo("Text")) + .body("LoggingConfig.LogGroup", equalTo("/aws/lambda/logging-update-fn")); + + given() + .when() + .get(BASE_PATH + "/functions/logging-update-fn/configuration") + .then() + .statusCode(200) + .body("LoggingConfig.LogFormat", equalTo("Text")) + .body("LoggingConfig.ApplicationLogLevel", nullValue()) + .body("LoggingConfig.LogGroup", equalTo("/aws/lambda/logging-update-fn")); + } + + @Test + void loggingConfigRejectsLogFormatOutsideTheEnum() { + given() + .contentType("application/json") + .body(""" + { + "FunctionName": "logging-invalid-fn", + "Runtime": "nodejs20.x", + "Role": "arn:aws:iam::000000000000:role/lambda-role", + "Handler": "index.handler", + "LoggingConfig": {"LogFormat": "YAML"} + } + """) + .when() + .post(BASE_PATH + "/functions") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", equalTo("1 validation error detected: Value 'YAML' at 'loggingConfig.logFormat' " + + "failed to satisfy constraint: Member must satisfy enum value set: [JSON, Text]")); + } + + @Test + void loggingConfigRejectsApplicationLogLevelOutsideTheEnum() { + given() + .contentType("application/json") + .body(""" + { + "FunctionName": "logging-invalid-app-level-fn", + "Runtime": "nodejs20.x", + "Role": "arn:aws:iam::000000000000:role/lambda-role", + "Handler": "index.handler", + "LoggingConfig": {"LogFormat": "JSON", "ApplicationLogLevel": "VERBOSE"} + } + """) + .when() + .post(BASE_PATH + "/functions") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", equalTo("1 validation error detected: Value 'VERBOSE' at " + + "'loggingConfig.applicationLogLevel' failed to satisfy constraint: Member must satisfy " + + "enum value set: [TRACE, DEBUG, INFO, WARN, ERROR, FATAL]")); + } + + @Test + void loggingConfigRejectsSystemLogLevelOutsideTheEnum() { + given() + .contentType("application/json") + .body(""" + { + "FunctionName": "logging-invalid-system-level-fn", + "Runtime": "nodejs20.x", + "Role": "arn:aws:iam::000000000000:role/lambda-role", + "Handler": "index.handler", + "LoggingConfig": {"LogFormat": "JSON", "SystemLogLevel": "TRACE"} + } + """) + .when() + .post(BASE_PATH + "/functions") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", equalTo("1 validation error detected: Value 'TRACE' at " + + "'loggingConfig.systemLogLevel' failed to satisfy constraint: Member must satisfy " + + "enum value set: [DEBUG, INFO, WARN]")); + } + + @Test + void loggingConfigRejectsLogGroupOutsideTheDocumentedPattern() { + given() + .contentType("application/json") + .body(""" + { + "FunctionName": "logging-invalid-group-fn", + "Runtime": "nodejs20.x", + "Role": "arn:aws:iam::000000000000:role/lambda-role", + "Handler": "index.handler", + "LoggingConfig": {"LogGroup": "my log group"} + } + """) + .when() + .post(BASE_PATH + "/functions") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + + @Test + void loggingConfigRejectsLogGroupLongerThanFiveHundredTwelveCharacters() { + String tooLong = "a".repeat(513); + + given() + .contentType("application/json") + .body(""" + { + "FunctionName": "logging-invalid-long-group-fn", + "Runtime": "nodejs20.x", + "Role": "arn:aws:iam::000000000000:role/lambda-role", + "Handler": "index.handler", + "LoggingConfig": {"LogGroup": "%s"} + } + """.formatted(tooLong)) + .when() + .post(BASE_PATH + "/functions") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + + @Test + void textFormatLogLevelsAreAcceptedButNeverStoredOrReturned() { + createFunction("logging-text-levels-fn", """ + , + "LoggingConfig": { + "LogFormat": "Text", + "ApplicationLogLevel": "DEBUG", + "SystemLogLevel": "WARN" + }"""); + + given() + .when() + .get(BASE_PATH + "/functions/logging-text-levels-fn/configuration") + .then() + .statusCode(200) + .body("LoggingConfig.LogFormat", equalTo("Text")) + .body("LoggingConfig.ApplicationLogLevel", nullValue()) + .body("LoggingConfig.SystemLogLevel", nullValue()); + } + + @Test + void updateFunctionConfigurationDetachesVpcConfigAndClearsVpcId() { + createFunction("vpc-detach-fn", vpcConfigJson()); + + given() + .when() + .get(BASE_PATH + "/functions/vpc-detach-fn/configuration") + .then() + .statusCode(200) + .body("VpcConfig.VpcId", equalTo(expectedVpcId)); + + given() + .contentType("application/json") + .body(""" + { + "VpcConfig": { + "SubnetIds": [], + "SecurityGroupIds": [] + } + } + """) + .when() + .put(BASE_PATH + "/functions/vpc-detach-fn/configuration") + .then() + .statusCode(200) + .body("VpcConfig", nullValue()); + + given() + .when() + .get(BASE_PATH + "/functions/vpc-detach-fn/configuration") + .then() + .statusCode(200) + .body("VpcConfig", nullValue()); + } + + @Test + void publishedVersionCarriesVpcAndLoggingConfig() { + createFunction("version-carry-fn", vpcConfigJson() + """ + , + "LoggingConfig": {"LogFormat": "JSON", "LogGroup": "/custom/version/group"}"""); + + given() + .contentType("application/json") + .body("{}") + .when() + .post(BASE_PATH + "/functions/version-carry-fn/versions") + .then() + .statusCode(201) + .body("Version", notNullValue()) + .body("VpcConfig.SubnetIds", contains(subnetId)) + .body("VpcConfig.VpcId", equalTo(expectedVpcId)) + .body("LoggingConfig.LogFormat", equalTo("JSON")) + .body("LoggingConfig.LogGroup", equalTo("/custom/version/group")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ram/RamIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ram/RamIntegrationTest.java new file mode 100644 index 0000000000..ed85860805 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ram/RamIntegrationTest.java @@ -0,0 +1,349 @@ +package io.github.hectorvent.floci.services.ram; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +/** + * Verifies the RAM restJson1 organization-sharing opt-in: + * {@code POST /enablesharingwithawsorganization} succeeds with or without a request body. + */ +@QuarkusTest +class RamIntegrationTest { + + private static final String AUTH_HEADER = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ram/aws4_request"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void enableSharingWithAwsOrganization_returnsTrue() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body("{}") + .when() + .post("/enablesharingwithawsorganization") + .then() + .statusCode(200) + .body("returnValue", equalTo(true)); + } + + @Test + void enableSharingWithAwsOrganization_withoutBody_returnsTrue() { + given() + .header("Authorization", AUTH_HEADER) + .when() + .post("/enablesharingwithawsorganization") + .then() + .statusCode(200) + .body("returnValue", equalTo(true)); + } + + @Test + void getResourceShareInvitations_returnsEmptyJson() { + // LZA's Custom::GetResourceShare Lambda pages this first; under organization + // sharing there are never invitations. The response must be JSON (restJson1) — + // an XML fallthrough here is exactly the SyntaxError seen in run b81f0999. + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body("{}") + .when() + .post("/getresourceshareinvitations") + .then() + .statusCode(200) + .contentType("application/json") + .body("resourceShareInvitations.size()", equalTo(0)); + } + + @Test + void ownerCanTagAndDeleteItsOwnShareOverHttp() { + // Mutations resolve the share within the caller's account, so the identity stamped at + // create time has to be the identity resolved at tag/delete time — otherwise LZA's + // AWS::RAM::ResourceShare teardown would fail against a share it had just created. + String shareArn = + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { + "name": "owner-mutation-share", + "principals": ["arn:aws:organizations::000000000000:ou/o-abc/ou-infra"], + "resourceArns": ["arn:aws:ec2:us-east-1:000000000000:transit-gateway/tgw-0own"] + } + """) + .when() + .post("/createresourceshare") + .then() + .statusCode(200) + .extract().path("resourceShare.resourceShareArn"); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { "resourceShareArn": "%s", "tags": [{"key": "Owner", "value": "network"}] } + """.formatted(shareArn)) + .when() + .post("/tagresource") + .then() + .statusCode(200); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .when() + .delete("/deleteresourceshare?resourceShareArn=" + shareArn) + .then() + .statusCode(200) + .body("returnValue", equalTo(true)); + } + + @Test + void getResourceSharesHonoursTheNameFilterOverHttp() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { + "name": "http-filtered-share", + "resourceArns": ["arn:aws:ec2:us-east-1:000000000000:transit-gateway/tgw-0flt"] + } + """) + .when() + .post("/createresourceshare") + .then() + .statusCode(200); + + // The filter has to be read off the body, not ignored: without it this returns every + // share the other tests in this class created. + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { "resourceOwner": "SELF", "name": "http-filtered-share" } + """) + .when() + .post("/getresourceshares") + .then() + .statusCode(200) + .body("resourceShares.size()", equalTo(1)) + .body("resourceShares[0].name", equalTo("http-filtered-share")); + } + + @Test + void deleteEchoesTheClientTokenAndSharesReportFeatureSet() { + String shareArn = + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { + "name": "token-echo-share", + "resourceArns": ["arn:aws:ec2:us-east-1:000000000000:transit-gateway/tgw-0tok"] + } + """) + .when() + .post("/createresourceshare") + .then() + .statusCode(200) + // Shares created through the API are STANDARD, not policy-derived. + .body("resourceShare.featureSet", equalTo("STANDARD")) + .extract().path("resourceShare.resourceShareArn"); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .when() + .delete("/deleteresourceshare?resourceShareArn=" + shareArn + "&clientToken=idem-1") + .then() + .statusCode(200) + .body("returnValue", equalTo(true)) + .body("clientToken", equalTo("idem-1")); + } + + /** + * Jackson's default readTree stops at the first complete value, so a body like + * {@code {} not-json} parsed as an empty object and the request executed. The JSON 1.0/1.1 + * controllers and the FIS REST controller all read with FAIL_ON_TRAILING_TOKENS; RAM was the + * outlier. + */ + @Test + void trailingContentAfterValidJsonIsSerializationException() { + for (String body : new String[] { + "{} not-json", + "{\"resourceOwner\":\"SELF\"}{\"second\":\"document\"}"}) { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(body) + .when() + .post("/getresourceshares") + .then() + .statusCode(400) + .body("__type", equalTo("SerializationException")); + } + } + + @Test + void malformedBodyIsRejectedAsSerializationException() { + // A body that is not JSON is a client error; without an explicit rejection the parse + // failure escapes as UncheckedIOException and the SDK sees a 500 InternalFailure. + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body("not json at all") + .when() + .post("/getresourceshares") + .then() + .statusCode(400) + .contentType("application/json") + .body("__type", equalTo("SerializationException")); + } + + @Test + void malformedInvitationsBodyIsRejectedAsSerializationException() { + // GetResourceShareInvitations ignores its body semantically (invitations are + // always empty under organization sharing), but a malformed body is still a + // client error, not a 200. + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body("not json at all") + .when() + .post("/getresourceshareinvitations") + .then() + .statusCode(400) + .contentType("application/json") + .body("__type", equalTo("SerializationException")); + } + + /** + * A present-but-unmodelled resourceOwner — including a non-string that {@code asText} + * coerces — has to reach the service check and come back as InvalidParameterException on the + * wire, which is the path LZA actually takes. + */ + @Test + void unmodelledResourceOwnerIsRejectedOnTheWire() { + for (String path : new String[] {"/getresourceshares", "/listprincipals", "/listresources"}) { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { "resourceOwner": "self" } + """) + .when() + .post(path) + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + } + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { "resourceOwner": 5 } + """) + .when() + .post("/getresourceshares") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + + } + + /** + * resourceOwner is a required member on all three read operations. Substituting SELF for an + * absent one answered a question the caller never asked — and answered it with the caller's + * own shares, which is the more dangerous of the two branches to guess at. + */ + @Test + void missingResourceOwnerIsRejectedOnEveryReadPath() { + for (String path : new String[] {"/getresourceshares", "/listprincipals", "/listresources"}) { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body("{}") + .when() + .post(path) + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + } + + // An explicit null is absent too, not a third state. + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { "resourceOwner": null } + """) + .when() + .post("/getresourceshares") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + } + + @Test + void createThenGetResourceSharesAndListResources() { + String tgwArn = "arn:aws:ec2:us-east-1:000000000000:transit-gateway/tgw-0abc"; + String shareArn = + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { + "name": "us-east-1-tgw-share", + "principals": ["arn:aws:organizations::000000000000:ou/o-abc/ou-infra"], + "resourceArns": ["%s"] + } + """.formatted(tgwArn)) + .when() + .post("/createresourceshare") + .then() + .statusCode(200) + .body("resourceShare.name", equalTo("us-east-1-tgw-share")) + .body("resourceShare.status", equalTo("ACTIVE")) + .extract().path("resourceShare.resourceShareArn"); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { "resourceOwner": "SELF" } + """) + .when() + .post("/getresourceshares") + .then() + .statusCode(200) + // Selected by name: the store is shared across the tests in this class. + .body("resourceShares.findAll { it.name == 'us-east-1-tgw-share' }.size()", equalTo(1)) + .body("resourceShares.find { it.name == 'us-east-1-tgw-share' }.owningAccountId", + equalTo("000000000000")); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { "resourceOwner": "SELF", "resourceShareArns": ["%s"] } + """.formatted(shareArn)) + .when() + .post("/listresources") + .then() + .statusCode(200) + .body("resources.size()", equalTo(1)) + .body("resources[0].arn", equalTo(tgwArn)) + .body("resources[0].type", equalTo("ec2:TransitGateway")) + .body("resources[0].resourceShareArn", equalTo(shareArn)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ram/RamResourceShareLifecycleConsumerTest.java b/src/test/java/io/github/hectorvent/floci/services/ram/RamResourceShareLifecycleConsumerTest.java new file mode 100644 index 0000000000..cbbce72cec --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ram/RamResourceShareLifecycleConsumerTest.java @@ -0,0 +1,214 @@ +package io.github.hectorvent.floci.services.ram; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.not; + +/** + * Wire-level tests for the RAM lifecycle operations LZA's TGW share flow needs beyond + * CreateResourceShare/GetResourceShares/ListResources: UpdateResourceShare, DeleteResourceShare, + * AssociateResourceShare, DisassociateResourceShare, ListPrincipals, TagResource, UntagResource. + * + *

New class, not appended to {@code RamIntegrationTest} (CS-001), so falsifiability isolates + * per operation. + */ +@QuarkusTest +class RamResourceShareLifecycleConsumerTest { + + private static final String AUTH_HEADER = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ram/aws4_request"; + private static final String TGW_ARN = "arn:aws:ec2:us-east-1:000000000000:transit-gateway/tgw-0lifecycle"; + private static final String OU_PRINCIPAL = "arn:aws:organizations::000000000000:ou/o-abc/ou-lifecycle"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + private String createShare(String name) { + return given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { "name": "%s", "resourceArns": ["%s"] } + """.formatted(name, TGW_ARN)) + .when() + .post("/createresourceshare") + .then() + .statusCode(200) + .extract().path("resourceShare.resourceShareArn"); + } + + @Test + void updateResourceShare_renamesAndTogglesAllowExternalPrincipals() { + String arn = createShare("lifecycle-update"); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { "resourceShareArn": "%s", "name": "renamed-share", "allowExternalPrincipals": true } + """.formatted(arn)) + .when() + .post("/updateresourceshare") + .then() + .statusCode(200) + .body("resourceShare.name", equalTo("renamed-share")) + .body("resourceShare.allowExternalPrincipals", equalTo(true)); + } + + @Test + void updateResourceShare_unknownArn_returns400() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { "resourceShareArn": "arn:aws:ram:us-east-1:000000000000:resource-share/does-not-exist" } + """) + .when() + .post("/updateresourceshare") + .then() + .statusCode(400) + .body("__type", equalTo("UnknownResourceException")); + } + + @Test + void deleteResourceShare_marksStatusDeleted() { + String arn = createShare("lifecycle-delete"); + + given() + .header("Authorization", AUTH_HEADER) + .queryParam("resourceShareArn", arn) + .when() + .delete("/deleteresourceshare") + .then() + .statusCode(200) + .body("returnValue", equalTo(true)); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { "resourceOwner": "SELF" } + """) + .when() + .post("/getresourceshares") + .then() + .statusCode(200) + .body("resourceShares.find { it.resourceShareArn == '%s' }.status".formatted(arn), equalTo("DELETED")); + } + + @Test + void associateThenDisassociateResourceShare_addsAndRemovesPrincipal() { + String arn = createShare("lifecycle-associate"); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { "resourceShareArn": "%s", "principals": ["%s"] } + """.formatted(arn, OU_PRINCIPAL)) + .when() + .post("/associateresourceshare") + .then() + .statusCode(200) + .body("resourceShareAssociations.size()", equalTo(1)) + .body("resourceShareAssociations[0].associatedEntity", equalTo(OU_PRINCIPAL)) + .body("resourceShareAssociations[0].associationType", equalTo("PRINCIPAL")) + .body("resourceShareAssociations[0].status", equalTo("ASSOCIATED")); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { "resourceOwner": "SELF" } + """) + .when() + .post("/listprincipals") + .then() + .statusCode(200) + .body("principals.id", hasItem(OU_PRINCIPAL)); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { "resourceShareArn": "%s", "principals": ["%s"] } + """.formatted(arn, OU_PRINCIPAL)) + .when() + .post("/disassociateresourceshare") + .then() + .statusCode(200) + .body("resourceShareAssociations[0].status", equalTo("DISASSOCIATED")); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { "resourceOwner": "SELF" } + """) + .when() + .post("/listprincipals") + .then() + .statusCode(200) + .body("principals.id", not(hasItem(OU_PRINCIPAL))); + } + + @Test + void tagThenUntagResource_addsAndRemovesTag() { + String arn = createShare("lifecycle-tags"); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { "resourceShareArn": "%s", "tags": [{ "key": "env", "value": "prod" }] } + """.formatted(arn)) + .when() + .post("/tagresource") + .then() + .statusCode(200); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { "resourceOwner": "SELF" } + """) + .when() + .post("/getresourceshares") + .then() + .statusCode(200) + .body("resourceShares.find { it.resourceShareArn == '%s' }.tags[0].key".formatted(arn), equalTo("env")) + .body("resourceShares.find { it.resourceShareArn == '%s' }.tags[0].value".formatted(arn), equalTo("prod")); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { "resourceShareArn": "%s", "tagKeys": ["env"] } + """.formatted(arn)) + .when() + .post("/untagresource") + .then() + .statusCode(200); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { "resourceOwner": "SELF" } + """) + .when() + .post("/getresourceshares") + .then() + .statusCode(200) + .body("resourceShares.find { it.resourceShareArn == '%s' }.tags.size()".formatted(arn), equalTo(0)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ram/RamServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/ram/RamServicePersistenceTest.java new file mode 100644 index 0000000000..0181ec93f4 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ram/RamServicePersistenceTest.java @@ -0,0 +1,75 @@ +package io.github.hectorvent.floci.services.ram; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.ram.model.ResourceShare; +import io.github.hectorvent.floci.services.ram.model.SharedResource; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** Verifies RAM organization settings and cross-account resource shares survive a restart. */ +class RamServicePersistenceTest { + + private static final String OWNER = "111111111111"; + private static final String ACCEPTER = "222222222222"; + private static final String TGW_ARN = + "arn:aws:ec2:us-east-1:111111111111:transit-gateway/tgw-0abc"; + + @Test + void resourceSharesAndOrganizationSettingSurviveRestart() { + SharedStorageFactory storage = new SharedStorageFactory(); + RamService first = serviceWithStorage(storage); + first.enableSharingWithAwsOrganization(); + ResourceShare created = first.createResourceShare( + "us-east-1-tgw-share", + List.of("arn:aws:organizations::000000000000:ou/o-abc/ou-infra"), + List.of(TGW_ARN), false, "us-east-1", OWNER); + + RamService reloaded = serviceWithStorage(storage); + + assertTrue(reloaded.isSharingWithOrganizationEnabled()); + List owned = reloaded.getResourceShares(OWNER, "SELF"); + assertEquals(1, owned.size()); + assertEquals(created.getResourceShareArn(), owned.getFirst().getResourceShareArn()); + assertEquals(created.getCreationTime(), owned.getFirst().getCreationTime()); + + List shared = reloaded.getResourceShares(ACCEPTER, "OTHER-ACCOUNTS"); + assertEquals(1, shared.size()); + List 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> stores = new HashMap<>(); + + private SharedStorageFactory() { + super(null, null); + } + + @Override + @SuppressWarnings("unchecked") + public AccountAwareStorageBackend create(String serviceName, + String fileName, + TypeReference> typeReference) { + return (AccountAwareStorageBackend) stores.computeIfAbsent( + fileName, ignored -> AccountAwareStorageBackend.inMemory("000000000000")); + } + } +} + diff --git a/src/test/java/io/github/hectorvent/floci/services/ram/RamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ram/RamServiceTest.java new file mode 100644 index 0000000000..51199f20c8 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ram/RamServiceTest.java @@ -0,0 +1,324 @@ +package io.github.hectorvent.floci.services.ram; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.ram.model.ResourceShare; +import io.github.hectorvent.floci.services.ram.model.SharedResource; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; + +import java.util.List; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * Resource-share semantics behind LZA's TGW share flow: the owning account creates a share + * (via {@code AWS::RAM::ResourceShare}), and the accepting account's Custom::GetResourceShare + * Lambda pages GetResourceShareInvitations (empty under organization sharing) then + * GetResourceShares(resourceOwner=OTHER-ACCOUNTS) filtering by owner + name, and finally + * Custom::GetResourceShareItem lists the shared resource ARNs via ListResources. + */ +class RamServiceTest { + + private static final String OWNER = "111111111111"; + private static final String ACCEPTER = "222222222222"; + private static final String OU_ARN = "arn:aws:organizations::000000000000:ou/o-abc123/ou-root-infra"; + private static final String TGW_ARN = "arn:aws:ec2:us-east-1:111111111111:transit-gateway/tgw-0abc"; + + private RamService service; + + @BeforeEach + void setUp() { + service = new RamService(new SharedStorageFactory()); + service.initializeStorage(); + } + + @Test + void deletedShareStopsExposingItsResourcesAndPrincipals() { + // Real RAM keeps a deleted share visible (status DELETED) for a retention + // window, but its resources and principals stop being consumable: a + // non-owning consumer must not discover AVAILABLE resources of a deleted + // share through ListResources or ListPrincipals. + ResourceShare share = service.createResourceShare( + "delete-me", List.of(OU_ARN), List.of(TGW_ARN), false, "us-east-1", OWNER); + service.deleteResourceShare(share.getResourceShareArn(), OWNER); + + assertTrue(service.listResources(ACCEPTER, "OTHER-ACCOUNTS", List.of()).isEmpty()); + assertTrue(service.listPrincipals(ACCEPTER, "OTHER-ACCOUNTS", List.of()).isEmpty()); + assertTrue(service.listResources(OWNER, "SELF", List.of()).isEmpty()); + + // The share itself remains readable with DELETED status. + List 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 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 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 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 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 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 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 active = service.getResourceShares(OWNER, "SELF", null, List.of(), "ACTIVE"); + assertEquals(1, active.size()); + assertEquals("live", active.get(0).getName()); + + List 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> stores = new HashMap<>(); + + private SharedStorageFactory() { + super(null, null); + } + + @Override + @SuppressWarnings("unchecked") + public AccountAwareStorageBackend create(String serviceName, + String fileName, + TypeReference> typeReference) { + return (AccountAwareStorageBackend) stores.computeIfAbsent( + fileName, ignored -> AccountAwareStorageBackend.inMemory("000000000000")); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/servicequotas/RequestServiceQuotaIncreaseConsumerTest.java b/src/test/java/io/github/hectorvent/floci/services/servicequotas/RequestServiceQuotaIncreaseConsumerTest.java new file mode 100644 index 0000000000..9435403de4 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/servicequotas/RequestServiceQuotaIncreaseConsumerTest.java @@ -0,0 +1,172 @@ +package io.github.hectorvent.floci.services.servicequotas; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.matchesRegex; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Wire-level tests for {@code ServiceQuotasV20190624.RequestServiceQuotaIncrease}. + * + *

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). + * + *

Known limitation asserted here deliberately: the emulator does not + * persist increase requests. {@code GetRequestedServiceQuotaChange} and + * {@code ListRequestedServiceQuotaChangeHistory} are unsupported, so a request is + * observable only in the response that creates it. {@code Status} is therefore always + * {@code PENDING} and never advances. Documented in {@code docs/services/servicequotas.md} + * per CS-021. + */ +@QuarkusTest +class RequestServiceQuotaIncreaseConsumerTest { + + private static final String CONTENT_TYPE = "application/x-amz-json-1.1"; + private static final String AUTH_HEADER = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/servicequotas/aws4_request"; + private static final String TARGET = "ServiceQuotasV20190624.RequestServiceQuotaIncrease"; + private static final String CONCURRENT_BUILDS_QUOTA = "L-2DC20C30"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + private static io.restassured.response.Response request(String body) { + return given() + .contentType(CONTENT_TYPE) + .header("X-Amz-Target", TARGET) + .header("Authorization", AUTH_HEADER) + .body(body) + .when() + .post("/"); + } + + @Test + void requestIncrease_curatedQuota_returnsFullyPopulatedPendingRequest() { + request("{\"ServiceCode\":\"codebuild\",\"QuotaCode\":\"" + CONCURRENT_BUILDS_QUOTA + + "\",\"DesiredValue\":9000}") + .then() + .statusCode(200) + .body("RequestedQuota.Id", matchesRegex("[0-9A-F]{8}")) + .body("RequestedQuota.ServiceCode", equalTo("codebuild")) + .body("RequestedQuota.ServiceName", equalTo("AWS CodeBuild")) + .body("RequestedQuota.QuotaCode", equalTo(CONCURRENT_BUILDS_QUOTA)) + .body("RequestedQuota.QuotaName", equalTo("Concurrently running builds")) + .body("RequestedQuota.QuotaArn", equalTo( + "arn:aws:servicequotas:us-east-1:000000000000:codebuild/" + CONCURRENT_BUILDS_QUOTA)) + .body("RequestedQuota.DesiredValue", equalTo(9000.0f)) + .body("RequestedQuota.Status", equalTo("PENDING")) + .body("RequestedQuota.Unit", equalTo("None")) + .body("RequestedQuota.GlobalQuota", equalTo(false)) + .body("RequestedQuota.QuotaRequestedAtLevel", equalTo("ACCOUNT")) + .body("RequestedQuota.Requester", notNullValue()) + .body("RequestedQuota.Created", notNullValue()) + .body("RequestedQuota.LastUpdated", notNullValue()); + } + + @Test + void requestIncrease_generatedQuotaOnUnknownService_resolves() { + String quotaCode = ServiceQuotasService.syntheticQuotaCode("widgetfactory", "Resources per Region"); + request("{\"ServiceCode\":\"widgetfactory\",\"QuotaCode\":\"" + quotaCode + + "\",\"DesiredValue\":1}") + .then() + .statusCode(200) + .body("RequestedQuota.QuotaCode", equalTo(quotaCode)) + .body("RequestedQuota.QuotaName", equalTo("Resources per Region")) + .body("RequestedQuota.ServiceCode", equalTo("widgetfactory")); + } + + /** The id must be stable so a caller can correlate a repeated request. */ + @Test + void requestIncrease_sameQuotaTwice_returnsSameId() { + String body = "{\"ServiceCode\":\"lambda\",\"QuotaCode\":\"L-B99A9384\",\"DesiredValue\":2000}"; + String first = request(body).then().statusCode(200) + .extract().path("RequestedQuota.Id"); + String second = request(body).then().statusCode(200) + .extract().path("RequestedQuota.Id"); + assertEquals(first, second); + } + + @Test + void requestIncrease_withContextId_emitsQuotaContext() { + request("{\"ServiceCode\":\"lambda\",\"QuotaCode\":\"L-B99A9384\",\"DesiredValue\":10," + + "\"ContextId\":\"arn:aws:lambda:us-east-1:000000000000:function:fn\"}") + .then() + .statusCode(200) + .body("RequestedQuota.QuotaContext.ContextId", + equalTo("arn:aws:lambda:us-east-1:000000000000:function:fn")) + .body("RequestedQuota.QuotaContext.ContextScope", equalTo("RESOURCE")); + } + + /** An unmodelled-by-the-emulator field must be absent, not null-valued or invented. */ + @Test + void requestIncrease_withoutContextId_omitsQuotaContextAndCaseId() { + request("{\"ServiceCode\":\"lambda\",\"QuotaCode\":\"L-B99A9384\",\"DesiredValue\":10}") + .then() + .statusCode(200) + .body("RequestedQuota.QuotaContext", nullValue()) + .body("RequestedQuota.CaseId", nullValue()); + } + + @Test + void requestIncrease_unknownQuotaCode_returnsNoSuchResource() { + request("{\"ServiceCode\":\"codebuild\",\"QuotaCode\":\"L-DEADBEEF\",\"DesiredValue\":1}") + .then() + .statusCode(400) + .body("__type", equalTo("NoSuchResourceException")); + } + + @Test + void requestIncrease_missingQuotaCode_returnsIllegalArgument() { + request("{\"ServiceCode\":\"codebuild\",\"DesiredValue\":1}") + .then() + .statusCode(400) + .body("__type", equalTo("IllegalArgumentException")); + } + + @Test + void requestIncrease_missingServiceCode_returnsIllegalArgument() { + request("{\"QuotaCode\":\"" + CONCURRENT_BUILDS_QUOTA + "\",\"DesiredValue\":1}") + .then() + .statusCode(400) + .body("__type", equalTo("IllegalArgumentException")); + } + + @Test + void requestIncrease_missingDesiredValue_returnsIllegalArgument() { + request("{\"ServiceCode\":\"codebuild\",\"QuotaCode\":\"" + CONCURRENT_BUILDS_QUOTA + "\"}") + .then() + .statusCode(400) + .body("__type", equalTo("IllegalArgumentException")); + } + + @Test + void requestIncrease_negativeDesiredValue_returnsIllegalArgument() { + request("{\"ServiceCode\":\"codebuild\",\"QuotaCode\":\"" + CONCURRENT_BUILDS_QUOTA + + "\",\"DesiredValue\":-1}") + .then() + .statusCode(400) + .body("__type", equalTo("IllegalArgumentException")); + } + + /** Packet bounds are min=0 max=10000000000; one past the top must be rejected. */ + @Test + void requestIncrease_desiredValueAboveModelledMaximum_returnsIllegalArgument() { + request("{\"ServiceCode\":\"codebuild\",\"QuotaCode\":\"" + CONCURRENT_BUILDS_QUOTA + + "\",\"DesiredValue\":10000000001}") + .then() + .statusCode(400) + .body("__type", equalTo("IllegalArgumentException")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasIntegrationTest.java new file mode 100644 index 0000000000..a5f6cebe12 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasIntegrationTest.java @@ -0,0 +1,237 @@ +package io.github.hectorvent.floci.services.servicequotas; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * Integration tests for the Service Quotas service. + * Protocol: JSON 1.1 — Content-Type: application/x-amz-json-1.1, + * X-Amz-Target: ServiceQuotasV20190624.<Action> + */ +@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 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 appliedCodes = applied.path("Quotas.QuotaCode"); + List defaultCodes = defaults.path("Quotas.QuotaCode"); + assertEquals(appliedCodes, defaultCodes); + assertEquals("L-B99A9384", appliedCodes.getFirst()); + } + + @Test + void unknownAction_returnsUnknownOperation() { + // Deliberately a name AWS will never define. This test previously used + // RequestServiceQuotaIncrease, which then became supported and silently + // inverted the test's premise. A synthetic name keeps the assertion honest + // no matter which real operations get implemented later. + given() + .contentType(CONTENT_TYPE) + .header("X-Amz-Target", "ServiceQuotasV20190624.ThisOperationDoesNotExist") + .header("Authorization", AUTH_HEADER) + .body("{}") + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("UnknownOperationException")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasServiceTest.java new file mode 100644 index 0000000000..80d9dccee7 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasServiceTest.java @@ -0,0 +1,82 @@ +package io.github.hectorvent.floci.services.servicequotas; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ServiceQuotasServiceTest { + + private final ServiceQuotasService service = new ServiceQuotasService(new ObjectMapper()); + + @Test + void syntheticQuotaCodesAreStableAndWellFormed() { + String code = ServiceQuotasService.syntheticQuotaCode("widgetfactory", "Resources per Region"); + assertEquals(code, ServiceQuotasService.syntheticQuotaCode("widgetfactory", "Resources per Region")); + assertTrue(code.matches("L-[0-9A-F]{8}"), code); + } + + @Test + void everyListedQuotaResolvesThroughGetServiceQuota() { + for (String serviceCode : List.of("codebuild", "lambda", "widgetfactory")) { + for (ServiceQuotasService.QuotaDefinition quota : service.quotasFor(serviceCode)) { + ObjectNode response = service.getServiceQuota( + serviceCode, quota.quotaCode(), "us-east-1", "000000000000"); + assertEquals(quota.quotaCode(), response.path("Quota").path("QuotaCode").asText()); + assertTrue(response.path("Quota").path("Value").asDouble() >= 60.0); + } + } + } + + @Test + void codebuildIncludesConcurrentlyRunningBuilds() { + List codes = service.quotasFor("codebuild").stream() + .map(ServiceQuotasService.QuotaDefinition::quotaCode) + .toList(); + assertTrue(codes.contains("L-2DC20C30"), codes.toString()); + } + + @Test + void getServiceQuota_unknownCode_throwsNoSuchResource() { + AwsException e = assertThrows(AwsException.class, + () -> service.getServiceQuota("codebuild", "L-DOESNOTEX", "us-east-1", "000000000000")); + assertEquals("NoSuchResourceException", e.getErrorCode()); + } + + /** + * Unknown-but-well-formed service codes deliberately generate a quota catalog, so a code that + * cannot name a service at all has to be rejected up front — otherwise "!!!" comes back with + * three invented quotas instead of an error. The model constrains ServiceCode to at most 63 + * characters matching {@code [a-zA-Z][a-zA-Z0-9-]{1,63}}. + */ + @Test + void malformedServiceCodeIsRejected() { + for (String bad : List.of("!!!", "1codebuild", "-codebuild", "code build", "c", "a".repeat(64))) { + AwsException listing = assertThrows(AwsException.class, + () -> service.listServiceQuotas(bad, null, null, null, "us-east-1", "000000000000"), + "expected ListServiceQuotas to reject " + bad); + assertEquals("IllegalArgumentException", listing.getErrorCode(), bad); + assertEquals(400, listing.getHttpStatus(), bad); + + AwsException get = assertThrows(AwsException.class, + () -> service.getServiceQuota(bad, "L-2DC20C30", "us-east-1", "000000000000"), + "expected GetServiceQuota to reject " + bad); + assertEquals("IllegalArgumentException", get.getErrorCode(), bad); + } + } + + @Test + void wellFormedServiceCodesAreStillAccepted() { + // Including an unknown-but-valid code: generating a catalog for those is deliberate. + for (String good : List.of("codebuild", "widgetfactory", "elasticloadbalancing", "AWS-Thing", "ec")) { + assertTrue(service.listServiceQuotas(good, null, null, null, "us-east-1", "000000000000") + .withArray("Quotas").size() > 0, good); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesCvetServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesCvetServiceTest.java index c3cfb956ef..b277079161 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesCvetServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesCvetServiceTest.java @@ -3,6 +3,9 @@ package io.github.hectorvent.floci.services.ses; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.services.ses.model.CustomVerificationEmailTemplate; +import io.github.hectorvent.floci.services.ses.model.Tag; + +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -66,6 +69,29 @@ class SesCvetServiceTest { assertTrue(service.find("t1", REGION).isEmpty()); } + @Test + void create_invalidTags_isAtomic_templateNotPersisted() { + CustomVerificationEmailTemplate t = template("t1"); + t.setTags(List.of(new Tag("dup", "1"), new Tag("dup", "2"))); + assertThrows(AwsException.class, + () -> service.createCustomVerificationEmailTemplate(t, REGION)); + assertTrue(service.find("t1", REGION).isEmpty()); + } + + @Test + void update_preservesTags() { + service.createCustomVerificationEmailTemplate(template("t1"), REGION); + service.tag("t1", REGION, List.of(new Tag("env", "dev"))); + + CustomVerificationEmailTemplate replacement = template("t1"); + replacement.setTemplateSubject("Verify again"); + service.updateCustomVerificationEmailTemplate(replacement, REGION); + + CustomVerificationEmailTemplate updated = service.getCustomVerificationEmailTemplate("t1", REGION); + assertEquals("Verify again", updated.getTemplateSubject()); + assertEquals(List.of(new Tag("env", "dev")), updated.getTags()); + } + @Test void update_unknown_throwsDoesNotExist() { AwsException e = assertThrows(AwsException.class, diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpServiceTest.java index b4cbccc963..197092f4fb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpServiceTest.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.ses; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.services.ses.model.DedicatedIpPool; +import io.github.hectorvent.floci.services.ses.model.Tag; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -30,7 +31,7 @@ class SesDedicatedIpServiceTest { @Test void create_defaultsScalingModeToStandard() { - DedicatedIpPool pool = service.createDedicatedIpPool("pool-a", null, REGION); + DedicatedIpPool pool = service.createDedicatedIpPool("pool-a", null, null, REGION); assertEquals("pool-a", pool.getPoolName()); assertEquals("STANDARD", pool.getScalingMode()); assertTrue(service.dedicatedIpPoolExists("pool-a", REGION)); @@ -38,18 +39,58 @@ class SesDedicatedIpServiceTest { @Test void create_rejectsBlankName() { - assertThrows(AwsException.class, () -> service.createDedicatedIpPool(" ", "STANDARD", REGION)); + assertThrows(AwsException.class, () -> service.createDedicatedIpPool(" ", "STANDARD", null, REGION)); } @Test void create_rejectsInvalidScalingMode() { - assertThrows(AwsException.class, () -> service.createDedicatedIpPool("pool-a", "TURBO", REGION)); + assertThrows(AwsException.class, () -> service.createDedicatedIpPool("pool-a", "TURBO", null, REGION)); } @Test void create_rejectsDuplicate() { - service.createDedicatedIpPool("pool-a", "STANDARD", REGION); - assertThrows(AwsException.class, () -> service.createDedicatedIpPool("pool-a", "STANDARD", REGION)); + service.createDedicatedIpPool("pool-a", "STANDARD", null, REGION); + assertThrows(AwsException.class, () -> service.createDedicatedIpPool("pool-a", "STANDARD", null, REGION)); + } + + @Test + void create_storesTags() { + DedicatedIpPool pool = service.createDedicatedIpPool("pool-a", "STANDARD", + List.of(new Tag("env", "dev")), REGION); + assertEquals(List.of(new Tag("env", "dev")), pool.getTags()); + assertEquals(List.of(new Tag("env", "dev")), + service.getDedicatedIpPool("pool-a", REGION).getTags()); + } + + @Test + void create_invalidTags_isAtomic_poolNotPersisted() { + assertThrows(AwsException.class, () -> service.createDedicatedIpPool("pool-a", "STANDARD", + List.of(new Tag("aws:reserved", "x")), REGION)); + assertFalse(service.dedicatedIpPoolExists("pool-a", REGION)); + } + + @Test + void tag_mergesAndUntagRemoves() { + service.createDedicatedIpPool("pool-a", "STANDARD", List.of(new Tag("env", "dev")), REGION); + service.tag("pool-a", REGION, List.of(new Tag("env", "prod"), new Tag("owner", "alice"))); + assertEquals(List.of(new Tag("env", "prod"), new Tag("owner", "alice")), + service.listTags("pool-a", REGION)); + + service.untag("pool-a", REGION, List.of("env")); + assertEquals(List.of(new Tag("owner", "alice")), service.listTags("pool-a", REGION)); + } + + @Test + void untag_immediatelyAfterCreateWithImmutableTags_works() { + service.createDedicatedIpPool("pool-a", "STANDARD", List.of(new Tag("env", "dev")), REGION); + service.untag("pool-a", REGION, List.of("env")); + assertEquals(List.of(), service.listTags("pool-a", REGION)); + } + + @Test + void tag_missingPool_throws() { + assertThrows(AwsException.class, + () -> service.tag("ghost", REGION, List.of(new Tag("env", "dev")))); } @Test @@ -59,16 +100,16 @@ class SesDedicatedIpServiceTest { @Test void list_isSortedAndPerRegion() { - service.createDedicatedIpPool("pool-b", "STANDARD", REGION); - service.createDedicatedIpPool("pool-a", "STANDARD", REGION); - service.createDedicatedIpPool("pool-other", "STANDARD", "eu-west-1"); + service.createDedicatedIpPool("pool-b", "STANDARD", null, REGION); + service.createDedicatedIpPool("pool-a", "STANDARD", null, REGION); + service.createDedicatedIpPool("pool-other", "STANDARD", null, "eu-west-1"); assertEquals(List.of("pool-a", "pool-b"), service.listDedicatedIpPools(REGION)); } @Test void delete_removesPool() { - service.createDedicatedIpPool("pool-a", "MANAGED", REGION); + service.createDedicatedIpPool("pool-a", "MANAGED", null, REGION); service.deleteDedicatedIpPool("pool-a", REGION); assertFalse(service.dedicatedIpPoolExists("pool-a", REGION)); } diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesTagsTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesTagsTest.java index 5edffae091..b8b2c6591c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesTagsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesTagsTest.java @@ -180,6 +180,38 @@ class SesTagsTest { assertDoesNotThrow(() -> SesTags.validateMergedCount(0)); } + @Test + void merge_overwritesExistingKeys_appendsNewOnes_preservingInsertionOrder() { + List merged = SesTags.merge( + List.of(tag("env", "dev"), tag("owner", "alice")), + List.of(tag("env", "prod"), tag("team", "mail"))); + assertEquals(List.of(tag("env", "prod"), tag("owner", "alice"), tag("team", "mail")), merged); + } + + @Test + void merge_updatingExistingKeyAtFifty_ok() { + List existing = new ArrayList<>(); + for (int i = 0; i < 50; i++) { + existing.add(tag("k" + i, "v")); + } + List merged = assertDoesNotThrow(() -> SesTags.merge(existing, List.of(tag("k0", "v2")))); + assertEquals(50, merged.size()); + assertEquals(tag("k0", "v2"), merged.get(0)); + } + + @Test + void merge_overFiftyUniqueKeys_rejectedWithMergeMessage() { + List existing = new ArrayList<>(); + for (int i = 0; i < 50; i++) { + existing.add(tag("k" + i, "v")); + } + AwsException e = assertThrows(AwsException.class, + () -> SesTags.merge(existing, List.of(tag("k50", "v")))); + assertEquals("BadRequestException", e.getErrorCode()); + assertEquals("Maximum of 50 user tags are allowed per resource, consider reducing the number " + + "of tags in the request or delete existing tags and retry", e.getMessage()); + } + @Test void unicodeWhitespace_isAllowed() { // U+00A0 (no-break space) is a Unicode separator (\p{Z}), not the ASCII space. AWS accepts it diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesTagsV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesTagsV2IntegrationTest.java index fce4297cc0..11bba2b88f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesTagsV2IntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesTagsV2IntegrationTest.java @@ -256,7 +256,9 @@ class SesTagsV2IntegrationTest { @Test @Order(7) - void tagResource_emptyTags_returns400() { + void tagResource_emptyTags_isNoOp() { + // An empty Tags list is not an error (probe-confirmed): the existence check still runs, + // then the empty merge no-ops. tag-cs-1 was left with a single "owner" tag by @Order(1). String arn = "arn:aws:ses:us-east-1:000000000000:configuration-set/tag-cs-1"; given() .contentType("application/json") @@ -267,12 +269,37 @@ class SesTagsV2IntegrationTest { .when() .post("/v2/email/tags") .then() - .statusCode(400); + .statusCode(200); + + given() + .header("Authorization", AUTH_HEADER) + .queryParam("ResourceArn", arn) + .when() + .get("/v2/email/tags") + .then() + .statusCode(200) + .body("Tags", hasSize(1)) + .body("Tags[0].Key", equalTo("owner")); + + // The no-op still checks existence: an unknown resource stays NotFound. + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"ResourceArn": "arn:aws:ses:us-east-1:000000000000:configuration-set/nowhere", "Tags": []} + """) + .when() + .post("/v2/email/tags") + .then() + .statusCode(404); } @Test @Order(8) - void untagResource_missingTagKeys_returns400() { + void untagResource_missingTagKeys_returnsBareValidationException() { + // A missing/empty TagKeys member is a message-less ValidationException (probe-confirmed: + // AWS sends only the error-type header with an empty body; Floci's standard error body + // carries "message":null, which restJson1 SDKs parse identically). String arn = "arn:aws:ses:us-east-1:000000000000:configuration-set/tag-cs-1"; given() .header("Authorization", AUTH_HEADER) @@ -280,7 +307,10 @@ class SesTagsV2IntegrationTest { .when() .delete("/v2/email/tags") .then() - .statusCode(400); + .statusCode(400) + .header("X-Amzn-Errortype", containsString("ValidationException")) + .body("__type", equalTo("ValidationException")) + .body("message", nullValue()); } @Test @@ -319,8 +349,7 @@ class SesTagsV2IntegrationTest { @Order(11) void tagResource_arnRegionMismatch_returns400() { // AWS rejects TagResource on ARN/signing region mismatch with BadRequestException - // ("Failed to tag resource"). The behaviour differs from UntagResource, which - // routes the lookup to the ARN's region and surfaces NotFoundException instead. + // ("Failed to tag resource") for every resource type (probe-confirmed). String arn = "arn:aws:ses:eu-west-1:000000000000:configuration-set/tag-cs-1"; given() .contentType("application/json") @@ -337,9 +366,10 @@ class SesTagsV2IntegrationTest { @Test @Order(12) - void untagResource_arnRegionMismatch_returns404() { - // tag-cs-1 exists in us-east-1 but the ARN points to eu-west-1, so AWS - // returns NotFoundException with the resource-specific message. + void untagResource_arnRegionMismatch_returns400() { + // AWS rejects UntagResource on ARN/signing region mismatch with BadRequestException + // ("Failed to untag resource") for every resource type, configuration sets included + // (probe-confirmed). String arn = "arn:aws:ses:eu-west-1:000000000000:configuration-set/tag-cs-1"; given() .header("Authorization", AUTH_HEADER) @@ -348,8 +378,8 @@ class SesTagsV2IntegrationTest { .when() .delete("/v2/email/tags") .then() - .statusCode(404) - .body(containsString("No ConfigurationSet present with name: tag-cs-1")); + .statusCode(400) + .body(containsString("Failed to untag resource")); } @Test @@ -390,11 +420,11 @@ class SesTagsV2IntegrationTest { @Test @Order(15) - void listTagsForResource_template_arnRegionIgnored_usesSigningRegion() { - // For template ARNs AWS ignores the ARN region for ListTagsForResource and - // resolves the template against the signing region instead. The seeded - // tag-tpl-1 lives in us-east-1 and was left with a single "owner=alice" tag - // by the lifecycle case at @Order(2); an eu-west-1 ARN must still surface it. + void listTagsForResource_template_arnRegionMismatch_returnsEmpty() { + // AWS checks existence against the signing region but keys tags by the literal ARN + // (probe-confirmed): tag-tpl-1 exists in us-east-1 (seeded with tags by the + // lifecycle case at @Order(2)), so an eu-west-1 ARN passes the existence check yet + // addresses an ARN nothing was tagged under — 200 with an empty tag set. String arn = "arn:aws:ses:eu-west-1:000000000000:template/tag-tpl-1"; given() .header("Authorization", AUTH_HEADER) @@ -403,9 +433,7 @@ class SesTagsV2IntegrationTest { .get("/v2/email/tags") .then() .statusCode(200) - .body("Tags", hasSize(1)) - .body("Tags[0].Key", equalTo("owner")) - .body("Tags[0].Value", equalTo("alice")); + .body("Tags", hasSize(0)); } @Test @@ -515,9 +543,10 @@ class SesTagsV2IntegrationTest { @Test @Order(19) - void listTagsForResource_identity_arnRegionIgnored_usesSigningRegion() { - // tag-id-1 lives in us-east-1 and was left with a single "owner=alice" tag by - // the lifecycle case at @Order(16); an eu-west-1 ARN must still surface it. + void listTagsForResource_identity_arnRegionMismatch_returnsEmpty() { + // tag-id-1 exists in us-east-1 (tagged by the lifecycle case at @Order(16)), so the + // signing-region existence check passes, but the eu-west-1 ARN addresses an ARN nothing + // was tagged under — 200 with an empty tag set (probe-confirmed). String arn = "arn:aws:ses:eu-west-1:000000000000:identity/tag-id-1@example.com"; given() .header("Authorization", AUTH_HEADER) @@ -526,9 +555,7 @@ class SesTagsV2IntegrationTest { .get("/v2/email/tags") .then() .statusCode(200) - .body("Tags", hasSize(1)) - .body("Tags[0].Key", equalTo("owner")) - .body("Tags[0].Value", equalTo("alice")); + .body("Tags", hasSize(0)); } @Test @@ -631,6 +658,560 @@ class SesTagsV2IntegrationTest { .statusCode(404); } + @Test + @Order(23) + void tags_lifecycle_onContactList() { + // Seed: create a contact list with inline tags + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"ContactListName": "tag-cl-1", "Tags": [{"Key": "env", "Value": "dev"}]} + """) + .when() + .post("/v2/email/contact-lists") + .then() + .statusCode(200); + + String arn = "arn:aws:ses:us-east-1:000000000000:contact-list/tag-cl-1"; + + // Inline create tags are visible via ListTagsForResource + given() + .header("Authorization", AUTH_HEADER) + .queryParam("ResourceArn", arn) + .when() + .get("/v2/email/tags") + .then() + .statusCode(200) + .body("Tags", hasSize(1)) + .body("Tags[0].Key", equalTo("env")); + + // TagResource merges an additional key + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"ResourceArn": "%s", "Tags": [{"Key": "owner", "Value": "alice"}]} + """.formatted(arn)) + .when() + .post("/v2/email/tags") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH_HEADER) + .queryParam("ResourceArn", arn) + .when() + .get("/v2/email/tags") + .then() + .statusCode(200) + .body("Tags", hasSize(2)); + + // UntagResource removes a key + given() + .header("Authorization", AUTH_HEADER) + .queryParam("ResourceArn", arn) + .queryParam("TagKeys", "env") + .when() + .delete("/v2/email/tags") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH_HEADER) + .queryParam("ResourceArn", arn) + .when() + .get("/v2/email/tags") + .then() + .statusCode(200) + .body("Tags", hasSize(1)) + .body("Tags[0].Key", equalTo("owner")); + + // Region mismatch handling (probe-confirmed): UntagResource rejects an + // ARN/signing region mismatch, and ListTagsForResource passes the signing-region + // existence check but returns an empty set for the untagged mismatched ARN. + String euArn = "arn:aws:ses:eu-west-1:000000000000:contact-list/tag-cl-1"; + given() + .header("Authorization", AUTH_HEADER) + .queryParam("ResourceArn", euArn) + .queryParam("TagKeys", "k") + .when() + .delete("/v2/email/tags") + .then() + .statusCode(400) + .body(containsString("Failed to untag resource")); + + given() + .header("Authorization", AUTH_HEADER) + .queryParam("ResourceArn", euArn) + .when() + .get("/v2/email/tags") + .then() + .statusCode(200) + .body("Tags", hasSize(0)); + + // Free the one-list-per-account slot so later contact-list tests aren't order-dependent. + given() + .header("Authorization", AUTH_HEADER) + .when() + .delete("/v2/email/contact-lists/tag-cl-1") + .then() + .statusCode(200); + } + + @Test + @Order(24) + void tagResource_unknownContactList_returns404() { + String arn = "arn:aws:ses:us-east-1:000000000000:contact-list/missing-cl"; + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"ResourceArn": "%s", "Tags": [{"Key": "env", "Value": "dev"}]} + """.formatted(arn)) + .when() + .post("/v2/email/tags") + .then() + .statusCode(404) + .body(containsString("No ContactList present with name: missing-cl")); + } + + @Test + @Order(25) + void tags_lifecycle_onCustomVerificationEmailTemplate() { + // Seed: CVET creation requires a verified From identity + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"EmailIdentity": "tag-cvet-sender@floci.test"} + """) + .when() + .post("/v2/email/identities") + .then() + .statusCode(200); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { + "TemplateName": "tag-cvet-1", + "FromEmailAddress": "tag-cvet-sender@floci.test", + "TemplateSubject": "Verify", + "TemplateContent": "verify", + "SuccessRedirectionURL": "https://example.com/ok", + "FailureRedirectionURL": "https://example.com/no" + } + """) + .when() + .post("/v2/email/custom-verification-email-templates") + .then() + .statusCode(200); + + String arn = "arn:aws:ses:us-east-1:000000000000:custom-verification-email-template/tag-cvet-1"; + + given() + .header("Authorization", AUTH_HEADER) + .queryParam("ResourceArn", arn) + .when() + .get("/v2/email/tags") + .then() + .statusCode(200) + .body("Tags", hasSize(0)); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"ResourceArn": "%s", "Tags": [ + {"Key": "env", "Value": "dev"}, + {"Key": "owner", "Value": "alice"} + ]} + """.formatted(arn)) + .when() + .post("/v2/email/tags") + .then() + .statusCode(200); + + // UpdateCustomVerificationEmailTemplate must not wipe the tags + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { + "FromEmailAddress": "tag-cvet-sender@floci.test", + "TemplateSubject": "Verify again", + "TemplateContent": "verify", + "SuccessRedirectionURL": "https://example.com/ok", + "FailureRedirectionURL": "https://example.com/no" + } + """) + .when() + .put("/v2/email/custom-verification-email-templates/tag-cvet-1") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH_HEADER) + .queryParam("ResourceArn", arn) + .when() + .get("/v2/email/tags") + .then() + .statusCode(200) + .body("Tags", hasSize(2)); + + given() + .header("Authorization", AUTH_HEADER) + .queryParam("ResourceArn", arn) + .queryParam("TagKeys", "env") + .when() + .delete("/v2/email/tags") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH_HEADER) + .queryParam("ResourceArn", arn) + .when() + .get("/v2/email/tags") + .then() + .statusCode(200) + .body("Tags", hasSize(1)) + .body("Tags[0].Key", equalTo("owner")); + } + + @Test + @Order(26) + void tagResource_unknownCustomVerificationEmailTemplate_returns404() { + String arn = "arn:aws:ses:us-east-1:000000000000:custom-verification-email-template/missing-cvet"; + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"ResourceArn": "%s", "Tags": [{"Key": "env", "Value": "dev"}]} + """.formatted(arn)) + .when() + .post("/v2/email/tags") + .then() + .statusCode(404) + .body(containsString("No CustomVerificationEmailTemplate present with name: missing-cvet")); + } + + @Test + @Order(27) + void tags_lifecycle_onDedicatedIpPool() { + // Seed: create a pool with inline tags + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"PoolName": "tag-pool-1", "Tags": [{"Key": "env", "Value": "dev"}]} + """) + .when() + .post("/v2/email/dedicated-ip-pools") + .then() + .statusCode(200); + + String arn = "arn:aws:ses:us-east-1:000000000000:dedicated-ip-pool/tag-pool-1"; + + given() + .header("Authorization", AUTH_HEADER) + .queryParam("ResourceArn", arn) + .when() + .get("/v2/email/tags") + .then() + .statusCode(200) + .body("Tags", hasSize(1)) + .body("Tags[0].Key", equalTo("env")); + + // GetDedicatedIpPool keeps the AWS shape: no Tags member + given() + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/dedicated-ip-pools/tag-pool-1") + .then() + .statusCode(200) + .body("DedicatedIpPool.PoolName", equalTo("tag-pool-1")) + .body("DedicatedIpPool.Tags", nullValue()); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"ResourceArn": "%s", "Tags": [{"Key": "owner", "Value": "alice"}]} + """.formatted(arn)) + .when() + .post("/v2/email/tags") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH_HEADER) + .queryParam("ResourceArn", arn) + .queryParam("TagKeys", "env") + .when() + .delete("/v2/email/tags") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH_HEADER) + .queryParam("ResourceArn", arn) + .when() + .get("/v2/email/tags") + .then() + .statusCode(200) + .body("Tags", hasSize(1)) + .body("Tags[0].Key", equalTo("owner")); + } + + @Test + @Order(28) + void tagResource_unknownDedicatedIpPool_returns404() { + String arn = "arn:aws:ses:us-east-1:000000000000:dedicated-ip-pool/missing-pool"; + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"ResourceArn": "%s", "Tags": [{"Key": "env", "Value": "dev"}]} + """.formatted(arn)) + .when() + .post("/v2/email/tags") + .then() + .statusCode(404) + .body(containsString("No DedicatedIpPool present with name: missing-pool")); + } + + @Test + @Order(29) + void createDedicatedIpPool_invalidInlineTags_isAtomic_poolNotPersisted() { + // A semantic tag error must fail CreateDedicatedIpPool before the pool is persisted, so a + // corrected retry does not hit AlreadyExistsException. + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"PoolName": "atomic-tag-pool", "Tags": [ + {"Key": "dup", "Value": "1"}, + {"Key": "dup", "Value": "2"} + ]} + """) + .when() + .post("/v2/email/dedicated-ip-pools") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo("Cannot provide multiple tags with the same key")); + + given() + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/dedicated-ip-pools/atomic-tag-pool") + .then() + .statusCode(404); + } + + @Test + @Order(30) + void untagResource_cvet_arnRegionMismatch_returns400() { + // Probe-confirmed. + String arn = "arn:aws:ses:eu-west-1:000000000000:custom-verification-email-template/tag-cvet-1"; + given() + .header("Authorization", AUTH_HEADER) + .queryParam("ResourceArn", arn) + .queryParam("TagKeys", "k") + .when() + .delete("/v2/email/tags") + .then() + .statusCode(400) + .body(containsString("Failed to untag resource")); + } + + @Test + @Order(31) + void listTagsForResource_cvet_arnRegionMismatch_returnsEmpty() { + // tag-cvet-1 exists in us-east-1 (tagged by the lifecycle case at @Order(25)), so the + // signing-region existence check passes, but the eu-west-1 ARN addresses an ARN nothing + // was tagged under — 200 with an empty tag set (probe-confirmed). + String arn = "arn:aws:ses:eu-west-1:000000000000:custom-verification-email-template/tag-cvet-1"; + given() + .header("Authorization", AUTH_HEADER) + .queryParam("ResourceArn", arn) + .when() + .get("/v2/email/tags") + .then() + .statusCode(200) + .body("Tags", hasSize(0)); + } + + @Test + @Order(32) + void untagResource_dedicatedIpPool_arnRegionMismatch_returns400() { + // Probe-confirmed. + String arn = "arn:aws:ses:eu-west-1:000000000000:dedicated-ip-pool/tag-pool-1"; + given() + .header("Authorization", AUTH_HEADER) + .queryParam("ResourceArn", arn) + .queryParam("TagKeys", "k") + .when() + .delete("/v2/email/tags") + .then() + .statusCode(400) + .body(containsString("Failed to untag resource")); + } + + @Test + @Order(33) + void listTagsForResource_dedicatedIpPool_arnRegionMismatch_returnsEmpty() { + // tag-pool-1 exists in us-east-1 (tagged by the lifecycle case at @Order(27)), so the + // signing-region existence check passes, but the eu-west-1 ARN addresses an ARN nothing + // was tagged under — 200 with an empty tag set (probe-confirmed). + String arn = "arn:aws:ses:eu-west-1:000000000000:dedicated-ip-pool/tag-pool-1"; + given() + .header("Authorization", AUTH_HEADER) + .queryParam("ResourceArn", arn) + .when() + .get("/v2/email/tags") + .then() + .statusCode(200) + .body("Tags", hasSize(0)); + } + + @Test + @Order(34) + void listTagsForResource_foreignAccountArn_returns400_beforeExistenceCheck() { + // A foreign-account ARN is rejected before any existence check (probe-confirmed): + // the name here exists nowhere, yet the account error wins over NotFound. + String arn = "arn:aws:ses:us-east-1:999999999999:configuration-set/nowhere"; + given() + .header("Authorization", AUTH_HEADER) + .queryParam("ResourceArn", arn) + .when() + .get("/v2/email/tags") + .then() + .statusCode(400) + .body(containsString("Operations on a resource created in a different account is not allowed")); + } + + @Test + @Order(35) + void tagResource_foreignAccountArn_returns400() { + String arn = "arn:aws:ses:us-east-1:999999999999:configuration-set/tag-cs-1"; + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"ResourceArn": "%s", "Tags": [{"Key": "k", "Value": "v"}]} + """.formatted(arn)) + .when() + .post("/v2/email/tags") + .then() + .statusCode(400) + .body(containsString("Operations on a resource created in a different account is not allowed")); + } + + @Test + @Order(36) + void untagResource_foreignAccountAndRegionMismatch_accountErrorWins() { + // With both the account and the region mismatched, AWS reports the account error, + // not "Failed to untag resource" (probe-confirmed). + String arn = "arn:aws:ses:eu-west-1:999999999999:configuration-set/tag-cs-1"; + given() + .header("Authorization", AUTH_HEADER) + .queryParam("ResourceArn", arn) + .queryParam("TagKeys", "k") + .when() + .delete("/v2/email/tags") + .then() + .statusCode(400) + .body(containsString("Operations on a resource created in a different account is not allowed")); + } + + @Test + @Order(37) + void createCustomVerificationEmailTemplate_inlineTags_storedAndAtomic() { + // v2 CreateCustomVerificationEmailTemplate accepts Tags (probe-confirmed); the From + // identity tag-cvet-sender@floci.test was verified by the lifecycle case at @Order(25). + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { + "TemplateName": "tag-cvet-inline", + "FromEmailAddress": "tag-cvet-sender@floci.test", + "TemplateSubject": "Verify", + "TemplateContent": "verify", + "SuccessRedirectionURL": "https://example.com/ok", + "FailureRedirectionURL": "https://example.com/no", + "Tags": [{"Key": "env", "Value": "dev"}] + } + """) + .when() + .post("/v2/email/custom-verification-email-templates") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH_HEADER) + .queryParam("ResourceArn", + "arn:aws:ses:us-east-1:000000000000:custom-verification-email-template/tag-cvet-inline") + .when() + .get("/v2/email/tags") + .then() + .statusCode(200) + .body("Tags", hasSize(1)) + .body("Tags[0].Key", equalTo("env")); + + // A semantic tag error fails the create before anything is persisted, so a corrected + // retry does not hit AlreadyExistsException (probe-confirmed message and atomicity). + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { + "TemplateName": "tag-cvet-atomic", + "FromEmailAddress": "tag-cvet-sender@floci.test", + "TemplateSubject": "Verify", + "TemplateContent": "verify", + "SuccessRedirectionURL": "https://example.com/ok", + "FailureRedirectionURL": "https://example.com/no", + "Tags": [{"Key": "dup", "Value": "1"}, {"Key": "dup", "Value": "2"}] + } + """) + .when() + .post("/v2/email/custom-verification-email-templates") + .then() + .statusCode(400) + .body(containsString("Cannot provide multiple tags with the same key")); + + given() + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/custom-verification-email-templates/tag-cvet-atomic") + .then() + .statusCode(404); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { + "TemplateName": "tag-cvet-atomic", + "FromEmailAddress": "tag-cvet-sender@floci.test", + "TemplateSubject": "Verify", + "TemplateContent": "verify", + "SuccessRedirectionURL": "https://example.com/ok", + "FailureRedirectionURL": "https://example.com/no", + "Tags": [{"Key": "env", "Value": "dev"}] + } + """) + .when() + .post("/v2/email/custom-verification-email-templates") + .then() + .statusCode(200); + } + private static String tagArray(int from, int to) { StringBuilder sb = new StringBuilder("["); for (int i = from; i < to; i++) { diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index a0145bdae2..d8cfa3f053 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -360,3 +360,7 @@ floci: enabled: true bedrock-agent-core-control: enabled: true + servicequotas: + enabled: true + ram: + enabled: true diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml index e70826377e..0755f38ff0 100644 --- a/tools/docs/services.yaml +++ b/tools/docs/services.yaml @@ -108,6 +108,10 @@ services: doc: docs/services/neptune.md sources: - { path: src/main/java/io/github/hectorvent/floci/services/neptune/NeptuneQueryHandler.java, mode: switch } + - service: ram + doc: docs/services/ram.md + sources: + - { path: src/main/java/io/github/hectorvent/floci/services/ram/RamController.java, mode: rest } - service: rds doc: docs/services/rds.md sources: @@ -121,6 +125,10 @@ services: doc: docs/services/secrets-manager.md sources: - { path: src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerJsonHandler.java, mode: switch } + - service: servicequotas + doc: docs/services/servicequotas.md + sources: + - { path: src/main/java/io/github/hectorvent/floci/services/servicequotas/ServiceQuotasJsonHandler.java, mode: switch } - service: sqs doc: docs/services/sqs.md sources: