software.amazon.awssdk
cognitoidentityprovider
diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
index 95d674b958..b4a77d3f69 100644
--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
@@ -106,6 +106,7 @@ import software.amazon.awssdk.services.neptune.NeptuneClient;
import software.amazon.awssdk.services.oam.OamClient;
import software.amazon.awssdk.services.opensearch.OpenSearchClient;
import software.amazon.awssdk.services.organizations.OrganizationsClient;
+import software.amazon.awssdk.services.paymentcryptography.PaymentCryptographyClient;
import software.amazon.awssdk.services.pipes.PipesClient;
import software.amazon.awssdk.services.ram.RamClient;
import software.amazon.awssdk.services.rds.RdsClient;
@@ -1085,6 +1086,23 @@ public final class TestFixtures {
.build();
}
+ /**
+ * The Payment Cryptography control plane. The real service is an awsJson 1.0 service
+ * that signs for {@code payment-cryptography}, and the SDK talks to it through the
+ * {@code PaymentCryptographyControlPlane} target prefix.
+ */
+ public static PaymentCryptographyClient paymentCryptographyClient() {
+ return paymentCryptographyClient(REGION);
+ }
+
+ public static PaymentCryptographyClient paymentCryptographyClient(Region region) {
+ return PaymentCryptographyClient.builder()
+ .endpointOverride(ENDPOINT)
+ .region(region)
+ .credentialsProvider(CREDENTIALS)
+ .build();
+ }
+
public static SecretsManagerClient secretsManagerClient() {
return SecretsManagerClient.builder()
.endpointOverride(ENDPOINT)
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyTest.java
new file mode 100644
index 0000000000..2d6b74b7ae
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyTest.java
@@ -0,0 +1,264 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.awscore.exception.AwsServiceException;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.paymentcryptography.PaymentCryptographyClient;
+import software.amazon.awssdk.services.paymentcryptography.model.Alias;
+import software.amazon.awssdk.services.paymentcryptography.model.Key;
+import software.amazon.awssdk.services.paymentcryptography.model.KeyAlgorithm;
+import software.amazon.awssdk.services.paymentcryptography.model.KeyAttributes;
+import software.amazon.awssdk.services.paymentcryptography.model.KeyCheckValueAlgorithm;
+import software.amazon.awssdk.services.paymentcryptography.model.KeyClass;
+import software.amazon.awssdk.services.paymentcryptography.model.KeyState;
+import software.amazon.awssdk.services.paymentcryptography.model.KeyUsage;
+import software.amazon.awssdk.services.paymentcryptography.model.ListKeysResponse;
+import software.amazon.awssdk.services.paymentcryptography.model.Tag;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/**
+ * The Payment Cryptography control plane through the AWS SDK.
+ *
+ * The real service is an awsJson 1.0 service whose operations are targeted by
+ * {@code PaymentCryptographyControlPlane.}, so a real client is the only way to
+ * prove that the wire format, the request shape and the answer shape all agree.
+ */
+@DisplayName("Payment Cryptography")
+class PaymentCryptographyTest {
+
+ private static PaymentCryptographyClient client;
+ private static final List keyArns = new ArrayList<>();
+ private static final List aliasNames = new ArrayList<>();
+
+ @BeforeAll
+ static void setup() {
+ client = TestFixtures.paymentCryptographyClient();
+ }
+
+ @AfterAll
+ static void cleanup() {
+ if (client == null) {
+ return;
+ }
+ for (String alias : aliasNames) {
+ try {
+ client.deleteAlias(a -> a.aliasName(alias));
+ } catch (Exception ignored) {
+ // The key may already be gone, and real AWS refuses to delete an alias of one.
+ }
+ }
+ for (String arn : keyArns) {
+ try {
+ client.deleteKey(k -> k.keyIdentifier(arn));
+ } catch (Exception ignored) {
+ // Real AWS wants a key disabled before it is deleted, and wants it gone by now.
+ }
+ }
+ client.close();
+ }
+
+ private static Key createAesKey() {
+ Key key = client.createKey(r -> r
+ .keyAttributes(a -> a
+ .keyAlgorithm(KeyAlgorithm.AES_256)
+ .keyClass(KeyClass.SYMMETRIC_KEY)
+ .keyUsage(KeyUsage.TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY)
+ .keyModesOfUse(m -> m.encrypt(true).decrypt(true)))
+ .exportable(true))
+ .key();
+ keyArns.add(key.keyArn());
+ return key;
+ }
+
+ /** The key identifier of an ARN: the part after the last slash. */
+ private static String keyIdOf(String arn) {
+ return arn.substring(arn.lastIndexOf('/') + 1);
+ }
+
+ @Test
+ void aKeyIsCreatedAndReadBackWithItsModesOfUse() {
+ Key created = createAesKey();
+
+ assertThat(created.keyArn()).isNotBlank();
+ assertThat(created.keyState()).isEqualTo(KeyState.CREATE_COMPLETE);
+ assertThat(created.keyCheckValueAlgorithm()).isEqualTo(KeyCheckValueAlgorithm.CMAC);
+ assertThat(created.keyCheckValue()).isNotBlank();
+ assertThat(created.enabled()).isTrue();
+ assertThat(created.exportable()).isTrue();
+
+ KeyAttributes attributes = created.keyAttributes();
+ assertThat(attributes.keyAlgorithm()).isEqualTo(KeyAlgorithm.AES_256);
+ assertThat(attributes.keyClass()).isEqualTo(KeyClass.SYMMETRIC_KEY);
+ assertThat(attributes.keyUsage()).isEqualTo(KeyUsage.TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY);
+ // The modes of use are a nested structure, and the answer must carry the ones asked for.
+ assertThat(attributes.keyModesOfUse()).isNotNull();
+ assertThat(attributes.keyModesOfUse().encrypt()).isTrue();
+ assertThat(attributes.keyModesOfUse().decrypt()).isTrue();
+
+ Key read = client.getKey(k -> k.keyIdentifier(created.keyArn())).key();
+ assertThat(read.keyArn()).isEqualTo(created.keyArn());
+ assertThat(read.keyAttributes().keyAlgorithm()).isEqualTo(KeyAlgorithm.AES_256);
+ assertThat(read.keyAttributes().keyModesOfUse().encrypt()).isTrue();
+ assertThat(read.keyAttributes().keyModesOfUse().decrypt()).isTrue();
+ assertThat(read.keyCheckValue()).isEqualTo(created.keyCheckValue());
+ }
+
+ @Test
+ void aKeyIsCreatedDisabledAndWithTags() {
+ Key key = client.createKey(r -> r
+ .keyAttributes(a -> a
+ .keyAlgorithm(KeyAlgorithm.AES_256)
+ .keyClass(KeyClass.SYMMETRIC_KEY)
+ .keyUsage(KeyUsage.TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY)
+ .keyModesOfUse(m -> m.encrypt(true)))
+ .exportable(false)
+ .enabled(false)
+ .tags(Tag.builder().key("owner").value("team").build()))
+ .key();
+ keyArns.add(key.keyArn());
+
+ assertThat(key.enabled()).isFalse();
+ assertThat(key.exportable()).isFalse();
+
+ Map tags = client.listTagsForResource(t -> t.resourceArn(key.keyArn())).tags()
+ .stream()
+ .collect(Collectors.toMap(Tag::key, Tag::value, (a, b) -> a));
+ assertThat(tags).containsEntry("owner", "team");
+ }
+
+ @Test
+ void theKeysAreListedAPageAtATime() {
+ createAesKey();
+ createAesKey();
+
+ ListKeysResponse first = client.listKeys(r -> r.maxResults(1));
+ assertThat(first.keys()).hasSize(1);
+ assertThat(first.nextToken()).isNotNull();
+
+ ListKeysResponse second = client.listKeys(r -> r.maxResults(1).nextToken(first.nextToken()));
+ assertThat(second.keys()).hasSize(1);
+ }
+
+ @Test
+ void theKeysOfTheRegionAreListed() {
+ Key key = createAesKey();
+
+ assertThat(client.listKeys(r -> r.maxResults(100)).keys())
+ .anySatisfy(listed -> assertThat(listed.keyArn()).isEqualTo(key.keyArn()));
+ }
+
+ @Test
+ void theAliasOfAKeyIsCreatedAndReadBack() {
+ Key key = createAesKey();
+ String alias = "alias/compat/" + keyIdOf(key.keyArn());
+ aliasNames.add(alias);
+
+ client.createAlias(a -> a.aliasName(alias).keyArn(key.keyArn()));
+
+ Alias read = client.getAlias(a -> a.aliasName(alias)).alias();
+ assertThat(read.aliasName()).isEqualTo(alias);
+ assertThat(read.keyArn()).isEqualTo(key.keyArn());
+ assertThat(client.listAliases(r -> r.maxResults(100)).aliases())
+ .anySatisfy(listed -> assertThat(listed.aliasName()).isEqualTo(alias));
+ }
+
+ @Test
+ void aKeyIsTaggedAndTheTagsAreListed() {
+ Key key = createAesKey();
+
+ client.tagResource(t -> t
+ .resourceArn(key.keyArn())
+ .tags(Tag.builder().key("owner").value("compat").build()));
+
+ Map tags = client.listTagsForResource(t -> t.resourceArn(key.keyArn())).tags()
+ .stream()
+ .collect(Collectors.toMap(Tag::key, Tag::value, (a, b) -> a));
+ assertThat(tags).containsEntry("owner", "compat");
+ }
+
+ /**
+ * A delete answers with the key it deleted, its state DELETE_PENDING and the
+ * moment it is deleted, so a caller reads the key and not an empty answer.
+ */
+ @Test
+ void aDeletedKeyIsAnsweredWithTheKey() {
+ Key created = createAesKey();
+
+ Key deleted = client.deleteKey(k -> k.keyIdentifier(created.keyArn())).key();
+
+ assertThat(deleted).isNotNull();
+ assertThat(deleted.keyArn()).isEqualTo(created.keyArn());
+ assertThat(deleted.keyState()).isEqualTo(KeyState.DELETE_PENDING);
+ assertThat(deleted.deletePendingTimestamp()).isNotNull();
+ assertThat(deleted.enabled()).isFalse();
+ }
+
+ /** A listing names the state of the keys it wants, and the service answers with those keys alone. */
+ @Test
+ void theKeysAreListedByTheirState() {
+ Key key = createAesKey();
+
+ assertThat(client.listKeys(r -> r.keyState(KeyState.CREATE_COMPLETE).maxResults(100)).keys())
+ .anySatisfy(listed -> assertThat(listed.keyArn()).isEqualTo(key.keyArn()));
+ assertThat(client.listKeys(r -> r.keyState(KeyState.DELETE_PENDING).maxResults(100)).keys())
+ .noneSatisfy(listed -> assertThat(listed.keyArn()).isEqualTo(key.keyArn()));
+ }
+
+ /**
+ * The key of an alias is optional, so an update naming no key removes the key
+ * the alias names, and the alias stays.
+ */
+ @Test
+ void anAliasIsDetachedFromItsKeyByAnUpdateNamingNoKey() {
+ Key key = createAesKey();
+ String alias = "alias/compat/detached-" + keyIdOf(key.keyArn());
+ aliasNames.add(alias);
+
+ client.createAlias(a -> a.aliasName(alias).keyArn(key.keyArn()));
+
+ Alias detached = client.updateAlias(a -> a.aliasName(alias)).alias();
+
+ assertThat(detached.aliasName()).isEqualTo(alias);
+ assertThat(detached.keyArn()).isNull();
+ assertThat(client.getAlias(a -> a.aliasName(alias)).alias().aliasName()).isEqualTo(alias);
+ }
+
+ /**
+ * A region the creating client did not sign for. It has to differ from the
+ * region of the suite, or the key would be in that region too and the key
+ * would be found.
+ */
+ private static Region anotherRegion() {
+ Region region = TestFixtures.region();
+ if (region.id().startsWith("cn-")) {
+ return region.id().equals("cn-northwest-1")
+ ? Region.of("cn-north-1") : Region.of("cn-northwest-1");
+ }
+ return Region.US_WEST_2.equals(region) ? Region.US_EAST_1 : Region.US_WEST_2;
+ }
+
+ @Test
+ void aKeyOfOneRegionIsNotFoundInAnother() {
+ Key key = createAesKey();
+ PaymentCryptographyClient elsewhere = TestFixtures.paymentCryptographyClient(anotherRegion());
+ try {
+ // The key is named by its ARN, as the model takes it: a bare id names no key at all.
+ assertThatThrownBy(() -> elsewhere.getKey(k -> k.keyIdentifier(key.keyArn())))
+ .isInstanceOf(AwsServiceException.class)
+ .satisfies(thrown -> assertThat(((AwsServiceException) thrown).awsErrorDetails()
+ .errorCode()).isEqualTo("ResourceNotFoundException"));
+ } finally {
+ elsewhere.close();
+ }
+ }
+}
diff --git a/docs/services/index.md b/docs/services/index.md
index 908ebeef60..da9116fb4b 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -34,6 +34,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [CloudHSM v2](cloudhsmv2.md) | `POST /` + `X-Amz-Target: BaldrApiService.*` | JSON 1.1 | 18 |
| [Kinesis](kinesis.md) | `POST /` + `X-Amz-Target: Kinesis_20131202.*` | JSON 1.1 | 29 |
| [Managed Service for Apache Flink](kinesisanalytics.md) | `POST /` + `X-Amz-Target: KinesisAnalytics_20180523.*` | JSON 1.1 | 15 |
+| [Payment Cryptography](payment-cryptography.md) | `POST /` + `X-Amz-Target: PaymentCryptographyControlPlane.*` | JSON 1.0 | 12 |
| [Secrets Manager](secrets-manager.md) | `POST /` + `X-Amz-Target: secretsmanager.*` | JSON 1.1 | 23 |
| [Step Functions](step-functions.md) | `POST /` + `X-Amz-Target: AmazonStatesService.*` | JSON 1.1 | 32 |
| [SWF](swf.md) | `POST /` + `X-Amz-Target: SimpleWorkflowService.*` | JSON 1.0 | 39 |
diff --git a/docs/services/payment-cryptography.md b/docs/services/payment-cryptography.md
new file mode 100644
index 0000000000..09d1b61c14
--- /dev/null
+++ b/docs/services/payment-cryptography.md
@@ -0,0 +1,93 @@
+# Payment Cryptography
+
+**Protocol:** JSON 1.0 (`X-Amz-Target: PaymentCryptographyControlPlane.*`)
+**Endpoint:** `POST http://localhost:4566/`
+
+## Supported Actions
+
+
+| Action | Description |
+| --- | --- |
+| `CreateKey` | Create a key with fresh AES-256 material |
+| `GetKey` | Get a key's attributes, state and check value |
+| `ListKeys` | List the keys of a region |
+| `DeleteKey` | Delete a key |
+| `CreateAlias` | Point an alias name at a key |
+| `GetAlias` | Get the key an alias name points at |
+| `ListAliases` | List the aliases of a region |
+| `UpdateAlias` | Point an alias name at another key |
+| `DeleteAlias` | Remove an alias name |
+| `TagResource` | Add tags to a key |
+| `UntagResource` | Remove tags from a key |
+| `ListTagsForResource` | List the tags of a key |
+
+
+## Emulation Behavior
+
+- **Real key material:** `CreateKey` generates 32 bytes of AES-256 material, and the
+ `KeyCheckValue` is the leftmost three bytes of the CMAC of sixteen zero bytes under
+ it, which is what the service computes for a `CMAC` check value. The material is
+ held by the key while the emulator runs and is not written to the store.
+- **Regional:** keys, aliases and tags all live in the region they were made in. The
+ service is regional, and so is this.
+- **Alias names are unique in a region, not in an account:** the same name may name a
+ key in two regions, and the two are two aliases. A name that is already taken in
+ the key's own region is a `ConflictException`.
+- **Tags are the region's:** they are not part of the replication process, so a key in
+ another region carries its own tag set, and tagging one leaves the others alone.
+- **Deletion:** `DeleteKey` removes the key and the aliases that name it, and answers
+ with the key, its state `DELETE_PENDING` and the moment its deletion takes effect.
+ A key that is gone does not come back: a tagging request for it is refused. The
+ service deletes a key the moment it is asked to, so the waiting period of
+ `DeleteKeyInDays` is read and checked but not waited for.
+- **Creating a key:** `CreateKey` takes `Exportable`, `Enabled` and `Tags`, and a key
+ created disabled or with tags comes back that way. The `KeyUsage` and the
+ `KeyModesOfUse` of the key are required, as the reference requires them. The answer
+ carries every mode of use the reference gives a key, the ones the key was not made
+ with as false, so a caller reading them finds a boolean for each of them. The check
+ value is a CMAC, which is the only algorithm this service computes, so a request
+ naming another one is refused.
+- **Which key a request may name:** `KeyIdentifier` takes the ARN of a key, the ARN of
+ an alias or the name of an alias, while `KeyArn` and `ResourceArn` take the ARN of
+ a key alone, as the reference states them. A request naming a key another way is
+ refused, and the permission check reads the same member the request does.
+- **Listing by state:** `ListKeys` takes a `KeyState` and answers with the keys in
+ that state alone, and with every key when it names none.
+- **An alias may name no key:** `UpdateAlias` names the key of an alias, and an update
+ that names none removes the key the alias names and leaves the alias. `CreateAlias`
+ refuses an alias without a key, as the reference does, though its model requires
+ only the name.
+- **Paging:** `ListKeys`, `ListAliases` and `ListTagsForResource` take `MaxResults`
+ and `NextToken`, and answer with one page and the token that asks for the next.
+- **Not yet emulated:** the data plane (`POST /encrypt` and the rest), the import and
+ export formats, and the multi-region replication operations.
+
+## Configuration
+
+| Variable | Default | Description |
+|---|---|---|
+| `FLOCI_SERVICES_PAYMENTCRYPTOGRAPHY_ENABLED` | `true` | Enable or disable the service |
+
+## Examples
+
+```bash
+export AWS_ENDPOINT_URL=http://localhost:4566
+
+# Create a key
+KEY_ARN=$(aws payment-cryptography create-key \
+ --key-attributes 'KeyAlgorithm=AES_256,KeyClass=SYMMETRIC_KEY,KeyUsage=TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY,KeyModesOfUse={Encrypt=true,Decrypt=true}' \
+ --exportable \
+ --query Key.KeyArn --output text)
+
+# Name it
+aws payment-cryptography create-alias \
+ --alias-name alias/team/card-key --key-arn "$KEY_ARN"
+
+# Tag it
+aws payment-cryptography tag-resource \
+ --resource-arn "$KEY_ARN" \
+ --tags Key=Origin,Value=PRIMARY
+
+# Read it back
+aws payment-cryptography get-key --key-identifier "$KEY_ARN"
+```
diff --git a/mkdocs.yml b/mkdocs.yml
index 4088f65317..0d8329612a 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -170,6 +170,7 @@ nav:
- AppIntegrations: services/appintegrations.md
- Amazon Data Lifecycle Manager: services/dlm.md
- ACM: services/acm.md
+ - Payment Cryptography: services/payment-cryptography.md
- ECS: services/ecs.md
- ECR: services/ecr.md
- AWS Resource Groups: services/resource-groups.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 150f887c22..e772b87eeb 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -366,6 +366,7 @@ public interface EmulatorConfig {
CloudWatchLogsStorageConfig cloudwatchlogs();
CloudWatchMetricsStorageConfig cloudwatchmetrics();
SecretsManagerStorageConfig secretsmanager();
+ PaymentCryptographyStorageConfig paymentcryptography();
AcmStorageConfig acm();
OpenSearchStorageConfig opensearch();
AppConfigStorageConfig appconfig();
@@ -488,6 +489,13 @@ public interface EmulatorConfig {
long flushIntervalMs();
}
+ interface PaymentCryptographyStorageConfig {
+ Optional mode();
+
+ @WithDefault("5000")
+ long flushIntervalMs();
+ }
+
interface AcmStorageConfig {
Optional mode();
@@ -771,6 +779,7 @@ public interface EmulatorConfig {
CloudWatchLogsServiceConfig cloudwatchlogs();
CloudWatchMetricsServiceConfig cloudwatchmetrics();
SecretsManagerServiceConfig secretsmanager();
+ PaymentCryptographyServiceConfig paymentcryptography();
ApiGatewayV2ServiceConfig apigatewayv2();
KinesisServiceConfig kinesis();
FirehoseServiceConfig firehose();
@@ -2112,6 +2121,11 @@ public interface EmulatorConfig {
boolean enabled();
}
+ interface PaymentCryptographyServiceConfig {
+ @WithDefault("true")
+ boolean enabled();
+ }
+
interface SecretsManagerServiceConfig {
@WithDefault("true")
boolean enabled();
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java
index 80dca3800e..e6becb632a 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.dynamodb.DynamoDbResponses;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamsJsonHandler;
import io.github.hectorvent.floci.services.marketplace.MarketplaceJsonHandler;
import io.github.hectorvent.floci.services.networkfirewall.NetworkFirewallJsonHandler;
+import io.github.hectorvent.floci.services.paymentcryptography.PaymentCryptographyJsonHandler;
import io.github.hectorvent.floci.services.sns.SnsJsonHandler;
import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;
import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsJsonHandler;
@@ -62,6 +63,7 @@ public class AwsJsonController {
private final CloudControlJsonHandler cloudControlJsonHandler;
private final SwfJsonHandler swfJsonHandler;
private final NetworkFirewallJsonHandler networkFirewallJsonHandler;
+ private final PaymentCryptographyJsonHandler paymentCryptographyJsonHandler;
private final MarketplaceJsonHandler marketplaceJsonHandler;
private final VerifiedPermissionsJsonHandler verifiedPermissionsJsonHandler;
private final BcmPricingCalculatorJsonHandler bcmPricingCalculatorJsonHandler;
@@ -78,6 +80,7 @@ public class AwsJsonController {
CloudControlJsonHandler cloudControlJsonHandler,
SwfJsonHandler swfJsonHandler,
NetworkFirewallJsonHandler networkFirewallJsonHandler,
+ PaymentCryptographyJsonHandler paymentCryptographyJsonHandler,
MarketplaceJsonHandler marketplaceJsonHandler,
VerifiedPermissionsJsonHandler verifiedPermissionsJsonHandler,
BcmPricingCalculatorJsonHandler bcmPricingCalculatorJsonHandler,
@@ -95,6 +98,7 @@ public class AwsJsonController {
this.cloudControlJsonHandler = cloudControlJsonHandler;
this.swfJsonHandler = swfJsonHandler;
this.networkFirewallJsonHandler = networkFirewallJsonHandler;
+ this.paymentCryptographyJsonHandler = paymentCryptographyJsonHandler;
this.marketplaceJsonHandler = marketplaceJsonHandler;
this.verifiedPermissionsJsonHandler = verifiedPermissionsJsonHandler;
this.bcmPricingCalculatorJsonHandler = bcmPricingCalculatorJsonHandler;
@@ -187,6 +191,10 @@ public class AwsJsonController {
action, request, region, regionResolver.getAccountId());
case "network-firewall" -> networkFirewallJsonHandler.handle(
action, request, region, regionResolver.getAccountId());
+ // The control plane of Payment Cryptography is an awsJson 1.0 service: the
+ // AWS SDK sends application/x-amz-json-1.0 and targets
+ // PaymentCryptographyControlPlane..
+ case "paymentcryptography" -> paymentCryptographyJsonHandler.handle(action, request, region);
case "marketplace" -> marketplaceJsonHandler.handle(action, request, region);
case "verifiedpermissions" -> verifiedPermissionsJsonHandler.handle(action, request, region);
case "bcm-pricing-calculator" -> bcmPricingCalculatorJsonHandler.handle(action, request, region);
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/RequestConstraintCheck.java b/src/main/java/io/github/hectorvent/floci/core/common/RequestConstraintCheck.java
index 30141cb358..e094b8dab6 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/RequestConstraintCheck.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/RequestConstraintCheck.java
@@ -78,6 +78,7 @@ public final class RequestConstraintCheck {
case "structure", "map" -> value.isObject();
case "list" -> value.isArray();
case "string" -> value.isTextual();
+ case "boolean" -> value.isBoolean();
case "integer", "long" -> value.isIntegralNumber() && value.canConvertToLong();
default -> false;
};
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/RequestResources.java b/src/main/java/io/github/hectorvent/floci/core/common/RequestResources.java
index 72300aea28..3482912919 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/RequestResources.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/RequestResources.java
@@ -374,22 +374,23 @@ public final class RequestResources {
}
/**
- * The ARN of a resource of a type whose service follows its name with an id it mints: the one {@code stored}
- * finds the caller's resource of that name under in the Region, or else the ARN with that id open; any other
- * type's as rendered.
+ * The ARN of a resource the namespace's service stores under the name the request gives: the one {@code stored}
+ * finds the caller's resource of that name under in the Region.
+ *
+ * The service is asked for every type of the namespace, not only for the ones whose ARN carries an id it
+ * mints, so a service may answer for a type whose ARN it does not mint: a key an alias names is the key the
+ * alias points at. A type whose service follows its name with an id it mints has that id open when the service
+ * stores none, and any other type's is as rendered.
*/
private static String withId(String arn, RequestResourceMembers.ArnFormat format, String type,
Map filling, StoredResourceArns stored, String region) {
- if (!format.minted()) {
- return arn;
- }
if (stored != null && filling.size() == 1) {
Optional found = stored.find(type, List.of(filling.values().iterator().next()), region);
if (found.isPresent()) {
return found.get();
}
}
- return arn + "/*";
+ return format.minted() ? arn + "/*" : arn;
}
/**
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 98c88a15ef..007a19b556 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
@@ -290,6 +290,16 @@ public class ResolvedServiceCatalog {
protocols(ServiceProtocol.QUERY, ServiceProtocol.JSON, ServiceProtocol.CBOR),
Set.of("GraniteServiceVersion20100801."), Set.of("monitoring"),
Set.of("GraniteServiceVersion20100801"), Set.of(), "CloudWatchVersion20130116."),
+ descriptor("paymentcryptography", "paymentcryptography",
+ config.services().paymentcryptography().enabled(), true,
+ "paymentcryptography",
+ storageMode(config.storage().services().paymentcryptography().mode(),
+ config.storage().mode()),
+ config.storage().services().paymentcryptography().flushIntervalMs(), null,
+ ServiceProtocol.JSON,
+ protocols(ServiceProtocol.JSON),
+ Set.of("PaymentCryptographyControlPlane."), Set.of("payment-cryptography"),
+ Set.of(), Set.of()),
descriptor("secretsmanager", "secretsmanager", config.services().secretsmanager().enabled(), true,
"secretsmanager", storageMode(config.storage().services().secretsmanager().mode(), config.storage().mode()),
config.storage().services().secretsmanager().flushIntervalMs(), null, ServiceProtocol.JSON,
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/StoredResourceArns.java b/src/main/java/io/github/hectorvent/floci/core/common/StoredResourceArns.java
index a2aefc802e..984fb113e7 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/StoredResourceArns.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/StoredResourceArns.java
@@ -4,15 +4,20 @@ import java.util.List;
import java.util.Optional;
/**
- * Finds the ARN a service stores a resource under, for a type of the request-resources table whose ARN carries an id
- * the service mints, which only the service knows: after the name a request gives ({@code connection//}),
- * or as all of it, a request naming the resource by members its ARN does not hold
+ * Finds the ARN a service stores a resource under, for a type of the request-resources table whose ARN only that
+ * service knows: after the name a request gives ({@code connection//}), or as all of it, a request naming
+ * the resource by members its ARN does not hold
* ({@code scalable-target/}, named by its service namespace, resource id and scalable dimension;
* {@code workgroup/}, named by its name).
*
+ * The reader asks for every type of the namespace, not only for the ones whose ARN carries an id the service
+ * mints, so a service may answer for a type whose ARN it does not mint: a key an alias names is the key the alias
+ * points at.
+ *
*
Implemented by the service that owns such resources or whose requests name them (EventBridge, for its
* connections and API destinations; Application Auto Scaling, for its scalable targets; Redshift Data, for the
- * Redshift Serverless workgroups it runs statements on); looked up lazily by {@code ResourceArnBuilder} through
+ * Redshift Serverless workgroups it runs statements on; Payment Cryptography, for the key an alias names);
+ * looked up lazily by {@code ResourceArnBuilder} through
* {@code Instance} for the namespace a request is of, so IAM never depends on that service
* directly.
*/
diff --git a/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyCrypto.java b/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyCrypto.java
new file mode 100644
index 0000000000..d12978c35e
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyCrypto.java
@@ -0,0 +1,141 @@
+package io.github.hectorvent.floci.services.paymentcryptography;
+
+import javax.crypto.Cipher;
+import javax.crypto.spec.SecretKeySpec;
+import java.security.GeneralSecurityException;
+import java.security.SecureRandom;
+import java.util.Arrays;
+import java.util.Locale;
+
+/**
+ * The cryptography a key record needs: its material, and its check value.
+ *
+ * The check value of an AES key is the leftmost three bytes of the CMAC of
+ * sixteen zero bytes under the key. That is what the service computes for a
+ * CMAC check value, and what the reference implementation its samples use
+ * computes.
+ *
+ *
The CMAC is the one RFC 4493 gives, so a key's check value is the one
+ * the standard's vectors give and a message of any length is authenticated
+ * the way the standard says.
+ */
+final class PaymentCryptographyCrypto {
+
+ /** The block size of AES, in bytes. */
+ private static final int BLOCK_SIZE = 16;
+
+ private static final byte[] ZERO_BLOCK = new byte[BLOCK_SIZE];
+
+ /** The Rijndael constant the subkey derivation exclusive-oreds in when the shift carries out. */
+ private static final int RB = 0x87;
+
+ private PaymentCryptographyCrypto() {
+ }
+
+ /** Fresh AES-256 material, as hexadecimal. */
+ static String randomAes256Hex(SecureRandom random) {
+ byte[] material = new byte[32];
+ random.nextBytes(material);
+ return toHex(material);
+ }
+
+ /** The check value of an AES key: the leftmost three bytes of the CMAC of sixteen zero bytes. */
+ static String checkValue(String keyHex) {
+ byte[] mac = cmac(fromHex(keyHex), ZERO_BLOCK);
+ return toHex(Arrays.copyOf(mac, 3)).toUpperCase(Locale.ROOT);
+ }
+
+ /**
+ * The AES-CMAC of a message under a key, as RFC 4493 gives it.
+ *
+ *
The message is divided into blocks and chained as CBC-MAC. A last
+ * block of the block size is exclusive-ored with K1, and one shorter is
+ * padded with a single one bit and exclusive-ored with K2, as the RFC
+ * says.
+ */
+ static byte[] cmac(byte[] key, byte[] message) {
+ try {
+ byte[] k1 = shiftLeft(encrypt(ZERO_BLOCK, key));
+ byte[] k2 = shiftLeft(k1);
+ int blocks = (message.length + BLOCK_SIZE - 1) / BLOCK_SIZE;
+ boolean complete = message.length > 0 && message.length % BLOCK_SIZE == 0;
+ if (blocks == 0) {
+ blocks = 1;
+ }
+ byte[] last = new byte[BLOCK_SIZE];
+ int offset = (blocks - 1) * BLOCK_SIZE;
+ if (complete) {
+ System.arraycopy(message, offset, last, 0, BLOCK_SIZE);
+ last = xor(last, k1);
+ } else {
+ int remaining = message.length - offset;
+ System.arraycopy(message, offset, last, 0, remaining);
+ last[remaining] = (byte) 0x80;
+ last = xor(last, k2);
+ }
+ byte[] chain = ZERO_BLOCK;
+ for (int i = 0; i < blocks - 1; i++) {
+ byte[] block = new byte[BLOCK_SIZE];
+ System.arraycopy(message, i * BLOCK_SIZE, block, 0, BLOCK_SIZE);
+ chain = encrypt(xor(chain, block), key);
+ }
+ return encrypt(xor(chain, last), key);
+ } catch (GeneralSecurityException e) {
+ throw new IllegalStateException("the AES key could not be used", e);
+ }
+ }
+
+ /**
+ * A block shifted left by one bit, with Rijndael's Rb exclusive-ored in
+ * when the shift carried out of the top.
+ *
+ *
The bit that falls off the top of the block comes from the byte
+ * above it, so the carry travels down the block.
+ */
+ private static byte[] shiftLeft(byte[] block) {
+ byte[] shifted = new byte[BLOCK_SIZE];
+ int carry = 0;
+ for (int i = BLOCK_SIZE - 1; i >= 0; i--) {
+ int nextCarry = (block[i] & 0x80) != 0 ? 1 : 0;
+ shifted[i] = (byte) (((block[i] << 1) | carry) & 0xff);
+ carry = nextCarry;
+ }
+ if ((block[0] & 0x80) != 0) {
+ shifted[BLOCK_SIZE - 1] ^= (byte) RB;
+ }
+ return shifted;
+ }
+
+ private static byte[] xor(byte[] left, byte[] right) {
+ byte[] out = new byte[left.length];
+ for (int i = 0; i < left.length; i++) {
+ out[i] = (byte) (left[i] ^ right[i % right.length]);
+ }
+ return out;
+ }
+
+ /** One block of AES in ECB mode, the block cipher the CMAC is built on. */
+ private static byte[] encrypt(byte[] input, byte[] key) throws GeneralSecurityException {
+ Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
+ cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"));
+ return cipher.doFinal(input);
+ }
+
+ static String toHex(byte[] bytes) {
+ StringBuilder sb = new StringBuilder(bytes.length * 2);
+ for (byte b : bytes) {
+ sb.append(Character.forDigit((b >> 4) & 0x0f, 16));
+ sb.append(Character.forDigit(b & 0x0f, 16));
+ }
+ return sb.toString();
+ }
+
+ static byte[] fromHex(String hex) {
+ int length = hex.length() / 2;
+ byte[] out = new byte[length];
+ for (int i = 0; i < length; i++) {
+ out[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
+ }
+ return out;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyJsonHandler.java
new file mode 100644
index 0000000000..954654d33c
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyJsonHandler.java
@@ -0,0 +1,362 @@
+package io.github.hectorvent.floci.services.paymentcryptography;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.PaginatedResult;
+import io.github.hectorvent.floci.core.common.Pagination;
+import io.github.hectorvent.floci.services.paymentcryptography.model.PaymentCryptographyAlias;
+import io.github.hectorvent.floci.services.paymentcryptography.model.PaymentCryptographyKey;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.core.Response;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * The Payment Cryptography control plane.
+ *
+ *
The service's control plane is JSON 1.1: the operation is named in the
+ * {@code X-Amz-Target} header and the body is a JSON object.
+ */
+@ApplicationScoped
+public class PaymentCryptographyJsonHandler {
+
+ /** The error a bad page size or a bad token is refused with. */
+ private static final String PAGINATION_ERROR = "ValidationException";
+
+ private final PaymentCryptographyService service;
+
+ @Inject
+ public PaymentCryptographyJsonHandler(PaymentCryptographyService service) {
+ this.service = service;
+ }
+
+ /** The actions whose requests are checked against the vendored model constraints first. */
+ private static final Set MODEL_CHECKED = Set.of(
+ "CreateKey", "GetKey", "ListKeys", "DeleteKey",
+ "CreateAlias", "GetAlias", "ListAliases", "UpdateAlias", "DeleteAlias",
+ "TagResource", "UntagResource", "ListTagsForResource");
+
+ public Response handle(String action, JsonNode request, String region) {
+ if (MODEL_CHECKED.contains(action)) {
+ PaymentCryptographyRequestShapes.check(action, request);
+ }
+ return switch (action) {
+ case "CreateKey" -> Response.ok(createKey(request, region)).build();
+ case "GetKey" -> Response.ok(getKey(request, region)).build();
+ case "ListKeys" -> Response.ok(listKeys(request, region)).build();
+ case "DeleteKey" -> Response.ok(deleteKey(request, region)).build();
+ case "CreateAlias" -> Response.ok(createAlias(request, region)).build();
+ case "GetAlias" -> Response.ok(getAlias(request, region)).build();
+ case "ListAliases" -> Response.ok(listAliases(request, region)).build();
+ case "UpdateAlias" -> Response.ok(updateAlias(request, region)).build();
+ case "DeleteAlias" -> Response.ok(deleteAlias(request, region)).build();
+ case "TagResource" -> Response.ok(tagResource(request, region)).build();
+ case "UntagResource" -> Response.ok(untagResource(request, region)).build();
+ case "ListTagsForResource" -> Response.ok(listTagsForResource(request, region)).build();
+ default -> throw new AwsException("UnknownOperationException",
+ "Operation " + action + " is not supported by floci", 400);
+ };
+ }
+
+ // ---- keys ---------------------------------------------------------------
+
+ private Map createKey(JsonNode request, String region) {
+ JsonNode attributes = request.get("KeyAttributes");
+ if (attributes == null || !attributes.isObject()) {
+ throw new AwsException("ValidationException", "KeyAttributes is required", 400);
+ }
+ // The service requires the usage and the modes of use of a key, as the
+ // reference does: a key without them says nothing about what it is for.
+ if (!attributes.hasNonNull("KeyUsage")) {
+ throw new AwsException("ValidationException", "KeyAttributes.KeyUsage is required", 400);
+ }
+ if (!attributes.hasNonNull("KeyModesOfUse")) {
+ throw new AwsException("ValidationException", "KeyAttributes.KeyModesOfUse is required", 400);
+ }
+ Map declared = new LinkedHashMap<>();
+ attributes.fields().forEachRemaining(entry -> {
+ // KeyModesOfUse is a nested structure, not a name: it is read below
+ // as its own map, and stringifying it here would lose the modes.
+ if (!"KeyModesOfUse".equals(entry.getKey())) {
+ declared.put(entry.getKey(), entry.getValue().asText());
+ }
+ });
+ // The check value of an AES key is a CMAC, which is the only algorithm this
+ // service computes, so a request naming another one is refused rather than
+ // answered with a check value of another kind.
+ if (request.hasNonNull("KeyCheckValueAlgorithm")
+ && !"CMAC".equals(request.get("KeyCheckValueAlgorithm").asText())) {
+ throw new AwsException("ValidationException",
+ "KeyCheckValueAlgorithm must be CMAC", 400);
+ }
+ // A key may be created disabled, and it may be created with tags.
+ boolean enabled = request.has("Enabled") ? request.path("Enabled").asBoolean(true) : true;
+ PaymentCryptographyKey key = service.createKey(region, declared, modesOfUse(attributes),
+ request.path("Exportable").asBoolean(false), enabled, tagsOf(request));
+ return Map.of("Key", keyObject(key));
+ }
+
+ /** The key operations name their key in {@code KeyIdentifier}. */
+ private static final String KEY_IDENTIFIER = "KeyIdentifier";
+
+ /** The alias operations name the key they point at in {@code KeyArn}. */
+ private static final String KEY_ARN = "KeyArn";
+
+ /** The tagging operations name their key in {@code ResourceArn}. */
+ private static final String RESOURCE_ARN = "ResourceArn";
+
+ /** The modes of use a key has, as the reference names them; the ones not asked for are false. */
+ private static final List MODES_OF_USE = List.of("Encrypt", "Decrypt", "Wrap", "Unwrap", "Generate",
+ "Sign", "Verify", "DeriveKey", "NoRestrictions");
+
+ private Map getKey(JsonNode request, String region) {
+ PaymentCryptographyKey key = requiredKey(request, region, KEY_IDENTIFIER);
+ return Map.of("Key", keyObject(key));
+ }
+
+ private Map listKeys(JsonNode request, String region) {
+ String state = request.hasNonNull("KeyState") ? request.get("KeyState").asText() : null;
+ PaginatedResult page = service.listKeys(region, state,
+ Pagination.parseMaxResults(request, "MaxResults", PAGINATION_ERROR),
+ Pagination.parseNextToken(request, "NextToken", PAGINATION_ERROR));
+ List