mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(paymentcryptography): the Payment Cryptography control plane (#7090)
This commit is contained in:
1 parent
9e270fbfe1
commit
6906759c9a
41 files changed
+3268
-25
No files matched your search
@@ -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<String> mode();
|
||||
|
||||
@WithDefault("5000")
|
||||
long flushIntervalMs();
|
||||
}
|
||||
|
||||
interface AcmStorageConfig {
|
||||
Optional<String> 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();
|
||||
|
||||
@@ -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.<Operation>.
|
||||
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);
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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<String, String> filling, StoredResourceArns stored, String region) {
|
||||
if (!format.minted()) {
|
||||
return arn;
|
||||
}
|
||||
if (stored != null && filling.size() == 1) {
|
||||
Optional<String> found = stored.find(type, List.of(filling.values().iterator().next()), region);
|
||||
if (found.isPresent()) {
|
||||
return found.get();
|
||||
}
|
||||
}
|
||||
return arn + "/*";
|
||||
return format.minted() ? arn + "/*" : arn;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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/<name>/<id>}),
|
||||
* 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/<name>/<id>}), or as all of it, a request naming
|
||||
* the resource by members its ARN does not hold
|
||||
* ({@code scalable-target/<id>}, named by its service namespace, resource id and scalable dimension;
|
||||
* {@code workgroup/<id>}, named by its name).
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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<StoredResourceArns>} for the namespace a request is of, so IAM never depends on that service
|
||||
* directly.</p>
|
||||
*/
|
||||
|
||||
+141
@@ -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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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;
|
||||
}
|
||||
}
|
||||
+362
@@ -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.
|
||||
*
|
||||
* <p>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<String> 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<String, Object> 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<String, Object> 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<String> MODES_OF_USE = List.of("Encrypt", "Decrypt", "Wrap", "Unwrap", "Generate",
|
||||
"Sign", "Verify", "DeriveKey", "NoRestrictions");
|
||||
|
||||
private Map<String, Object> getKey(JsonNode request, String region) {
|
||||
PaymentCryptographyKey key = requiredKey(request, region, KEY_IDENTIFIER);
|
||||
return Map.of("Key", keyObject(key));
|
||||
}
|
||||
|
||||
private Map<String, Object> listKeys(JsonNode request, String region) {
|
||||
String state = request.hasNonNull("KeyState") ? request.get("KeyState").asText() : null;
|
||||
PaginatedResult<PaymentCryptographyKey> page = service.listKeys(region, state,
|
||||
Pagination.parseMaxResults(request, "MaxResults", PAGINATION_ERROR),
|
||||
Pagination.parseNextToken(request, "NextToken", PAGINATION_ERROR));
|
||||
List<Map<String, Object>> keys = new ArrayList<>();
|
||||
for (PaymentCryptographyKey key : page.items()) {
|
||||
keys.add(keyObject(key));
|
||||
}
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("Keys", keys);
|
||||
if (page.nextToken() != null) {
|
||||
out.put("NextToken", page.nextToken());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a key and answers with the key, as the reference does.
|
||||
*
|
||||
* <p>The waiting period the reference offers is read, and the key is
|
||||
* deleted at once all the same: the service deletes a key the moment it
|
||||
* is asked to.
|
||||
*/
|
||||
private Map<String, Object> deleteKey(JsonNode request, String region) {
|
||||
PaymentCryptographyKey key = service.deleteKey(requiredKey(request, region, KEY_IDENTIFIER));
|
||||
return Map.of("Key", keyObject(key));
|
||||
}
|
||||
|
||||
// ---- aliases ------------------------------------------------------------
|
||||
|
||||
private Map<String, Object> createAlias(JsonNode request, String region) {
|
||||
String aliasName = aliasName(request);
|
||||
// The model requires only the name of an alias, but the reference refuses one
|
||||
// without a key, so the request is refused the way it refuses it.
|
||||
if (!request.hasNonNull(KEY_ARN)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"You can't create an alias without a key.", 400);
|
||||
}
|
||||
PaymentCryptographyKey key = requiredKey(request, region, KEY_ARN);
|
||||
PaymentCryptographyAlias alias = service.createAlias(aliasName, key);
|
||||
return Map.of("Alias", aliasObject(alias));
|
||||
}
|
||||
|
||||
private Map<String, Object> getAlias(JsonNode request, String region) {
|
||||
String aliasName = aliasName(request);
|
||||
PaymentCryptographyAlias alias = service.findAlias(region, aliasName);
|
||||
if (alias == null) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"Alias " + aliasName + " is not found", 400);
|
||||
}
|
||||
return Map.of("Alias", aliasObject(alias));
|
||||
}
|
||||
|
||||
private Map<String, Object> listAliases(JsonNode request, String region) {
|
||||
String keyArn = request.hasNonNull("KeyArn") ? request.get("KeyArn").asText() : null;
|
||||
PaginatedResult<PaymentCryptographyAlias> page = service.listAliases(region,
|
||||
keyArn, Pagination.parseMaxResults(request, "MaxResults", PAGINATION_ERROR),
|
||||
Pagination.parseNextToken(request, "NextToken", PAGINATION_ERROR));
|
||||
List<Map<String, Object>> aliases = new ArrayList<>();
|
||||
for (PaymentCryptographyAlias alias : page.items()) {
|
||||
aliases.add(aliasObject(alias));
|
||||
}
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("Aliases", aliases);
|
||||
if (page.nextToken() != null) {
|
||||
out.put("NextToken", page.nextToken());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Points an alias at a key, or removes the key it names when the request
|
||||
* names no key, as the reference does: the key of an alias is optional.
|
||||
*/
|
||||
private Map<String, Object> updateAlias(JsonNode request, String region) {
|
||||
String aliasName = aliasName(request);
|
||||
if (!request.hasNonNull(KEY_ARN)) {
|
||||
return Map.of("Alias", aliasObject(service.detachAlias(region, aliasName)));
|
||||
}
|
||||
PaymentCryptographyKey key = requiredKey(request, region, KEY_ARN);
|
||||
PaymentCryptographyAlias alias = service.updateAlias(aliasName, key);
|
||||
return Map.of("Alias", aliasObject(alias));
|
||||
}
|
||||
|
||||
private Map<String, Object> deleteAlias(JsonNode request, String region) {
|
||||
service.deleteAlias(region, aliasName(request));
|
||||
return Map.of();
|
||||
}
|
||||
|
||||
// ---- tags ---------------------------------------------------------------
|
||||
|
||||
private Map<String, Object> tagResource(JsonNode request, String region) {
|
||||
PaymentCryptographyKey key = requiredKey(request, region, RESOURCE_ARN);
|
||||
service.tag(key, tagsOf(request));
|
||||
return Map.of();
|
||||
}
|
||||
|
||||
private Map<String, Object> untagResource(JsonNode request, String region) {
|
||||
PaymentCryptographyKey key = requiredKey(request, region, RESOURCE_ARN);
|
||||
List<String> tagKeys = new ArrayList<>();
|
||||
JsonNode declared = request.get("TagKeys");
|
||||
if (declared != null && declared.isArray()) {
|
||||
for (JsonNode tagKey : declared) {
|
||||
tagKeys.add(tagKey.asText());
|
||||
}
|
||||
}
|
||||
service.untag(key, tagKeys);
|
||||
return Map.of();
|
||||
}
|
||||
|
||||
private Map<String, Object> listTagsForResource(JsonNode request, String region) {
|
||||
PaymentCryptographyKey key = requiredKey(request, region, RESOURCE_ARN);
|
||||
PaginatedResult<Map.Entry<String, String>> page = service.listTags(key,
|
||||
Pagination.parseMaxResults(request, "MaxResults", PAGINATION_ERROR),
|
||||
Pagination.parseNextToken(request, "NextToken", PAGINATION_ERROR));
|
||||
List<Map<String, Object>> tags = new ArrayList<>();
|
||||
for (Map.Entry<String, String> tag : page.items()) {
|
||||
tags.add(Map.of("Key", tag.getKey(), "Value", tag.getValue()));
|
||||
}
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("Tags", tags);
|
||||
if (page.nextToken() != null) {
|
||||
out.put("NextToken", page.nextToken());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The tags of a request, as the name and the value of each. */
|
||||
private static Map<String, String> tagsOf(JsonNode request) {
|
||||
Map<String, String> tags = new LinkedHashMap<>();
|
||||
JsonNode declared = request.get("Tags");
|
||||
if (declared != null && declared.isArray()) {
|
||||
for (JsonNode tag : declared) {
|
||||
String tagKey = tag.path("Key").asText();
|
||||
if (tagKey.isEmpty()) {
|
||||
throw new AwsException("ValidationException", "each Tag requires Key", 400);
|
||||
}
|
||||
tags.put(tagKey, tag.path("Value").asText());
|
||||
}
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
// ---- helpers ------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The key's modes of use, as the request states them.
|
||||
*
|
||||
* <p>The attributes are read as text, and a mode is a boolean, so the
|
||||
* modes are read from the request itself rather than from the flattened
|
||||
* attributes: a boolean read as text is a string, and the key would come
|
||||
* back with no modes at all.
|
||||
*/
|
||||
private static Map<String, Boolean> modesOfUse(JsonNode attributes) {
|
||||
Map<String, Boolean> modes = new LinkedHashMap<>();
|
||||
JsonNode declared = attributes.get("KeyModesOfUse");
|
||||
if (declared != null && declared.isObject()) {
|
||||
declared.fields().forEachRemaining(entry -> {
|
||||
if (MODES_OF_USE.contains(entry.getKey())) {
|
||||
modes.put(entry.getKey(), entry.getValue().asBoolean());
|
||||
}
|
||||
});
|
||||
}
|
||||
return modes;
|
||||
}
|
||||
|
||||
/**
|
||||
* The modes of use a key answers with: every mode the reference gives a key, the ones the key does not
|
||||
* have as false, so a caller reading them finds a boolean for each of them and none of them is null.
|
||||
*/
|
||||
private static Map<String, Boolean> answeredModes(PaymentCryptographyKey key) {
|
||||
Map<String, Boolean> modes = new LinkedHashMap<>();
|
||||
for (String mode : MODES_OF_USE) {
|
||||
modes.put(mode, Boolean.FALSE);
|
||||
}
|
||||
modes.putAll(key.getKeyModesOfUse());
|
||||
return modes;
|
||||
}
|
||||
|
||||
/**
|
||||
* The key an operation names, in the member that operation names it in.
|
||||
*
|
||||
* <p>The key is named in a different member by each operation:
|
||||
* {@code KeyIdentifier} by the key operations, {@code KeyArn} by the alias ones, and
|
||||
* {@code ResourceArn} by the tagging ones. Only that member is read, so a request cannot
|
||||
* name one key for the permission check and another for the change: the IAM check reads
|
||||
* the same member this reads.
|
||||
*/
|
||||
private PaymentCryptographyKey requiredKey(JsonNode request, String region, String member) {
|
||||
String identifier = request.path(member).asText();
|
||||
if (identifier.isEmpty()) {
|
||||
throw new AwsException("ValidationException", member + " is required", 400);
|
||||
}
|
||||
PaymentCryptographyKey key = service.findKey(region, identifier);
|
||||
if (key == null) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"Key not found: " + identifier, 400);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
private static String aliasName(JsonNode request) {
|
||||
return request.path("AliasName").asText();
|
||||
}
|
||||
|
||||
private static Map<String, Object> keyObject(PaymentCryptographyKey key) {
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("KeyArn", key.getArn());
|
||||
Map<String, Object> attributes = new LinkedHashMap<>();
|
||||
attributes.put("KeyAlgorithm", key.getKeyAlgorithm());
|
||||
attributes.put("KeyClass", key.getKeyClass());
|
||||
attributes.put("KeyUsage", key.getKeyUsage());
|
||||
attributes.put("KeyModesOfUse", answeredModes(key));
|
||||
out.put("KeyAttributes", attributes);
|
||||
out.put("KeyCheckValue", key.getKeyCheckValue());
|
||||
out.put("KeyCheckValueAlgorithm", key.getKeyCheckValueAlgorithm());
|
||||
out.put("KeyState", key.getKeyState());
|
||||
out.put("KeyOrigin", key.getKeyOrigin());
|
||||
out.put("Enabled", key.isEnabled());
|
||||
out.put("Exportable", key.isExportable());
|
||||
out.put("CreateTimestamp", key.getCreateTimestamp());
|
||||
out.put("UsageStartTimestamp", key.getUsageStartTimestamp());
|
||||
if (key.getDeletePendingTimestamp() > 0) {
|
||||
out.put("DeletePendingTimestamp", key.getDeletePendingTimestamp());
|
||||
}
|
||||
if (key.getDeleteTimestamp() > 0) {
|
||||
out.put("DeleteTimestamp", key.getDeleteTimestamp());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static Map<String, Object> aliasObject(PaymentCryptographyAlias alias) {
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("AliasName", alias.getAliasName());
|
||||
if (alias.getKeyArn() != null) {
|
||||
out.put("KeyArn", alias.getKeyArn());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package io.github.hectorvent.floci.services.paymentcryptography;
|
||||
|
||||
import jakarta.enterprise.context.RequestScoped;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* What this request resolved, kept for the request.
|
||||
*
|
||||
* <p>An alias names a key, and another request may move that alias to another key while this one
|
||||
* is running. The permission check resolves the alias to the key it names, and the request must act
|
||||
* on that key: a key resolved again afterwards could be one no policy was checked against.
|
||||
*/
|
||||
@RequestScoped
|
||||
public class PaymentCryptographyRequestContext {
|
||||
|
||||
/** The key an alias named, by the alias's name and the Region it is in. */
|
||||
private final Map<String, String> aliasKeyIds = new LinkedHashMap<>();
|
||||
|
||||
/**
|
||||
* The id of the key the alias named when this request resolved it, an empty one when it named
|
||||
* no key, and null when this request has not resolved the alias yet.
|
||||
*/
|
||||
String aliasKeyId(String region, String aliasName) {
|
||||
return aliasKeyIds.get(key(region, aliasName));
|
||||
}
|
||||
|
||||
/** Remembers the key the alias named, so that the request acts on that key and not another. */
|
||||
void pinAliasKeyId(String region, String aliasName, String keyId) {
|
||||
aliasKeyIds.put(key(region, aliasName), keyId);
|
||||
}
|
||||
|
||||
private static String key(String region, String aliasName) {
|
||||
return region + SEPARATOR + aliasName;
|
||||
}
|
||||
|
||||
/** The separator between the Region and the alias name, which neither of them carries. */
|
||||
private static final String SEPARATOR = "\u0000";
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
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.RequestConstraintCheck;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Checks a Payment Cryptography request against the constraints vendored in
|
||||
* {@code aws/payment-cryptography-request-shapes.json} by
|
||||
* {@code tools/aws/regen_payment_cryptography_shapes.py}.
|
||||
*
|
||||
* <p>The patterns are what settle which key a request may name: {@code KeyIdentifier} takes the ARN
|
||||
* of a key, the ARN of an alias or the name of an alias, while {@code KeyArn} and {@code ResourceArn}
|
||||
* take the ARN of a key alone. A violation is a {@code ValidationException}, with the member's path
|
||||
* from the request's top level.
|
||||
*/
|
||||
final class PaymentCryptographyRequestShapes {
|
||||
|
||||
private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load(
|
||||
"aws/payment-cryptography-request-shapes.json", "Payment Cryptography request shapes",
|
||||
new RequestConstraintCheck.Messages() {
|
||||
@Override
|
||||
public AwsException type(String path, String type) {
|
||||
return invalid(path, "Member must be a " + type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AwsException bounds(String path, String type, Long min, Long max, long size) {
|
||||
String measure = "integer".equals(type) || "long".equals(type) ? "value" : "length";
|
||||
return min != null && size < min
|
||||
? invalid(path, "Member must have " + measure + " greater than or equal to " + min)
|
||||
: invalid(path, "Member must have " + measure + " less than or equal to " + max);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AwsException pattern(String path, String pattern) {
|
||||
return invalid(path, "must satisfy regular expression '" + pattern + "'");
|
||||
}
|
||||
|
||||
@Override
|
||||
public AwsException enumValue(String path, List<String> values) {
|
||||
return invalid(path, "Member must satisfy enum value set: " + values);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AwsException required(String path) {
|
||||
return invalid(path, "Member must not be null");
|
||||
}
|
||||
});
|
||||
|
||||
private PaymentCryptographyRequestShapes() {
|
||||
}
|
||||
|
||||
static void check(String operation, JsonNode request) {
|
||||
CHECK.check(operation, request);
|
||||
}
|
||||
|
||||
/** The member's path below the operation, with list elements folded into their list. */
|
||||
private static AwsException invalid(String path, String rule) {
|
||||
int dot = path.indexOf('.');
|
||||
String member = (dot < 0 ? "" : path.substring(dot + 1)).replace("[]", "");
|
||||
return new AwsException("ValidationException",
|
||||
"Invalid parameter at '" + member + "' failed to satisfy constraint: '" + rule + "'", 400);
|
||||
}
|
||||
}
|
||||
+474
@@ -0,0 +1,474 @@
|
||||
package io.github.hectorvent.floci.services.paymentcryptography;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
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.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.core.common.StoredResourceArns;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
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 java.security.SecureRandom;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* The Payment Cryptography key store.
|
||||
*
|
||||
* <p>Keys, aliases and tags all live in the region they were made in. The
|
||||
* service is regional, and an alias name is unique in an account and a region
|
||||
* rather than in an account, so the same name may name a key in two regions
|
||||
* and the two are two aliases.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class PaymentCryptographyService implements Resettable, StoredResourceArns {
|
||||
|
||||
/** The storage key, which is the one the catalog's descriptor names. */
|
||||
private static final String STORAGE_KEY = "paymentcryptography";
|
||||
|
||||
/** The service in the ARN, which is the service's own name. */
|
||||
private static final String SERVICE = "payment-cryptography";
|
||||
|
||||
/** The number of results a listing returns when the caller asks for none. */
|
||||
private static final int DEFAULT_PAGE_SIZE = 50;
|
||||
|
||||
/** The most results a listing returns when the caller asks for a number. */
|
||||
private static final int MAX_RESULTS = 100;
|
||||
|
||||
/** The error a bad page size or a bad token is refused with. */
|
||||
private static final String PAGINATION_ERROR = "ValidationException";
|
||||
|
||||
/** The only algorithm this service makes material for. */
|
||||
private static final String SUPPORTED_ALGORITHM = "AES_256";
|
||||
|
||||
/** The only class this service makes material for. */
|
||||
private static final String SUPPORTED_CLASS = "SYMMETRIC_KEY";
|
||||
|
||||
private final StorageBackend<String, PaymentCryptographyKey> keyStore;
|
||||
private final StorageBackend<String, PaymentCryptographyAlias> aliasStore;
|
||||
private final RegionResolver regionResolver;
|
||||
private final SecureRandom secureRandom;
|
||||
private final PaymentCryptographyRequestContext requestContext;
|
||||
|
||||
@Inject
|
||||
public PaymentCryptographyService(StorageFactory storageFactory, RegionResolver regionResolver,
|
||||
PaymentCryptographyRequestContext requestContext) {
|
||||
this(storageFactory.create(STORAGE_KEY, "payment-cryptography-keys.json",
|
||||
new TypeReference<>() {}),
|
||||
storageFactory.create(STORAGE_KEY, "payment-cryptography-aliases.json",
|
||||
new TypeReference<>() {}),
|
||||
regionResolver,
|
||||
new SecureRandom(),
|
||||
requestContext);
|
||||
}
|
||||
|
||||
PaymentCryptographyService(StorageBackend<String, PaymentCryptographyKey> keyStore,
|
||||
StorageBackend<String, PaymentCryptographyAlias> aliasStore,
|
||||
RegionResolver regionResolver,
|
||||
PaymentCryptographyRequestContext requestContext) {
|
||||
this(keyStore, aliasStore, regionResolver, new SecureRandom(), requestContext);
|
||||
}
|
||||
|
||||
PaymentCryptographyService(StorageBackend<String, PaymentCryptographyKey> keyStore,
|
||||
StorageBackend<String, PaymentCryptographyAlias> aliasStore,
|
||||
RegionResolver regionResolver,
|
||||
SecureRandom secureRandom,
|
||||
PaymentCryptographyRequestContext requestContext) {
|
||||
this.keyStore = keyStore;
|
||||
this.aliasStore = aliasStore;
|
||||
this.regionResolver = regionResolver;
|
||||
this.secureRandom = secureRandom;
|
||||
this.requestContext = requestContext;
|
||||
}
|
||||
|
||||
// ---- keys ---------------------------------------------------------------
|
||||
|
||||
/** Creates a key with fresh AES-256 material. */
|
||||
public PaymentCryptographyKey createKey(String region, Map<String, Object> attributes,
|
||||
Map<String, Boolean> modesOfUse, boolean exportable,
|
||||
boolean enabled, Map<String, String> tags) {
|
||||
String algorithm = string(attributes, "KeyAlgorithm", "AES_256");
|
||||
String keyClass = string(attributes, "KeyClass", "SYMMETRIC_KEY");
|
||||
// The material is AES-256 and symmetric, so a key that says otherwise would be a key
|
||||
// whose attributes do not describe it.
|
||||
if (!SUPPORTED_ALGORITHM.equals(algorithm)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"KeyAlgorithm '" + algorithm + "' is not supported, this service makes "
|
||||
+ SUPPORTED_ALGORITHM + " keys", 400);
|
||||
}
|
||||
if (!SUPPORTED_CLASS.equals(keyClass)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"KeyClass '" + keyClass + "' is not supported, this service makes "
|
||||
+ SUPPORTED_CLASS + " keys", 400);
|
||||
}
|
||||
PaymentCryptographyKey key = new PaymentCryptographyKey();
|
||||
key.setKeyId(UUID.randomUUID().toString().replace("-", ""));
|
||||
key.setRegion(region);
|
||||
key.setArn(regionResolver.buildArn(SERVICE, region, "key/" + key.getKeyId()));
|
||||
key.setKeyAlgorithm(algorithm);
|
||||
key.setKeyClass(keyClass);
|
||||
key.setKeyUsage(usage(attributes));
|
||||
key.setKeyModesOfUse(modesOfUse);
|
||||
key.setExportable(exportable);
|
||||
key.setEnabled(enabled);
|
||||
key.setTags(new LinkedHashMap<>(tags));
|
||||
key.setKeyState("CREATE_COMPLETE");
|
||||
key.setKeyMaterialHex(PaymentCryptographyCrypto.randomAes256Hex(secureRandom));
|
||||
key.setKeyCheckValue(PaymentCryptographyCrypto.checkValue(key.getKeyMaterialHex()));
|
||||
key.setKeyCheckValueAlgorithm("CMAC");
|
||||
long now = Instant.now().getEpochSecond();
|
||||
key.setCreateTimestamp(now);
|
||||
key.setUsageStartTimestamp(now);
|
||||
keyStore.put(key.getKeyId(), key);
|
||||
return key;
|
||||
}
|
||||
|
||||
/** The key an identifier names, or null when there is none. */
|
||||
public PaymentCryptographyKey findKey(String region, String identifier) {
|
||||
if (identifier == null || identifier.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
if (identifier.startsWith("alias/")) {
|
||||
return keyOfAlias(region, identifier);
|
||||
}
|
||||
if (AwsArnUtils.looksLikeArn(identifier)) {
|
||||
Optional<String> resource = AwsArnUtils.resourceIfArnFor(identifier, SERVICE);
|
||||
if (resource.isPresent() && resource.get().startsWith("alias/")) {
|
||||
// The ARN names the alias in the Region, the account and the partition it was
|
||||
// minted in, so an alias of another one is not this Region's alias.
|
||||
String name = "alias/" + resource.get().substring("alias/".length());
|
||||
if (!identifier.equals(aliasArn(region, name))) {
|
||||
return null;
|
||||
}
|
||||
return keyOfAlias(region, name);
|
||||
}
|
||||
for (PaymentCryptographyKey key : keyStore.scan(k -> true)) {
|
||||
if (identifier.equals(key.getArn()) && region.equals(key.getRegion())) {
|
||||
return key;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
PaymentCryptographyKey byId = keyStore.get(identifier).orElse(null);
|
||||
return byId != null && region.equals(byId.getRegion()) ? byId : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The keys of a region, a page at a time.
|
||||
*
|
||||
* <p>The service answers with as many keys as the caller asks for, and a
|
||||
* token that asks for the page after that one. The key's own ARN is the
|
||||
* cursor, so a page can be resumed after the key it stopped at.
|
||||
*
|
||||
* <p>A request naming a state is answered with the keys in that state
|
||||
* only, and with every key when it names none.
|
||||
*/
|
||||
public PaginatedResult<PaymentCryptographyKey> listKeys(String region, String keyState,
|
||||
Integer maxResults, String nextToken) {
|
||||
return Pagination.paginate(listKeys(region, keyState), PaymentCryptographyKey::getArn,
|
||||
maxResults, nextToken, DEFAULT_PAGE_SIZE, MAX_RESULTS, PAGINATION_ERROR);
|
||||
}
|
||||
|
||||
/** The keys of a region, in the state the request names, or in any when it names none. */
|
||||
public List<PaymentCryptographyKey> listKeys(String region, String keyState) {
|
||||
List<PaymentCryptographyKey> out = new ArrayList<>();
|
||||
for (PaymentCryptographyKey key : keyStore.scan(k -> true)) {
|
||||
if (region.equals(key.getRegion()) && (keyState == null || keyState.equals(key.getKeyState()))) {
|
||||
out.add(key);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a key and answers the key as the service does when a deletion is
|
||||
* scheduled: the key's own metadata, its state {@code DELETE_PENDING} and
|
||||
* the pending timestamp of that deletion.
|
||||
*
|
||||
* <p>The service deletes a key the moment it is asked to, so the waiting
|
||||
* period the service offers is not one: the key is gone when the answer
|
||||
* goes out. The answer carries only the pending timestamp of that
|
||||
* deletion; the delete timestamp stays unset, because the key is already
|
||||
* gone when the answer goes out.
|
||||
*
|
||||
* <p>The lock is the same one the tagging operations take, so a key that
|
||||
* is being tagged cannot be written back after it was deleted.
|
||||
*/
|
||||
public synchronized PaymentCryptographyKey deleteKey(PaymentCryptographyKey key) {
|
||||
long now = Instant.now().getEpochSecond();
|
||||
key.setKeyState("DELETE_PENDING");
|
||||
key.setEnabled(false);
|
||||
key.setDeletePendingTimestamp(now);
|
||||
keyStore.delete(key.getKeyId());
|
||||
for (PaymentCryptographyAlias alias : aliasStore.scan(a -> true)) {
|
||||
if (key.getKeyId().equals(alias.getKeyId())) {
|
||||
aliasStore.delete(aliasKey(alias.getAliasName(), alias.getRegion()));
|
||||
}
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
// ---- aliases ------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The alias of a name in a region.
|
||||
*
|
||||
* <p>The alias belongs to the region of the key it names, so the lookup is
|
||||
* by name and region together.
|
||||
*/
|
||||
public PaymentCryptographyAlias findAlias(String region, String aliasName) {
|
||||
return aliasStore.get(aliasKey(aliasName, region)).orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* The key an alias names, as this request resolved it.
|
||||
*
|
||||
* <p>The alias is resolved once for the request, and the resolution is kept: the
|
||||
* permission check resolves the alias to the key it names, and the request must act on
|
||||
* that key. Another request may move the alias in between, and a key resolved again
|
||||
* afterwards could be one no policy was checked against.
|
||||
*/
|
||||
private PaymentCryptographyKey keyOfAlias(String region, String aliasName) {
|
||||
String keyId = requestContext.aliasKeyId(region, aliasName);
|
||||
if (keyId == null) {
|
||||
PaymentCryptographyAlias alias = findAlias(region, aliasName);
|
||||
keyId = alias == null || alias.getKeyId() == null ? "" : alias.getKeyId();
|
||||
requestContext.pinAliasKeyId(region, aliasName, keyId);
|
||||
}
|
||||
return keyId.isEmpty() ? null : keyStore.get(keyId).orElse(null);
|
||||
}
|
||||
|
||||
/** Points a name at a key. The name must be free in the key's region. */
|
||||
public synchronized PaymentCryptographyAlias createAlias(String aliasName, PaymentCryptographyKey key) {
|
||||
liveKey(key);
|
||||
if (findAlias(key.getRegion(), aliasName) != null) {
|
||||
throw new AwsException("ConflictException",
|
||||
"Alias " + aliasName + " already exists", 400);
|
||||
}
|
||||
PaymentCryptographyAlias alias = new PaymentCryptographyAlias(
|
||||
aliasName, key.getRegion(), key.getArn(), key.getKeyId());
|
||||
aliasStore.put(aliasKey(aliasName, alias.getRegion()), alias);
|
||||
return alias;
|
||||
}
|
||||
|
||||
/** Points a name at another key, in the same region. */
|
||||
public synchronized PaymentCryptographyAlias updateAlias(String aliasName, PaymentCryptographyKey key) {
|
||||
liveKey(key);
|
||||
PaymentCryptographyAlias existing = findAlias(key.getRegion(), aliasName);
|
||||
if (existing == null) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"Alias " + aliasName + " is not found", 400);
|
||||
}
|
||||
existing.setKeyArn(key.getArn());
|
||||
existing.setKeyId(key.getKeyId());
|
||||
aliasStore.put(aliasKey(aliasName, existing.getRegion()), existing);
|
||||
return existing;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the key an alias names, leaving the alias itself.
|
||||
*
|
||||
* <p>The service answers an update that names no key this way: the alias
|
||||
* names no key afterwards, and it answers with the alias alone.
|
||||
*/
|
||||
public synchronized PaymentCryptographyAlias detachAlias(String region, String aliasName) {
|
||||
PaymentCryptographyAlias existing = findAlias(region, aliasName);
|
||||
if (existing == null) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"Alias " + aliasName + " is not found", 400);
|
||||
}
|
||||
existing.setKeyArn(null);
|
||||
existing.setKeyId(null);
|
||||
aliasStore.put(aliasKey(aliasName, existing.getRegion()), existing);
|
||||
return existing;
|
||||
}
|
||||
|
||||
/** Removes a name from a region. */
|
||||
public synchronized void deleteAlias(String region, String aliasName) {
|
||||
if (findAlias(region, aliasName) == null) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"Alias " + aliasName + " is not found", 400);
|
||||
}
|
||||
aliasStore.delete(aliasKey(aliasName, region));
|
||||
}
|
||||
|
||||
/**
|
||||
* The aliases of a region, or of one key, a page at a time.
|
||||
*
|
||||
* <p>The service answers with as many aliases as the caller asks for, and
|
||||
* a token that asks for the page after that one.
|
||||
*/
|
||||
public PaginatedResult<PaymentCryptographyAlias> listAliases(String region, String keyArn,
|
||||
Integer maxResults, String nextToken) {
|
||||
return Pagination.paginate(listAliases(region, keyArn), PaymentCryptographyAlias::getAliasName,
|
||||
maxResults, nextToken, DEFAULT_PAGE_SIZE, MAX_RESULTS, PAGINATION_ERROR);
|
||||
}
|
||||
|
||||
/** The aliases of a region, or of one key. */
|
||||
public List<PaymentCryptographyAlias> listAliases(String region, String keyArn) {
|
||||
List<PaymentCryptographyAlias> out = new ArrayList<>();
|
||||
for (PaymentCryptographyAlias alias : aliasStore.scan(a -> true)) {
|
||||
if (!region.equals(alias.getRegion())) {
|
||||
continue;
|
||||
}
|
||||
if (keyArn != null && !keyArn.equals(alias.getKeyArn())) {
|
||||
continue;
|
||||
}
|
||||
out.add(alias);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- tags ---------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Adds tags to a key.
|
||||
*
|
||||
* <p>The tags are the region's: they are not part of the replication
|
||||
* process, so a key in another region carries its own tag set.
|
||||
*/
|
||||
public synchronized void tag(PaymentCryptographyKey key, Map<String, String> tags) {
|
||||
PaymentCryptographyKey current = liveKey(key);
|
||||
current.getTags().putAll(tags);
|
||||
keyStore.put(current.getKeyId(), current);
|
||||
}
|
||||
|
||||
/**
|
||||
* The key as it is in the store now.
|
||||
*
|
||||
* <p>The caller looked the key up before it asked for the change, and the
|
||||
* key may be gone by the time the change is made. Writing the looked-up
|
||||
* object back would put a deleted key into the store again, so the key is
|
||||
* read again under the lock and the request fails if it is not there.
|
||||
*/
|
||||
private PaymentCryptographyKey liveKey(PaymentCryptographyKey key) {
|
||||
PaymentCryptographyKey current = keyStore.get(key.getKeyId()).orElse(null);
|
||||
if (current == null) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"Key " + key.getArn() + " is not found", 400);
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
/** Removes tags from a key, in this region only. */
|
||||
public synchronized void untag(PaymentCryptographyKey key, List<String> tagKeys) {
|
||||
PaymentCryptographyKey current = liveKey(key);
|
||||
for (String tagKey : tagKeys) {
|
||||
current.getTags().remove(tagKey);
|
||||
}
|
||||
keyStore.put(current.getKeyId(), current);
|
||||
}
|
||||
|
||||
/**
|
||||
* The tags of a key.
|
||||
*
|
||||
* <p>The copy takes the lock the tagging operations take, so it cannot read the map while
|
||||
* another request is writing to it.
|
||||
*/
|
||||
public synchronized Map<String, String> listTags(PaymentCryptographyKey key) {
|
||||
return new LinkedHashMap<>(key.getTags());
|
||||
}
|
||||
|
||||
/**
|
||||
* The tags of a key, a page at a time.
|
||||
*
|
||||
* <p>The service answers with as many tags as the caller asks for, and a
|
||||
* token that asks for the page after that one.
|
||||
*/
|
||||
public PaginatedResult<Map.Entry<String, String>> listTags(PaymentCryptographyKey key,
|
||||
Integer maxResults, String nextToken) {
|
||||
return Pagination.paginate(new ArrayList<>(listTags(key).entrySet()), Map.Entry::getKey,
|
||||
maxResults, nextToken, DEFAULT_PAGE_SIZE, MAX_RESULTS, PAGINATION_ERROR);
|
||||
}
|
||||
|
||||
// ---- helpers ------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The namespace of the resource types this service finds, as the request-resources table names it.
|
||||
*/
|
||||
@Override
|
||||
public String namespace() {
|
||||
return "payment-cryptography";
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARN the caller's key or alias of the name in the Region is stored under.
|
||||
*
|
||||
* <p>A key is named by its id or by an alias, and an alias names the key it points at, so a
|
||||
* request naming a key by an alias is checked on the key the alias names, as the handler
|
||||
* resolves it: an {@code Allow} scoped to that key passes and a {@code Deny} scoped to it
|
||||
* holds, whichever of the two names the request used.
|
||||
*
|
||||
* <p>An alias's ARN is the name it was given, which the request carries with the
|
||||
* {@code alias/} its own name starts with, so the ARN is that name without the prefix the
|
||||
* alias's own resource part carries.
|
||||
*/
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
if (names.size() != 1 || names.getFirst() == null || names.getFirst().isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String name = names.getFirst();
|
||||
return switch (type) {
|
||||
case "key" -> Optional.ofNullable(findKey(region, name)).map(PaymentCryptographyKey::getArn);
|
||||
case "alias" -> Optional.of(aliasArn(region, name));
|
||||
default -> Optional.empty();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARN of the alias of the name in the Region, which the name gives whether or not the
|
||||
* alias exists yet, as a create names the alias it makes.
|
||||
*/
|
||||
private String aliasArn(String region, String name) {
|
||||
String alias = name.startsWith("alias/") ? name.substring("alias/".length()) : name;
|
||||
return regionResolver.buildArn(SERVICE, region, "alias/" + alias);
|
||||
}
|
||||
|
||||
/**
|
||||
* The storage key of an alias.
|
||||
*
|
||||
* <p>The name and the region together, because the name is unique in the
|
||||
* region and not in the account.
|
||||
*/
|
||||
private static String aliasKey(String aliasName, String region) {
|
||||
return region + "\u0000" + aliasName;
|
||||
}
|
||||
|
||||
private static String string(Map<String, Object> attributes, String name, String fallback) {
|
||||
Object value = attributes.get(name);
|
||||
return value == null ? fallback : String.valueOf(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* The usage of the key the attributes name.
|
||||
*
|
||||
* <p>The service requires it, as the reference does: a key's usage says
|
||||
* what the key is for, and a key without one is not a key.
|
||||
*/
|
||||
private static String usage(Map<String, Object> attributes) {
|
||||
Object value = attributes.get("KeyUsage");
|
||||
if (value == null || String.valueOf(value).isBlank()) {
|
||||
throw new AwsException("ValidationException", "KeyUsage is required", 400);
|
||||
}
|
||||
return String.valueOf(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
keyStore.clear();
|
||||
aliasStore.clear();
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package io.github.hectorvent.floci.services.paymentcryptography.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
/**
|
||||
* A Payment Cryptography alias.
|
||||
*
|
||||
* <p>An alias name is unique in an account and a region, not in an account:
|
||||
* the same name may name a key in another region, and a program that creates
|
||||
* keys in two regions uses the same name in both. The alias therefore
|
||||
* carries the region it belongs to.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class PaymentCryptographyAlias {
|
||||
private String aliasName;
|
||||
private String region;
|
||||
private String keyArn;
|
||||
private String keyId;
|
||||
|
||||
public PaymentCryptographyAlias() {
|
||||
}
|
||||
|
||||
public PaymentCryptographyAlias(String aliasName, String region, String keyArn, String keyId) {
|
||||
this.aliasName = aliasName;
|
||||
this.region = region;
|
||||
this.keyArn = keyArn;
|
||||
this.keyId = keyId;
|
||||
}
|
||||
|
||||
public String getAliasName() { return aliasName; }
|
||||
public void setAliasName(String aliasName) { this.aliasName = aliasName; }
|
||||
|
||||
public String getRegion() { return region; }
|
||||
public void setRegion(String region) { this.region = region; }
|
||||
|
||||
public String getKeyArn() { return keyArn; }
|
||||
public void setKeyArn(String keyArn) { this.keyArn = keyArn; }
|
||||
|
||||
public String getKeyId() { return keyId; }
|
||||
public void setKeyId(String keyId) { this.keyId = keyId; }
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
package io.github.hectorvent.floci.services.paymentcryptography.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A Payment Cryptography key.
|
||||
*
|
||||
* <p>The material is kept as hexadecimal, the way the service's own import and
|
||||
* export formats carry it, so a key that arrives from an import is the same
|
||||
* key that leaves from an export.
|
||||
*
|
||||
* <p>The material is not written to the store: it is held by the key while the
|
||||
* emulator runs, and no operation of this service returns it or needs it, so
|
||||
* leaving it out of the persisted key keeps it off the disk. A key read back
|
||||
* from a store has no material, and the slice that exports a key decides how
|
||||
* one is kept.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class PaymentCryptographyKey {
|
||||
private String keyId;
|
||||
private String arn;
|
||||
private String region;
|
||||
private String keyAlgorithm;
|
||||
private String keyClass;
|
||||
private String keyUsage;
|
||||
private Map<String, Boolean> keyModesOfUse = new HashMap<>();
|
||||
private String keyOrigin = "AWS_PAYMENT_CRYPTOGRAPHY";
|
||||
private String keyCheckValue;
|
||||
private String keyCheckValueAlgorithm = "CMAC";
|
||||
private String keyState = "CREATE_COMPLETE";
|
||||
private boolean exportable;
|
||||
private boolean enabled = true;
|
||||
private String keyMaterialHex;
|
||||
private long createTimestamp;
|
||||
private long usageStartTimestamp;
|
||||
private long deletePendingTimestamp;
|
||||
private long deleteTimestamp;
|
||||
private Map<String, String> tags = new HashMap<>();
|
||||
|
||||
public String getKeyId() { return keyId; }
|
||||
public void setKeyId(String keyId) { this.keyId = keyId; }
|
||||
|
||||
public String getArn() { return arn; }
|
||||
public void setArn(String arn) { this.arn = arn; }
|
||||
|
||||
public String getRegion() { return region; }
|
||||
public void setRegion(String region) { this.region = region; }
|
||||
|
||||
public String getKeyAlgorithm() { return keyAlgorithm; }
|
||||
public void setKeyAlgorithm(String keyAlgorithm) { this.keyAlgorithm = keyAlgorithm; }
|
||||
|
||||
public String getKeyClass() { return keyClass; }
|
||||
public void setKeyClass(String keyClass) { this.keyClass = keyClass; }
|
||||
|
||||
public String getKeyUsage() { return keyUsage; }
|
||||
public void setKeyUsage(String keyUsage) { this.keyUsage = keyUsage; }
|
||||
|
||||
public Map<String, Boolean> getKeyModesOfUse() { return keyModesOfUse; }
|
||||
public void setKeyModesOfUse(Map<String, Boolean> keyModesOfUse) { this.keyModesOfUse = keyModesOfUse; }
|
||||
|
||||
public String getKeyOrigin() { return keyOrigin; }
|
||||
public void setKeyOrigin(String keyOrigin) { this.keyOrigin = keyOrigin; }
|
||||
|
||||
public String getKeyCheckValue() { return keyCheckValue; }
|
||||
public void setKeyCheckValue(String keyCheckValue) { this.keyCheckValue = keyCheckValue; }
|
||||
|
||||
public String getKeyCheckValueAlgorithm() { return keyCheckValueAlgorithm; }
|
||||
public void setKeyCheckValueAlgorithm(String keyCheckValueAlgorithm) {
|
||||
this.keyCheckValueAlgorithm = keyCheckValueAlgorithm;
|
||||
}
|
||||
|
||||
public String getKeyState() { return keyState; }
|
||||
public void setKeyState(String keyState) { this.keyState = keyState; }
|
||||
|
||||
public boolean isExportable() { return exportable; }
|
||||
public void setExportable(boolean exportable) { this.exportable = exportable; }
|
||||
|
||||
public boolean isEnabled() { return enabled; }
|
||||
public void setEnabled(boolean enabled) { this.enabled = enabled; }
|
||||
|
||||
/** The material of the key, which is held by the key and never written to the store. */
|
||||
@JsonIgnore
|
||||
public String getKeyMaterialHex() { return keyMaterialHex; }
|
||||
public void setKeyMaterialHex(String keyMaterialHex) { this.keyMaterialHex = keyMaterialHex; }
|
||||
|
||||
public long getCreateTimestamp() { return createTimestamp; }
|
||||
public void setCreateTimestamp(long createTimestamp) { this.createTimestamp = createTimestamp; }
|
||||
|
||||
public long getUsageStartTimestamp() { return usageStartTimestamp; }
|
||||
public void setUsageStartTimestamp(long usageStartTimestamp) {
|
||||
this.usageStartTimestamp = usageStartTimestamp;
|
||||
}
|
||||
|
||||
/** When the key is deleted, zero while it is not scheduled for deletion. */
|
||||
public long getDeletePendingTimestamp() { return deletePendingTimestamp; }
|
||||
public void setDeletePendingTimestamp(long deletePendingTimestamp) {
|
||||
this.deletePendingTimestamp = deletePendingTimestamp;
|
||||
}
|
||||
|
||||
/** When the key was deleted, zero while it is not. */
|
||||
public long getDeleteTimestamp() { return deleteTimestamp; }
|
||||
public void setDeleteTimestamp(long deleteTimestamp) { this.deleteTimestamp = deleteTimestamp; }
|
||||
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags; }
|
||||
}
|
||||
Reference in new issue
Block a user