mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(paymentcryptography): the data plane as a service of its own (#7396)
* feat(paymentcryptography): the data plane as a service of its own docs(paymentcryptography): the data plane has a page of its own fix(paymentcryptography): a MAC under a three-key Triple DES key is computed test(paymentcryptography): a key of another purpose does not encrypt data feat(paymentcryptography): the data plane's IAM is generated fix(paymentcryptography): a DUKPT MAC needs a base derivation key fix(paymentcryptography): a key whose material is not held is refused docs(paymentcryptography): the data plane's example runs test(paymentcryptography): the data plane through the AWS SDK test(paymentcryptography): the data plane through the AWS CLI fix(paymentcryptography): the CLI test removes the keys it makes docs(compat): the AWS CLI suite names the data plane test(paymentcryptography): the route is read as the registry reads it test(paymentcryptography): the request names its method and its URI fix(paymentcryptography): the cipher pads no data fix(paymentcryptography): the data plane takes the service scope fix(paymentcryptography): a MAC length that is not a number is refused docs(paymentcryptography): the data plane says the cipher pads no data fix(paymentcryptography): the data plane ciphers with Triple DES as well fix(paymentcryptography): the scope alias names the model's scope fix(paymentcryptography): the Triple DES cipher is BouncyCastle's fix(paymentcryptography): the usage and the blob keep their comments fix(paymentcryptography): a key's family is read from its algorithm fix(paymentcryptography): the cipher reads the vector through one helper test(paymentcryptography): the keys are built by one builder fix(paymentcryptography): the data plane checks the model's rules fix(paymentcryptography): the Triple DES check value is BouncyCastle's fix(paymentcryptography): the SDK names it TDES_2_KEY docs(contributing): the ciphers come from BouncyCastle refactor(paymentcryptography): the model owns the request shapes refactor(paymentcryptography): the ciphers are BouncyCastle's test(compat): one helper makes a key of either algorithm docs(contributing): the cipher rule comes out fix(paymentcryptography): the refusals are the model's refactor(paymentcryptography): the ciphers are one helper each refactor(paymentcryptography): the generators share the helper docs(paymentcryptography): the javadocs name both ciphers test(aws): the moved constants read from the shared helper fix(paymentcryptography): the deprecated cipher constructors go chore(paymentcryptography): the duplicate import goes test(paymentcryptography): the DUKPT vectors the standard publishes fix(paymentcryptography): the DUKPT refusal is the derivation's docs(paymentcryptography): the retail MAC is over a double-length key fix(paymentcryptography): the ISO 9797-1 MAC pads only a partial block refactor(paymentcryptography): the refusals the model already makes chore(aws): the routes are generated from the models again * chore(aws): the IAM resources are generated again
This commit is contained in:
1 parent
ae196fb9ac
commit
4617e4a4f8
45 files changed
+3942
-356
No files matched your search
@@ -28,6 +28,9 @@
|
||||
# src/main/resources/aws/payment-cryptography-request-shapes.json, the Payment Cryptography
|
||||
# request constraints, is generated from botocore's model by
|
||||
# tools/aws/regen_payment_cryptography_shapes.py.
|
||||
# src/main/resources/aws/payment-cryptography-data-request-shapes.json, the Payment Cryptography
|
||||
# data plane request constraints, is generated from botocore's data plane model by
|
||||
# tools/aws/regen_payment_cryptography_data_shapes.py.
|
||||
# src/main/resources/aws/rds-ca-certificates.json, each Region's RDS certificate authorities, is
|
||||
# generated from the certificate bundles AWS publishes by tools/aws/regen_rds_ca_certificates.py.
|
||||
# src/main/resources/aws/iam-request-shapes.json, the IAM request constraints of the operations
|
||||
@@ -277,6 +280,7 @@ aws-data-sync-botocore: ## Regenerate only the AWS data derived from botocore, s
|
||||
$(PYTHON) tools/aws/regen_logs_delivery_shapes.py
|
||||
$(PYTHON) tools/aws/regen_ecr_shapes.py
|
||||
$(PYTHON) tools/aws/regen_payment_cryptography_shapes.py
|
||||
$(PYTHON) tools/aws/regen_payment_cryptography_data_shapes.py
|
||||
$(PYTHON) tools/aws/regen_iam_shapes.py
|
||||
$(PYTHON) tools/aws/regen_sts_shapes.py
|
||||
$(PYTHON) tools/aws/regen_apigateway_types.py
|
||||
@@ -371,6 +375,12 @@ aws-data-check-botocore: ## The AWS data derived from botocore must match a fres
|
||||
echo " Run 'make aws-data-sync' and commit the result."; \
|
||||
exit 1; \
|
||||
}
|
||||
@$(PYTHON) tools/aws/regen_payment_cryptography_data_shapes.py --check || { \
|
||||
echo ""; \
|
||||
echo "error: src/main/resources/aws/payment-cryptography-data-request-shapes.json is out of date."; \
|
||||
echo " Run 'make aws-data-sync' and commit the result."; \
|
||||
exit 1; \
|
||||
}
|
||||
@$(PYTHON) tools/aws/regen_apigateway_types.py --check || { \
|
||||
echo "error: API Gateway integration types are out of date; run 'make aws-data-sync'."; \
|
||||
exit 1; \
|
||||
|
||||
@@ -20,6 +20,7 @@ Tests are plain bash scripts that call `aws` CLI commands with `--endpoint-url`
|
||||
| `kms` | Keys, aliases, encrypt/decrypt |
|
||||
| `cognito` | User pools, clients |
|
||||
| `s3-notifications` | S3 → SQS event notifications |
|
||||
| `payment-cryptography-data` | The Payment Cryptography data plane: encrypt, decrypt, MAC |
|
||||
|
||||
## Requirements
|
||||
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
#!/usr/bin/env bats
|
||||
# Payment Cryptography data plane tests
|
||||
#
|
||||
# The data plane is a rest-json service of its own, signed for its own scope, so a
|
||||
# client of it reaches the routes under the internal prefix the router rewrites them
|
||||
# onto. These tests drive it with the AWS CLI, which is such a client.
|
||||
|
||||
setup() {
|
||||
load 'test_helper/common-setup'
|
||||
KEY_ARN=""
|
||||
MAC_KEY_ARN=""
|
||||
}
|
||||
|
||||
teardown() {
|
||||
for key in "$KEY_ARN" "$MAC_KEY_ARN"; do
|
||||
if [ -n "$key" ]; then
|
||||
aws_cmd payment-cryptography delete-key --key-identifier "$key" \
|
||||
--delete-key-in-days 7 >/dev/null 2>&1 || true
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
# A key of the data encryption usage, for the data the cipher encrypts.
|
||||
create_data_key() {
|
||||
aws_cmd 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
|
||||
}
|
||||
|
||||
# A key of the CMAC usage, for the MAC the service makes.
|
||||
create_mac_key() {
|
||||
aws_cmd payment-cryptography create-key \
|
||||
--key-attributes 'KeyAlgorithm=AES_256,KeyClass=SYMMETRIC_KEY,KeyUsage=TR31_M6_ISO_9797_5_CMAC_KEY,KeyModesOfUse={Generate=true,Verify=true}' \
|
||||
--exportable \
|
||||
--query 'Key.KeyArn' --output text
|
||||
}
|
||||
|
||||
@test "Payment Cryptography data plane: a key encrypts and decrypts" {
|
||||
KEY_ARN=$(create_data_key)
|
||||
[ -n "$KEY_ARN" ]
|
||||
|
||||
# The cipher pads no data, so the plaintext is a whole number of AES blocks.
|
||||
PLAIN_TEXT="68656c6c6f20776f726c642121212121"
|
||||
|
||||
run aws_cmd payment-cryptography-data encrypt-data \
|
||||
--key-identifier "$KEY_ARN" \
|
||||
--plain-text "$PLAIN_TEXT" \
|
||||
--encryption-attributes 'Symmetric={Mode=CBC}'
|
||||
assert_success
|
||||
CIPHER_TEXT=$(json_get "$output" '.CipherText')
|
||||
[ -n "$CIPHER_TEXT" ]
|
||||
[ "$CIPHER_TEXT" != "$PLAIN_TEXT" ]
|
||||
|
||||
run aws_cmd payment-cryptography-data decrypt-data \
|
||||
--key-identifier "$KEY_ARN" \
|
||||
--cipher-text "$CIPHER_TEXT" \
|
||||
--decryption-attributes 'Symmetric={Mode=CBC}'
|
||||
assert_success
|
||||
# The service carries the plaintext as hexadecimal in capitals.
|
||||
[ "$(json_get "$output" '.PlainText')" = "$(echo "$PLAIN_TEXT" | tr '[:lower:]' '[:upper:]')" ]
|
||||
}
|
||||
|
||||
@test "Payment Cryptography data plane: a key makes a MAC and verifies it" {
|
||||
MAC_KEY_ARN=$(create_mac_key)
|
||||
[ -n "$MAC_KEY_ARN" ]
|
||||
|
||||
MESSAGE="6d65737361676520746f2061757468656e746963617465"
|
||||
|
||||
run aws_cmd payment-cryptography-data generate-mac \
|
||||
--key-identifier "$MAC_KEY_ARN" \
|
||||
--message-data "$MESSAGE" \
|
||||
--mac-length 16 \
|
||||
--generation-attributes 'Algorithm=CMAC'
|
||||
assert_success
|
||||
MAC=$(json_get "$output" '.Mac')
|
||||
[ -n "$MAC" ]
|
||||
|
||||
run aws_cmd payment-cryptography-data verify-mac \
|
||||
--key-identifier "$MAC_KEY_ARN" \
|
||||
--message-data "$MESSAGE" \
|
||||
--mac "$MAC" \
|
||||
--mac-length 16 \
|
||||
--verification-attributes 'Algorithm=CMAC'
|
||||
assert_success
|
||||
}
|
||||
|
||||
@test "Payment Cryptography data plane: a MAC of another message is refused" {
|
||||
MAC_KEY_ARN=$(create_mac_key)
|
||||
[ -n "$MAC_KEY_ARN" ]
|
||||
|
||||
MESSAGE="6d65737361676520746f2061757468656e746963617465"
|
||||
|
||||
run aws_cmd payment-cryptography-data generate-mac \
|
||||
--key-identifier "$MAC_KEY_ARN" \
|
||||
--message-data "$MESSAGE" \
|
||||
--mac-length 16 \
|
||||
--generation-attributes 'Algorithm=CMAC'
|
||||
assert_success
|
||||
MAC=$(json_get "$output" '.Mac')
|
||||
|
||||
run aws_cmd payment-cryptography-data verify-mac \
|
||||
--key-identifier "$MAC_KEY_ARN" \
|
||||
--message-data "616e6f74686572206d65737361676520656e746972656c79" \
|
||||
--mac "$MAC" \
|
||||
--mac-length 16 \
|
||||
--verification-attributes 'Algorithm=CMAC'
|
||||
assert_failure
|
||||
}
|
||||
|
||||
@test "Payment Cryptography data plane: a key that is not there is refused" {
|
||||
run aws_cmd payment-cryptography-data encrypt-data \
|
||||
--key-identifier "arn:aws:payment-cryptography:us-east-1:000000000000:key/nope" \
|
||||
--plain-text "68656c6c6f20776f726c642121212121" \
|
||||
--encryption-attributes 'Symmetric={Mode=CBC}'
|
||||
assert_failure
|
||||
}
|
||||
|
||||
@test "Payment Cryptography data plane: a key of another purpose does not encrypt" {
|
||||
# A MAC key may not encrypt data, so the request is refused.
|
||||
MAC_KEY_ARN=$(create_mac_key)
|
||||
[ -n "$MAC_KEY_ARN" ]
|
||||
|
||||
run aws_cmd payment-cryptography-data encrypt-data \
|
||||
--key-identifier "$MAC_KEY_ARN" \
|
||||
--plain-text "68656c6c6f20776f726c642121212121" \
|
||||
--encryption-attributes 'Symmetric={Mode=CBC}'
|
||||
assert_failure
|
||||
}
|
||||
@@ -160,6 +160,10 @@
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>paymentcryptography</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>paymentcryptographydata</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>cognitoidentityprovider</artifactId>
|
||||
|
||||
@@ -107,6 +107,7 @@ 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.paymentcryptographydata.PaymentCryptographyDataClient;
|
||||
import software.amazon.awssdk.services.pipes.PipesClient;
|
||||
import software.amazon.awssdk.services.quicksight.QuickSightClient;
|
||||
import software.amazon.awssdk.services.ram.RamClient;
|
||||
@@ -1136,6 +1137,18 @@ public final class TestFixtures {
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* The Payment Cryptography data plane. The real service is a rest-json service of its
|
||||
* own, at its own host, so the client talks to it over the paths of that protocol.
|
||||
*/
|
||||
public static PaymentCryptographyDataClient paymentCryptographyDataClient() {
|
||||
return PaymentCryptographyDataClient.builder()
|
||||
.endpointOverride(ENDPOINT)
|
||||
.region(REGION)
|
||||
.credentialsProvider(CREDENTIALS)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static SecretsManagerClient secretsManagerClient() {
|
||||
return SecretsManagerClient.builder()
|
||||
.endpointOverride(ENDPOINT)
|
||||
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
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.services.paymentcryptography.model.KeyAlgorithm;
|
||||
import software.amazon.awssdk.services.paymentcryptography.model.KeyClass;
|
||||
import software.amazon.awssdk.services.paymentcryptography.model.KeyUsage;
|
||||
import software.amazon.awssdk.services.paymentcryptographydata.PaymentCryptographyDataClient;
|
||||
import software.amazon.awssdk.services.paymentcryptographydata.model.EncryptionDecryptionAttributes;
|
||||
import software.amazon.awssdk.services.paymentcryptographydata.model.EncryptionMode;
|
||||
import software.amazon.awssdk.services.paymentcryptographydata.model.GenerateMacRequest;
|
||||
import software.amazon.awssdk.services.paymentcryptographydata.model.MacAlgorithm;
|
||||
import software.amazon.awssdk.services.paymentcryptographydata.model.MacAttributes;
|
||||
import software.amazon.awssdk.services.paymentcryptographydata.model.ReEncryptionAttributes;
|
||||
import software.amazon.awssdk.services.paymentcryptographydata.model.SymmetricEncryptionAttributes;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
@DisplayName("Payment Cryptography data plane")
|
||||
class PaymentCryptographyDataPlaneTest {
|
||||
|
||||
/**
|
||||
* A plaintext long enough for the service to encrypt it. The cipher pads no data, so it
|
||||
* fills whole blocks.
|
||||
*/
|
||||
private static final String PLAIN_TEXT = hex("the quick brown fox jumps over the lazy dog!!!!!");
|
||||
|
||||
/** A message long enough for the service to make a MAC over it. */
|
||||
private static final String MESSAGE = hex("a message to authenticate");
|
||||
|
||||
private static PaymentCryptographyDataClient client;
|
||||
private static String keyArn;
|
||||
private static String macKeyArn;
|
||||
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
client = TestFixtures.paymentCryptographyDataClient();
|
||||
keyArn = TestFixtures.paymentCryptographyClient().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).generate(true).verify(true)))
|
||||
.exportable(true))
|
||||
.key().keyArn();
|
||||
// A MAC is made under a key of the MAC usage, so it is one of its own.
|
||||
macKeyArn = TestFixtures.paymentCryptographyClient().createKey(r -> r
|
||||
.keyAttributes(a -> a
|
||||
.keyAlgorithm(KeyAlgorithm.AES_256)
|
||||
.keyClass(KeyClass.SYMMETRIC_KEY)
|
||||
.keyUsage(KeyUsage.TR31_M6_ISO_9797_5_CMAC_KEY)
|
||||
.keyModesOfUse(m -> m.generate(true).verify(true)))
|
||||
.exportable(true))
|
||||
.key().keyArn();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void cleanup() {
|
||||
if (client != null) {
|
||||
client.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyEncryptsAndDecrypts() {
|
||||
String cipherText = client.encryptData(r -> r
|
||||
.keyIdentifier(keyArn)
|
||||
.plainText(PLAIN_TEXT)
|
||||
.encryptionAttributes(EncryptionDecryptionAttributes.builder()
|
||||
.symmetric(SymmetricEncryptionAttributes.builder().mode(EncryptionMode.CBC).build())
|
||||
.build()))
|
||||
.cipherText();
|
||||
|
||||
assertThat(cipherText).isNotBlank();
|
||||
assertThat(cipherText).isNotEqualTo(PLAIN_TEXT);
|
||||
|
||||
String plainText = client.decryptData(r -> r
|
||||
.keyIdentifier(keyArn)
|
||||
.cipherText(cipherText)
|
||||
.decryptionAttributes(EncryptionDecryptionAttributes.builder()
|
||||
.symmetric(SymmetricEncryptionAttributes.builder().mode(EncryptionMode.CBC).build())
|
||||
.build()))
|
||||
.plainText();
|
||||
|
||||
assertThat(plainText).isEqualTo(PLAIN_TEXT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyReEncryptsUnderAnother() {
|
||||
String otherArn = TestFixtures.paymentCryptographyClient().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().keyArn();
|
||||
|
||||
String cipherText = client.encryptData(r -> r
|
||||
.keyIdentifier(keyArn)
|
||||
.plainText(PLAIN_TEXT)
|
||||
.encryptionAttributes(EncryptionDecryptionAttributes.builder()
|
||||
.symmetric(SymmetricEncryptionAttributes.builder().mode(EncryptionMode.CBC).build())
|
||||
.build()))
|
||||
.cipherText();
|
||||
|
||||
// The re-encryption names the key it decrypts under in the path and the key it encrypts
|
||||
// under in the body, so the request carries two keys.
|
||||
String reEncrypted = client.reEncryptData(r -> r
|
||||
.incomingKeyIdentifier(keyArn)
|
||||
.outgoingKeyIdentifier(otherArn)
|
||||
.cipherText(cipherText)
|
||||
.incomingEncryptionAttributes(ReEncryptionAttributes.builder()
|
||||
.symmetric(SymmetricEncryptionAttributes.builder().mode(EncryptionMode.CBC).build())
|
||||
.build())
|
||||
.outgoingEncryptionAttributes(ReEncryptionAttributes.builder()
|
||||
.symmetric(SymmetricEncryptionAttributes.builder().mode(EncryptionMode.CBC).build())
|
||||
.build()))
|
||||
.cipherText();
|
||||
|
||||
assertThat(reEncrypted).isNotBlank();
|
||||
assertThat(reEncrypted).isNotEqualTo(cipherText);
|
||||
|
||||
// The block under the other key decrypts there and not under the first.
|
||||
String plainText = client.decryptData(r -> r
|
||||
.keyIdentifier(otherArn)
|
||||
.cipherText(reEncrypted)
|
||||
.decryptionAttributes(EncryptionDecryptionAttributes.builder()
|
||||
.symmetric(SymmetricEncryptionAttributes.builder().mode(EncryptionMode.CBC).build())
|
||||
.build()))
|
||||
.plainText();
|
||||
|
||||
assertThat(plainText).isEqualTo(PLAIN_TEXT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyMakesAMacAndVerifiesIt() {
|
||||
GenerateMacRequest mac = GenerateMacRequest.builder()
|
||||
.keyIdentifier(macKeyArn)
|
||||
.messageData(MESSAGE)
|
||||
.macLength(16)
|
||||
.generationAttributes(MacAttributes.builder()
|
||||
.algorithm(MacAlgorithm.CMAC)
|
||||
.build())
|
||||
.build();
|
||||
|
||||
String value = client.generateMac(mac).mac();
|
||||
|
||||
assertThat(value).isNotBlank();
|
||||
|
||||
// The service fails the request when the MAC is not the one over the message.
|
||||
client.verifyMac(r -> r
|
||||
.keyIdentifier(macKeyArn)
|
||||
.messageData(MESSAGE)
|
||||
.mac(value)
|
||||
.macLength(16)
|
||||
.verificationAttributes(MacAttributes.builder()
|
||||
.algorithm(MacAlgorithm.CMAC)
|
||||
.build()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMacOfAnotherMessageIsRefused() {
|
||||
String value = client.generateMac(r -> r
|
||||
.keyIdentifier(macKeyArn)
|
||||
.messageData(MESSAGE)
|
||||
.macLength(16)
|
||||
.generationAttributes(MacAttributes.builder()
|
||||
.algorithm(MacAlgorithm.CMAC)
|
||||
.build()))
|
||||
.mac();
|
||||
|
||||
// The failure names the reason the model's shape carries, so a caller can tell a bad
|
||||
// MAC from a bad request.
|
||||
AwsServiceException refusal = assertThrows(AwsServiceException.class, () -> client.verifyMac(r -> r
|
||||
.keyIdentifier(macKeyArn)
|
||||
.messageData(hex("another message entirely"))
|
||||
.mac(value)
|
||||
.macLength(16)
|
||||
.verificationAttributes(MacAttributes.builder()
|
||||
.algorithm(MacAlgorithm.CMAC)
|
||||
.build())));
|
||||
assertThat(refusal.awsErrorDetails().errorCode()).isEqualTo("VerificationFailedException");
|
||||
assertThat(refusal.statusCode()).isEqualTo(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyThatIsNotThereIsRefused() {
|
||||
// The identifier matches the model's pattern, so the request reaches the key it names
|
||||
// rather than being refused as a malformed one.
|
||||
AwsServiceException refusal = assertThrows(AwsServiceException.class, () -> client.encryptData(r -> r
|
||||
.keyIdentifier("arn:aws:payment-cryptography:us-east-1:000000000000:key/0123456789abcdef")
|
||||
.plainText(PLAIN_TEXT)
|
||||
.encryptionAttributes(EncryptionDecryptionAttributes.builder()
|
||||
.symmetric(SymmetricEncryptionAttributes.builder().mode(EncryptionMode.CBC).build())
|
||||
.build())));
|
||||
assertThat(refusal.awsErrorDetails().errorCode()).isEqualTo("ResourceNotFoundException");
|
||||
assertThat(refusal.statusCode()).isEqualTo(404);
|
||||
}
|
||||
|
||||
/** Bytes as the data plane carries them: hexadecimal. */
|
||||
private static String hex(String text) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (byte b : text.getBytes(StandardCharsets.UTF_8)) {
|
||||
sb.append(String.format("%02X", b));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
+34
-1
@@ -68,9 +68,24 @@ class PaymentCryptographyTest {
|
||||
}
|
||||
|
||||
private static Key createAesKey() {
|
||||
return createKey(KeyAlgorithm.AES_256);
|
||||
}
|
||||
|
||||
/**
|
||||
* A Triple DES key, whose check value is the ANSI X9.24 one.
|
||||
*
|
||||
* <p>The key is created here because creating it computes that value, and the cipher
|
||||
* behind it is the one the native image has to carry.
|
||||
*/
|
||||
private static Key createTdesKey() {
|
||||
return createKey(KeyAlgorithm.TDES_2_KEY);
|
||||
}
|
||||
|
||||
/** A key of the given algorithm, for the data the cipher protects. */
|
||||
private static Key createKey(KeyAlgorithm algorithm) {
|
||||
Key key = client.createKey(r -> r
|
||||
.keyAttributes(a -> a
|
||||
.keyAlgorithm(KeyAlgorithm.AES_256)
|
||||
.keyAlgorithm(algorithm)
|
||||
.keyClass(KeyClass.SYMMETRIC_KEY)
|
||||
.keyUsage(KeyUsage.TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY)
|
||||
.keyModesOfUse(m -> m.encrypt(true).decrypt(true)))
|
||||
@@ -113,6 +128,24 @@ class PaymentCryptographyTest {
|
||||
assertThat(read.keyCheckValue()).isEqualTo(created.keyCheckValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTripleDesKeyIsCreatedAndItsCheckValueIsTheX924One() {
|
||||
// The check value of a Triple DES key is the ANSI X9.24 one, so it is the leftmost
|
||||
// three bytes of encrypting eight zero bytes with the key. The native image has to
|
||||
// carry that cipher, so the key is created here and the value is read back.
|
||||
Key created = createTdesKey();
|
||||
|
||||
assertThat(created.keyArn()).isNotBlank();
|
||||
assertThat(created.keyState()).isEqualTo(KeyState.CREATE_COMPLETE);
|
||||
assertThat(created.keyCheckValueAlgorithm()).isEqualTo(KeyCheckValueAlgorithm.ANSI_X9_24);
|
||||
assertThat(created.keyCheckValue()).hasSize(6);
|
||||
assertThat(created.keyAttributes().keyAlgorithm()).isEqualTo(KeyAlgorithm.TDES_2_KEY);
|
||||
|
||||
Key read = client.getKey(k -> k.keyIdentifier(created.keyArn())).key();
|
||||
assertThat(read.keyCheckValue()).isEqualTo(created.keyCheckValue());
|
||||
assertThat(read.keyCheckValueAlgorithm()).isEqualTo(KeyCheckValueAlgorithm.ANSI_X9_24);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyIsCreatedDisabledAndWithTags() {
|
||||
Key key = client.createKey(r -> r
|
||||
|
||||
@@ -35,6 +35,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
|
||||
| [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 |
|
||||
| [Payment Cryptography data plane](payment-cryptography-data.md) | `POST /keys/{KeyIdentifier}/encrypt` and the rest | REST JSON | 5 |
|
||||
| [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 |
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
# Payment Cryptography data plane
|
||||
|
||||
**Protocol:** REST JSON
|
||||
**Endpoint:** `http://localhost:4566`
|
||||
|
||||
The data plane of AWS Payment Cryptography: the operations that use a key. It is a service of
|
||||
its own, with its own host at `dataplane.payment-cryptography` and its own sign name, so a
|
||||
client that talks to the control plane does not reach it by accident.
|
||||
|
||||
## Supported Actions
|
||||
|
||||
<!-- floci:actions:start -->
|
||||
| Action | Description |
|
||||
| --- | --- |
|
||||
| `EncryptData` | Encrypt plaintext under a key, on `POST /keys/{KeyIdentifier}/encrypt` |
|
||||
| `DecryptData` | Decrypt a ciphertext under a key, on `POST /keys/{KeyIdentifier}/decrypt` |
|
||||
| `ReEncryptData` | Decrypt under one key and encrypt under another, on `POST /keys/{IncomingKeyIdentifier}/reencrypt` |
|
||||
| `GenerateMac` | A MAC of a message under a key, on `POST /mac/generate` |
|
||||
| `VerifyMac` | Verify a MAC over a message, on `POST /mac/verify` |
|
||||
<!-- floci:actions:end -->
|
||||
|
||||
## Emulation Behavior
|
||||
|
||||
- **The encryption is AES or Triple DES in CBC mode without padding**, so the caller supplies
|
||||
whole blocks: sixteen bytes under an AES key and eight under a Triple DES one, as the reference
|
||||
says. A plaintext that does not fill them is refused. A key of another family is refused rather
|
||||
than read as a key of one of these. The ciphertext is the encrypted bytes alone and is as long as
|
||||
the plaintext it holds: the initialization vector travels in the request's attributes, and a
|
||||
request that names none gets a zero vector. The blobs of the data plane are hexadecimal, which is
|
||||
what the reference says they are.
|
||||
- **The MAC is the one the request asks for.** The ISO 9797-1 algorithms 1 and 3 are the ones
|
||||
defined over Triple DES, and the CMAC is the AES-CMAC of RFC 4493, which is a whole block
|
||||
wide, so it is cut to a length the caller asks for. The service fails the request when the
|
||||
MAC is not the one over the message, because the answer of a verification has no verdict in
|
||||
it.
|
||||
- **The modes of use of a key decide what it may be used for.** A key without the `Encrypt`
|
||||
mode is refused for an encryption, and a key with `NoRestrictions` is refused for nothing.
|
||||
- **The usage of a key decides what it may be used for.** The modes say whether a key may be
|
||||
used at all; the usage says for what. A key of the PIN encryption usage is not used to
|
||||
encrypt arbitrary data, and a key of a MAC usage is not used to encrypt either.
|
||||
- **The key's own algorithm is the cipher that runs.** A key of an algorithm this service does
|
||||
not cipher with is refused rather than read as bytes it is not.
|
||||
|
||||
The two-segment paths are moved to an internal prefix for the requests signed for this
|
||||
service, so a path-style request for a bucket of that name still reaches S3.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Variable | Default | Description |
|
||||
|---|---|---|
|
||||
| `FLOCI_SERVICES_PAYMENTCRYPTOGRAPHY_ENABLED` | `true` | Enable or disable the service |
|
||||
|
||||
## Examples
|
||||
|
||||
```bash
|
||||
export AWS_ENDPOINT_URL=http://localhost:4566
|
||||
|
||||
# A key of the data encryption usage
|
||||
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)
|
||||
|
||||
# Encrypt under it. The cipher pads no data, so the plaintext is a whole number of
|
||||
# blocks: sixteen bytes for an AES key.
|
||||
aws payment-cryptography-data encrypt-data \
|
||||
--key-identifier "$KEY_ARN" \
|
||||
--plain-text "$(printf 'hello world!!!!!' | xxd -p -c 32)" \
|
||||
--encryption-attributes '{"Symmetric":{"Mode":"CBC"}}'
|
||||
```
|
||||
@@ -8,7 +8,7 @@
|
||||
<!-- floci:actions:start -->
|
||||
| Action | Description |
|
||||
| --- | --- |
|
||||
| `CreateKey` | Create a key with fresh AES-256 material |
|
||||
| `CreateKey` | Create a key with fresh material |
|
||||
| `GetKey` | Get a key's attributes, state and check value |
|
||||
| `ListKeys` | List the keys of a region |
|
||||
| `DeleteKey` | Delete a key |
|
||||
@@ -24,10 +24,12 @@
|
||||
|
||||
## 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.
|
||||
- **Real key material:** `CreateKey` generates the material the algorithm it names
|
||||
calls for: 32 bytes of AES-256 for an AES-256 key, 16 or 24 bytes for the two Triple
|
||||
DES ones, and a key pair for an RSA or EC one. The `KeyCheckValue` follows the
|
||||
algorithm: the leftmost three bytes of the CMAC of sixteen zero bytes under an AES
|
||||
key, and the ANSI X9.24 one for a Triple DES key. 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
|
||||
@@ -59,8 +61,11 @@
|
||||
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.
|
||||
- **The data plane is a service of its own:** the operations that use a key are on
|
||||
[the data plane's page](payment-cryptography-data.md), which is reached at its own
|
||||
routes.
|
||||
- **Not yet emulated:** the import and export formats, and the multi-region replication
|
||||
operations.
|
||||
|
||||
## Configuration
|
||||
|
||||
|
||||
@@ -172,6 +172,7 @@ nav:
|
||||
- Amazon Data Lifecycle Manager: services/dlm.md
|
||||
- ACM: services/acm.md
|
||||
- Payment Cryptography: services/payment-cryptography.md
|
||||
- Payment Cryptography data plane: services/payment-cryptography-data.md
|
||||
- ECS: services/ecs.md
|
||||
- ECR: services/ecr.md
|
||||
- AWS Resource Groups: services/resource-groups.md
|
||||
|
||||
@@ -67,6 +67,7 @@ import io.floci.aws.services.mwaa.MwaaController;
|
||||
import io.floci.aws.services.oam.OamController;
|
||||
import io.floci.aws.services.opensearch.ElasticsearchController;
|
||||
import io.floci.aws.services.opensearch.OpenSearchController;
|
||||
import io.floci.aws.services.paymentcryptography.PaymentCryptographyCryptoController;
|
||||
import io.floci.aws.services.pipes.PipesController;
|
||||
import io.floci.aws.services.quicksight.QuickSightController;
|
||||
import io.floci.aws.services.quicksight.QuickSightEmbedController;
|
||||
@@ -122,7 +123,11 @@ public class ResolvedServiceCatalog {
|
||||
* directory-bucket requests as {@code s3express} while the actions, ARNs and condition keys
|
||||
* remain {@code s3}; the IoT Jobs Data Plane signs as {@code iot-jobs-data} while its actions
|
||||
* are {@code iot:} ({@code iot:DescribeJobExecution} and peers in the Service Authorization
|
||||
* Reference). Keep this minimal: every entry suppresses a distinct IAM namespace.
|
||||
* Reference); the Payment Cryptography data plane's model signs as
|
||||
* {@code payment-cryptography}, the service the control plane signs for as well, while a
|
||||
* client that signs under the data plane's own name {@code payment-cryptography-data} is
|
||||
* served as that same namespace, whose actions are {@code payment-cryptography:}. Keep
|
||||
* this minimal: every entry suppresses a distinct IAM namespace.
|
||||
*/
|
||||
private static final Map<String, String> CREDENTIAL_SCOPE_ALIASES =
|
||||
Map.of(
|
||||
@@ -130,7 +135,8 @@ public class ResolvedServiceCatalog {
|
||||
"iot-jobs-data", "iot",
|
||||
"monitoring", "cloudwatch",
|
||||
"awsssoportal", "sso",
|
||||
"eventsv2", "events");
|
||||
"eventsv2", "events",
|
||||
"payment-cryptography-data", "payment-cryptography");
|
||||
|
||||
private final ServiceCatalog catalog;
|
||||
|
||||
@@ -304,6 +310,19 @@ public class ResolvedServiceCatalog {
|
||||
protocols(ServiceProtocol.JSON),
|
||||
Set.of("PaymentCryptographyControlPlane."), Set.of("payment-cryptography"),
|
||||
Set.of(), Set.of()),
|
||||
descriptor("payment-cryptography-data", "paymentcryptography",
|
||||
config.services().paymentcryptography().enabled(), true,
|
||||
"paymentcryptography",
|
||||
storageMode(config.storage().services().paymentcryptography().mode(),
|
||||
config.storage().mode()),
|
||||
config.storage().services().paymentcryptography().flushIntervalMs(), null,
|
||||
ServiceProtocol.REST_JSON,
|
||||
protocols(ServiceProtocol.REST_JSON),
|
||||
// The data plane is a rest-json service of its own, and its client
|
||||
// signs for the service, which is one scope for both of its planes; the
|
||||
// scope its own plane is named by is an alias of that one.
|
||||
Set.of(), Set.of("payment-cryptography", "payment-cryptography-data"), Set.of(),
|
||||
Set.of(PaymentCryptographyCryptoController.class)),
|
||||
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,
|
||||
|
||||
@@ -5,6 +5,7 @@ import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
@@ -26,7 +27,7 @@ import java.util.function.Predicate;
|
||||
public final class SignedServiceRoute {
|
||||
|
||||
private final ResolvedServiceCatalog catalog;
|
||||
private final String externalKey;
|
||||
private final Set<String> externalKeys;
|
||||
private final String internalPrefix;
|
||||
private final Predicate<String> publicPaths;
|
||||
|
||||
@@ -37,12 +38,25 @@ public final class SignedServiceRoute {
|
||||
*/
|
||||
public SignedServiceRoute(ResolvedServiceCatalog catalog, String externalKey, String internalPrefix,
|
||||
Predicate<String> publicPaths) {
|
||||
this(catalog, Set.of(externalKey), internalPrefix, publicPaths);
|
||||
}
|
||||
|
||||
/**
|
||||
* A service with more than one plane has one external key per plane, and a request signed for
|
||||
* either of them belongs to the service.
|
||||
*
|
||||
* @param externalKeys the service's external keys, one per plane
|
||||
* @param internalPrefix one path segment beginning with an underscore, such as {@code /_dlm}
|
||||
* @param publicPaths which normalized request paths are the service's contested routes
|
||||
*/
|
||||
public SignedServiceRoute(ResolvedServiceCatalog catalog, Set<String> externalKeys, String internalPrefix,
|
||||
Predicate<String> publicPaths) {
|
||||
if (!internalPrefix.startsWith("/_") || internalPrefix.indexOf('/', 1) >= 0) {
|
||||
throw new IllegalArgumentException("Internal prefix must be one segment starting with '/_': "
|
||||
+ internalPrefix);
|
||||
}
|
||||
this.catalog = catalog;
|
||||
this.externalKey = externalKey;
|
||||
this.externalKeys = Set.copyOf(externalKeys);
|
||||
this.internalPrefix = internalPrefix;
|
||||
this.publicPaths = publicPaths;
|
||||
}
|
||||
@@ -84,7 +98,7 @@ public final class SignedServiceRoute {
|
||||
return signingService(ctx)
|
||||
.flatMap(catalog::byCredentialScope)
|
||||
.map(ServiceDescriptor::externalKey)
|
||||
.filter(externalKey::equals)
|
||||
.filter(externalKeys::contains)
|
||||
.isPresent();
|
||||
}
|
||||
|
||||
|
||||
+136
-193
@@ -1,15 +1,11 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import io.floci.aws.services.paymentcryptography.crypto.Ciphers;
|
||||
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Arrays;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* The cryptography a key record needs: its material, its check value, and the operations the
|
||||
@@ -20,21 +16,30 @@ import java.util.Locale;
|
||||
* CMAC check value, and what the reference implementation its samples use
|
||||
* computes.
|
||||
*
|
||||
* <p>The data plane encrypts with AES in CBC mode and the padding the service calls PKCS#5,
|
||||
* which is PKCS#7 for a block cipher, and answers with the initialization vector and the
|
||||
* ciphertext in one blob. The MAC is the CMAC of the message under the key, cut to the
|
||||
* length the caller asks for.
|
||||
* <p>The data plane encrypts with AES or Triple DES in CBC mode and pads no data, so the
|
||||
* caller supplies whole blocks and the ciphertext is as long as the plaintext it holds, and
|
||||
* answers with the initialization vector and the ciphertext in one blob. The MAC is the CMAC of
|
||||
* the message under the key, cut to the length the caller asks for.
|
||||
*/
|
||||
final class PaymentCryptographyCrypto {
|
||||
|
||||
private static final byte[] ZERO_BLOCK = new byte[16];
|
||||
|
||||
/** The hexadecimal the key material is written in. */
|
||||
private static final HexFormat HEX = HexFormat.of();
|
||||
|
||||
/** The hexadecimal a check value is written in: the capitals the reference writes it in. */
|
||||
private static final HexFormat HEX_UPPER = HexFormat.of().withUpperCase();
|
||||
|
||||
/** The block size of AES, in bytes. */
|
||||
private static final int BLOCK = 16;
|
||||
|
||||
/** The initialization vector of a CBC encryption, in bytes. */
|
||||
private static final int IV_LENGTH = 16;
|
||||
|
||||
/** The initialization vector of a Triple DES CBC encryption, in bytes. */
|
||||
private static final int TDES_IV_LENGTH = 8;
|
||||
|
||||
/** The initial value of a key wrap, which the standard gives as it. */
|
||||
private static final byte[] INITIAL_VALUE = {
|
||||
(byte) 0xa6, (byte) 0xa6, (byte) 0xa6, (byte) 0xa6,
|
||||
@@ -69,7 +74,7 @@ final class PaymentCryptographyCrypto {
|
||||
: tdesEcbEncrypt(new byte[8], key);
|
||||
byte[] value = new byte[3];
|
||||
System.arraycopy(mac, 0, value, 0, 3);
|
||||
return toHex(value).toUpperCase(Locale.ROOT);
|
||||
return HEX_UPPER.formatHex(value);
|
||||
}
|
||||
|
||||
/** The check value of a key of that algorithm, from the key's bytes. */
|
||||
@@ -79,7 +84,7 @@ final class PaymentCryptographyCrypto {
|
||||
: tdesEcbEncrypt(new byte[8], key);
|
||||
byte[] value = new byte[3];
|
||||
System.arraycopy(mac, 0, value, 0, 3);
|
||||
return toHex(value).toUpperCase(Locale.ROOT);
|
||||
return HEX_UPPER.formatHex(value);
|
||||
}
|
||||
|
||||
/** The check value of an AES key: the leftmost three bytes of the CMAC of sixteen zero bytes. */
|
||||
@@ -87,36 +92,25 @@ final class PaymentCryptographyCrypto {
|
||||
byte[] mac = cmac(fromHex(keyHex), ZERO_BLOCK);
|
||||
byte[] value = new byte[3];
|
||||
System.arraycopy(mac, 0, value, 0, 3);
|
||||
return toHex(value).toUpperCase(Locale.ROOT);
|
||||
return HEX_UPPER.formatHex(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Triple DES encryption of a block under a key, in ECB mode.
|
||||
* The Triple DES encryption of one block under a key, in ECB mode.
|
||||
*
|
||||
* <p>The check value of a Triple DES key is the leftmost three bytes of the encrypted
|
||||
* zeroes, so the block is encrypted and the first three bytes are taken.
|
||||
*
|
||||
* @param data the bytes to encrypt
|
||||
* <p>BouncyCastle's cipher is used rather than the JCE's, whose Triple DES is not
|
||||
* registered in the native image: a request that needs it there hangs until the job
|
||||
* is cancelled at its timeout.
|
||||
*
|
||||
* @param block8 the eight-byte block to encrypt
|
||||
* @param key the key, sixteen or twenty-four bytes
|
||||
* @return the encrypted bytes
|
||||
*/
|
||||
private static byte[] tdesEcbEncrypt(byte[] data, byte[] key) {
|
||||
try {
|
||||
byte[] key24 = key.length == 24 ? key : widenTdesKey(key);
|
||||
Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key24, "DESede"));
|
||||
return cipher.doFinal(data);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("the Triple DES key could not be used", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** A two-key Triple DES key widened to the three the cipher takes. */
|
||||
private static byte[] widenTdesKey(byte[] key) {
|
||||
byte[] wide = new byte[24];
|
||||
System.arraycopy(key, 0, wide, 0, 16);
|
||||
System.arraycopy(key, 0, wide, 16, 8);
|
||||
return wide;
|
||||
private static byte[] tdesEcbEncrypt(byte[] block8, byte[] key) {
|
||||
return Ciphers.tdes2Encrypt(block8, key);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -127,30 +121,26 @@ final class PaymentCryptographyCrypto {
|
||||
* subkey when it is whole and with the second when it is padded.
|
||||
*/
|
||||
static byte[] cmac(byte[] key, byte[] message) {
|
||||
try {
|
||||
byte[] k1 = subkeyOne(key);
|
||||
byte[] k2 = shiftLeft(k1);
|
||||
int blocks = Math.max(1, (message.length + BLOCK - 1) / BLOCK);
|
||||
byte[] last = new byte[BLOCK];
|
||||
int lastLength = message.length - (blocks - 1) * BLOCK;
|
||||
System.arraycopy(message, (blocks - 1) * BLOCK, last, 0, lastLength);
|
||||
if (lastLength == BLOCK) {
|
||||
last = xor(last, k1);
|
||||
} else {
|
||||
// The padding of a partial block is a one bit and zeroes, as the standard says.
|
||||
last[lastLength] = (byte) 0x80;
|
||||
last = xor(last, k2);
|
||||
}
|
||||
byte[] state = new byte[BLOCK];
|
||||
for (int i = 0; i < blocks - 1; i++) {
|
||||
byte[] block = new byte[BLOCK];
|
||||
System.arraycopy(message, i * BLOCK, block, 0, BLOCK);
|
||||
state = encrypt(xor(state, block), key);
|
||||
}
|
||||
return encrypt(xor(state, last), key);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("the AES key could not be used", e);
|
||||
byte[] k1 = subkeyOne(key);
|
||||
byte[] k2 = shiftLeft(k1);
|
||||
int blocks = Math.max(1, (message.length + BLOCK - 1) / BLOCK);
|
||||
byte[] last = new byte[BLOCK];
|
||||
int lastLength = message.length - (blocks - 1) * BLOCK;
|
||||
System.arraycopy(message, (blocks - 1) * BLOCK, last, 0, lastLength);
|
||||
if (lastLength == BLOCK) {
|
||||
last = Ciphers.xor(last, k1);
|
||||
} else {
|
||||
// The padding of a partial block is a one bit and zeroes, as the standard says.
|
||||
last[lastLength] = (byte) 0x80;
|
||||
last = Ciphers.xor(last, k2);
|
||||
}
|
||||
byte[] state = new byte[BLOCK];
|
||||
for (int i = 0; i < blocks - 1; i++) {
|
||||
byte[] block = new byte[BLOCK];
|
||||
System.arraycopy(message, i * BLOCK, block, 0, BLOCK);
|
||||
state = Ciphers.aesEcbEncrypt(Ciphers.xor(state, block), key);
|
||||
}
|
||||
return Ciphers.aesEcbEncrypt(Ciphers.xor(state, last), key);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -161,11 +151,7 @@ final class PaymentCryptographyCrypto {
|
||||
* the top.
|
||||
*/
|
||||
private static byte[] subkeyOne(byte[] key) {
|
||||
try {
|
||||
return shiftLeft(encrypt(ZERO_BLOCK, key));
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("the AES key could not be used", e);
|
||||
}
|
||||
return shiftLeft(Ciphers.aesEcbEncrypt(ZERO_BLOCK, key));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -199,74 +185,78 @@ final class PaymentCryptographyCrypto {
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The ciphertext of a plaintext under a key: the initialization vector and the encrypted
|
||||
* bytes in one blob, which is how the service answers.
|
||||
*/
|
||||
static byte[] encryptCbc(byte[] key, byte[] plaintext, SecureRandom random) {
|
||||
return encryptCbc(key, plaintext, null, random);
|
||||
}
|
||||
|
||||
/**
|
||||
* The ciphertext of a plaintext under a key, with the initialization vector the request
|
||||
* names.
|
||||
*
|
||||
* <p>A request that names a vector gets the ciphertext under it, so two parties that
|
||||
* agree on the vector can read each other's ciphertext. A request that names none gets a
|
||||
* fresh one.
|
||||
* zero vector, which is what the reference uses.
|
||||
*
|
||||
* @param key the key
|
||||
* @param plaintext the bytes to encrypt
|
||||
* @param initializationVector the vector to encrypt under, or null for a fresh one
|
||||
* @param random the randomness a fresh vector comes from
|
||||
* @return the vector and the encrypted bytes in one blob
|
||||
* @param initializationVector the vector to encrypt under, or null for the zero vector
|
||||
* @return the encrypted bytes
|
||||
*/
|
||||
static byte[] encryptCbc(byte[] key, byte[] plaintext, byte[] initializationVector,
|
||||
SecureRandom random) {
|
||||
try {
|
||||
byte[] iv;
|
||||
if (initializationVector == null) {
|
||||
iv = new byte[IV_LENGTH];
|
||||
random.nextBytes(iv);
|
||||
} else {
|
||||
if (initializationVector.length != IV_LENGTH) {
|
||||
throw new IllegalArgumentException("the initialization vector is "
|
||||
+ initializationVector.length + " bytes; it is " + IV_LENGTH);
|
||||
}
|
||||
iv = initializationVector.clone();
|
||||
}
|
||||
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
|
||||
byte[] encrypted = cipher.doFinal(plaintext);
|
||||
byte[] out = new byte[iv.length + encrypted.length];
|
||||
System.arraycopy(iv, 0, out, 0, iv.length);
|
||||
System.arraycopy(encrypted, 0, out, iv.length, encrypted.length);
|
||||
return out;
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("the AES key could not be used", e);
|
||||
}
|
||||
static byte[] encryptCbc(byte[] key, byte[] plaintext, byte[] initializationVector) {
|
||||
return aesCbcEncrypt(key, vector(initializationVector, IV_LENGTH), plaintext);
|
||||
}
|
||||
|
||||
/**
|
||||
* The plaintext of a blob the service encrypted.
|
||||
* The plaintext of a ciphertext the service encrypted.
|
||||
*
|
||||
* <p>The blob is the initialization vector and the ciphertext, so the vector is read first
|
||||
* and the rest is decrypted under it. A blob that is not the key's does not decrypt, and
|
||||
* the padding does not hold.
|
||||
* <p>The ciphertext is decrypted under the vector the request names. The cipher pads no
|
||||
* data, so a ciphertext that is not a whole number of blocks does not decrypt, and a
|
||||
* ciphertext that is not the key's does not decrypt either.
|
||||
*
|
||||
* @param key the key
|
||||
* @param ciphertext the encrypted bytes
|
||||
* @param initializationVector the vector to decrypt under, or null for the zero vector
|
||||
* @return the plaintext
|
||||
*/
|
||||
static byte[] decryptCbc(byte[] key, byte[] blob) {
|
||||
if (blob.length <= IV_LENGTH) {
|
||||
throw new IllegalArgumentException("the ciphertext is shorter than the initialization vector");
|
||||
static byte[] decryptCbc(byte[] key, byte[] ciphertext, byte[] initializationVector) {
|
||||
return aesCbcDecrypt(key, vector(initializationVector, IV_LENGTH), ciphertext);
|
||||
}
|
||||
|
||||
/**
|
||||
* The ciphertext of a plaintext under a Triple DES key, with the initialization vector the
|
||||
* request names.
|
||||
*
|
||||
* <p>The cipher pads no data, so the caller supplies whole blocks of eight bytes, and the
|
||||
* ciphertext is as long as the plaintext it holds. A two-key key is used under the three keys
|
||||
* it holds, as the cipher takes them.
|
||||
*
|
||||
* @param key the key
|
||||
* @param plaintext the bytes to encrypt
|
||||
* @param initializationVector the vector to encrypt under, or null for the zero vector
|
||||
* @return the encrypted bytes
|
||||
*/
|
||||
static byte[] tdesCbcEncrypt(byte[] key, byte[] plaintext, byte[] initializationVector) {
|
||||
return Ciphers.tdesCbcEncrypt(plaintext, key, vector(initializationVector, TDES_IV_LENGTH));
|
||||
}
|
||||
|
||||
/**
|
||||
* The plaintext of a ciphertext the service encrypted under a Triple DES key.
|
||||
*
|
||||
* @param key the key
|
||||
* @param ciphertext the encrypted bytes
|
||||
* @param initializationVector the vector to decrypt under, or null for the zero vector
|
||||
* @return the plaintext
|
||||
*/
|
||||
static byte[] tdesCbcDecrypt(byte[] key, byte[] ciphertext, byte[] initializationVector) {
|
||||
return Ciphers.tdesCbcDecrypt(ciphertext, key, vector(initializationVector, TDES_IV_LENGTH));
|
||||
}
|
||||
|
||||
/** The vector a cipher starts from, the zero vector when the request names none. */
|
||||
private static byte[] vector(byte[] initializationVector, int length) {
|
||||
if (initializationVector == null) {
|
||||
return new byte[length];
|
||||
}
|
||||
try {
|
||||
byte[] iv = Arrays.copyOfRange(blob, 0, IV_LENGTH);
|
||||
byte[] encrypted = Arrays.copyOfRange(blob, IV_LENGTH, blob.length);
|
||||
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
|
||||
return cipher.doFinal(encrypted);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalArgumentException("the ciphertext did not open under the key", e);
|
||||
if (initializationVector.length != length) {
|
||||
throw new IllegalArgumentException("the initialization vector is "
|
||||
+ initializationVector.length + " bytes; it is " + length);
|
||||
}
|
||||
return initializationVector.clone();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -274,28 +264,24 @@ final class PaymentCryptographyCrypto {
|
||||
* key was the right one.
|
||||
*/
|
||||
static byte[] keyWrap(byte[] key, byte[] plaintext) {
|
||||
try {
|
||||
byte[] a = INITIAL_VALUE.clone();
|
||||
byte[][] r = split(plaintext, 8);
|
||||
int n = r.length;
|
||||
for (int j = 0; j < 6; j++) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
byte[] block = concat(a, r[i]);
|
||||
byte[] encrypted = encrypt(block, key);
|
||||
a = Arrays.copyOfRange(encrypted, 0, 8);
|
||||
r[i] = Arrays.copyOfRange(encrypted, 8, encrypted.length);
|
||||
a = xor(a, counter(j, n, i));
|
||||
}
|
||||
}
|
||||
byte[] out = new byte[8 + plaintext.length];
|
||||
System.arraycopy(a, 0, out, 0, 8);
|
||||
byte[] a = INITIAL_VALUE.clone();
|
||||
byte[][] r = split(plaintext, 8);
|
||||
int n = r.length;
|
||||
for (int j = 0; j < 6; j++) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
System.arraycopy(r[i], 0, out, 8 + i * 8, 8);
|
||||
byte[] block = concat(a, r[i]);
|
||||
byte[] encrypted = Ciphers.aesEcbEncrypt(block, key);
|
||||
a = Arrays.copyOfRange(encrypted, 0, 8);
|
||||
r[i] = Arrays.copyOfRange(encrypted, 8, encrypted.length);
|
||||
a = Ciphers.xor(a, counter(j, n, i));
|
||||
}
|
||||
return out;
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("the AES key could not be used", e);
|
||||
}
|
||||
byte[] out = new byte[8 + plaintext.length];
|
||||
System.arraycopy(a, 0, out, 0, 8);
|
||||
for (int i = 0; i < n; i++) {
|
||||
System.arraycopy(r[i], 0, out, 8 + i * 8, 8);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -305,27 +291,23 @@ final class PaymentCryptographyCrypto {
|
||||
if (wrapped.length < 16 || (wrapped.length - 8) % 8 != 0) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
byte[] a = Arrays.copyOfRange(wrapped, 0, 8);
|
||||
byte[][] r = split(Arrays.copyOfRange(wrapped, 8, wrapped.length), 8);
|
||||
int n = r.length;
|
||||
for (int j = 5; j >= 0; j--) {
|
||||
for (int i = n - 1; i >= 0; i--) {
|
||||
byte[] block = concat(xor(a, counter(j, n, i)), r[i]);
|
||||
byte[] decrypted = decrypt(block, key);
|
||||
a = Arrays.copyOfRange(decrypted, 0, 8);
|
||||
r[i] = Arrays.copyOfRange(decrypted, 8, decrypted.length);
|
||||
}
|
||||
byte[] a = Arrays.copyOfRange(wrapped, 0, 8);
|
||||
byte[][] r = split(Arrays.copyOfRange(wrapped, 8, wrapped.length), 8);
|
||||
int n = r.length;
|
||||
for (int j = 5; j >= 0; j--) {
|
||||
for (int i = n - 1; i >= 0; i--) {
|
||||
byte[] block = concat(Ciphers.xor(a, counter(j, n, i)), r[i]);
|
||||
byte[] decrypted = Ciphers.aesEcbDecrypt(block, key);
|
||||
a = Arrays.copyOfRange(decrypted, 0, 8);
|
||||
r[i] = Arrays.copyOfRange(decrypted, 8, decrypted.length);
|
||||
}
|
||||
byte[] check = INITIAL_VALUE;
|
||||
byte[] out = new byte[wrapped.length - 8];
|
||||
for (int i = 0; i < n; i++) {
|
||||
System.arraycopy(r[i], 0, out, i * 8, 8);
|
||||
}
|
||||
return Arrays.equals(a, check) ? out : null;
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("the AES key could not be used", e);
|
||||
}
|
||||
byte[] check = INITIAL_VALUE;
|
||||
byte[] out = new byte[wrapped.length - 8];
|
||||
for (int i = 0; i < n; i++) {
|
||||
System.arraycopy(r[i], 0, out, i * 8, 8);
|
||||
}
|
||||
return Arrays.equals(a, check) ? out : null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -354,72 +336,33 @@ final class PaymentCryptographyCrypto {
|
||||
return out;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* The AES-CBC encryption of data under a key and an initialization vector, without
|
||||
* padding: the vector is the length of the data's block size already.
|
||||
*/
|
||||
static byte[] aesCbcEncrypt(byte[] key, byte[] iv, byte[] data) {
|
||||
try {
|
||||
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
|
||||
return cipher.doFinal(data);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("the AES key could not be used", e);
|
||||
}
|
||||
return Ciphers.aesCbcEncrypt(data, key, iv);
|
||||
}
|
||||
|
||||
/** The AES-CBC decryption of data under a key and an initialization vector, without padding. */
|
||||
static byte[] aesCbcDecrypt(byte[] key, byte[] iv, byte[] data) {
|
||||
try {
|
||||
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
|
||||
return cipher.doFinal(data);
|
||||
} catch (GeneralSecurityException e) {
|
||||
return Ciphers.aesCbcDecrypt(data, key, iv);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new IllegalArgumentException("the data did not decrypt under the key", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** One block of AES in ECB mode. */
|
||||
static byte[] aesEcbEncrypt(byte[] input, byte[] key) {
|
||||
try {
|
||||
return encrypt(input, key);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("the AES key could not be used", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** One block of AES in ECB mode. */
|
||||
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);
|
||||
}
|
||||
|
||||
/** One block of AES in ECB mode, the other way round. */
|
||||
private static byte[] decrypt(byte[] input, byte[] key) throws GeneralSecurityException {
|
||||
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"));
|
||||
return cipher.doFinal(input);
|
||||
return Ciphers.aesEcbEncrypt(input, key);
|
||||
}
|
||||
|
||||
static String toHex(byte[] bytes) {
|
||||
return HexFormat.of().formatHex(bytes);
|
||||
return HEX.formatHex(bytes);
|
||||
}
|
||||
|
||||
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;
|
||||
return HEX.parseHex(hex);
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.PathParam;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
/**
|
||||
* The data plane's encryption and its MACs.
|
||||
*
|
||||
* <p>The routes are the ones the AWS SDK builds: the key is in the path, and the body says
|
||||
* what to do with it.
|
||||
*/
|
||||
@Path(PaymentCryptographyDataPlaneRouteFilter.INTERNAL_PREFIX)
|
||||
public class PaymentCryptographyCryptoController extends PaymentCryptographyDataPlaneController {
|
||||
|
||||
private final PaymentCryptographyCryptoHandler handler;
|
||||
|
||||
@Inject
|
||||
public PaymentCryptographyCryptoController(PaymentCryptographyCryptoHandler handler,
|
||||
ObjectMapper objectMapper,
|
||||
RegionResolver regionResolver) {
|
||||
super(objectMapper, regionResolver);
|
||||
this.handler = handler;
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/keys/{keyIdentifier:.+}/encrypt")
|
||||
public Response encryptData(@PathParam("keyIdentifier") String keyIdentifier, String body,
|
||||
@Context HttpHeaders headers) {
|
||||
return respond(handler.encryptData(request(body, keyIdentifier, "KeyIdentifier"), region(headers)));
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/keys/{keyIdentifier:.+}/decrypt")
|
||||
public Response decryptData(@PathParam("keyIdentifier") String keyIdentifier, String body,
|
||||
@Context HttpHeaders headers) {
|
||||
return respond(handler.decryptData(request(body, keyIdentifier, "KeyIdentifier"), region(headers)));
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/keys/{incomingKeyIdentifier:.+}/reencrypt")
|
||||
public Response reEncryptData(@PathParam("incomingKeyIdentifier") String incomingKeyIdentifier,
|
||||
String body, @Context HttpHeaders headers) {
|
||||
// The key the block is encrypted under is in the body, and it is the only other
|
||||
// key the request may name. The model says the request must name it, so a request
|
||||
// that does not is refused there.
|
||||
JsonNode request = request(body, incomingKeyIdentifier, "IncomingKeyIdentifier");
|
||||
return respond(handler.reEncryptData(request, region(headers)));
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/mac/generate")
|
||||
public Response generateMac(String body, @Context HttpHeaders headers) {
|
||||
return respond(handler.generateMac(parse(body), region(headers)));
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/mac/verify")
|
||||
public Response verifyMac(String body, @Context HttpHeaders headers) {
|
||||
return respond(handler.verifyMac(parse(body), region(headers)));
|
||||
}
|
||||
}
|
||||
+684
@@ -0,0 +1,684 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.paymentcryptography.crypto.Ciphers;
|
||||
import io.floci.aws.services.paymentcryptography.crypto.DukptCrypto;
|
||||
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The data plane's encryption and its MACs: the operations that use a key to protect data.
|
||||
*
|
||||
* <p>The data plane is a service of its own, with its own host and its own sign name, and it
|
||||
* is served over rest-json rather than over the control plane's awsJson. The operations are
|
||||
* the same either way, so they live here and the protocol handler calls them.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class PaymentCryptographyCryptoHandler {
|
||||
|
||||
/** The usages a key may have for the data encryption operations. */
|
||||
private static final List<String> DATA_ENCRYPTION_USAGES = List.of(
|
||||
"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
|
||||
|
||||
/** The usages a key may have for the MAC operations. */
|
||||
private static final List<String> MAC_USAGES = List.of(
|
||||
"TR31_M0_ISO_16609_MAC_KEY",
|
||||
"TR31_M1_ISO_9797_1_MAC_KEY",
|
||||
"TR31_M3_ISO_9797_3_MAC_KEY",
|
||||
"TR31_M6_ISO_9797_5_CMAC_KEY",
|
||||
"TR31_M7_HMAC_KEY");
|
||||
|
||||
/** The usages a key may have for the derivation a DUKPT MAC key is made by. */
|
||||
private static final List<String> DERIVATION_USAGES = List.of(
|
||||
"TR31_B0_BASE_DERIVATION_KEY");
|
||||
|
||||
/** The hexadecimal the blobs of the protocol carry themselves in. */
|
||||
private static final HexFormat HEX = HexFormat.of().withUpperCase();
|
||||
|
||||
/** The block size of AES, in bytes: the block the cipher works in. */
|
||||
private static final int AES_BLOCK = 16;
|
||||
|
||||
/** The block size of Triple DES, in bytes: the block the cipher works in. */
|
||||
private static final int TDES_BLOCK = 8;
|
||||
|
||||
/** The shortest MAC the service computes, in bytes. */
|
||||
private static final int SHORTEST_MAC = 4;
|
||||
|
||||
/** The longest MAC the ISO 9797 algorithms give, in bytes. */
|
||||
private static final int LONGEST_MAC = 8;
|
||||
|
||||
/** The longest MAC the CMAC gives, in bytes: a whole AES block. */
|
||||
private static final int LONGEST_CMAC = 16;
|
||||
|
||||
private final PaymentCryptographyService service;
|
||||
|
||||
@Inject
|
||||
public PaymentCryptographyCryptoHandler(PaymentCryptographyService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
/**
|
||||
* Encrypts the plaintext under the key the request names.
|
||||
*
|
||||
* <p>The service encrypts with the cipher the key's algorithm names, in CBC mode, and
|
||||
* pads no data, so the plaintext fills whole blocks, and answers with the ciphertext
|
||||
* alone: the initialization vector travels in the request's attributes.
|
||||
*/
|
||||
public Map<String, Object> encryptData(JsonNode request, String region) {
|
||||
// The request is checked against the constraints the model states for it.
|
||||
PaymentCryptographyDataRequestShapes.check("EncryptData", request);
|
||||
PaymentCryptographyKey key = requiredKey(request, region, "KeyIdentifier");
|
||||
requireMode(key, "Encrypt", "encrypt");
|
||||
Encryption encryption = encryptionAttributes(request.get("EncryptionAttributes"));
|
||||
requireCipherFamily(key, "encrypt");
|
||||
requireUsage(key, DATA_ENCRYPTION_USAGES, "encrypt data");
|
||||
byte[] plaintext = blob(request, "PlainText");
|
||||
requireBlockAligned(plaintext, key, "PlainText");
|
||||
byte[] ciphertext = encrypt(material(key), plaintext,
|
||||
initializationVector(encryption, key, "encrypting"), key);
|
||||
return answer(key, Map.of("CipherText", encode(ciphertext)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypts a blob the service encrypted.
|
||||
*/
|
||||
public Map<String, Object> decryptData(JsonNode request, String region) {
|
||||
// The request is checked against the constraints the model states for it.
|
||||
PaymentCryptographyDataRequestShapes.check("DecryptData", request);
|
||||
PaymentCryptographyKey key = requiredKey(request, region, "KeyIdentifier");
|
||||
requireMode(key, "Decrypt", "decrypt");
|
||||
Encryption encryption = encryptionAttributes(request.get("DecryptionAttributes"));
|
||||
requireCipherFamily(key, "decrypt");
|
||||
requireUsage(key, DATA_ENCRYPTION_USAGES, "decrypt data");
|
||||
byte[] ciphertext = blob(request, "CipherText");
|
||||
requireBlockAligned(ciphertext, key, "CipherText");
|
||||
byte[] plaintext = decrypt(material(key), ciphertext,
|
||||
initializationVector(encryption, key, "decrypting"), key);
|
||||
return answer(key, Map.of("PlainText", encode(plaintext)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypts under one key and encrypts under another.
|
||||
*/
|
||||
public Map<String, Object> reEncryptData(JsonNode request, String region) {
|
||||
// The request is checked against the constraints the model states for it.
|
||||
PaymentCryptographyDataRequestShapes.check("ReEncryptData", request);
|
||||
PaymentCryptographyKey incoming = requiredKey(request, region, "IncomingKeyIdentifier");
|
||||
requireMode(incoming, "Decrypt", "decrypt");
|
||||
PaymentCryptographyKey outgoing = requiredKey(request, region, "OutgoingKeyIdentifier");
|
||||
requireMode(outgoing, "Encrypt", "encrypt");
|
||||
Encryption incomingEncryption =
|
||||
encryptionAttributes(request.get("IncomingEncryptionAttributes"));
|
||||
Encryption outgoingEncryption =
|
||||
encryptionAttributes(request.get("OutgoingEncryptionAttributes"));
|
||||
requireCipherFamily(incoming, "decrypt");
|
||||
requireCipherFamily(outgoing, "encrypt");
|
||||
requireUsage(incoming, DATA_ENCRYPTION_USAGES, "decrypt data");
|
||||
requireUsage(outgoing, DATA_ENCRYPTION_USAGES, "encrypt data");
|
||||
byte[] ciphertext = blob(request, "CipherText");
|
||||
requireBlockAligned(ciphertext, incoming, "CipherText");
|
||||
byte[] plaintext = decrypt(material(incoming), ciphertext,
|
||||
initializationVector(incomingEncryption, incoming, "decrypting"), incoming);
|
||||
requireBlockAligned(plaintext, outgoing, "the plaintext");
|
||||
byte[] reEncrypted = encrypt(material(outgoing), plaintext,
|
||||
initializationVector(outgoingEncryption, outgoing, "encrypting"), outgoing);
|
||||
return answer(outgoing, Map.of("CipherText", encode(reEncrypted)));
|
||||
}
|
||||
|
||||
/**
|
||||
* The MAC of a message under the key: the CMAC of the message, cut to the length the
|
||||
* caller asks for.
|
||||
*/
|
||||
public Map<String, Object> generateMac(JsonNode request, String region) {
|
||||
// The request is checked against the constraints the model states for it.
|
||||
PaymentCryptographyDataRequestShapes.check("GenerateMac", request);
|
||||
PaymentCryptographyKey key = requiredKey(request, region, "KeyIdentifier");
|
||||
MacLeg leg = resolveMacLeg(request.get("GenerationAttributes"), key, region, "Generate",
|
||||
"generating a MAC with");
|
||||
byte[] message = blob(request, "MessageData");
|
||||
int length = macLength(request, leg, leg.longest);
|
||||
byte[] mac = leg.mac.apply(leg.keyBytes, message);
|
||||
byte[] answer = new byte[length];
|
||||
System.arraycopy(mac, 0, answer, 0, length);
|
||||
return answer(key, Map.of("Mac", encode(answer)));
|
||||
}
|
||||
|
||||
/**
|
||||
* The verdict of a MAC over a message.
|
||||
*/
|
||||
public Map<String, Object> verifyMac(JsonNode request, String region) {
|
||||
// The request is checked against the constraints the model states for it.
|
||||
PaymentCryptographyDataRequestShapes.check("VerifyMac", request);
|
||||
PaymentCryptographyKey key = requiredKey(request, region, "KeyIdentifier");
|
||||
MacLeg leg = resolveMacLeg(request.get("VerificationAttributes"), key, region, "Verify",
|
||||
"verifying a MAC with");
|
||||
byte[] message = blob(request, "MessageData");
|
||||
byte[] mac = blob(request, "Mac");
|
||||
int length = macLength(request, leg, mac.length);
|
||||
if (length != mac.length) {
|
||||
throw new AwsException("ValidationException",
|
||||
"MacLength does not match the length of Mac", 400);
|
||||
}
|
||||
byte[] expected = leg.mac.apply(leg.keyBytes, message);
|
||||
byte[] cut = new byte[length];
|
||||
System.arraycopy(expected, 0, cut, 0, Math.min(length, expected.length));
|
||||
if (!MessageDigest.isEqual(cut, mac)) {
|
||||
// The service does not answer that a MAC is not valid: it fails, because a caller
|
||||
// that asks whether a MAC is good gets an error rather than a false.
|
||||
throw new AwsException("VerificationFailedException",
|
||||
"This request failed verification.", 400, Map.of("Reason", "INVALID_MAC"));
|
||||
}
|
||||
return answer(key, Map.of());
|
||||
}
|
||||
|
||||
|
||||
/** The PIN data of a card account, verified against a generation key. */
|
||||
|
||||
/** The PIN data of one scheme translated into another. */
|
||||
|
||||
/** The card validation value of a card account. */
|
||||
|
||||
/** The card validation value of a card account, verified. */
|
||||
|
||||
/** The cryptogram of an authorization request, verified. */
|
||||
|
||||
/** The cryptogram of an authorization request, generated. */
|
||||
|
||||
/** The material of a key translated into another form. */
|
||||
public Map<String, Object> translateKeyMaterial(JsonNode request, String region) {
|
||||
refused("TranslateKeyMaterial");
|
||||
return Map.of();
|
||||
}
|
||||
|
||||
/**
|
||||
* The operation is not served, and says so.
|
||||
*/
|
||||
private static void refused(String operation) {
|
||||
throw new AwsException("ValidationException",
|
||||
operation + " is not served: its algorithm belongs to the payment scheme, and this "
|
||||
+ "service does not make one up", 400);
|
||||
}
|
||||
|
||||
/** The answer of an operation: what the operation made, and which key it made it with. */
|
||||
private static Map<String, Object> answer(PaymentCryptographyKey key, Map<String, Object> made) {
|
||||
Map<String, Object> out = new LinkedHashMap<>(made);
|
||||
out.put("KeyArn", key.getArn());
|
||||
out.put("KeyCheckValue", key.getKeyCheckValue());
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The cipher the request asks for.
|
||||
*
|
||||
* <p>The attributes name the mode and, for a symmetric cipher, the initialization vector.
|
||||
* The service encrypts in CBC mode, so a request that names another mode is refused
|
||||
* rather than answered with a cipher it did not ask for.
|
||||
*
|
||||
* @param attributes the attributes of the request, which may be absent
|
||||
* @return the cipher the request asks for
|
||||
*/
|
||||
private static Encryption encryptionAttributes(JsonNode attributes) {
|
||||
if (attributes == null || attributes.isNull()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"the encryption attributes are required", 400);
|
||||
}
|
||||
String variant = soleVariant(attributes);
|
||||
if (variant == null) {
|
||||
throw new AwsException("ValidationException",
|
||||
"the encryption attributes must specify exactly one variant", 400);
|
||||
}
|
||||
if (!"Symmetric".equals(variant)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"the encryption variant '" + variant + "' is not supported by this service "
|
||||
+ "(Symmetric)", 400);
|
||||
}
|
||||
JsonNode symmetric = attributes.get(variant);
|
||||
String mode = symmetric == null ? "" : symmetric.path("Mode").asText();
|
||||
if (!"CBC".equals(mode)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"the encryption mode '" + (mode.isEmpty() ? "(missing)" : mode)
|
||||
+ "' is not supported by this service (CBC)", 400);
|
||||
}
|
||||
if (symmetric != null && symmetric.hasNonNull("PaddingType")) {
|
||||
throw new AwsException("ValidationException",
|
||||
"PaddingType applies to RSA only; the symmetric cipher does not pad", 400);
|
||||
}
|
||||
byte[] iv = null;
|
||||
if (symmetric != null && symmetric.hasNonNull("InitializationVector")) {
|
||||
String hex = symmetric.path("InitializationVector").asText();
|
||||
if (!hex.isEmpty()) {
|
||||
// The model's pattern says the vector is hexadecimal, so it only decodes here.
|
||||
iv = HexFormat.of().parseHex(hex);
|
||||
}
|
||||
}
|
||||
return new Encryption(iv);
|
||||
}
|
||||
|
||||
/**
|
||||
* The initialization vector of a request, checked against the cipher's block size.
|
||||
*
|
||||
* <p>The length follows the key: an AES key takes a sixteen-byte vector and a Triple DES
|
||||
* one an eight-byte one, so a vector for one is not a vector for the other. A vector of
|
||||
* the wrong length is refused here, where the caller can act on it, and not by the
|
||||
* cipher, where it would be a server error.
|
||||
*
|
||||
* @param encryption the attributes of the request
|
||||
* @param key the key the cipher runs under
|
||||
* @param what the operation that is refused, for the message
|
||||
* @return the vector, or null when the request names none
|
||||
*/
|
||||
private static byte[] initializationVector(Encryption encryption, PaymentCryptographyKey key,
|
||||
String what) {
|
||||
byte[] iv = encryption.initializationVector();
|
||||
if (iv == null) {
|
||||
return null;
|
||||
}
|
||||
int length = isAes(key) ? 16 : 8;
|
||||
if (iv.length != length) {
|
||||
throw new AwsException("ValidationException",
|
||||
"the initialization vector is " + iv.length + " bytes; " + what + " under a "
|
||||
+ (isAes(key) ? "AES" : "Triple DES") + " key takes " + length, 400);
|
||||
}
|
||||
return iv;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a key is an AES key.
|
||||
*
|
||||
* <p>The key record knows its algorithm, so the family is read from there and not guessed
|
||||
* from the length of the material: a sixteen-byte key is a two-key Triple DES one and an
|
||||
* AES-128 one.
|
||||
*/
|
||||
private static boolean isAes(PaymentCryptographyKey key) {
|
||||
return PaymentCryptographyService.isAes(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the key is a Triple DES one.
|
||||
*
|
||||
* <p>The reference ciphers with AES and with Triple DES, and the block and the vector follow
|
||||
* the key's family: sixteen bytes and a sixteen-byte vector for AES, eight for Triple DES.
|
||||
*
|
||||
* @param key the key the cipher runs under
|
||||
* @return whether the key is a Triple DES one
|
||||
*/
|
||||
private static boolean isTdes(PaymentCryptographyKey key) {
|
||||
return PaymentCryptographyService.isTdes(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* The family a key's algorithm has to be for an operation.
|
||||
*
|
||||
* <p>The algorithm runs under the key: the ISO 9797 MACs are defined over Triple DES and
|
||||
* the CMAC over AES, so a key of the other family would be read as bytes it is not.
|
||||
*
|
||||
* @param key the key the operation runs under
|
||||
* @param aes whether the operation needs an AES key
|
||||
* @param what the operation, for the message
|
||||
*/
|
||||
private static void requireFamily(PaymentCryptographyKey key, boolean aes, String what) {
|
||||
if (isAes(key) != aes) {
|
||||
throw new AwsException("ValidationException",
|
||||
"the key " + key.getArn() + " is a " + key.getKeyAlgorithm() + " key, and "
|
||||
+ what + " needs a " + (aes ? "AES" : "Triple DES") + " one", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The family a key's algorithm belongs to.
|
||||
*
|
||||
* <p>The cipher runs under the key's own algorithm: an AES key is encrypted with AES and
|
||||
* a Triple DES one with Triple DES. A key whose algorithm this service does not cipher
|
||||
* with is refused rather than run through the cipher it does have.
|
||||
*
|
||||
* @param key the key the cipher runs under
|
||||
* @param what the operation that is refused, for the message
|
||||
*/
|
||||
private static void requireCipherFamily(PaymentCryptographyKey key, String what) {
|
||||
if (!isAes(key) && !isTdes(key)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"the key " + key.getArn() + " is a " + key.getKeyAlgorithm()
|
||||
+ " key, and this service does not cipher with that algorithm to "
|
||||
+ what, 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The ciphertext of a plaintext under the key, in the cipher the key's family runs.
|
||||
*
|
||||
* @param key the key's material
|
||||
* @param plaintext the bytes to encrypt
|
||||
* @param initializationVector the vector to encrypt under
|
||||
* @param record the key the cipher runs under, whose family names the cipher
|
||||
* @return the encrypted bytes
|
||||
*/
|
||||
private byte[] encrypt(byte[] key, byte[] plaintext, byte[] initializationVector,
|
||||
PaymentCryptographyKey record) {
|
||||
return isAes(record)
|
||||
? PaymentCryptographyCrypto.encryptCbc(key, plaintext, initializationVector)
|
||||
: PaymentCryptographyCrypto.tdesCbcEncrypt(key, plaintext, initializationVector);
|
||||
}
|
||||
|
||||
/**
|
||||
* The plaintext of a ciphertext the service encrypted under the key.
|
||||
*
|
||||
* @param key the key's material
|
||||
* @param ciphertext the encrypted bytes
|
||||
* @param initializationVector the vector to decrypt under
|
||||
* @param record the key the cipher runs under, whose family names the cipher
|
||||
* @return the plaintext
|
||||
*/
|
||||
private static byte[] decrypt(byte[] key, byte[] ciphertext, byte[] initializationVector,
|
||||
PaymentCryptographyKey record) {
|
||||
return isAes(record)
|
||||
? PaymentCryptographyCrypto.decryptCbc(key, ciphertext, initializationVector)
|
||||
: PaymentCryptographyCrypto.tdesCbcDecrypt(key, ciphertext, initializationVector);
|
||||
}
|
||||
|
||||
/** The cipher a request asks for. */
|
||||
private record Encryption(byte[] initializationVector) {
|
||||
}
|
||||
|
||||
/** The key the request names, in the member the operation names it in. */
|
||||
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, 404);
|
||||
}
|
||||
requireEnabled(key);
|
||||
return key;
|
||||
}
|
||||
|
||||
/**
|
||||
* A key that is disabled does no work.
|
||||
*
|
||||
* <p>The service reads a disabled key and tells the caller about it, but it does not
|
||||
* encrypt with it, decrypt with it, or make a MAC under it.
|
||||
*
|
||||
* @param key the key the request names
|
||||
*/
|
||||
private static void requireEnabled(PaymentCryptographyKey key) {
|
||||
if (!key.isEnabled()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"the key " + key.getArn() + " is disabled", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The material of a key.
|
||||
*
|
||||
* <p>The material is held by the key while the emulator runs and is not written to the
|
||||
* store, so a key read back after a restart has none. A request that needs the material
|
||||
* is then refused with an error that says so, rather than failing on the missing value.
|
||||
*
|
||||
* @param key the key the operation runs under
|
||||
* @return the key's material
|
||||
*/
|
||||
private static byte[] material(PaymentCryptographyKey key) {
|
||||
return PaymentCryptographyCrypto.fromHex(materialHex(key));
|
||||
}
|
||||
|
||||
/**
|
||||
* The material of a key, as it is held.
|
||||
*
|
||||
* <p>The material is held by the key while the emulator runs and is not written to the
|
||||
* store, so a key read back after a restart has none. A request that needs the material
|
||||
* is then refused with an error that says so, rather than failing on the missing value.
|
||||
*
|
||||
* @param key the key the operation runs under
|
||||
* @return the key's material, as hexadecimal
|
||||
*/
|
||||
private static String materialHex(PaymentCryptographyKey key) {
|
||||
String hex = key.getKeyMaterialHex();
|
||||
if (hex == null || hex.isEmpty()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"the material of the key " + key.getArn() + " is not held: it is kept while the "
|
||||
+ "emulator runs and is not written to the store, so a key read back after "
|
||||
+ "a restart has none", 400);
|
||||
}
|
||||
return hex;
|
||||
}
|
||||
|
||||
/**
|
||||
* The block the key's cipher works in: sixteen bytes for AES and eight for Triple DES, as
|
||||
* the reference says.
|
||||
*
|
||||
* @param key the key the cipher runs under
|
||||
* @return the block size, in bytes
|
||||
*/
|
||||
private static int blockOf(PaymentCryptographyKey key) {
|
||||
return isAes(key) ? AES_BLOCK : TDES_BLOCK;
|
||||
}
|
||||
|
||||
/**
|
||||
* The data must fill whole blocks of the key's cipher.
|
||||
*
|
||||
* <p>The cipher pads no data, so the caller supplies whole blocks: a plaintext that does
|
||||
* not fill them is refused, rather than padded into a ciphertext that is longer than the
|
||||
* data it holds. The block follows the key's cipher, as the reference says: sixteen bytes
|
||||
* for AES and eight for Triple DES.
|
||||
*
|
||||
* @param data the data the request names
|
||||
* @param key the key the cipher runs under, whose cipher sets the block size
|
||||
* @param member the member the data is, for the message
|
||||
*/
|
||||
private static void requireBlockAligned(byte[] data, PaymentCryptographyKey key, String member) {
|
||||
int block = blockOf(key);
|
||||
if (data.length % block != 0) {
|
||||
throw new AwsException("ValidationException",
|
||||
member + " must be a multiple of " + block + " bytes (one "
|
||||
+ (isAes(key) ? "AES" : "TDES") + " block)", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The usage a key has to have for an operation.
|
||||
*
|
||||
* <p>The usage is what binds a key to its purpose, so an operation that belongs to one
|
||||
* purpose is not served with a key of another: a PIN encryption key does not encrypt
|
||||
* arbitrary data, and a MAC key does not either. The check is on the usage itself, not
|
||||
* on the mode, because a key may carry the mode and still be of another purpose.
|
||||
*
|
||||
* @param key the key the operation runs under
|
||||
* @param usages the usages the operation serves
|
||||
* @param what the operation, for the message
|
||||
*/
|
||||
private static void requireUsage(PaymentCryptographyKey key, List<String> usages, String what) {
|
||||
String usage = key.getKeyUsage();
|
||||
if (usage == null || usages.contains(usage)) {
|
||||
return;
|
||||
}
|
||||
throw new AwsException("ValidationException",
|
||||
"the key " + key.getArn() + " is of the usage " + usage + ", and it may not be used to "
|
||||
+ what + ", which needs a key of the usage " + String.join(" or ", usages), 400);
|
||||
}
|
||||
|
||||
/** The modes of use a key has to have for an operation. */
|
||||
private static void requireMode(PaymentCryptographyKey key, String mode, String what) {
|
||||
Map<String, Boolean> modes = key.getKeyModesOfUse();
|
||||
if (modes == null) {
|
||||
return;
|
||||
}
|
||||
// A NoRestrictions that is false is not a permission: a request that names the
|
||||
// member says nothing about what it allows, so the mode itself decides.
|
||||
if (Boolean.TRUE.equals(modes.get("NoRestrictions"))) {
|
||||
return;
|
||||
}
|
||||
if (!Boolean.TRUE.equals(modes.get(mode))) {
|
||||
throw new AwsException("ValidationException",
|
||||
"the key " + key.getArn() + " does not have the mode of use " + mode
|
||||
+ ", which it needs to " + what, 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The MAC a request asks for, and the key it is computed under.
|
||||
*
|
||||
* <p>The attributes name the algorithm: the ISO 9797-1 algorithms 1 and 3 for the
|
||||
* {@code Algorithm} variant, and the DUKPT derivations of the same two for the DUKPT
|
||||
* variants. A DUKPT MAC key is derived from the base derivation key, so that is what the
|
||||
* key has to allow.
|
||||
*/
|
||||
private MacLeg resolveMacLeg(JsonNode attributes, PaymentCryptographyKey key, String region,
|
||||
String mode, String what) {
|
||||
String variant = soleVariant(attributes);
|
||||
if (variant == null) {
|
||||
throw new AwsException("ValidationException",
|
||||
"MacAttributes must specify exactly one variant", 400);
|
||||
}
|
||||
if ("Algorithm".equals(variant)) {
|
||||
// The algorithm is a member of the attributes themselves, not of the variant.
|
||||
String algorithm = text(attributes, "Algorithm");
|
||||
if ("ISO9797_ALGORITHM1".equals(algorithm)) {
|
||||
requireMode(key, mode, what);
|
||||
requireUsage(key, MAC_USAGES, what);
|
||||
// The ISO 9797 MACs are defined over Triple DES, so the key is one.
|
||||
requireFamily(key, false, what);
|
||||
return new MacLeg(Ciphers::iso9797Alg1, material(key), LONGEST_MAC);
|
||||
}
|
||||
if ("ISO9797_ALGORITHM3".equals(algorithm)) {
|
||||
requireMode(key, mode, what);
|
||||
requireUsage(key, MAC_USAGES, what);
|
||||
requireFamily(key, false, what);
|
||||
return new MacLeg(Ciphers::iso9797Alg3, material(key), LONGEST_MAC);
|
||||
}
|
||||
if ("CMAC".equals(algorithm)) {
|
||||
// The CMAC is the AES-CMAC of RFC 4493, which is a whole block
|
||||
// wide, so it is cut to a length the caller asks for.
|
||||
requireMode(key, mode, what);
|
||||
requireUsage(key, MAC_USAGES, what);
|
||||
// The CMAC is defined over AES, so the key is one.
|
||||
requireFamily(key, true, what);
|
||||
return new MacLeg(PaymentCryptographyCrypto::cmac, material(key), LONGEST_CMAC);
|
||||
}
|
||||
throw new AwsException("ValidationException",
|
||||
"Algorithm '" + algorithm + "' not supported by this service "
|
||||
+ "(ISO9797_ALGORITHM1, ISO9797_ALGORITHM3, CMAC)", 400);
|
||||
}
|
||||
if ("DukptIso9797Algorithm1".equals(variant) || "DukptIso9797Algorithm3".equals(variant)) {
|
||||
// A DUKPT MAC key is derived from the base derivation key, so that is what the key
|
||||
// has to allow, and the derivation is over Triple DES, so the key is one.
|
||||
requireMode(key, "DeriveKey", "deriving a MAC key");
|
||||
requireUsage(key, DERIVATION_USAGES, "deriving a MAC key");
|
||||
requireFamily(key, false, "deriving a MAC key");
|
||||
JsonNode variantAttributes = attributes.get(variant);
|
||||
// The model's pattern says the serial number is hexadecimal, so it only decodes here.
|
||||
String ksn = text(variantAttributes, "KeySerialNumber");
|
||||
String keyVariant = text(variantAttributes, "DukptKeyVariant");
|
||||
if (!keyVariant.isEmpty() && !"REQUEST".equals(keyVariant)) {
|
||||
throw new AwsException("ValidationException",
|
||||
variant + ".DukptKeyVariant '" + keyVariant
|
||||
+ "' not supported by this service (REQUEST)", 400);
|
||||
}
|
||||
String derivationType = text(variantAttributes, "DukptDerivationType");
|
||||
if (!derivationType.isEmpty() && !"TDES_2KEY".equals(derivationType)) {
|
||||
throw new AwsException("ValidationException",
|
||||
variant + ".DukptDerivationType '" + derivationType
|
||||
+ "' not supported by this service (TDES_2KEY)", 400);
|
||||
}
|
||||
byte[] derived;
|
||||
try {
|
||||
derived = DukptCrypto.macKey(materialHex(key), ksn);
|
||||
} catch (IllegalArgumentException e) {
|
||||
// The derivation refuses what the request names, so the refusal is the
|
||||
// caller's to act on. Anything else is a fault of the service and is
|
||||
// left to travel as one.
|
||||
throw new AwsException("ValidationException",
|
||||
"DUKPT derivation failed: " + e.getMessage(), 400);
|
||||
}
|
||||
return new MacLeg("DukptIso9797Algorithm1".equals(variant)
|
||||
? Ciphers::iso9797Alg1 : Ciphers::iso9797Alg3, derived, LONGEST_MAC);
|
||||
}
|
||||
throw new AwsException("ValidationException",
|
||||
"MacAttributes." + variant + " not supported by this service", 400);
|
||||
}
|
||||
|
||||
/** The MAC a request asks for, and the key it is computed under. */
|
||||
private static final class MacLeg {
|
||||
final MacFunction mac;
|
||||
final byte[] keyBytes;
|
||||
/** The longest MAC this algorithm gives, in bytes. */
|
||||
final int longest;
|
||||
|
||||
MacLeg(MacFunction mac, byte[] keyBytes, int longest) {
|
||||
this.mac = mac;
|
||||
this.keyBytes = keyBytes;
|
||||
this.longest = longest;
|
||||
}
|
||||
}
|
||||
|
||||
/** A MAC over a message under a key. */
|
||||
private interface MacFunction {
|
||||
byte[] apply(byte[] key, byte[] message);
|
||||
}
|
||||
|
||||
/** The one variant of an attributes structure, or null when there is not exactly one. */
|
||||
private static String soleVariant(JsonNode attributes) {
|
||||
if (attributes == null || !attributes.isObject()) {
|
||||
return null;
|
||||
}
|
||||
String found = null;
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = attributes.fields();
|
||||
while (fields.hasNext()) {
|
||||
if (found != null) {
|
||||
return null;
|
||||
}
|
||||
found = fields.next().getKey();
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** The text of a member. */
|
||||
private static String text(JsonNode request, String member) {
|
||||
if (request == null) {
|
||||
return "";
|
||||
}
|
||||
JsonNode declared = request.get(member);
|
||||
return declared == null || declared.isNull() ? "" : declared.asText("");
|
||||
}
|
||||
|
||||
/**
|
||||
* A blob of the request.
|
||||
*
|
||||
* <p>The data plane carries its blobs as hexadecimal, which is what the reference says it
|
||||
* does. The request has already been checked against the model, which says that the
|
||||
* member is there, that it is a string and what it holds, so this only decodes it.
|
||||
*/
|
||||
private static byte[] blob(JsonNode request, String member) {
|
||||
return PaymentCryptographyCrypto.fromHex(request.get(member).textValue());
|
||||
}
|
||||
|
||||
/**
|
||||
* The length of the MAC the caller asks for, which the service computes.
|
||||
*
|
||||
* <p>The model says the length is a whole number of at least four bytes, and the
|
||||
* request has been checked against it. What the algorithm gives is shorter than the
|
||||
* model allows, so a length above it is refused here.
|
||||
*/
|
||||
private static int macLength(JsonNode request, MacLeg leg, int fallback) {
|
||||
int length = request.path("MacLength").asInt(fallback);
|
||||
if (length < SHORTEST_MAC || length > leg.longest) {
|
||||
throw new AwsException("ValidationException",
|
||||
"MacLength must be between " + SHORTEST_MAC + " and " + leg.longest, 400);
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
/** A blob as the protocol carries it: hexadecimal. */
|
||||
private static String encode(byte[] bytes) {
|
||||
return HEX.formatHex(bytes);
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* What the data plane's controllers share: the body of a request, the region it is for, and
|
||||
* the answer it gives.
|
||||
*
|
||||
* <p>The data plane is a service of its own (Smithy restJson1): it has its own host, its own
|
||||
* sign name and its own protocol, and its operations are routed by the path rather than by a
|
||||
* target header. The routes are the ones the AWS SDK builds, so a client reaches them without
|
||||
* knowing anything about this service.
|
||||
*
|
||||
* <p>A path that names the key is the key the operation acts on. The body may name one
|
||||
* besides it, and then the two must agree, so a request cannot act on a key other than the
|
||||
* one its path names.
|
||||
*
|
||||
* <p>{@code /mac}, {@code /pindata}, {@code /cardvalidationdata} and {@code /cryptogram} are
|
||||
* two-segment paths, which S3's path-style routes would claim, so
|
||||
* {@link PaymentCryptographyDataPlaneRouteFilter} moves them for the requests signed for this
|
||||
* service.
|
||||
*
|
||||
* <p>The operations are grouped by what they do, and each group has its own controller: the
|
||||
* encryption and the MACs, the PIN data, and the card validation values with the authorization
|
||||
* cryptograms. The groups share this base and nothing else, so each of them can be read on
|
||||
* its own.
|
||||
*/
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public abstract class PaymentCryptographyDataPlaneController {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
public PaymentCryptographyDataPlaneController(ObjectMapper objectMapper,
|
||||
RegionResolver regionResolver) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
/** The body of a request, with the key the path names. */
|
||||
protected JsonNode request(String body, String pathIdentifier, String member) {
|
||||
JsonNode request = parse(body);
|
||||
String named = request.path(member).asText();
|
||||
if (!named.isEmpty() && !named.equals(pathIdentifier)) {
|
||||
throw new AwsException("ValidationException",
|
||||
member + " in the body is not the key the path names", 400);
|
||||
}
|
||||
ObjectNode withKey = ((ObjectNode) request).deepCopy();
|
||||
withKey.put(member, pathIdentifier);
|
||||
return withKey;
|
||||
}
|
||||
|
||||
/** The body of a request, which is a JSON object. */
|
||||
protected JsonNode parse(String body) {
|
||||
if (body == null || body.isBlank()) {
|
||||
return objectMapper.createObjectNode();
|
||||
}
|
||||
try {
|
||||
JsonNode request = objectMapper.readTree(body);
|
||||
if (request == null || !request.isObject()) {
|
||||
throw new AwsException("ValidationException", "the body must be a JSON object", 400);
|
||||
}
|
||||
return request;
|
||||
} catch (AwsException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("ValidationException", "the body is not valid JSON", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/** The region the request is for. */
|
||||
protected String region(HttpHeaders headers) {
|
||||
return regionResolver.resolveRegion(headers);
|
||||
}
|
||||
|
||||
/** The answer of an operation. */
|
||||
protected static Response respond(Map<String, Object> answer) {
|
||||
return Response.ok(answer).build();
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import io.floci.aws.core.common.ResolvedServiceCatalog;
|
||||
import io.floci.aws.core.common.SignedServiceRoute;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.container.ContainerRequestFilter;
|
||||
import jakarta.ws.rs.container.PreMatching;
|
||||
import jakarta.ws.rs.ext.Provider;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Rewrites the data plane's two-segment paths to an internal prefix before JAX-RS route
|
||||
* matching. Registered directly, {@code /mac/generate} and the rest would outrank S3's
|
||||
* {@code /{bucket}/{key}} routes, so a path-style request for a bucket of that name would
|
||||
* reach the data plane. Only a request signed for the data plane is rewritten; anything else
|
||||
* falls through to S3.
|
||||
*/
|
||||
@Provider
|
||||
@PreMatching
|
||||
public class PaymentCryptographyDataPlaneRouteFilter implements ContainerRequestFilter {
|
||||
|
||||
static final String INTERNAL_PREFIX = "/_paymentcryptography";
|
||||
|
||||
private final SignedServiceRoute route;
|
||||
|
||||
@Inject
|
||||
public PaymentCryptographyDataPlaneRouteFilter(ResolvedServiceCatalog catalog) {
|
||||
// Both planes of the service are signed for the same scope, so the
|
||||
// path says which plane a request is for, and the control plane never
|
||||
// uses these paths. A client that signs for the data plane's own scope
|
||||
// is served as well, so that either scope reaches the data plane.
|
||||
this.route = new SignedServiceRoute(catalog,
|
||||
Set.of("paymentcryptography", "payment-cryptography-data"), INTERNAL_PREFIX,
|
||||
SignedServiceRoute.under("/mac")
|
||||
.or(SignedServiceRoute.under("/pindata"))
|
||||
.or(SignedServiceRoute.under("/cardvalidationdata"))
|
||||
.or(SignedServiceRoute.under("/cryptogram"))
|
||||
.or(SignedServiceRoute.under("/keys")));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void filter(ContainerRequestContext ctx) {
|
||||
route.apply(ctx);
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.floci.aws.core.common.RequestConstraintCheck;
|
||||
|
||||
/**
|
||||
* Checks a Payment Cryptography data plane request against the constraints vendored in
|
||||
* {@code aws/payment-cryptography-data-request-shapes.json} by
|
||||
* {@code tools/aws/regen_payment_cryptography_data_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, and the identifier of a key on its own
|
||||
* names none of them. A violation is a {@code ValidationException}, with the member's path from
|
||||
* the request's top level.
|
||||
*/
|
||||
final class PaymentCryptographyDataRequestShapes {
|
||||
|
||||
private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load(
|
||||
"aws/payment-cryptography-data-request-shapes.json",
|
||||
"Payment Cryptography data plane request shapes",
|
||||
PaymentCryptographyShapeErrors.MESSAGES);
|
||||
|
||||
private PaymentCryptographyDataRequestShapes() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks a request of an operation against the constraints the model states for it.
|
||||
*
|
||||
* @param operation the operation the request is
|
||||
* @param request the request
|
||||
*/
|
||||
static void check(String operation, JsonNode request) {
|
||||
CHECK.check(operation, request);
|
||||
}
|
||||
}
|
||||
+10
@@ -88,6 +88,16 @@ enum PaymentCryptographyKeyAlgorithm {
|
||||
return aes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the key is a Triple DES key rather than an AES one.
|
||||
*
|
||||
* <p>A symmetric key is an AES one or a Triple DES one, so the family follows from the
|
||||
* two.
|
||||
*/
|
||||
boolean isTdes() {
|
||||
return symmetric() && !aes;
|
||||
}
|
||||
|
||||
/** Whether the key is an EC key, which has a key pair rather than key material. */
|
||||
boolean isEcc() {
|
||||
return ecc;
|
||||
|
||||
+1
-40
@@ -1,11 +1,8 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.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
|
||||
@@ -20,35 +17,7 @@ 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");
|
||||
}
|
||||
});
|
||||
PaymentCryptographyShapeErrors.MESSAGES);
|
||||
|
||||
private PaymentCryptographyRequestShapes() {
|
||||
}
|
||||
@@ -56,12 +25,4 @@ final class 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);
|
||||
}
|
||||
}
|
||||
+14
-2
@@ -582,6 +582,19 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
|
||||
return algorithm != null && algorithm.aes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a key is a Triple DES key rather than an AES one.
|
||||
*
|
||||
* <p>The key record knows its algorithm, so the family is read from there and not guessed
|
||||
* from the length of the material, because a 16-byte key is a two-key TDES one and an
|
||||
* AES-128 one, and a 24-byte key is a three-key TDES one and an AES-192 one.
|
||||
*/
|
||||
static boolean isTdes(PaymentCryptographyKey key) {
|
||||
PaymentCryptographyKeyAlgorithm algorithm =
|
||||
PaymentCryptographyKeyAlgorithm.from(key.getKeyAlgorithm());
|
||||
return algorithm != null && algorithm.isTdes();
|
||||
}
|
||||
|
||||
/**
|
||||
* The algorithm byte of a key: {@code A} for an AES key and {@code T} for a TDES one.
|
||||
*
|
||||
@@ -590,8 +603,7 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
|
||||
* different keys.
|
||||
*/
|
||||
static String algorithmByte(PaymentCryptographyKey key) {
|
||||
return "AES_256".equals(key.getKeyAlgorithm()) || "AES_192".equals(key.getKeyAlgorithm())
|
||||
|| "AES_128".equals(key.getKeyAlgorithm()) ? "A" : "T";
|
||||
return isAes(key) ? "A" : "T";
|
||||
}
|
||||
|
||||
/** The usage name of a TR-31 usage code, such as {@code TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY}. */
|
||||
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RequestConstraintCheck;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* How a Payment Cryptography request that breaks a constraint is refused.
|
||||
*
|
||||
* <p>The control plane and the data plane are checked by the same machinery and are worded the
|
||||
* same way, so the wording is here rather than in each of them. The path a violation names is the
|
||||
* member's path below the operation, with the list elements folded into their list.
|
||||
*/
|
||||
final class PaymentCryptographyShapeErrors {
|
||||
|
||||
/** The wording every constraint violation of this service is refused with. */
|
||||
static final RequestConstraintCheck.Messages MESSAGES = 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 PaymentCryptographyShapeErrors() {
|
||||
}
|
||||
|
||||
/** The violation, as the service refuses it. */
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
package io.floci.aws.services.paymentcryptography.crypto;
|
||||
|
||||
import org.bouncycastle.crypto.BlockCipher;
|
||||
import org.bouncycastle.crypto.engines.AESEngine;
|
||||
import org.bouncycastle.crypto.engines.DESEngine;
|
||||
import org.bouncycastle.crypto.engines.DESedeEngine;
|
||||
import org.bouncycastle.crypto.macs.CBCBlockCipherMac;
|
||||
import org.bouncycastle.crypto.macs.ISO9797Alg3Mac;
|
||||
import org.bouncycastle.crypto.modes.CBCBlockCipher;
|
||||
import org.bouncycastle.crypto.params.KeyParameter;
|
||||
import org.bouncycastle.crypto.params.ParametersWithIV;
|
||||
|
||||
|
||||
/**
|
||||
* The block ciphers the data plane's MACs are built from.
|
||||
*
|
||||
* <p>The Triple DES and the Single DES are the two the ISO 9797-1 MACs and the DUKPT
|
||||
* derivations use, and both are used in ECB mode over a single block. BouncyCastle is used
|
||||
* for them rather than the JCE, whose provider defaults differ: its {@code DESede} takes the
|
||||
* two-key form K1||K2 as the three keys K1||K2||K1, so both the cipher and the key are the
|
||||
* ones the MAC is defined over.
|
||||
*
|
||||
* <p>The JCE's Triple DES is not registered in the native image, so a request that needs
|
||||
* it there hangs until the job is cancelled at its timeout, and the suite that would have
|
||||
* caught it never answers. Every cipher here is BouncyCastle's, so none of them depends
|
||||
* on what the image happens to carry.
|
||||
*
|
||||
* <p>ECB is the mode the block ciphers implement themselves, so one block goes in and one
|
||||
* block comes out, which is what the MACs read.
|
||||
*/
|
||||
public final class Ciphers {
|
||||
|
||||
private Ciphers() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The AES encryption of data under a key and an initialization vector, in CBC mode, without
|
||||
* padding.
|
||||
*
|
||||
* <p>The cipher pads no data, so the caller supplies whole blocks: a partial block is
|
||||
* refused rather than padded.
|
||||
*
|
||||
* @param data the bytes to encrypt
|
||||
* @param key the sixteen-, twenty-four- or thirty-two-byte key
|
||||
* @param iv16 the sixteen-byte vector to encrypt under
|
||||
* @return the encrypted bytes
|
||||
*/
|
||||
public static byte[] aesCbcEncrypt(byte[] data, byte[] key, byte[] iv16) {
|
||||
return blocks(AESEngine.newInstance(), true, data, key, iv16);
|
||||
}
|
||||
|
||||
/**
|
||||
* The AES decryption of data under a key and an initialization vector, in CBC mode, without
|
||||
* padding.
|
||||
*
|
||||
* @param data the bytes to decrypt
|
||||
* @param key the sixteen-, twenty-four- or thirty-two-byte key
|
||||
* @param iv16 the sixteen-byte vector to decrypt under
|
||||
* @return the decrypted bytes
|
||||
*/
|
||||
public static byte[] aesCbcDecrypt(byte[] data, byte[] key, byte[] iv16) {
|
||||
return blocks(AESEngine.newInstance(), false, data, key, iv16);
|
||||
}
|
||||
|
||||
/**
|
||||
* One block of AES in ECB mode.
|
||||
*
|
||||
* @param block16 the sixteen-byte block to encrypt
|
||||
* @param key the sixteen-, twenty-four- or thirty-two-byte key
|
||||
* @return the encrypted bytes
|
||||
*/
|
||||
public static byte[] aesEcbEncrypt(byte[] block16, byte[] key) {
|
||||
return block(AESEngine.newInstance(), true, block16, key);
|
||||
}
|
||||
|
||||
/**
|
||||
* One block of AES in ECB mode, the other way round.
|
||||
*
|
||||
* @param block16 the sixteen-byte block to decrypt
|
||||
* @param key the sixteen-, twenty-four- or thirty-two-byte key
|
||||
* @return the decrypted bytes
|
||||
*/
|
||||
public static byte[] aesEcbDecrypt(byte[] block16, byte[] key) {
|
||||
return block(AESEngine.newInstance(), false, block16, key);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Triple DES encryption of a block under a two-key key, in ECB mode.
|
||||
*
|
||||
* <p>The two-key form is K1||K2, and the cipher takes the three keys K1||K2||K1, which
|
||||
* is what the two-key form means. A three-key key is taken as it is.
|
||||
*
|
||||
* @param block8 the eight-byte block to encrypt
|
||||
* @param key the sixteen- or twenty-four-byte key
|
||||
* @return the encrypted block
|
||||
*/
|
||||
public static byte[] tdes2Encrypt(byte[] block8, byte[] key) {
|
||||
return tdes3Encrypt(block8, key);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Triple DES encryption of a block under a three-key key, in ECB mode.
|
||||
*
|
||||
* @param block8 the eight-byte block to encrypt
|
||||
* @param key24 the twenty-four-byte key
|
||||
* @return the encrypted block
|
||||
*/
|
||||
public static byte[] tdes3Encrypt(byte[] block8, byte[] key24) {
|
||||
return block(new DESedeEngine(), true, block8, key24);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Single DES encryption of a block under a key, in ECB mode.
|
||||
*
|
||||
* @param block8 the eight-byte block to encrypt
|
||||
* @param key8 the eight-byte key
|
||||
* @return the encrypted block
|
||||
*/
|
||||
public static byte[] tdesSingleDesEncrypt(byte[] block8, byte[] key8) {
|
||||
return block(new DESEngine(), true, block8, key8);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Triple DES encryption of data under a two-key key, in CBC mode.
|
||||
*
|
||||
* <p>The two-key form is K1||K2, and the cipher takes three keys, so it is widened to
|
||||
* K1||K2||K1, which is what the two-key form means. A three-key key is taken as it is.
|
||||
* The cipher pads no data, so the data fills whole blocks of eight bytes.
|
||||
*
|
||||
* @param data the data to encrypt, a whole number of blocks
|
||||
* @param key the sixteen- or twenty-four-byte key
|
||||
* @param iv8 the eight-byte vector to encrypt under
|
||||
* @return the encrypted bytes
|
||||
*/
|
||||
public static byte[] tdesCbcEncrypt(byte[] data, byte[] key, byte[] iv8) {
|
||||
return blocks(new DESedeEngine(), true, data, key, iv8);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Triple DES decryption of data under a two-key key, in CBC mode.
|
||||
*
|
||||
* @param data the encrypted bytes, a whole number of blocks
|
||||
* @param key the sixteen- or twenty-four-byte key
|
||||
* @param iv8 the eight-byte vector to decrypt under
|
||||
* @return the plaintext
|
||||
*/
|
||||
public static byte[] tdesCbcDecrypt(byte[] data, byte[] key, byte[] iv8) {
|
||||
return blocks(new DESedeEngine(), false, data, key, iv8);
|
||||
}
|
||||
|
||||
/**
|
||||
* The exclusive-or of two byte arrays of the same length.
|
||||
*
|
||||
* @param a the first bytes
|
||||
* @param b the second bytes
|
||||
* @return the exclusive-or of the two
|
||||
*/
|
||||
public static byte[] xor(byte[] a, byte[] b) {
|
||||
if (a == null || b == null) {
|
||||
throw new IllegalArgumentException("both byte arrays are required");
|
||||
}
|
||||
if (a.length != b.length) {
|
||||
throw new IllegalArgumentException("the byte arrays are of different lengths: "
|
||||
+ a.length + " and " + b.length);
|
||||
}
|
||||
byte[] out = new byte[a.length];
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
out[i] = (byte) (a[i] ^ b[i]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The ISO 9797-1 MAC algorithm 1 over Triple DES, with padding method 1.
|
||||
*
|
||||
* <p>Algorithm 1 is the CBC mode's chain over the zero-padded message, so the last
|
||||
* block it leaves is the MAC.
|
||||
*
|
||||
* <p>Padding method 1 pads the message with zeroes only when it does not already fill
|
||||
* its blocks: a message that fills them is chained as it is, and no block is added.
|
||||
*
|
||||
* @param key16 the sixteen-byte key
|
||||
* @param data the message to authenticate
|
||||
* @return the eight-byte MAC
|
||||
*/
|
||||
public static byte[] iso9797Alg1(byte[] key16, byte[] data) {
|
||||
// The MAC without a padding of its own pads the last block with zeroes, which is
|
||||
// padding method 1. A padder that fills a whole block would chain an empty one
|
||||
// after a message that already fills its blocks, which the standard does not do.
|
||||
CBCBlockCipherMac mac = new CBCBlockCipherMac(new DESedeEngine(), 64);
|
||||
mac.init(new ParametersWithIV(new KeyParameter(key16), new byte[8]));
|
||||
mac.update(data, 0, data.length);
|
||||
byte[] out = new byte[mac.getMacSize()];
|
||||
mac.doFinal(out, 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The ISO 9797-1 MAC algorithm 3, the retail MAC, over a double-length DES key,
|
||||
* with padding method 1.
|
||||
*
|
||||
* <p>Algorithm 3 is the retail MAC: a single-DES chain under K1 for all but the
|
||||
* last block, then a final EDE under K1||K2.
|
||||
*
|
||||
* @param key16 the sixteen-byte key, K1||K2
|
||||
* @param data the message to authenticate
|
||||
* @return the eight-byte MAC
|
||||
*/
|
||||
public static byte[] iso9797Alg3(byte[] key16, byte[] data) {
|
||||
ISO9797Alg3Mac mac = new ISO9797Alg3Mac(new DESEngine());
|
||||
mac.init(new KeyParameter(key16));
|
||||
mac.update(data, 0, data.length);
|
||||
byte[] out = new byte[mac.getMacSize()];
|
||||
mac.doFinal(out, 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The encryption or decryption of one block under a key, in the cipher's own ECB mode.
|
||||
*/
|
||||
private static byte[] block(BlockCipher cipher, boolean encrypt, byte[] block, byte[] key) {
|
||||
int size = cipher.getBlockSize();
|
||||
if (block == null || block.length != size) {
|
||||
throw new IllegalArgumentException("the block is "
|
||||
+ (block == null ? "missing" : block.length + " bytes") + "; it is " + size);
|
||||
}
|
||||
if (key == null) {
|
||||
throw new IllegalArgumentException("key is required");
|
||||
}
|
||||
cipher.init(encrypt, new KeyParameter(key));
|
||||
byte[] out = new byte[size];
|
||||
cipher.processBlock(block, 0, out, 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The encryption or decryption of whole blocks under a key, in CBC mode.
|
||||
*/
|
||||
private static byte[] blocks(BlockCipher cipher, boolean encrypt, byte[] data, byte[] key, byte[] iv) {
|
||||
int size = cipher.getBlockSize();
|
||||
if (data == null || data.length % size != 0) {
|
||||
throw new IllegalArgumentException("the data is "
|
||||
+ (data == null ? "missing" : data.length + " bytes")
|
||||
+ "; it is a whole number of " + size + "-byte blocks");
|
||||
}
|
||||
if (key == null) {
|
||||
throw new IllegalArgumentException("key is required");
|
||||
}
|
||||
if (iv == null || iv.length != size) {
|
||||
throw new IllegalArgumentException("the initialization vector is "
|
||||
+ (iv == null ? "missing" : iv.length + " bytes") + "; it is " + size);
|
||||
}
|
||||
BlockCipher cbc = CBCBlockCipher.newInstance(cipher);
|
||||
cbc.init(encrypt, new ParametersWithIV(new KeyParameter(key), iv));
|
||||
byte[] out = new byte[data.length];
|
||||
for (int offset = 0; offset < data.length; offset += size) {
|
||||
cbc.processBlock(data, offset, out, offset);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package io.floci.aws.services.paymentcryptography.crypto;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HexFormat;
|
||||
|
||||
/**
|
||||
* ANSI X9.24-1 TDES DUKPT - Derived Unique Key Per Transaction.
|
||||
*
|
||||
* <pre>
|
||||
* 1. IPEK derivation BDK + initial KSN -> IPEK
|
||||
* 2. Transaction key IPEK + KSN counter bits -> derived key (one-way)
|
||||
* 3. Working-key variant derived key XOR mask -> MAC-request key
|
||||
* </pre>
|
||||
*
|
||||
* <p>Validated against the vectors ANSI X9.24-1 publishes, which the test holds: the
|
||||
* initial sequence of the standard's annex A.4.2. TDES only: AES DUKPT (X9.24-3) is
|
||||
* out of scope.
|
||||
*
|
||||
* <p>The odd parity the standard puts on the key bytes is not enforced here. The cipher
|
||||
* ignores the parity bits, and the published vectors carry parity-bearing keys, so the
|
||||
* derivation holds for the keys the standard defines.
|
||||
*/
|
||||
public final class DukptCrypto {
|
||||
|
||||
private static final byte[] KEY_VARIANT = HexFormat.of().parseHex("C0C0C0C000000000C0C0C0C000000000");
|
||||
private static final byte[] MAC_REQUEST_MASK = HexFormat.of().parseHex("000000000000FF00000000000000FF00");
|
||||
|
||||
private DukptCrypto() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a KSN to 10 bytes. A shorter KSN is left-padded with F nibbles:
|
||||
* transmitted KSNs routinely drop leading FF padding.
|
||||
*/
|
||||
public static byte[] normalizeKsn(String ksnHex) {
|
||||
String h = ksnHex == null ? "" : ksnHex.toUpperCase();
|
||||
if (h.isEmpty() || !h.matches("[0-9A-F]+")) {
|
||||
throw new IllegalArgumentException("KSN must be hexadecimal");
|
||||
}
|
||||
if (h.length() > 20) {
|
||||
throw new IllegalArgumentException("KSN must be at most 20 hex characters (10 bytes)");
|
||||
}
|
||||
StringBuilder padded = new StringBuilder(20);
|
||||
for (int i = h.length(); i < 20; i++) {
|
||||
padded.append('F');
|
||||
}
|
||||
padded.append(h);
|
||||
return HexFormat.of().parseHex(padded.toString());
|
||||
}
|
||||
|
||||
/** The rightmost 21 bits of the KSN: the transaction counter. */
|
||||
public static int ksnCounter(byte[] ksn10) {
|
||||
return ((ksn10[7] & 0x1f) << 16) | ((ksn10[8] & 0xff) << 8) | (ksn10[9] & 0xff);
|
||||
}
|
||||
|
||||
/** A copy of the KSN with the 21 counter bits zeroed. */
|
||||
public static byte[] zeroCounter(byte[] ksn10) {
|
||||
byte[] z = ksn10.clone();
|
||||
z[7] &= (byte) 0xe0;
|
||||
z[8] = 0;
|
||||
z[9] = 0;
|
||||
return z;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code IPEK = TDES(BDK, left8) || TDES(BDK XOR C0C0..., left8)}, where
|
||||
* {@code left8} is the KSN with its counter cleared, first 8 bytes.
|
||||
*/
|
||||
public static byte[] deriveIpek(String bdkHex, String ksnHex) {
|
||||
byte[] bdk = HexFormat.of().parseHex(bdkHex);
|
||||
if (bdk.length != 16) {
|
||||
throw new IllegalArgumentException("BDK must be a 16-byte (double-length TDES) key");
|
||||
}
|
||||
byte[] left8 = Arrays.copyOfRange(zeroCounter(normalizeKsn(ksnHex)), 0, 8);
|
||||
return concat(
|
||||
Ciphers.tdes2Encrypt(left8, bdk),
|
||||
Ciphers.tdes2Encrypt(left8, Ciphers.xor(bdk, KEY_VARIANT)));
|
||||
}
|
||||
|
||||
/** The X9.24-1 non-reversible key generation step, the single-DES "black box". */
|
||||
public static byte[] deriveStep(byte[] key16, byte[] reg8) {
|
||||
// Order matters: the variant-keyed half comes first.
|
||||
return concat(right(Ciphers.xor(key16, KEY_VARIANT), reg8), right(key16, reg8));
|
||||
}
|
||||
|
||||
/**
|
||||
* The derived transaction key for the KSN's counter, by walking the set
|
||||
* counter bits from most to least significant.
|
||||
*/
|
||||
public static byte[] deriveTransactionKey(String bdkHex, String ksnHex) {
|
||||
byte[] ksn = normalizeKsn(ksnHex);
|
||||
int counter = ksnCounter(ksn);
|
||||
if (counter == 0) {
|
||||
throw new IllegalArgumentException("KSN transaction counter must be non-zero");
|
||||
}
|
||||
byte[] key = deriveIpek(bdkHex, ksnHex);
|
||||
// The rightmost 8 bytes of the counter-cleared KSN, which become the
|
||||
// shift register the counter bits are written into.
|
||||
byte[] reg = Arrays.copyOfRange(zeroCounter(ksn), 2, 10);
|
||||
for (int bit = 20; bit >= 0; bit--) {
|
||||
int mask = 1 << bit;
|
||||
if ((counter & mask) == 0) {
|
||||
continue;
|
||||
}
|
||||
reg[5] |= (byte) ((mask >> 16) & 0x1f);
|
||||
reg[6] |= (byte) ((mask >> 8) & 0xff);
|
||||
reg[7] |= (byte) (mask & 0xff);
|
||||
key = deriveStep(key, reg);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
/** The MAC-request working key. */
|
||||
public static byte[] macKey(String bdkHex, String ksnHex) {
|
||||
return Ciphers.xor(deriveTransactionKey(bdkHex, ksnHex), MAC_REQUEST_MASK);
|
||||
}
|
||||
|
||||
private static byte[] right(byte[] key16, byte[] reg8) {
|
||||
byte[] kl = Arrays.copyOfRange(key16, 0, 8);
|
||||
byte[] kr = Arrays.copyOfRange(key16, 8, 16);
|
||||
return Ciphers.xor(Ciphers.tdesSingleDesEncrypt(Ciphers.xor(reg8, kr), kl), kr);
|
||||
}
|
||||
|
||||
private static byte[] concat(byte[]... parts) {
|
||||
int n = 0;
|
||||
for (byte[] p : parts) {
|
||||
n += p.length;
|
||||
}
|
||||
byte[] out = new byte[n];
|
||||
int at = 0;
|
||||
for (byte[] p : parts) {
|
||||
System.arraycopy(p, 0, out, at, p.length);
|
||||
at += p.length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
"_source": {
|
||||
"generator": "tools/aws/regen_iam_authorized_actions.py",
|
||||
"reference": "https://servicereference.us-east-1.amazonaws.com/",
|
||||
"retrieved": "2026-11-03",
|
||||
"retrieved": "2026-11-04",
|
||||
"note": "make iam-authorized-actions-verify checks every entry against AWS. QuickSight actions without resource types added from its AWS Service Reference on 2026-11-05; other entries retain their vendored snapshot."
|
||||
},
|
||||
"authorizedActions": {
|
||||
@@ -422,6 +422,17 @@
|
||||
"ListWebFunctions",
|
||||
"PassNetworkConnector"
|
||||
],
|
||||
"payment-cryptography": [
|
||||
"CreateKey",
|
||||
"DisableDefaultKeyReplicationRegions",
|
||||
"EnableDefaultKeyReplicationRegions",
|
||||
"GetDefaultKeyReplicationRegions",
|
||||
"GetParametersForExport",
|
||||
"GetParametersForImport",
|
||||
"ImportKey",
|
||||
"ListAliases",
|
||||
"ListKeys"
|
||||
],
|
||||
"pipes": [
|
||||
"ListPipes"
|
||||
],
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"_source": {"generator": "tools/aws/regen_iam_request_resources.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.43.118 (installed package)", "retrieved": "2026-11-05", "note": "make iam-request-resources-check re-derives every operation's resources from botocore; make iam-request-resources-verify checks every action, type and format against AWS. QuickSight added from its AWS Service Reference on 2026-11-05; other namespaces retain their vendored snapshot. QuickSight resource types refreshed from the AWS Service Reference on 2026-11-06."},
|
||||
"namespaces": {"access-analyzer": ["accessanalyzer"], "acm": ["acm"], "application-autoscaling": ["application-autoscaling"], "athena": ["athena"], "bcm-data-exports": ["bcm-data-exports"], "bcm-pricing-calculator": ["bcm-pricing-calculator"], "budgets": ["budgets"], "ce": ["ce"], "cloudtrail": ["cloudtrail"], "codebuild": ["codebuild"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "cur": ["cur"], "datasync": ["datasync"], "dynamodb": ["dynamodb"], "ecr": ["ecr"], "elasticloadbalancing": ["elb", "elbv2"], "elasticmapreduce": ["emr"], "es": ["es", "opensearch"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "globalaccelerator": ["globalaccelerator"], "kinesisanalytics": ["kinesisanalyticsv2"], "logs": ["logs"], "payment-cryptography": ["payment-cryptography"], "quicksight": ["quicksight"], "redshift": ["redshift"], "redshift-data": ["redshift-data"], "rekognition": ["rekognition"], "servicediscovery": ["servicediscovery"], "servicequotas": ["service-quotas"], "sso": ["sso", "sso-admin"], "states": ["stepfunctions"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "translate": ["translate"]},
|
||||
"clientsNotRead": {"kinesisanalytics": "Kinesis Data Analytics v1, SQL applications on the KinesisAnalytics_20150814 target, which Floci does not serve (it serves v2, kinesisanalyticsv2); its operations share v2's names and name their resources by other members", "payment-cryptography-data": "the Payment Cryptography data plane, REST routes such as /keys/{KeyIdentifier}/encrypt, which Floci does not serve (it serves the control plane's JSON operations); its KeyIdentifier may be an alias, read on the control plane by the handler, not by its path"},
|
||||
"_source": {"generator": "tools/aws/regen_iam_request_resources.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.43.118 (installed package)", "retrieved": "2026-11-06", "note": "make iam-request-resources-check re-derives every operation's resources from botocore; make iam-request-resources-verify checks every action, type and format against AWS."},
|
||||
"namespaces": {"access-analyzer": ["accessanalyzer"], "acm": ["acm"], "application-autoscaling": ["application-autoscaling"], "athena": ["athena"], "bcm-data-exports": ["bcm-data-exports"], "bcm-pricing-calculator": ["bcm-pricing-calculator"], "budgets": ["budgets"], "ce": ["ce"], "cloudtrail": ["cloudtrail"], "codebuild": ["codebuild"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "cur": ["cur"], "datasync": ["datasync"], "dynamodb": ["dynamodb"], "ecr": ["ecr"], "elasticloadbalancing": ["elb", "elbv2"], "elasticmapreduce": ["emr"], "es": ["es", "opensearch"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "globalaccelerator": ["globalaccelerator"], "kinesisanalytics": ["kinesisanalyticsv2"], "logs": ["logs"], "payment-cryptography": ["payment-cryptography", "payment-cryptography-data"], "quicksight": ["quicksight"], "redshift": ["redshift"], "redshift-data": ["redshift-data"], "rekognition": ["rekognition"], "servicediscovery": ["servicediscovery"], "servicequotas": ["service-quotas"], "sso": ["sso", "sso-admin"], "states": ["stepfunctions"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "translate": ["translate"]},
|
||||
"clientsNotRead": {"kinesisanalytics": "Kinesis Data Analytics v1, SQL applications on the KinesisAnalytics_20150814 target, which Floci does not serve (it serves v2, kinesisanalyticsv2); its operations share v2's names and name their resources by other members"},
|
||||
"handBuilt": ["apigateway", "bedrock", "dsql", "dynamodb", "eks", "iam", "kinesis", "kms", "lambda", "logs", "pipes", "resource-groups", "s3", "scheduler", "secretsmanager", "sns", "sqs", "ssm", "sts"],
|
||||
"notCovered": {"account": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "airflow": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "app-integrations": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "appconfig": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "appsync": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "aps": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "autoscaling": "not read yet: AWS's group and launch configuration ARNs carry an id the service mints, `autoScalingGroup:<id>:autoScalingGroupName/<name>`, while Floci mints `autoScalingGroup:<name>`, which other services (ECS capacity providers) read back; the mint is fixed first", "aws-marketplace": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "backup": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "batch": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "bedrock-agentcore": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "cloudformation": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "cloudfront": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "cloudhsm": "not read yet: its ARN formats end in ${CloudHsmClusterInstanceName} and ${CloudHsmBackupInstanceName}, names, while its requests give ClusterId and BackupId, ids, which the rule does not fill a name from, so nearly every operation needs a correction", "cloudwatch": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "codeartifact": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "codedeploy": "not read yet: the Service Reference gives an on-premises instance's ARN as `instance:${InstanceName}`, while the CodeDeploy permissions reference gives arn:aws:codedeploy:region:account-id:instance/instance-ID and AWS's GetOnPremisesInstance example answers instance/<name>_<id>, an id the service mints after the name; reading it needs that format corrected", "codeguru-reviewer": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "comprehend": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "config": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "connect": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "controlcatalog": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "controltower": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "detective": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not Line truncated
|
||||
"otherNamespaces": ["a4b", "account-access", "acm-pca", "aco-automation", "agent-registry", "aidevops", "aiops", "airflow-serverless", "amplify", "amplifybackend", "amplifyuibuilder", "aoss", "appfabric", "appflow", "application-signals", "application-signals-mcp", "appmesh", "appmesh-preview", "apprunner", "appstream", "apptest", "arc-region-switch", "arc-zonal-shift", "artifact", "assurance", "auditmanager", "aws-external-anthropic", "b2bi", "backup-gateway", "backup-search", "bedrock-mantle", "bedrock-websearch", "billing", "billingconductor", "braket", "bugbust", "cases", "cassandra", "chatbot", "chime", "cleanrooms", "cleanrooms-ml", "cloud9", "clouddirectory", "cloudfront-keyvaluestore", "cloudsearch", "cloudshell", "cloudtrail-data", "codecatalyst", "codecommit", "codeconnections", "codeguru-profiler", "codeguru-security", "codestar-connections", "codestar-notifications", "codewhisperer", "cognito-sync", "connect-campaigns", "consoleapp", "continuum", "databrew", "dataexchange", "datapipeline", "datazone", "dax", "deadline", "devicefarm", "devops-guru", "directconnect", "docdb-elastic", "drs", "ds", "ds-data", "ebs", "ec2-instance-connect", "ecr-public", "eks-auth", "elastictranscoder", "elemental-appliances-software", "elemental-inference", "elemental-support-cases", "emr-containers", "end-user-messaging", "entityresolution", "evs", "finspace", "finspace-api", "fms", "forecast", "frauddetector", "freertos", "fsx", "gamelift", "gameliftstreams", "geo", "geo-maps", "geo-places", "geo-routes", "glacier", "grafana", "greengrass", "groundstation", "health", "health-agent", "healthlake", "honeycode", "identity-sync", "imagebuilder", "interconnect", "internetmonitor", "invoicing", "iotanalytics", "iotdeviceadvisor", "iotfleethub", "iotfleetwise", "iotjobsdata", "iotmanagedintegrations", "iotsitewise", "iottwinmaker", "iotwireless", "iq", "iq-permission", "ivs", "ivschat", "kafka-cluster", "kafkaconnect", "kendra", "kendra-ranking", "kinesisvideo", "launchwizard", "lex", "license-manager", "license-manager-linux-subscriptions", "license-manager-user-subscriptions", "lookoutequipment", "lookoutmetrics", "lookoutvision", "m2", "machinelearning", "managedblockchain", "mapcredits", "mediaconnect", "mediaconvert", "medialive", "mediapackage", "mediapackage-vod", "mediapackagev2", "mediastore", "mediatailor", "medical-imaging", "mgh", "mgn", "migrationhub-orchestrator", "mobiletargeting", "monitron", "mpa", "neptune-db", "neptune-graph", "network-security-manager", "networkflowmonitor", "networkmanager", "networkmonitor", "nimble", "notifications", "notifications-contacts", "nova-act", "observabilityadmin", "odb", "omics", "one", "opensearch", "opsworks", "osis", "outposts", "panorama", "partnercentral", "payments", "pca-connector-ad", "pca-connector-scep", "pcs", "personalize", "pi", "polly", "private-networks", "profile", "proton", "purchase-orders", "q", "qapps", "qbusiness", "qdeveloper", "qldb", "rbin", "rds-db", "refactor-spaces", "repostspace", "resiliencehub", "robomaker", "rolesanywhere", "route53-recovery-cluster", "route53-recovery-control-config", "route53-recovery-readiness", "route53globalresolver", "route53profiles", "rtbfabric", "s3-object-lambda", "s3-outposts", "s3express", "s3files", "sagemaker-geospatial", "sagemaker-mlflow", "savingsplans", "schemas", "scn", "sdb", "security-ir", "securityagent", "securitylake", "serverlessrepo", "shield", "signer", "simspaceweaver", "sms-voice", "snow-device-management", "social-messaging", "sqlworkbench", "ssm-contacts", "ssm-incidents", "ssm-quicksetup", "ssm-sap", "storagegateway", "supportauthz", "synthetics", "thinclient", "timestream", "tnb", "transform", "transform-custom", "trustedadvisor", "ts", "vendor-insights", "voiceid", "vpc-lattice", "vpc-lattice-svcs", "vpce", "waf", "waf-regional", "wellarchitected", "wickr", "wisdom", "workdocs", "worklink", "workmail", "workmailmessageflow", "workspaces", "workspaces-instances", "workspaces-web", "xray"],
|
||||
"arnFormats": {"access-analyzer": {"Analyzer": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}", "ArchiveRule": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}/archive-rule/${RuleName}"}, "acm": {"acme-domain-validation": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-domain-validation/${AcmeDomainValidationId}", "acme-endpoint": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}", "acme-external-account-binding": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-external-account-binding/${ExternalAccountBindingId}", "certificate": "arn:${Partition}:acm:${Region}:${Account}:certificate/${CertificateId}"}, "application-autoscaling": {"ScalableTarget": "arn:${Partition}:application-autoscaling:${Region}:${Account}:scalable-target/${ResourceId}"}, "athena": {"capacity-reservation": "arn:${Partition}:athena:${Region}:${Account}:capacity-reservation/${CapacityReservationName}", "datacatalog": "arn:${Partition}:athena:${Region}:${Account}:datacatalog/${DataCatalogName}", "session": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}/session/${SessionId}", "workgroup": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}"}, "bcm-data-exports": {"billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "export": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:export/${Identifier}", "table": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:table/${Identifier}"}, "bcm-pricing-calculator": {"bill-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-estimate/${BillEstimateId}", "bill-scenario": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-scenario/${BillScenarioId}", "workload-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:workload-estimate/${WorkloadEstimateId}"}, "budgets": {"budget": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}", "budgetAction": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}/action/${ActionId}"}, "ce": {"anomalymonitor": "arn:${Partition}:ce::${Account}:anomalymonitor/${Identifier}", "anomalysubscription": "arn:${Partition}:ce::${Account}:anomalysubscription/${Identifier}", "billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "costcategory": "arn:${Partition}:ce::${Account}:costcategory/${Identifier}"}, "cloudtrail": {"channel": "arn:${Partition}:cloudtrail:${Region}:${Account}:channel/${ChannelId}", "dashboard": "arn:${Partition}:cloudtrail:${Region}:${Account}:dashboard/${DashboardName}", "eventdatastore": "arn:${Partition}:cloudtrail:${Region}:${Account}:eventdatastore/${EventDataStoreId}", "trail": "arn:${Partition}:cloudtrail:${Region}:${Account}:trail/${TrailName}"}, "codebuild": {"build": "arn:${Partition}:codebuild:${Region}:${Account}:build/${BuildId}", "build-batch": "arn:${Partition}:codebuild:${Region}:${Account}:build-batch/${BuildBatchId}", "fleet": "arn:${Partition}:codebuild:${Region}:${Account}:fleet/${FleetName}:${FleetId}", "project": "arn:${Partition}:codebuild:${Region}:${Account}:project/${ProjectName}", "report": "arn:${Partition}:codebuild:${Region}:${Account}:report/${ReportGroupName}:${ReportId}", "report-group": "arn:${Partition}:codebuild:${Region}:${Account}:report-group/${ReportGroupName}", "sandbox": "arn:${Partition}:codebuild:${Region}:${Account}:sandbox/${SandboxId}"}, "codepipeline": {"action": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}/${StageName}/${ActionName}", "actiontype": "arn:${Partition}:codepipeline:${Region}:${Account}:actiontype:${Owner}/${Category}/${Provider}/${Version}", "pipeline": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}", "stage": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}/${StageName}", "webhook": "arn:${Partition}:codepipeline:${Region}:${Account}:webhook:${WebhookName}"}, "cognito-identity": {"identitypool": "arn:${Partition}:cognito-identity:${Region}:${Account}:identitypool/${IdentityPoolId}"}, "cognito-idp": {"userpool": "arn:${Partition}:cognito-idp:${Region}:${Account}:userpool/${UserPoolId}", "webacl": "arn:${Partition}:wafv2:${Region}:${Account}:${Scope}/webacl/${Name}/${Id}"}, "cur": {"cur": "arn:${Partition}:cur:${Region}:${Account}:definition/${ReportName}"}, "datasync": {"agent": "arn:${Partition}:datasync:${Region}:${Account}:agent/${AgentId}", "discoveryjob": "arn:${Partition}:datasync:${Region}:${Account}:system/${StorageSystemId}/job/${DiscoveryJobId}", "location": "arn:${Partition}:datasync:${Region}:${Account}:location/${LocationId}", "storagesystem": "arn:${Partition}:datasync:${Region}:${Account}:system/${StorageSystemId}", "task": "arn:${Partition}:datasync:${Region}:${Account}:task/${TaskId}", "taskexecution": "arn:${Partition}:datasync:${Region}:${Account}:task/${TaskId}/execution/${ExecutionId}"}, "dynamodb": {"backup":Line truncated
|
||||
"otherNamespaces": ["a4b", "account-access", "acm-pca", "aco-automation", "agent-registry", "aidevops", "aiops", "airflow-serverless", "amplify", "amplifybackend", "amplifyuibuilder", "aoss", "appfabric", "appflow", "application-signals", "application-signals-mcp", "appmesh", "appmesh-preview", "apprunner", "appstream", "apptest", "arc-region-switch", "arc-zonal-shift", "artifact", "assurance", "auditmanager", "aws-external-anthropic", "b2bi", "backup-gateway", "backup-search", "bedrock-mantle", "bedrock-websearch", "billing", "billingconductor", "braket", "bugbust", "cases", "cassandra", "chatbot", "chime", "cleanrooms", "cleanrooms-ml", "cloud9", "clouddirectory", "cloudfront-keyvaluestore", "cloudsearch", "cloudshell", "cloudtrail-data", "codecatalyst", "codecommit", "codeconnections", "codeguru-profiler", "codeguru-security", "codestar-connections", "codestar-notifications", "codewhisperer", "cognito-sync", "connect-campaigns", "consoleapp", "continuum", "databrew", "dataexchange", "datapipeline", "datazone", "dax", "deadline", "devicefarm", "devops-guru", "directconnect", "docdb-elastic", "drs", "ds", "ds-data", "ebs", "ec2-instance-connect", "ecr-public", "eks-auth", "elastictranscoder", "elemental-appliances-software", "elemental-inference", "elemental-support-cases", "emr-containers", "end-user-messaging", "entityresolution", "evs", "finspace", "finspace-api", "fms", "forecast", "frauddetector", "freertos", "fsx", "gamelift", "gameliftstreams", "geo", "geo-maps", "geo-places", "geo-routes", "glacier", "grafana", "greengrass", "groundstation", "health", "health-agent", "healthlake", "honeycode", "identity-sync", "imagebuilder", "interconnect", "internetmonitor", "invoicing", "iotanalytics", "iotdeviceadvisor", "iotfleethub", "iotfleetwise", "iotjobsdata", "iotmanagedintegrations", "iotsitewise", "iottwinmaker", "iotwireless", "iq", "iq-permission", "ivs", "ivschat", "kafka-cluster", "kafkaconnect", "kendra", "kendra-ranking", "kinesisvideo", "launchwizard", "lex", "license-manager", "license-manager-linux-subscriptions", "license-manager-user-subscriptions", "lookoutequipment", "lookoutmetrics", "lookoutvision", "m2", "machinelearning", "managedblockchain", "mapcredits", "mediaconnect", "mediaconvert", "medialive", "mediapackage", "mediapackage-vod", "mediapackagev2", "mediastore", "mediatailor", "medical-imaging", "mgh", "mgn", "migrationhub-orchestrator", "mobiletargeting", "monitron", "mpa", "neptune-db", "neptune-graph", "network-security-manager", "networkflowmonitor", "networkmanager", "networkmonitor", "nimble", "notifications", "notifications-contacts", "nova-act", "observabilityadmin", "odb", "omics", "one", "opensearch", "opsworks", "osis", "outposts", "panorama", "partnercentral", "payments", "pca-connector-ad", "pca-connector-scep", "pcs", "personalize", "pi", "polly", "private-networks", "profile", "proton", "purchase-orders", "q", "qapps", "qbusiness", "qdeveloper", "qldb", "rbin", "rds-db", "refactor-spaces", "repostspace", "resiliencehub", "robomaker", "rolesanywhere", "route53-recovery-cluster", "route53-recovery-control-config", "route53-recovery-readiness", "route53globalresolver", "route53profiles", "rtbfabric", "s3-object-lambda", "s3-outposts", "s3express", "s3files", "sagemaker-geospatial", "sagemaker-mlflow", "savingsplans", "schemas", "scn", "sdb", "security-ir", "securityagent", "securitylake", "serverlessrepo", "shield", "signer", "simspaceweaver", "sms-voice", "snow-device-management", "social-messaging", "sqlworkbench", "ssm-contacts", "ssm-incidents", "ssm-quicksetup", "ssm-sap", "ssmmessages", "storagegateway", "supportauthz", "synthetics", "thinclient", "timestream", "tnb", "transform", "transform-custom", "trustedadvisor", "ts", "vendor-insights", "voiceid", "vpc-lattice", "vpc-lattice-svcs", "vpce", "waf", "waf-regional", "wellarchitected", "wickr", "wisdom", "workdocs", "worklink", "workmail", "workmailmessageflow", "workspaces", "workspaces-instances", "workspaces-web", "xray"],
|
||||
"arnFormats": {"access-analyzer": {"Analyzer": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}", "ArchiveRule": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}/archive-rule/${RuleName}"}, "acm": {"acme-domain-validation": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-domain-validation/${AcmeDomainValidationId}", "acme-endpoint": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}", "acme-external-account-binding": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-external-account-binding/${ExternalAccountBindingId}", "certificate": "arn:${Partition}:acm:${Region}:${Account}:certificate/${CertificateId}"}, "application-autoscaling": {"ScalableTarget": "arn:${Partition}:application-autoscaling:${Region}:${Account}:scalable-target/${ResourceId}"}, "athena": {"capacity-reservation": "arn:${Partition}:athena:${Region}:${Account}:capacity-reservation/${CapacityReservationName}", "datacatalog": "arn:${Partition}:athena:${Region}:${Account}:datacatalog/${DataCatalogName}", "session": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}/session/${SessionId}", "system-table": "arn:${Partition}:athena:${Region}:${Account}:system-table/${TableName}", "workgroup": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}"}, "bcm-data-exports": {"billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "export": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:export/${Identifier}", "table": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:table/${Identifier}"}, "bcm-pricing-calculator": {"bill-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-estimate/${BillEstimateId}", "bill-scenario": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-scenario/${BillScenarioId}", "workload-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:workload-estimate/${WorkloadEstimateId}"}, "budgets": {"budget": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}", "budgetAction": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}/action/${ActionId}"}, "ce": {"anomalymonitor": "arn:${Partition}:ce::${Account}:anomalymonitor/${Identifier}", "anomalysubscription": "arn:${Partition}:ce::${Account}:anomalysubscription/${Identifier}", "billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "costcategory": "arn:${Partition}:ce::${Account}:costcategory/${Identifier}"}, "cloudtrail": {"channel": "arn:${Partition}:cloudtrail:${Region}:${Account}:channel/${ChannelId}", "dashboard": "arn:${Partition}:cloudtrail:${Region}:${Account}:dashboard/${DashboardName}", "eventdatastore": "arn:${Partition}:cloudtrail:${Region}:${Account}:eventdatastore/${EventDataStoreId}", "trail": "arn:${Partition}:cloudtrail:${Region}:${Account}:trail/${TrailName}"}, "codebuild": {"build": "arn:${Partition}:codebuild:${Region}:${Account}:build/${BuildId}", "build-batch": "arn:${Partition}:codebuild:${Region}:${Account}:build-batch/${BuildBatchId}", "fleet": "arn:${Partition}:codebuild:${Region}:${Account}:fleet/${FleetName}:${FleetId}", "project": "arn:${Partition}:codebuild:${Region}:${Account}:project/${ProjectName}", "report": "arn:${Partition}:codebuild:${Region}:${Account}:report/${ReportGroupName}:${ReportId}", "report-group": "arn:${Partition}:codebuild:${Region}:${Account}:report-group/${ReportGroupName}", "sandbox": "arn:${Partition}:codebuild:${Region}:${Account}:sandbox/${SandboxId}"}, "codepipeline": {"action": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}/${StageName}/${ActionName}", "actiontype": "arn:${Partition}:codepipeline:${Region}:${Account}:actiontype:${Owner}/${Category}/${Provider}/${Version}", "pipeline": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}", "stage": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}/${StageName}", "webhook": "arn:${Partition}:codepipeline:${Region}:${Account}:webhook:${WebhookName}"}, "cognito-identity": {"identitypool": "arn:${Partition}:cognito-identity:${Region}:${Account}:identitypool/${IdentityPoolId}"}, "cognito-idp": {"userpool": "arn:${Partition}:cognito-idp:${Region}:${Account}:userpool/${UserPoolId}", "webacl": "arn:${Partition}:wafv2:${Region}:${Account}:${Scope}/webacl/${Name}/${Id}"}, "cur": {"cur": "arn:${Partition}:cur:${Region}:${Account}:definition/${ReportName}"}, "datasync": {"agent": "arn:${Partition}:datasync:${Region}:${Account}:agent/${AgentId}", "discoveryjob": "arn:${Partition}:datasync:${Region}:${Account}:system/${StorageSystemId}/job/${DiscoveryJobId}", "location": "arn:${Partition}:datasync:${Region}:${Account}:location/${LocationId}", "storagesystem": "arn:${Partition}:datasync:${Region}:${Account}:system/${StorageSystemId}", "task": "arn:${Partition}:datasync:${Region}:${Account}:task/${TaskId}", "taskexecution": "arn:${Partition}:datasLine truncated
|
||||
"unqualified": {"states": ["statemachine"]},
|
||||
"mintedIds": {"events": ["api-destination", "connection"]},
|
||||
"operations": {
|
||||
@@ -112,12 +112,14 @@
|
||||
"athena:CreateNotebook": {"action": "athena:CreateNotebook", "types": ["workgroup"], "resources": [{"type": "workgroup", "fill": {"WorkGroupName": "WorkGroup"}}]},
|
||||
"athena:CreatePreparedStatement": {"action": "athena:CreatePreparedStatement", "types": ["workgroup"], "resources": [{"type": "workgroup", "fill": {"WorkGroupName": "WorkGroup"}}]},
|
||||
"athena:CreatePresignedNotebookUrl": {"action": "athena:CreatePresignedNotebookUrl", "types": ["workgroup"], "resources": []},
|
||||
"athena:CreateSystemTableConfiguration": {"action": "athena:CreateSystemTableConfiguration", "types": ["system-table"], "resources": []},
|
||||
"athena:CreateWorkGroup": {"action": "athena:CreateWorkGroup", "types": ["workgroup"], "resources": [{"type": "workgroup", "fill": {"WorkGroupName": "Name"}}]},
|
||||
"athena:DeleteCapacityReservation": {"action": "athena:DeleteCapacityReservation", "types": ["capacity-reservation"], "resources": [{"type": "capacity-reservation", "fill": {"CapacityReservationName": "Name"}}]},
|
||||
"athena:DeleteDataCatalog": {"action": "athena:DeleteDataCatalog", "types": ["datacatalog"], "resources": [{"type": "datacatalog", "fill": {"DataCatalogName": "Name"}}]},
|
||||
"athena:DeleteNamedQuery": {"action": "athena:DeleteNamedQuery", "types": ["workgroup"], "resources": []},
|
||||
"athena:DeleteNotebook": {"action": "athena:DeleteNotebook", "types": ["workgroup"], "resources": []},
|
||||
"athena:DeletePreparedStatement": {"action": "athena:DeletePreparedStatement", "types": ["workgroup"], "resources": [{"type": "workgroup", "fill": {"WorkGroupName": "WorkGroup"}}]},
|
||||
"athena:DeleteSystemTableConfiguration": {"action": "athena:DeleteSystemTableConfiguration", "types": ["system-table"], "resources": []},
|
||||
"athena:DeleteWorkGroup": {"action": "athena:DeleteWorkGroup", "types": ["workgroup"], "resources": [{"type": "workgroup", "fill": {"WorkGroupName": "WorkGroup"}}]},
|
||||
"athena:ExportNotebook": {"action": "athena:ExportNotebook", "types": ["workgroup"], "resources": []},
|
||||
"athena:GetCalculationExecution": {"action": "athena:GetCalculationExecution", "types": ["workgroup"], "resources": []},
|
||||
@@ -137,6 +139,7 @@
|
||||
"athena:GetSession": {"action": "athena:GetSession", "types": ["session", "workgroup"], "resources": [{"type": "session", "fill": {"SessionId": "SessionId"}}]},
|
||||
"athena:GetSessionEndpoint": {"action": "athena:GetSessionEndpoint", "types": ["session", "workgroup"], "resources": [{"type": "session", "fill": {"SessionId": "SessionId"}}]},
|
||||
"athena:GetSessionStatus": {"action": "athena:GetSessionStatus", "types": ["session", "workgroup"], "resources": [{"type": "session", "fill": {"SessionId": "SessionId"}}]},
|
||||
"athena:GetSystemTableConfiguration": {"action": "athena:GetSystemTableConfiguration", "types": ["system-table"], "resources": []},
|
||||
"athena:GetTableMetadata": {"action": "athena:GetTableMetadata", "types": ["datacatalog"], "resources": [{"type": "datacatalog", "fill": {"DataCatalogName": "CatalogName"}, "absent": {"CatalogName": "AwsDataCatalog"}}, {"type": "datacatalog", "fill": {}, "fixed": {"DataCatalogName": "AwsDataCatalog"}}]},
|
||||
"athena:GetWorkGroup": {"action": "athena:GetWorkGroup", "types": ["workgroup"], "resources": [{"type": "workgroup", "fill": {"WorkGroupName": "WorkGroup"}, "absent": {"WorkGroup": "primary"}}]},
|
||||
"athena:ImportNotebook": {"action": "athena:ImportNotebook", "types": ["workgroup"], "resources": [{"type": "workgroup", "fill": {"WorkGroupName": "WorkGroup"}}]},
|
||||
@@ -153,8 +156,9 @@
|
||||
"athena:ListPreparedStatements": {"action": "athena:ListPreparedStatements", "types": ["workgroup"], "resources": [{"type": "workgroup", "fill": {"WorkGroupName": "WorkGroup"}}]},
|
||||
"athena:ListQueryExecutions": {"action": "athena:ListQueryExecutions", "types": ["workgroup"], "resources": [{"type": "workgroup", "fill": {"WorkGroupName": "WorkGroup"}, "absent": {"WorkGroup": "primary"}}]},
|
||||
"athena:ListSessions": {"action": "athena:ListSessions", "types": ["workgroup"], "resources": [{"type": "workgroup", "fill": {"WorkGroupName": "WorkGroup"}}]},
|
||||
"athena:ListSystemTableStatuses": {"action": "athena:ListSystemTableStatuses", "types": [], "resources": []},
|
||||
"athena:ListTableMetadata": {"action": "athena:ListTableMetadata", "types": ["datacatalog"], "resources": [{"type": "datacatalog", "fill": {"DataCatalogName": "CatalogName"}, "absent": {"CatalogName": "AwsDataCatalog"}}, {"type": "datacatalog", "fill": {}, "fixed": {"DataCatalogName": "AwsDataCatalog"}}]},
|
||||
"athena:ListTagsForResource": {"action": "athena:ListTagsForResource", "types": ["capacity-reservation", "datacatalog", "session", "workgroup"], "resources": [{"types": ["capacity-reservation", "datacatalog", "session", "workgroup"], "arn": "ResourceARN"}]},
|
||||
"athena:ListTagsForResource": {"action": "athena:ListTagsForResource", "types": ["capacity-reservation", "datacatalog", "session", "system-table", "workgroup"], "resources": [{"types": ["capacity-reservation", "datacatalog", "session", "system-table", "workgroup"], "arn": "ResourceARN"}]},
|
||||
"athena:ListWorkGroups": {"action": "athena:ListWorkGroups", "types": [], "resources": []},
|
||||
"athena:PutCapacityAssignmentConfiguration": {"action": "athena:PutCapacityAssignmentConfiguration", "types": ["capacity-reservation", "workgroup"], "resources": [{"type": "capacity-reservation", "fill": {"CapacityReservationName": "CapacityReservationName"}}]},
|
||||
"athena:StartCalculationExecution": {"action": "athena:StartCalculationExecution", "types": ["workgroup"], "resources": []},
|
||||
@@ -162,15 +166,16 @@
|
||||
"athena:StartSession": {"action": "athena:StartSession", "types": ["session", "workgroup"], "resources": [{"type": "workgroup", "fill": {"WorkGroupName": "WorkGroup"}}]},
|
||||
"athena:StopCalculationExecution": {"action": "athena:StopCalculationExecution", "types": ["workgroup"], "resources": []},
|
||||
"athena:StopQueryExecution": {"action": "athena:StopQueryExecution", "types": ["workgroup"], "resources": []},
|
||||
"athena:TagResource": {"action": "athena:TagResource", "types": ["capacity-reservation", "datacatalog", "session", "workgroup"], "resources": [{"types": ["capacity-reservation", "datacatalog", "session", "workgroup"], "arn": "ResourceARN"}]},
|
||||
"athena:TagResource": {"action": "athena:TagResource", "types": ["capacity-reservation", "datacatalog", "session", "system-table", "workgroup"], "resources": [{"types": ["capacity-reservation", "datacatalog", "session", "system-table", "workgroup"], "arn": "ResourceARN"}]},
|
||||
"athena:TerminateSession": {"action": "athena:TerminateSession", "types": ["session", "workgroup"], "resources": [{"type": "session", "fill": {"SessionId": "SessionId"}}]},
|
||||
"athena:UntagResource": {"action": "athena:UntagResource", "types": ["capacity-reservation", "datacatalog", "session", "workgroup"], "resources": [{"types": ["capacity-reservation", "datacatalog", "session", "workgroup"], "arn": "ResourceARN"}]},
|
||||
"athena:UntagResource": {"action": "athena:UntagResource", "types": ["capacity-reservation", "datacatalog", "session", "system-table", "workgroup"], "resources": [{"types": ["capacity-reservation", "datacatalog", "session", "system-table", "workgroup"], "arn": "ResourceARN"}]},
|
||||
"athena:UpdateCapacityReservation": {"action": "athena:UpdateCapacityReservation", "types": ["capacity-reservation"], "resources": [{"type": "capacity-reservation", "fill": {"CapacityReservationName": "Name"}}]},
|
||||
"athena:UpdateDataCatalog": {"action": "athena:UpdateDataCatalog", "types": ["datacatalog"], "resources": [{"type": "datacatalog", "fill": {"DataCatalogName": "Name"}}]},
|
||||
"athena:UpdateNamedQuery": {"action": "athena:UpdateNamedQuery", "types": ["workgroup"], "resources": []},
|
||||
"athena:UpdateNotebook": {"action": "athena:UpdateNotebook", "types": ["workgroup"], "resources": []},
|
||||
"athena:UpdateNotebookMetadata": {"action": "athena:UpdateNotebookMetadata", "types": ["workgroup"], "resources": []},
|
||||
"athena:UpdatePreparedStatement": {"action": "athena:UpdatePreparedStatement", "types": ["workgroup"], "resources": [{"type": "workgroup", "fill": {"WorkGroupName": "WorkGroup"}}]},
|
||||
"athena:UpdateSystemTableConfiguration": {"action": "athena:UpdateSystemTableConfiguration", "types": ["system-table"], "resources": []},
|
||||
"athena:UpdateWorkGroup": {"action": "athena:UpdateWorkGroup", "types": ["workgroup"], "resources": [{"type": "workgroup", "fill": {"WorkGroupName": "WorkGroup"}}]},
|
||||
"bcm-data-exports:CreateExport": {"action": "bcm-data-exports:CreateExport", "types": ["billingview", "table"], "resources": []},
|
||||
"bcm-data-exports:DeleteExport": {"action": "bcm-data-exports:DeleteExport", "types": ["export"], "resources": [{"types": ["export"], "arn": "ExportArn"}]},
|
||||
@@ -1179,21 +1184,21 @@
|
||||
"payment-cryptography:AssociateMpaTeam": {"action": "payment-cryptography:AssociateMpaTeam", "types": ["approval-team"], "resources": [{"types": ["approval-team"], "arn": "MpaTeamArn"}]},
|
||||
"payment-cryptography:CreateAlias": {"action": "payment-cryptography:CreateAlias", "types": ["alias", "key"], "resources": [{"types": ["alias", "key"], "arn": "KeyArn"}, {"type": "alias", "fill": {"Alias": "AliasName"}, "made": true}]},
|
||||
"payment-cryptography:CreateKey": {"action": "payment-cryptography:CreateKey", "types": [], "resources": []},
|
||||
"payment-cryptography:DecryptData": {"action": "payment-cryptography:DecryptData", "types": ["alias", "key"], "resources": []},
|
||||
"payment-cryptography:DecryptData": {"action": "payment-cryptography:DecryptData", "types": ["alias", "key"], "resources": [{"type": "key", "fill": {"KeyId": "KeyIdentifier"}}], "located": {"KeyIdentifier": "{KeyIdentifier}"}},
|
||||
"payment-cryptography:DeleteAlias": {"action": "payment-cryptography:DeleteAlias", "types": ["alias"], "resources": [{"type": "alias", "fill": {"Alias": "AliasName"}}]},
|
||||
"payment-cryptography:DeleteKey": {"action": "payment-cryptography:DeleteKey", "types": ["key"], "resources": [{"type": "key", "fill": {"KeyId": "KeyIdentifier"}}]},
|
||||
"payment-cryptography:DeleteResourcePolicy": {"action": "payment-cryptography:DeleteResourcePolicy", "types": ["key"], "resources": [{"types": ["key"], "arn": "ResourceArn"}]},
|
||||
"payment-cryptography:DisableDefaultKeyReplicationRegions": {"action": "payment-cryptography:DisableDefaultKeyReplicationRegions", "types": [], "resources": []},
|
||||
"payment-cryptography:DisassociateMpaTeam": {"action": "payment-cryptography:DisassociateMpaTeam", "types": ["approval-team"], "resources": []},
|
||||
"payment-cryptography:EnableDefaultKeyReplicationRegions": {"action": "payment-cryptography:EnableDefaultKeyReplicationRegions", "types": [], "resources": []},
|
||||
"payment-cryptography:EncryptData": {"action": "payment-cryptography:EncryptData", "types": ["alias", "key"], "resources": []},
|
||||
"payment-cryptography:ExportKey": {"action": "payment-cryptography:ExportKey", "types": ["key"], "resources": []},
|
||||
"payment-cryptography:GenerateAs2805KekValidation": {"action": "payment-cryptography:GenerateAs2805KekValidation", "types": ["alias", "key"], "resources": []},
|
||||
"payment-cryptography:GenerateAuthRequestCryptogram": {"action": "payment-cryptography:GenerateAuthRequestCryptogram", "types": ["alias", "key"], "resources": []},
|
||||
"payment-cryptography:GenerateCardValidationData": {"action": "payment-cryptography:GenerateCardValidationData", "types": ["alias", "key"], "resources": []},
|
||||
"payment-cryptography:GenerateMac": {"action": "payment-cryptography:GenerateMac", "types": ["alias", "key"], "resources": []},
|
||||
"payment-cryptography:GenerateMacEmvPinChange": {"action": "payment-cryptography:GenerateMacEmvPinChange", "types": ["alias", "key"], "resources": []},
|
||||
"payment-cryptography:GeneratePinData": {"action": "payment-cryptography:GeneratePinData", "types": ["alias", "key"], "resources": []},
|
||||
"payment-cryptography:EncryptData": {"action": "payment-cryptography:EncryptData", "types": ["alias", "key"], "resources": [{"type": "key", "fill": {"KeyId": "KeyIdentifier"}}], "located": {"KeyIdentifier": "{KeyIdentifier}"}},
|
||||
"payment-cryptography:ExportKey": {"action": "payment-cryptography:ExportKey", "types": ["key"], "resources": [{"type": "key", "fill": {"KeyId": "ExportKeyIdentifier"}}]},
|
||||
"payment-cryptography:GenerateAs2805KekValidation": {"action": "payment-cryptography:GenerateAs2805KekValidation", "types": ["alias", "key"], "resources": [{"type": "key", "fill": {"KeyId": "KeyIdentifier"}}]},
|
||||
"payment-cryptography:GenerateAuthRequestCryptogram": {"action": "payment-cryptography:GenerateAuthRequestCryptogram", "types": ["alias", "key"], "resources": [{"type": "key", "fill": {"KeyId": "KeyIdentifier"}}]},
|
||||
"payment-cryptography:GenerateCardValidationData": {"action": "payment-cryptography:GenerateCardValidationData", "types": ["alias", "key"], "resources": [{"type": "key", "fill": {"KeyId": "KeyIdentifier"}}]},
|
||||
"payment-cryptography:GenerateMac": {"action": "payment-cryptography:GenerateMac", "types": ["alias", "key"], "resources": [{"type": "key", "fill": {"KeyId": "KeyIdentifier"}}]},
|
||||
"payment-cryptography:GenerateMacEmvPinChange": {"action": "payment-cryptography:GenerateMacEmvPinChange", "types": ["alias", "key"], "resources": [{"type": "key", "fill": {"KeyId": "SecureMessagingIntegrityKeyIdentifier"}}, {"type": "key", "fill": {"KeyId": "SecureMessagingConfidentialityKeyIdentifier"}}]},
|
||||
"payment-cryptography:GeneratePinData": {"action": "payment-cryptography:GeneratePinData", "types": ["alias", "key"], "resources": [{"type": "key", "fill": {"KeyId": "EncryptionKeyIdentifier"}}, {"type": "key", "fill": {"KeyId": "GenerationKeyIdentifier"}}]},
|
||||
"payment-cryptography:GetAlias": {"action": "payment-cryptography:GetAlias", "types": ["alias", "key"], "resources": [{"type": "alias", "fill": {"Alias": "AliasName"}}]},
|
||||
"payment-cryptography:GetCertificateSigningRequest": {"action": "payment-cryptography:GetCertificateSigningRequest", "types": ["alias", "key"], "resources": [{"type": "key", "fill": {"KeyId": "KeyIdentifier"}}]},
|
||||
"payment-cryptography:GetDefaultKeyReplicationRegions": {"action": "payment-cryptography:GetDefaultKeyReplicationRegions", "types": [], "resources": []},
|
||||
@@ -1208,20 +1213,20 @@
|
||||
"payment-cryptography:ListKeys": {"action": "payment-cryptography:ListKeys", "types": [], "resources": []},
|
||||
"payment-cryptography:ListTagsForResource": {"action": "payment-cryptography:ListTagsForResource", "types": ["key"], "resources": [{"types": ["key"], "arn": "ResourceArn"}]},
|
||||
"payment-cryptography:PutResourcePolicy": {"action": "payment-cryptography:PutResourcePolicy", "types": ["key"], "resources": [{"types": ["key"], "arn": "ResourceArn"}]},
|
||||
"payment-cryptography:ReEncryptData": {"action": "payment-cryptography:ReEncryptData", "types": ["alias", "key"], "resources": []},
|
||||
"payment-cryptography:ReEncryptData": {"action": "payment-cryptography:ReEncryptData", "types": ["alias", "key"], "resources": [{"type": "key", "fill": {"KeyId": "IncomingKeyIdentifier"}}, {"type": "key", "fill": {"KeyId": "OutgoingKeyIdentifier"}}], "located": {"IncomingKeyIdentifier": "{IncomingKeyIdentifier}"}},
|
||||
"payment-cryptography:RemoveKeyReplicationRegions": {"action": "payment-cryptography:RemoveKeyReplicationRegions", "types": ["alias", "key"], "resources": [{"type": "key", "fill": {"KeyId": "KeyIdentifier"}}]},
|
||||
"payment-cryptography:RestoreKey": {"action": "payment-cryptography:RestoreKey", "types": ["key"], "resources": [{"type": "key", "fill": {"KeyId": "KeyIdentifier"}}]},
|
||||
"payment-cryptography:StartKeyUsage": {"action": "payment-cryptography:StartKeyUsage", "types": ["key"], "resources": [{"type": "key", "fill": {"KeyId": "KeyIdentifier"}}]},
|
||||
"payment-cryptography:StopKeyUsage": {"action": "payment-cryptography:StopKeyUsage", "types": ["key"], "resources": [{"type": "key", "fill": {"KeyId": "KeyIdentifier"}}]},
|
||||
"payment-cryptography:TagResource": {"action": "payment-cryptography:TagResource", "types": ["key"], "resources": [{"types": ["key"], "arn": "ResourceArn"}]},
|
||||
"payment-cryptography:TranslateKeyMaterial": {"action": "payment-cryptography:TranslateKeyMaterial", "types": ["alias", "key"], "resources": []},
|
||||
"payment-cryptography:TranslatePinData": {"action": "payment-cryptography:TranslatePinData", "types": ["alias", "key"], "resources": []},
|
||||
"payment-cryptography:TranslatePinData": {"action": "payment-cryptography:TranslatePinData", "types": ["alias", "key"], "resources": [{"type": "key", "fill": {"KeyId": "IncomingKeyIdentifier"}}, {"type": "key", "fill": {"KeyId": "OutgoingKeyIdentifier"}}]},
|
||||
"payment-cryptography:UntagResource": {"action": "payment-cryptography:UntagResource", "types": ["key"], "resources": [{"types": ["key"], "arn": "ResourceArn"}]},
|
||||
"payment-cryptography:UpdateAlias": {"action": "payment-cryptography:UpdateAlias", "types": ["alias", "key"], "resources": [{"types": ["alias", "key"], "arn": "KeyArn"}, {"type": "alias", "fill": {"Alias": "AliasName"}}]},
|
||||
"payment-cryptography:VerifyAuthRequestCryptogram": {"action": "payment-cryptography:VerifyAuthRequestCryptogram", "types": ["alias", "key"], "resources": []},
|
||||
"payment-cryptography:VerifyCardValidationData": {"action": "payment-cryptography:VerifyCardValidationData", "types": ["alias", "key"], "resources": []},
|
||||
"payment-cryptography:VerifyMac": {"action": "payment-cryptography:VerifyMac", "types": ["alias", "key"], "resources": []},
|
||||
"payment-cryptography:VerifyPinData": {"action": "payment-cryptography:VerifyPinData", "types": ["alias", "key"], "resources": []},
|
||||
"payment-cryptography:VerifyAuthRequestCryptogram": {"action": "payment-cryptography:VerifyAuthRequestCryptogram", "types": ["alias", "key"], "resources": [{"type": "key", "fill": {"KeyId": "KeyIdentifier"}}]},
|
||||
"payment-cryptography:VerifyCardValidationData": {"action": "payment-cryptography:VerifyCardValidationData", "types": ["alias", "key"], "resources": [{"type": "key", "fill": {"KeyId": "KeyIdentifier"}}]},
|
||||
"payment-cryptography:VerifyMac": {"action": "payment-cryptography:VerifyMac", "types": ["alias", "key"], "resources": [{"type": "key", "fill": {"KeyId": "KeyIdentifier"}}]},
|
||||
"payment-cryptography:VerifyPinData": {"action": "payment-cryptography:VerifyPinData", "types": ["alias", "key"], "resources": [{"type": "key", "fill": {"KeyId": "EncryptionKeyIdentifier"}}, {"type": "key", "fill": {"KeyId": "VerificationKeyIdentifier"}}]},
|
||||
"quicksight:BatchCreateTopicReviewedAnswer": {"action": "quicksight:BatchCreateTopicReviewedAnswer", "types": ["topic"], "resources": [{"types": ["topic"], "arn": "Answers[].DatasetArn"}, {"type": "topic", "fill": {"ResourceId": "TopicId"}}], "located": {"TopicId": "{TopicId}"}},
|
||||
"quicksight:BatchDeleteKnowledgeBase": {"action": "quicksight:BatchDeleteKnowledgeBase", "types": ["knowledgeBase"], "resources": [{"type": "knowledgeBase", "fill": {"ResourceId": "KnowledgeBaseIds[]"}}]},
|
||||
"quicksight:BatchDeleteTopicReviewedAnswer": {"action": "quicksight:BatchDeleteTopicReviewedAnswer", "types": ["topic"], "resources": [{"type": "topic", "fill": {"ResourceId": "TopicId"}}], "located": {"TopicId": "{TopicId}"}},
|
||||
@@ -1356,6 +1361,7 @@
|
||||
"quicksight:DescribeQPersonalizationConfiguration": {"action": "quicksight:DescribeQPersonalizationConfiguration", "types": [], "resources": []},
|
||||
"quicksight:DescribeQuickSightQSearchConfiguration": {"action": "quicksight:DescribeQuickSightQSearchConfiguration", "types": [], "resources": []},
|
||||
"quicksight:DescribeRefreshSchedule": {"action": "quicksight:DescribeRefreshSchedule", "types": ["refreshschedule"], "resources": [{"type": "refreshschedule", "fill": {"DatasetId": "DataSetId"}}], "located": {"DataSetId": "{DataSetId}"}},
|
||||
"quicksight:DescribeResourcePermissions": {"action": "quicksight:DescribeResourcePermissions", "types": [], "resources": []},
|
||||
"quicksight:DescribeRoleCustomPermission": {"action": "quicksight:DescribeRoleCustomPermission", "types": [], "resources": []},
|
||||
"quicksight:DescribeSelfUpgradeConfiguration": {"action": "quicksight:DescribeSelfUpgradeConfiguration", "types": [], "resources": []},
|
||||
"quicksight:DescribeSpace": {"action": "quicksight:DescribeSpace", "types": ["space"], "resources": [{"type": "space", "fill": {"ResourceId": "SpaceId"}}], "located": {"SpaceId": "{SpaceId}"}},
|
||||
@@ -1500,6 +1506,7 @@
|
||||
"quicksight:UpdateQPersonalizationConfiguration": {"action": "quicksight:UpdateQPersonalizationConfiguration", "types": [], "resources": []},
|
||||
"quicksight:UpdateQuickSightQSearchConfiguration": {"action": "quicksight:UpdateQuickSightQSearchConfiguration", "types": [], "resources": []},
|
||||
"quicksight:UpdateRefreshSchedule": {"action": "quicksight:UpdateRefreshSchedule", "types": ["refreshschedule"], "resources": [{"types": ["refreshschedule"], "arn": "Schedule.Arn"}, {"type": "refreshschedule", "fill": {"DatasetId": "DataSetId"}}], "located": {"DataSetId": "{DataSetId}"}},
|
||||
"quicksight:UpdateResourcePermissions": {"action": "quicksight:UpdateResourcePermissions", "types": [], "resources": []},
|
||||
"quicksight:UpdateRoleCustomPermission": {"action": "quicksight:UpdateRoleCustomPermission", "types": [], "resources": []},
|
||||
"quicksight:UpdateSPICECapacityConfiguration": {"action": "quicksight:UpdateSPICECapacityConfiguration", "types": [], "resources": []},
|
||||
"quicksight:UpdateSelfUpgrade": {"action": "quicksight:UpdateSelfUpgrade", "types": ["user"], "resources": []},
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
{
|
||||
"_source": {
|
||||
"generator": "tools/aws/regen_payment_cryptography_data_shapes.py",
|
||||
"botocore": "botocore 1.43.118 (installed package)"
|
||||
},
|
||||
"operations": {
|
||||
"EncryptData": "EncryptDataInput",
|
||||
"DecryptData": "DecryptDataInput",
|
||||
"ReEncryptData": "ReEncryptDataInput",
|
||||
"GenerateMac": "GenerateMacInput",
|
||||
"VerifyMac": "VerifyMacInput"
|
||||
},
|
||||
"shapes": {
|
||||
"ApplicationCryptogramType": {
|
||||
"type": "string",
|
||||
"min": 16,
|
||||
"max": 16,
|
||||
"pattern": "[0-9a-fA-F]+"
|
||||
},
|
||||
"AsymmetricEncryptionAttributes": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"PaddingType": "PaddingType"
|
||||
}
|
||||
},
|
||||
"CertificateType": {
|
||||
"type": "string",
|
||||
"min": 1,
|
||||
"max": 32768,
|
||||
"pattern": "[^\\[;\\]<>]+"
|
||||
},
|
||||
"CipherTextType": {
|
||||
"type": "string",
|
||||
"min": 2,
|
||||
"max": 4224,
|
||||
"pattern": "(?:[0-9a-fA-F][0-9a-fA-F])+"
|
||||
},
|
||||
"DecryptDataInput": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"KeyIdentifier",
|
||||
"CipherText",
|
||||
"DecryptionAttributes"
|
||||
],
|
||||
"members": {
|
||||
"KeyIdentifier": "KeyArnOrKeyAliasType",
|
||||
"CipherText": "CipherTextType",
|
||||
"DecryptionAttributes": "EncryptionDecryptionAttributes",
|
||||
"WrappedKey": "WrappedKey"
|
||||
}
|
||||
},
|
||||
"DukptDerivationType": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"TDES_2KEY",
|
||||
"TDES_3KEY",
|
||||
"AES_128",
|
||||
"AES_192",
|
||||
"AES_256"
|
||||
]
|
||||
},
|
||||
"DukptEncryptionAttributes": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"KeySerialNumber"
|
||||
],
|
||||
"members": {
|
||||
"KeySerialNumber": "HexLength16Or20Or24",
|
||||
"Mode": "DukptEncryptionMode",
|
||||
"DukptKeyDerivationType": "DukptDerivationType",
|
||||
"DukptKeyVariant": "DukptKeyVariant",
|
||||
"InitializationVector": "InitializationVectorType"
|
||||
}
|
||||
},
|
||||
"DukptEncryptionMode": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"ECB",
|
||||
"CBC"
|
||||
]
|
||||
},
|
||||
"DukptKeyVariant": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"BIDIRECTIONAL",
|
||||
"REQUEST",
|
||||
"RESPONSE"
|
||||
]
|
||||
},
|
||||
"EcdhDerivationAttributes": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"CertificateAuthorityPublicKeyIdentifier",
|
||||
"PublicKeyCertificate",
|
||||
"KeyAlgorithm",
|
||||
"KeyDerivationFunction",
|
||||
"KeyDerivationHashAlgorithm",
|
||||
"SharedInformation"
|
||||
],
|
||||
"members": {
|
||||
"CertificateAuthorityPublicKeyIdentifier": "KeyArnOrKeyAliasType",
|
||||
"PublicKeyCertificate": "CertificateType",
|
||||
"KeyAlgorithm": "SymmetricKeyAlgorithm",
|
||||
"KeyDerivationFunction": "KeyDerivationFunction",
|
||||
"KeyDerivationHashAlgorithm": "KeyDerivationHashAlgorithm",
|
||||
"SharedInformation": "SharedInformation"
|
||||
}
|
||||
},
|
||||
"EmvEncryptionAttributes": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"MajorKeyDerivationMode",
|
||||
"PrimaryAccountNumber",
|
||||
"PanSequenceNumber",
|
||||
"SessionDerivationData"
|
||||
],
|
||||
"members": {
|
||||
"MajorKeyDerivationMode": "EmvMajorKeyDerivationMode",
|
||||
"PrimaryAccountNumber": "PrimaryAccountNumberType",
|
||||
"PanSequenceNumber": "NumberLengthEquals2",
|
||||
"SessionDerivationData": "SessionDerivationDataType",
|
||||
"Mode": "EmvEncryptionMode",
|
||||
"InitializationVector": "InitializationVectorType"
|
||||
}
|
||||
},
|
||||
"EmvEncryptionMode": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"ECB",
|
||||
"CBC"
|
||||
]
|
||||
},
|
||||
"EmvMajorKeyDerivationMode": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"EMV_OPTION_A",
|
||||
"EMV_OPTION_B"
|
||||
]
|
||||
},
|
||||
"EncryptDataInput": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"KeyIdentifier",
|
||||
"PlainText",
|
||||
"EncryptionAttributes"
|
||||
],
|
||||
"members": {
|
||||
"KeyIdentifier": "KeyArnOrKeyAliasType",
|
||||
"PlainText": "PlainTextType",
|
||||
"EncryptionAttributes": "EncryptionDecryptionAttributes",
|
||||
"WrappedKey": "WrappedKey"
|
||||
}
|
||||
},
|
||||
"EncryptionDecryptionAttributes": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"Symmetric": "SymmetricEncryptionAttributes",
|
||||
"Asymmetric": "AsymmetricEncryptionAttributes",
|
||||
"Dukpt": "DukptEncryptionAttributes",
|
||||
"Emv": "EmvEncryptionAttributes"
|
||||
}
|
||||
},
|
||||
"EncryptionMode": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"ECB",
|
||||
"CBC",
|
||||
"CFB",
|
||||
"CFB1",
|
||||
"CFB8",
|
||||
"CFB64",
|
||||
"CFB128",
|
||||
"OFB"
|
||||
]
|
||||
},
|
||||
"GenerateMacInput": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"KeyIdentifier",
|
||||
"MessageData",
|
||||
"GenerationAttributes"
|
||||
],
|
||||
"members": {
|
||||
"KeyIdentifier": "KeyArnOrKeyAliasType",
|
||||
"MessageData": "MessageDataType",
|
||||
"GenerationAttributes": "MacAttributes",
|
||||
"MacLength": "IntegerRangeBetween4And32"
|
||||
}
|
||||
},
|
||||
"HexLength16Or20Or24": {
|
||||
"type": "string",
|
||||
"min": 16,
|
||||
"max": 24,
|
||||
"pattern": "(?:[0-9a-fA-F]{16}|[0-9a-fA-F]{20}|[0-9a-fA-F]{24})"
|
||||
},
|
||||
"HexLengthEquals4": {
|
||||
"type": "string",
|
||||
"min": 4,
|
||||
"max": 4,
|
||||
"pattern": "[0-9a-fA-F]+"
|
||||
},
|
||||
"InitializationVectorType": {
|
||||
"type": "string",
|
||||
"min": 16,
|
||||
"max": 32,
|
||||
"pattern": "(?:[0-9a-fA-F]{16}|[0-9a-fA-F]{32})"
|
||||
},
|
||||
"IntegerRangeBetween4And32": {
|
||||
"type": "integer",
|
||||
"min": 4,
|
||||
"max": 32
|
||||
},
|
||||
"KeyArnOrKeyAliasType": {
|
||||
"type": "string",
|
||||
"min": 7,
|
||||
"max": 322,
|
||||
"pattern": "arn:aws[a-z0-9-]*:payment-cryptography:[a-z]{2,4}(-[a-z]{1,16})+-[0-9]+:[0-9]{12}:(key/[0-9a-zA-Z]{16,64}|alias/[a-zA-Z0-9/_-]+)$|^alias/[a-zA-Z0-9/_-]+"
|
||||
},
|
||||
"KeyCheckValueAlgorithm": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"CMAC",
|
||||
"ANSI_X9_24",
|
||||
"HMAC",
|
||||
"SHA_1"
|
||||
]
|
||||
},
|
||||
"KeyDerivationFunction": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"NIST_SP800",
|
||||
"ANSI_X963"
|
||||
]
|
||||
},
|
||||
"KeyDerivationHashAlgorithm": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"SHA_256",
|
||||
"SHA_384",
|
||||
"SHA_512"
|
||||
]
|
||||
},
|
||||
"MacAlgorithm": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"ISO9797_ALGORITHM1",
|
||||
"ISO9797_ALGORITHM3",
|
||||
"CMAC",
|
||||
"HMAC",
|
||||
"HMAC_SHA224",
|
||||
"HMAC_SHA256",
|
||||
"HMAC_SHA384",
|
||||
"HMAC_SHA512",
|
||||
"AS2805_4_1"
|
||||
]
|
||||
},
|
||||
"MacAlgorithmDukpt": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"KeySerialNumber",
|
||||
"DukptKeyVariant"
|
||||
],
|
||||
"members": {
|
||||
"KeySerialNumber": "HexLength16Or20Or24",
|
||||
"DukptKeyVariant": "DukptKeyVariant",
|
||||
"DukptDerivationType": "DukptDerivationType"
|
||||
}
|
||||
},
|
||||
"MacAlgorithmEmv": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"MajorKeyDerivationMode",
|
||||
"PrimaryAccountNumber",
|
||||
"PanSequenceNumber",
|
||||
"SessionKeyDerivationMode",
|
||||
"SessionKeyDerivationValue"
|
||||
],
|
||||
"members": {
|
||||
"MajorKeyDerivationMode": "MajorKeyDerivationMode",
|
||||
"PrimaryAccountNumber": "PrimaryAccountNumberType",
|
||||
"PanSequenceNumber": "NumberLengthEquals2",
|
||||
"SessionKeyDerivationMode": "SessionKeyDerivationMode",
|
||||
"SessionKeyDerivationValue": "SessionKeyDerivationValue"
|
||||
}
|
||||
},
|
||||
"MacAttributes": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"Algorithm": "MacAlgorithm",
|
||||
"EmvMac": "MacAlgorithmEmv",
|
||||
"DukptIso9797Algorithm1": "MacAlgorithmDukpt",
|
||||
"DukptIso9797Algorithm3": "MacAlgorithmDukpt",
|
||||
"DukptCmac": "MacAlgorithmDukpt"
|
||||
}
|
||||
},
|
||||
"MacType": {
|
||||
"type": "string",
|
||||
"min": 4,
|
||||
"max": 128,
|
||||
"pattern": "(?:[0-9a-fA-F][0-9a-fA-F])+"
|
||||
},
|
||||
"MajorKeyDerivationMode": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"EMV_OPTION_A",
|
||||
"EMV_OPTION_B"
|
||||
]
|
||||
},
|
||||
"MessageDataType": {
|
||||
"type": "string",
|
||||
"min": 2,
|
||||
"max": 8192,
|
||||
"pattern": "(?:[0-9a-fA-F][0-9a-fA-F])+"
|
||||
},
|
||||
"NumberLengthEquals2": {
|
||||
"type": "string",
|
||||
"min": 2,
|
||||
"max": 2,
|
||||
"pattern": "[0-9]+"
|
||||
},
|
||||
"PaddingType": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"PKCS1",
|
||||
"OAEP_SHA1",
|
||||
"OAEP_SHA256",
|
||||
"OAEP_SHA512"
|
||||
]
|
||||
},
|
||||
"PlainTextType": {
|
||||
"type": "string",
|
||||
"min": 2,
|
||||
"max": 4096,
|
||||
"pattern": "(?:[0-9a-fA-F][0-9a-fA-F])+"
|
||||
},
|
||||
"PrimaryAccountNumberType": {
|
||||
"type": "string",
|
||||
"min": 12,
|
||||
"max": 19,
|
||||
"pattern": "[0-9]+"
|
||||
},
|
||||
"ReEncryptDataInput": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"IncomingKeyIdentifier",
|
||||
"OutgoingKeyIdentifier",
|
||||
"CipherText",
|
||||
"IncomingEncryptionAttributes",
|
||||
"OutgoingEncryptionAttributes"
|
||||
],
|
||||
"members": {
|
||||
"IncomingKeyIdentifier": "KeyArnOrKeyAliasType",
|
||||
"OutgoingKeyIdentifier": "KeyArnOrKeyAliasType",
|
||||
"CipherText": "CipherTextType",
|
||||
"IncomingEncryptionAttributes": "ReEncryptionAttributes",
|
||||
"OutgoingEncryptionAttributes": "ReEncryptionAttributes",
|
||||
"IncomingWrappedKey": "WrappedKey",
|
||||
"OutgoingWrappedKey": "WrappedKey"
|
||||
}
|
||||
},
|
||||
"ReEncryptionAttributes": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"Symmetric": "SymmetricEncryptionAttributes",
|
||||
"Asymmetric": "AsymmetricEncryptionAttributes",
|
||||
"Dukpt": "DukptEncryptionAttributes"
|
||||
}
|
||||
},
|
||||
"SessionDerivationDataType": {
|
||||
"type": "string",
|
||||
"min": 16,
|
||||
"max": 16,
|
||||
"pattern": "[0-9a-fA-F]+"
|
||||
},
|
||||
"SessionKeyDerivationMode": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"EMV_COMMON_SESSION_KEY",
|
||||
"EMV2000",
|
||||
"AMEX",
|
||||
"MASTERCARD_SESSION_KEY",
|
||||
"VISA",
|
||||
"UNION_PAY"
|
||||
]
|
||||
},
|
||||
"SessionKeyDerivationValue": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"ApplicationCryptogram": "ApplicationCryptogramType",
|
||||
"ApplicationTransactionCounter": "HexLengthEquals4"
|
||||
}
|
||||
},
|
||||
"SharedInformation": {
|
||||
"type": "string",
|
||||
"min": 2,
|
||||
"max": 2048,
|
||||
"pattern": "(?:[0-9a-fA-F][0-9a-fA-F])+"
|
||||
},
|
||||
"SymmetricEncryptionAttributes": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"Mode"
|
||||
],
|
||||
"members": {
|
||||
"Mode": "EncryptionMode",
|
||||
"InitializationVector": "InitializationVectorType",
|
||||
"PaddingType": "PaddingType"
|
||||
}
|
||||
},
|
||||
"SymmetricKeyAlgorithm": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"TDES_2KEY",
|
||||
"TDES_3KEY",
|
||||
"AES_128",
|
||||
"AES_192",
|
||||
"AES_256",
|
||||
"HMAC_SHA256",
|
||||
"HMAC_SHA384",
|
||||
"HMAC_SHA512",
|
||||
"HMAC_SHA224"
|
||||
]
|
||||
},
|
||||
"Tr31WrappedKeyBlock": {
|
||||
"type": "string",
|
||||
"min": 56,
|
||||
"max": 9984,
|
||||
"pattern": "[0-9a-zA-Z]+"
|
||||
},
|
||||
"VerifyMacInput": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"KeyIdentifier",
|
||||
"MessageData",
|
||||
"Mac",
|
||||
"VerificationAttributes"
|
||||
],
|
||||
"members": {
|
||||
"KeyIdentifier": "KeyArnOrKeyAliasType",
|
||||
"MessageData": "MessageDataType",
|
||||
"Mac": "MacType",
|
||||
"VerificationAttributes": "MacAttributes",
|
||||
"MacLength": "IntegerRangeBetween4And32"
|
||||
}
|
||||
},
|
||||
"WrappedKey": {
|
||||
"type": "structure",
|
||||
"required": [
|
||||
"WrappedKeyMaterial"
|
||||
],
|
||||
"members": {
|
||||
"WrappedKeyMaterial": "WrappedKeyMaterial",
|
||||
"KeyCheckValueAlgorithm": "KeyCheckValueAlgorithm"
|
||||
}
|
||||
},
|
||||
"WrappedKeyMaterial": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"Tr31KeyBlock": "Tr31WrappedKeyBlock",
|
||||
"DiffieHellmanSymmetricKey": "EcdhDerivationAttributes"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -689,6 +689,28 @@
|
||||
"UpgradeDomain": {"method": "POST", "requestUri": "/2021-01-01/opensearch/upgradeDomain"}
|
||||
}
|
||||
},
|
||||
"payment-cryptography-data": {
|
||||
"credentialScope": "payment-cryptography",
|
||||
"apiVersion": "2022-02-03",
|
||||
"accessDeniedStatus": 403,
|
||||
"operations": {
|
||||
"DecryptData": {"method": "POST", "requestUri": "/_paymentcryptography/keys/{KeyIdentifier+}/decrypt"},
|
||||
"EncryptData": {"method": "POST", "requestUri": "/_paymentcryptography/keys/{KeyIdentifier+}/encrypt"},
|
||||
"GenerateAs2805KekValidation": {"method": "POST", "requestUri": "/_paymentcryptography/as2805kekvalidation/generate"},
|
||||
"GenerateAuthRequestCryptogram": {"method": "POST", "requestUri": "/_paymentcryptography/cryptogram/generate"},
|
||||
"GenerateCardValidationData": {"method": "POST", "requestUri": "/_paymentcryptography/cardvalidationdata/generate"},
|
||||
"GenerateMac": {"method": "POST", "requestUri": "/_paymentcryptography/mac/generate"},
|
||||
"GenerateMacEmvPinChange": {"method": "POST", "requestUri": "/_paymentcryptography/macemvpinchange/generate"},
|
||||
"GeneratePinData": {"method": "POST", "requestUri": "/_paymentcryptography/pindata/generate"},
|
||||
"ReEncryptData": {"method": "POST", "requestUri": "/_paymentcryptography/keys/{IncomingKeyIdentifier+}/reencrypt"},
|
||||
"TranslateKeyMaterial": {"method": "POST", "requestUri": "/_paymentcryptography/keymaterial/translate"},
|
||||
"TranslatePinData": {"method": "POST", "requestUri": "/_paymentcryptography/pindata/translate"},
|
||||
"VerifyAuthRequestCryptogram": {"method": "POST", "requestUri": "/_paymentcryptography/cryptogram/verify"},
|
||||
"VerifyCardValidationData": {"method": "POST", "requestUri": "/_paymentcryptography/cardvalidationdata/verify"},
|
||||
"VerifyMac": {"method": "POST", "requestUri": "/_paymentcryptography/mac/verify"},
|
||||
"VerifyPinData": {"method": "POST", "requestUri": "/_paymentcryptography/pindata/verify"}
|
||||
}
|
||||
},
|
||||
"pipes": {
|
||||
"credentialScope": "pipes",
|
||||
"apiVersion": "2015-10-07",
|
||||
|
||||
@@ -57,6 +57,15 @@ class CredentialScopeAliasTest {
|
||||
assertEquals("sso", catalog.canonicalCredentialScope("awsssoportal"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void paymentCryptographyDataAliasNormalisesToPaymentCryptography() {
|
||||
// The Payment Cryptography data plane signs as payment-cryptography-data, but its actions
|
||||
// live under the payment-cryptography: namespace (payment-cryptography:EncryptData and
|
||||
// peers in the Service Authorization Reference), so enforcement has to resolve it there
|
||||
// rather than invent payment-cryptography-data:.
|
||||
assertEquals("payment-cryptography", catalog.canonicalCredentialScope("payment-cryptography-data"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void canonicalScopeIsUnchanged() {
|
||||
assertEquals("s3", catalog.canonicalCredentialScope("s3"));
|
||||
@@ -89,7 +98,8 @@ class CredentialScopeAliasTest {
|
||||
.filter(scope -> !scope.equals(catalog.canonicalCredentialScope(scope)))
|
||||
.collect(Collectors.toMap(scope -> scope, catalog::canonicalCredentialScope));
|
||||
|
||||
assertEquals(Map.of("s3express", "s3", "iot-jobs-data", "iot", "awsssoportal", "sso", "monitoring", "cloudwatch"), rewritten);
|
||||
assertEquals(Map.of("s3express", "s3", "iot-jobs-data", "iot", "awsssoportal", "sso",
|
||||
"monitoring", "cloudwatch", "payment-cryptography-data", "payment-cryptography"), rewritten);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -13,6 +13,7 @@ import java.net.URL;
|
||||
import java.net.URLClassLoader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@@ -88,6 +89,22 @@ class IamRestRoutesTest {
|
||||
assertEquals(Optional.of("GetThingVersion"), get("/things/web:3"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The values the path holds are read under the names the route gives its labels, so that a
|
||||
* service which names a resource in the path reads the resource from it. A label holding an
|
||||
* ARN spans the slashes the ARN holds, so the route names it with a {@code +}.
|
||||
*/
|
||||
@Test
|
||||
void theValuesThePathHoldsAreReadUnderTheNamesItsLabelsCarry() {
|
||||
IamRestRoutes table = routes(ROUTES.replace("\"/things/{ThingName}\"", "\"/keys/{KeyIdentifier+}\"")
|
||||
.replace("\"GetThing\"", "\"GetKey\""));
|
||||
assertEquals(Map.of("KeyIdentifier", "arn:aws:service:region:account:key/abc"),
|
||||
table.match("svc", "GET", "/keys/arn:aws:service:region:account:key/abc", null)
|
||||
.map(IamRestRoutes.Match::labels).orElse(Map.of()));
|
||||
assertEquals(Map.of(), table.match("svc", "GET", "/things/web", null)
|
||||
.map(IamRestRoutes.Match::labels).orElse(Map.of()));
|
||||
}
|
||||
|
||||
/** A greedy label takes the rest of the path, one segment or more, and ranks below a literal there. */
|
||||
@Test
|
||||
void aGreedyLabelTakesTheRestOfThePath() {
|
||||
|
||||
+251
@@ -0,0 +1,251 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import io.floci.aws.testing.EnforcementFixtures;
|
||||
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
|
||||
import io.floci.aws.testing.IamEnforcementProfile;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* The data plane's requests are authorized by the action of their route, and a policy that
|
||||
* denies that action is enforced however the key is named.
|
||||
*
|
||||
* <p>The key of a data-plane request may be named by its identifier or by its ARN, and a
|
||||
* client sends an ARN with its colon and slash encoded. The router rewrites the request onto
|
||||
* the internal prefix, and the IAM rules are matched on the rewritten path, which is decoded.
|
||||
* So the ARN arrives as a path that holds a real slash, and a rule that stopped at the first
|
||||
* slash would not match it: the request would resolve to no action, and the denial would not
|
||||
* be enforced.
|
||||
*
|
||||
* <p>The rest of the repository holds a request to its standard: a request is refused however
|
||||
* it is sent. This is that standard for the data plane.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class PaymentCryptographyDataPlaneIamEnforcementTest {
|
||||
|
||||
/** The key every test works with. */
|
||||
private String keyArn;
|
||||
|
||||
private String keyId;
|
||||
|
||||
/** The caller whose policy the test writes. */
|
||||
private UserCredentials caller;
|
||||
|
||||
/** The account the administrator acts in. */
|
||||
private static final String ADMIN = "test";
|
||||
|
||||
/** The caller of each test, with a name of its own. */
|
||||
private String callerName;
|
||||
|
||||
/** The key the MAC operations use, which is a MAC key and not a data-encryption one. */
|
||||
private String macKeyArn;
|
||||
|
||||
@TestHTTPResource("/")
|
||||
static URI baseUri;
|
||||
|
||||
private final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@BeforeEach
|
||||
void createTheKeyAndTheCaller() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
keyArn = given().contentType("application/x-amz-json-1.0")
|
||||
.header("X-Amz-Target", "PaymentCryptographyControlPlane.CreateKey")
|
||||
.header("Authorization", auth(ADMIN, "payment-cryptography"))
|
||||
.body("{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\",\"KeyClass\":\"SYMMETRIC_KEY\","
|
||||
+ "\"KeyUsage\":\"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY\","
|
||||
+ "\"KeyModesOfUse\":{\"Encrypt\":true,\"Decrypt\":true}},\"Exportable\":true}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().path("Key.KeyArn");
|
||||
keyId = keyArn.substring(keyArn.lastIndexOf('/') + 1);
|
||||
macKeyArn = given().contentType("application/x-amz-json-1.0")
|
||||
.header("X-Amz-Target", "PaymentCryptographyControlPlane.CreateKey")
|
||||
.header("Authorization", auth(ADMIN, "payment-cryptography"))
|
||||
.body("{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\",\"KeyClass\":\"SYMMETRIC_KEY\","
|
||||
+ "\"KeyUsage\":\"TR31_M6_ISO_9797_5_CMAC_KEY\","
|
||||
+ "\"KeyModesOfUse\":{\"Generate\":true,\"Verify\":true}},\"Exportable\":true}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().path("Key.KeyArn");
|
||||
callerName = "payment-cryptography-data-" + Long.toString(System.nanoTime(), 36);
|
||||
caller = EnforcementFixtures.createUser(cleanup, port(), auth(ADMIN, "iam"), callerName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenialIsEnforcedWhenTheKeyIsNamedByItsIdentifier() {
|
||||
denyEncryptData();
|
||||
assertEquals(403, encrypt("/keys/" + keyId + "/encrypt").extract().statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenialIsEnforcedWhenTheKeyIsNamedByItsArn() {
|
||||
denyEncryptData();
|
||||
assertEquals(403, encrypt("/keys/" + keyArn + "/encrypt").extract().statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenialIsEnforcedWhenTheKeyIsNamedByItsEncodedArn() {
|
||||
denyEncryptData();
|
||||
String encoded = keyArn.replace(":", "%3A").replace("/", "%2F");
|
||||
assertEquals(403, encrypt("/keys/" + encoded + "/encrypt").extract().statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCallerWithNoPermissionIsRefused() {
|
||||
// A policy with no statement at all: the caller may do nothing.
|
||||
EnforcementFixtures.putUserPolicy(port(), auth(ADMIN, "iam"), callerName, "p",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[]}");
|
||||
assertEquals(403, encrypt("/keys/" + keyArn + "/encrypt").extract().statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestIsServedWhenTheActionIsAllowed() {
|
||||
// The action is allowed, so the request is served and the answer carries the ciphertext.
|
||||
allowEncryptData();
|
||||
ValidatableResponse response = encrypt("/keys/" + keyArn + "/encrypt");
|
||||
assertEquals(200, response.extract().statusCode());
|
||||
response.body("CipherText", notNullValue());
|
||||
}
|
||||
|
||||
/** The request is made as the caller, whose policy is what is under test. */
|
||||
private ValidatableResponse encrypt(String path) {
|
||||
return given().contentType("application/json")
|
||||
.header("Authorization", auth(caller.accessKeyId(), "payment-cryptography"))
|
||||
.body("{\"PlainText\":\"" + "00".repeat(16) + "\","
|
||||
+ "\"EncryptionAttributes\":{\"Symmetric\":{\"Mode\":\"CBC\"}}}")
|
||||
.when().post(path)
|
||||
.then();
|
||||
}
|
||||
|
||||
/** A policy that allows the one action of the route. */
|
||||
private void allowEncryptData() {
|
||||
EnforcementFixtures.putUserPolicy(port(), auth(ADMIN, "iam"), callerName, "p",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"payment-cryptography:EncryptData\","
|
||||
+ "\"Resource\":\"*\"}]}");
|
||||
}
|
||||
|
||||
/** A policy that allows everything and denies the one action of the route. */
|
||||
@Test
|
||||
void aDenialOnOneKeyIsEnforcedWhenThatKeyIsNamed() {
|
||||
// The request names the key, so the action is checked on that key and a denial
|
||||
// limited to it holds.
|
||||
EnforcementFixtures.putUserPolicy(port(), auth(ADMIN, "iam"), callerName, "p",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":\"payment-cryptography:EncryptData\","
|
||||
+ "\"Resource\":\"" + keyArn + "\"}]}");
|
||||
|
||||
assertEquals(403, encrypt("/keys/" + keyArn + "/encrypt").extract().statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAllowOnOneKeyIsEnoughWhenThatKeyIsNamed() {
|
||||
// The policy allows the one key and nothing else, and the request names it.
|
||||
EnforcementFixtures.putUserPolicy(port(), auth(ADMIN, "iam"), callerName, "p",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"payment-cryptography:*\","
|
||||
+ "\"Resource\":\"" + keyArn + "\"}]}");
|
||||
|
||||
ValidatableResponse response = encrypt("/keys/" + keyArn + "/encrypt");
|
||||
assertEquals(200, response.extract().statusCode());
|
||||
response.body("CipherText", notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyIsReadFromThePathWhicheverWayTheRouteIsSpelled() {
|
||||
// The route may end in a slash, and the key is named in the path either way, so the
|
||||
// action is checked on the key and a denial limited to it holds.
|
||||
EnforcementFixtures.putUserPolicy(port(), auth(ADMIN, "iam"), callerName, "p",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":\"payment-cryptography:EncryptData\","
|
||||
+ "\"Resource\":\"" + keyArn + "\"}]}");
|
||||
|
||||
assertEquals(403, encrypt("/keys/" + keyArn + "/encrypt/").extract().statusCode());
|
||||
}
|
||||
|
||||
private void denyEncryptData() {
|
||||
EnforcementFixtures.putUserPolicy(port(), auth(ADMIN, "iam"), callerName, "p",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":\"payment-cryptography:EncryptData\","
|
||||
+ "\"Resource\":\"*\"}]}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenialOnOneKeyIsEnforcedWhenTheMacNamesIt() {
|
||||
// The MAC names its key in the body, and the action is checked on that key.
|
||||
EnforcementFixtures.putUserPolicy(port(), auth(ADMIN, "iam"), callerName, "p",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":\"payment-cryptography:GenerateMac\","
|
||||
+ "\"Resource\":\"" + macKeyArn + "\"}]}");
|
||||
|
||||
assertEquals(403, generateMac().extract().statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAllowOnOneKeyIsEnoughWhenTheMacNamesIt() {
|
||||
// The policy allows the one key and nothing else, and the MAC names it.
|
||||
EnforcementFixtures.putUserPolicy(port(), auth(ADMIN, "iam"), callerName, "p",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"payment-cryptography:*\","
|
||||
+ "\"Resource\":\"" + macKeyArn + "\"}]}");
|
||||
|
||||
assertEquals(200, generateMac().extract().statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenialOnOneKeyIsEnforcedWhenTheReEncryptionNamesIt() {
|
||||
// The re-encryption names the incoming key in the path and the outgoing one in the body,
|
||||
// and the action is checked on both, so a denial on either of them holds.
|
||||
EnforcementFixtures.putUserPolicy(port(), auth(ADMIN, "iam"), callerName, "p",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":\"payment-cryptography:ReEncryptData\","
|
||||
+ "\"Resource\":\"" + keyArn + "\"}]}");
|
||||
|
||||
// The denied key is the one the path names, and the body names another.
|
||||
assertEquals(403, reEncrypt("/keys/" + keyArn + "/reencrypt", macKeyArn).extract().statusCode());
|
||||
// The denied key is the one the body names, and the path names another.
|
||||
assertEquals(403, reEncrypt("/keys/" + macKeyArn + "/reencrypt", keyArn).extract().statusCode());
|
||||
}
|
||||
|
||||
/** The request is made as the caller, whose policy is what is under test. */
|
||||
private ValidatableResponse generateMac() {
|
||||
return given().contentType("application/json")
|
||||
.header("Authorization", auth(caller.accessKeyId(), "payment-cryptography"))
|
||||
.body("{\"KeyIdentifier\":\"" + macKeyArn + "\",\"MessageData\":\"" + "00".repeat(16) + "\","
|
||||
+ "\"GenerationAttributes\":{\"Algorithm\":\"CMAC\"}}")
|
||||
.when().post("/mac/generate")
|
||||
.then();
|
||||
}
|
||||
|
||||
/** The request is made as the caller, whose policy is what is under test. */
|
||||
private ValidatableResponse reEncrypt(String path, String outgoingKeyArn) {
|
||||
return given().contentType("application/json")
|
||||
.header("Authorization", auth(caller.accessKeyId(), "payment-cryptography"))
|
||||
.body("{\"OutgoingKeyIdentifier\":\"" + outgoingKeyArn + "\",\"CipherText\":\"" + "00".repeat(16) + "\"}")
|
||||
.when().post(path)
|
||||
.then();
|
||||
}
|
||||
|
||||
private static int port() {
|
||||
return baseUri.getPort();
|
||||
}
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The data plane's routes are checked as the actions AWS checks them for, however the key is
|
||||
* named.
|
||||
*
|
||||
* <p>The key of a data-plane request may be named by its identifier or by its ARN, and an ARN
|
||||
* carries a slash that a client sends encoded. The router rewrites the request onto the
|
||||
* internal prefix, and the IAM rules are matched on the rewritten path, which is decoded. So
|
||||
* the ARN arrives as a path that holds a real slash, and a rule that stops at the first slash
|
||||
* would not match it: the request would resolve to no action, and a policy that denies the
|
||||
* action would not be enforced.
|
||||
*
|
||||
* <p>The rest of the repository holds a request to its standard: a request is refused however
|
||||
* it is sent. This is that standard for the data plane.
|
||||
*/
|
||||
class PaymentCryptographyDataPlaneIamRouteTest {
|
||||
|
||||
private final IamActionRegistry registry = new IamActionRegistry();
|
||||
|
||||
private static final String KEY_ID = "1234abcd-12ab-34cd-56ef-1234567890ab";
|
||||
|
||||
private static final String KEY_ARN =
|
||||
"arn:aws:payment-cryptography:us-east-1:000000000000:key/" + KEY_ID;
|
||||
|
||||
@Test
|
||||
void theKeyIdentifierResolvesToItsAction() {
|
||||
assertEquals("payment-cryptography:EncryptData",
|
||||
resolve("/_paymentcryptography/keys/" + KEY_ID + "/encrypt"));
|
||||
assertEquals("payment-cryptography:DecryptData",
|
||||
resolve("/_paymentcryptography/keys/" + KEY_ID + "/decrypt"));
|
||||
assertEquals("payment-cryptography:ReEncryptData",
|
||||
resolve("/_paymentcryptography/keys/" + KEY_ID + "/reencrypt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theKeyArnResolvesToTheSameAction() {
|
||||
assertEquals("payment-cryptography:EncryptData",
|
||||
resolve("/_paymentcryptography/keys/" + KEY_ARN + "/encrypt"));
|
||||
assertEquals("payment-cryptography:DecryptData",
|
||||
resolve("/_paymentcryptography/keys/" + KEY_ARN + "/decrypt"));
|
||||
assertEquals("payment-cryptography:ReEncryptData",
|
||||
resolve("/_paymentcryptography/keys/" + KEY_ARN + "/reencrypt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theEncodedKeyArnResolvesToTheSameAction() {
|
||||
// The router matches the rewritten path decoded, so the encoded slash of the ARN is a
|
||||
// real slash by the time the rule is matched.
|
||||
String encoded = KEY_ARN.replace(":", "%3A").replace("/", "%2F");
|
||||
assertEquals("payment-cryptography:EncryptData",
|
||||
resolve("/_paymentcryptography/keys/" + encoded + "/encrypt"));
|
||||
assertEquals("payment-cryptography:DecryptData",
|
||||
resolve("/_paymentcryptography/keys/" + encoded + "/decrypt"));
|
||||
assertEquals("payment-cryptography:ReEncryptData",
|
||||
resolve("/_paymentcryptography/keys/" + encoded + "/reencrypt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theOtherOperationsResolveToTheirActions() {
|
||||
assertEquals("payment-cryptography:GenerateMac", resolve("/_paymentcryptography/mac/generate"));
|
||||
assertEquals("payment-cryptography:VerifyMac", resolve("/_paymentcryptography/mac/verify"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRoutesAreReadUnderTheServicesScope() {
|
||||
// A client of the data plane signs for the service, which is one scope for both of
|
||||
// its planes, and a client that signs for the data plane's own scope is served under
|
||||
// that scope too (see CredentialScopeAliasTest), so the routes are read under the one
|
||||
// scope the actions live in.
|
||||
assertEquals("payment-cryptography:EncryptData",
|
||||
resolve("/_paymentcryptography/keys/" + KEY_ID + "/encrypt"));
|
||||
assertEquals("payment-cryptography:EncryptData",
|
||||
resolve("/_paymentcryptography/keys/" + KEY_ARN + "/encrypt"));
|
||||
}
|
||||
|
||||
/** The action the registry resolves for a POST to the path, for the service's scope. */
|
||||
private String resolve(String path) {
|
||||
return resolve("payment-cryptography", path);
|
||||
}
|
||||
|
||||
/** The action the registry resolves for a POST to the path. */
|
||||
private String resolve(String scope, String path) {
|
||||
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
|
||||
UriInfo uriInfo = mock(UriInfo.class);
|
||||
when(uriInfo.getPath()).thenReturn(path);
|
||||
when(uriInfo.getRequestUri()).thenReturn(URI.create("http://localhost:4566" + path));
|
||||
when(uriInfo.getBaseUri()).thenReturn(URI.create("http://localhost:4566/"));
|
||||
when(ctx.getUriInfo()).thenReturn(uriInfo);
|
||||
when(ctx.getMethod()).thenReturn("POST");
|
||||
return registry.resolveRoute(scope, ctx);
|
||||
}
|
||||
}
|
||||
@@ -1285,6 +1285,11 @@ class ResourceArnBuilderTest {
|
||||
void paymentCryptographyResolvesAnAliasToTheKeyItPointsAt() {
|
||||
ResourceArnBuilder reading = reading(stored("payment-cryptography", "key", "alias/team/card-key", PC_KEY_ARN));
|
||||
|
||||
// The route its resources are read from is the one the request's path matches, so the
|
||||
// request names its method and its URI.
|
||||
when(ctx.getMethod()).thenReturn("POST");
|
||||
when(uriInfo.getRequestUri()).thenReturn(URI.create("http://localhost:4566/"));
|
||||
when(uriInfo.getBaseUri()).thenReturn(URI.create("http://localhost:4566/"));
|
||||
setJsonBody("{\"KeyIdentifier\":\"alias/team/card-key\"}");
|
||||
assertEquals(List.of(PC_KEY_ARN),
|
||||
reading.buildResources("payment-cryptography", "payment-cryptography:GetKey", ctx,
|
||||
|
||||
+553
@@ -0,0 +1,553 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class PaymentCryptographyCryptoHandlerTest {
|
||||
|
||||
private PaymentCryptographyService service;
|
||||
private PaymentCryptographyCryptoHandler handler;
|
||||
private InMemoryStorage<String, PaymentCryptographyKey> keys;
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
keys = new InMemoryStorage<>();
|
||||
service = new PaymentCryptographyService(
|
||||
keys,
|
||||
new InMemoryStorage<>(),
|
||||
new RegionResolver("us-east-1", "000000000000"));
|
||||
handler = new PaymentCryptographyCryptoHandler(service);
|
||||
}
|
||||
|
||||
/** A TDES key, which is what the ISO 9797-1 MAC is computed under. */
|
||||
private PaymentCryptographyKey createTdesKey(String... modes) {
|
||||
return createKeyOf("TDES_2KEY", "TR31_M6_ISO_9797_5_CMAC_KEY", modes);
|
||||
}
|
||||
|
||||
private PaymentCryptographyKey createTdesKeyOf(String algorithm, String... modes) {
|
||||
return createKeyOf(algorithm, "TR31_M6_ISO_9797_5_CMAC_KEY", modes);
|
||||
}
|
||||
|
||||
/** A Triple DES key of the data encryption usage, which the data plane ciphers with. */
|
||||
private PaymentCryptographyKey createTdesDataKey(String algorithm, String... modes) {
|
||||
return createKeyOf(algorithm, "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", modes);
|
||||
}
|
||||
|
||||
private PaymentCryptographyKey createKey(String... modes) {
|
||||
return createKeyOf("AES_256", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", modes);
|
||||
}
|
||||
|
||||
/** A key of the algorithm and the usage a test asks for. */
|
||||
private PaymentCryptographyKey createKeyOf(String algorithm, String usage, String... modes) {
|
||||
Map<String, Object> attributes = new LinkedHashMap<>();
|
||||
attributes.put("KeyAlgorithm", algorithm);
|
||||
attributes.put("KeyClass", "SYMMETRIC_KEY");
|
||||
attributes.put("KeyUsage", usage);
|
||||
Map<String, Boolean> declared = new LinkedHashMap<>();
|
||||
for (String mode : modes) {
|
||||
declared.put(mode, Boolean.TRUE);
|
||||
}
|
||||
return service.createKey("us-east-1", attributes, declared, true, true, Map.of());
|
||||
}
|
||||
|
||||
private static byte[] hexBytes(String hex) {
|
||||
return PaymentCryptographyCrypto.fromHex(hex);
|
||||
}
|
||||
|
||||
/** The MAC attributes of the ISO 9797-1 algorithm 3, the retail MAC. */
|
||||
private static JsonNode iso9797() {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
ObjectNode attributes = mapper.createObjectNode();
|
||||
attributes.put("Algorithm", "ISO9797_ALGORITHM3");
|
||||
return attributes;
|
||||
}
|
||||
|
||||
private static String hex(byte[] bytes) {
|
||||
return PaymentCryptographyCrypto.toHex(bytes).toUpperCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
/** A request body, built as a map so the test says what it means. */
|
||||
private JsonNode request(Map<String, Object> members) {
|
||||
ObjectNode node = mapper.createObjectNode();
|
||||
members.forEach((name, value) -> {
|
||||
if (value instanceof JsonNode json) {
|
||||
node.set(name, json);
|
||||
} else if (value instanceof Integer number) {
|
||||
node.put(name, number);
|
||||
} else {
|
||||
node.put(name, String.valueOf(value));
|
||||
}
|
||||
});
|
||||
return node;
|
||||
}
|
||||
|
||||
|
||||
/** The encryption attributes of a request that encrypts in CBC mode. */
|
||||
private JsonNode cbc() {
|
||||
ObjectNode symmetric = mapper.createObjectNode();
|
||||
symmetric.put("Mode", "CBC");
|
||||
ObjectNode attributes = mapper.createObjectNode();
|
||||
attributes.set("Symmetric", symmetric);
|
||||
return attributes;
|
||||
}
|
||||
|
||||
/** The CBC attributes with the vector the request names. */
|
||||
private JsonNode cbcWithVector(String vector) {
|
||||
ObjectNode symmetric = mapper.createObjectNode();
|
||||
symmetric.put("Mode", "CBC");
|
||||
symmetric.put("InitializationVector", vector);
|
||||
ObjectNode attributes = mapper.createObjectNode();
|
||||
attributes.set("Symmetric", symmetric);
|
||||
return attributes;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyEncryptsAndDecrypts() {
|
||||
PaymentCryptographyKey key = createKey("Encrypt", "Decrypt");
|
||||
|
||||
Map<String, Object> encrypted = handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(),
|
||||
"PlainText", hex("hello, world!!!!".getBytes()),
|
||||
"EncryptionAttributes", cbc())), "us-east-1");
|
||||
|
||||
assertEquals(key.getArn(), encrypted.get("KeyArn"));
|
||||
assertEquals(key.getKeyCheckValue(), encrypted.get("KeyCheckValue"));
|
||||
String cipherText = (String) encrypted.get("CipherText");
|
||||
|
||||
Map<String, Object> decrypted = handler.decryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(),
|
||||
"CipherText", cipherText,
|
||||
"DecryptionAttributes", cbc())), "us-east-1");
|
||||
|
||||
assertEquals(hex("hello, world!!!!".getBytes()), decrypted.get("PlainText"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCiphertextIsNotThePlaintextAndTheVectorTravelsBesideIt() {
|
||||
PaymentCryptographyKey key = createKey("Encrypt", "Decrypt");
|
||||
String plain = hex("the same data!!!".getBytes());
|
||||
|
||||
String first = (String) handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "PlainText", plain,
|
||||
"EncryptionAttributes", cbc())), "us-east-1").get("CipherText");
|
||||
String second = (String) handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "PlainText", plain,
|
||||
"EncryptionAttributes", cbc())), "us-east-1").get("CipherText");
|
||||
|
||||
assertNotEquals(plain, first);
|
||||
// The vector is not in the ciphertext, so two encryptions under the same vector are
|
||||
// the same ciphertext, and two under different vectors are not.
|
||||
assertEquals(first, second, "the same vector gives the same ciphertext");
|
||||
String other = (String) handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "PlainText", plain,
|
||||
"EncryptionAttributes", cbcWithVector("00112233445566778899aabbccddeeff"))),
|
||||
"us-east-1").get("CipherText");
|
||||
assertNotEquals(first, other, "another vector gives another ciphertext");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyThatMayNotEncryptRefuses() {
|
||||
PaymentCryptographyKey key = createKey("Decrypt");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "PlainText", hex("xxxxxxxxxxxxxxxx".getBytes()),
|
||||
"EncryptionAttributes", cbc())), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyOfAnotherPurposeRefuses() {
|
||||
// A PIN encryption key may encrypt a PIN block and nothing else, so it does not encrypt
|
||||
// arbitrary data, and a MAC key does not either.
|
||||
PaymentCryptographyKey pin =
|
||||
createKeyOf("AES_256", "TR31_P0_PIN_ENCRYPTION_KEY", "Encrypt", "Decrypt");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", pin.getArn(), "PlainText", hex("xxxxxxxxxxxxxxxx".getBytes()),
|
||||
"EncryptionAttributes", cbc())), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
|
||||
PaymentCryptographyKey mac = createTdesKey("Generate", "Verify");
|
||||
|
||||
AwsException refusedMac = assertThrows(AwsException.class, () -> handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", mac.getArn(), "PlainText", hex("xxxxxxxxxxxxxxxx".getBytes()),
|
||||
"EncryptionAttributes", cbc())), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refusedMac.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyIdentifierThatNamesNoKeyIsRefused() {
|
||||
// The identifier of a key on its own is not the ARN of a key nor an alias, and the
|
||||
// model says so, so the request is refused before it looks for the key.
|
||||
PaymentCryptographyKey key = createTdesKey("Encrypt", "Decrypt");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getKeyId(), "PlainText", hex("xxxxxxxxxxxxxxxx".getBytes()),
|
||||
"EncryptionAttributes", cbc())), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyThatIsNotThereIsNotFound() {
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", "arn:aws:payment-cryptography:us-east-1:000000000000:key/"
|
||||
+ "1234abcd1234abcd",
|
||||
"PlainText", hex("xxxxxxxxxxxxxxxx".getBytes()),
|
||||
"EncryptionAttributes", cbc())), "us-east-1"));
|
||||
|
||||
assertEquals("ResourceNotFoundException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMacIsComputedAndVerified() {
|
||||
PaymentCryptographyKey key = createTdesKey("Generate", "Verify");
|
||||
String message = hex("a message".getBytes());
|
||||
|
||||
Map<String, Object> mac = handler.generateMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", message, "MacLength", 8,
|
||||
"GenerationAttributes", iso9797())), "us-east-1");
|
||||
String value = (String) mac.get("Mac");
|
||||
|
||||
assertEquals(8, hexBytes(value).length);
|
||||
|
||||
Map<String, Object> verified = handler.verifyMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", message, "Mac", value, "MacLength", 8,
|
||||
"VerificationAttributes", iso9797())), "us-east-1");
|
||||
assertEquals(key.getArn(), verified.get("KeyArn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMacUnderAThreeKeyTdesKeyIsComputedAndVerified() {
|
||||
// The ISO 9797 MACs are defined over Triple DES, and the cipher takes the three keys
|
||||
// a three-key key holds, so such a key computes a MAC rather than failing.
|
||||
PaymentCryptographyKey key = createTdesKeyOf("TDES_3KEY", "Generate", "Verify");
|
||||
String message = hex("a message".getBytes());
|
||||
|
||||
Map<String, Object> mac = handler.generateMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", message, "MacLength", 8,
|
||||
"GenerationAttributes", iso9797())), "us-east-1");
|
||||
String value = (String) mac.get("Mac");
|
||||
|
||||
assertEquals(8, hexBytes(value).length);
|
||||
|
||||
Map<String, Object> verified = handler.verifyMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", message, "Mac", value, "MacLength", 8,
|
||||
"VerificationAttributes", iso9797())), "us-east-1");
|
||||
assertEquals(key.getArn(), verified.get("KeyArn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMacOfAnotherMessageIsNotValid() {
|
||||
PaymentCryptographyKey key = createTdesKey("Generate", "Verify");
|
||||
String mac = (String) handler.generateMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(),
|
||||
"MessageData", hex("a message".getBytes()),
|
||||
"GenerationAttributes", iso9797())), "us-east-1").get("Mac");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.verifyMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(),
|
||||
"MessageData", hex("another message".getBytes()),
|
||||
"Mac", mac,
|
||||
"VerificationAttributes", iso9797())), "us-east-1"));
|
||||
|
||||
assertEquals("VerificationFailedException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTripleDesKeyEncryptsAndDecrypts() {
|
||||
// The reference ciphers with Triple DES as well as with AES, and the block follows the
|
||||
// key's cipher: eight bytes for Triple DES.
|
||||
PaymentCryptographyKey key = createTdesDataKey("TDES_2KEY", "Encrypt", "Decrypt");
|
||||
String plaintext = "0011223344556677";
|
||||
|
||||
Map<String, Object> encrypted = handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "PlainText", plaintext,
|
||||
"EncryptionAttributes", cbc())), "us-east-1");
|
||||
String cipherText = (String) encrypted.get("CipherText");
|
||||
|
||||
assertEquals(plaintext.length(), cipherText.length());
|
||||
|
||||
Map<String, Object> decrypted = handler.decryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "CipherText", cipherText,
|
||||
"DecryptionAttributes", cbc())), "us-east-1");
|
||||
|
||||
assertEquals(plaintext, decrypted.get("PlainText"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTripleDesPlaintextThatDoesNotFillWholeBlocksIsRefused() {
|
||||
// The block of a Triple DES key is eight bytes, so twelve bytes do not fill one.
|
||||
PaymentCryptographyKey key = createTdesDataKey("TDES_2KEY", "Encrypt", "Decrypt");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "PlainText", "00112233445566778899ab",
|
||||
"EncryptionAttributes", cbc())), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("8 bytes (one TDES block)"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPlaintextThatDoesNotFillWholeBlocksIsRefused() {
|
||||
// The cipher pads no data, so the caller supplies whole blocks: a plaintext of
|
||||
// fifteen bytes does not fill an AES block and is refused rather than padded.
|
||||
PaymentCryptographyKey key = createKey("Encrypt", "Decrypt");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "PlainText", "00".repeat(15),
|
||||
"EncryptionAttributes", cbc())), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("16 bytes"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCipherTextIsAsLongAsThePlainTextItHolds() {
|
||||
// The cipher pads no data, so a ciphertext is as long as its plaintext.
|
||||
PaymentCryptographyKey key = createKey("Encrypt", "Decrypt");
|
||||
String plaintext = "00".repeat(32);
|
||||
|
||||
Map<String, Object> answer = handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "PlainText", plaintext,
|
||||
"EncryptionAttributes", cbc())), "us-east-1");
|
||||
|
||||
assertEquals(plaintext.length(), ((String) answer.get("CipherText")).length());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMacLengthThatIsNotANumberIsRefused() {
|
||||
// The protocol carries the length as a number, so a member that is not one is a
|
||||
// malformed request, and not the length the service would compute.
|
||||
PaymentCryptographyKey key = createTdesKey("Generate", "Verify");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.generateMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", "00".repeat(16),
|
||||
"GenerationAttributes", iso9797(), "MacLength", "abc")), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyWhoseMaterialIsNotHeldIsRefusedRatherThanFailing() {
|
||||
// The material is held by the key while the emulator runs and is not written to the
|
||||
// store, so a key read back after a restart has none. A request that needs it is then
|
||||
// refused with an error that says so, and not with a server error.
|
||||
PaymentCryptographyKey key = createKey("Encrypt", "Decrypt");
|
||||
key.setKeyMaterialHex(null);
|
||||
keys.put("us-east-1\u0000" + key.getKeyId(), key);
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "PlainText", "00".repeat(16),
|
||||
"EncryptionAttributes", cbc())), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("material"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMacLengthTheServiceDoesNotComputeIsRefused() {
|
||||
PaymentCryptographyKey key = createKey("Generate", "Verify");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.generateMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", "", "MacLength", 7)), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
/** The MAC attributes of a DUKPT MAC, derived from a base derivation key. */
|
||||
private static JsonNode dukpt(String variant) {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
ObjectNode dukpt = mapper.createObjectNode();
|
||||
// The model asks for at least sixteen hexadecimal digits, and a KSN is ten bytes.
|
||||
dukpt.put("KeySerialNumber", "98765432109876543210");
|
||||
dukpt.put("DukptKeyVariant", "REQUEST");
|
||||
dukpt.put("DukptDerivationType", "TDES_2KEY");
|
||||
ObjectNode attributes = mapper.createObjectNode();
|
||||
attributes.set(variant, dukpt);
|
||||
return attributes;
|
||||
}
|
||||
|
||||
/** The base derivation key the DUKPT MAC is derived from. */
|
||||
private PaymentCryptographyKey createBaseDerivationKey(String algorithm, String... modes) {
|
||||
Map<String, Object> attributes = new LinkedHashMap<>();
|
||||
attributes.put("KeyAlgorithm", algorithm);
|
||||
attributes.put("KeyClass", "SYMMETRIC_KEY");
|
||||
attributes.put("KeyUsage", "TR31_B0_BASE_DERIVATION_KEY");
|
||||
Map<String, Boolean> declared = new LinkedHashMap<>();
|
||||
for (String mode : modes) {
|
||||
declared.put(mode, Boolean.TRUE);
|
||||
}
|
||||
return service.createKey("us-east-1", attributes, declared, true, true, Map.of());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDukptMacIsComputedAndVerifiedUnderABaseDerivationKey() {
|
||||
// The DUKPT MAC key is derived from the base derivation key, so that is the key the
|
||||
// request names, and it derives rather than computes the MAC itself.
|
||||
PaymentCryptographyKey key = createBaseDerivationKey("TDES_2KEY", "DeriveKey");
|
||||
String message = hex("a message".getBytes());
|
||||
|
||||
Map<String, Object> mac = handler.generateMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", message, "MacLength", 8,
|
||||
"GenerationAttributes", dukpt("DukptIso9797Algorithm1"))), "us-east-1");
|
||||
String value = (String) mac.get("Mac");
|
||||
|
||||
assertEquals(8, hexBytes(value).length);
|
||||
|
||||
Map<String, Object> verified = handler.verifyMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", message, "Mac", value, "MacLength", 8,
|
||||
"VerificationAttributes", dukpt("DukptIso9797Algorithm1"))), "us-east-1");
|
||||
assertEquals(key.getArn(), verified.get("KeyArn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDukptMacUnderAKeyThatMayNotDeriveRefuses() {
|
||||
// The key is named by the request but may only compute MACs of its own, so it cannot
|
||||
// be the base a DUKPT MAC key is derived from.
|
||||
PaymentCryptographyKey key = createTdesKey("Generate", "Verify");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.generateMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", hex("a message".getBytes()), "MacLength", 8,
|
||||
"GenerationAttributes", dukpt("DukptIso9797Algorithm1"))), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDukptMacUnderAKeyOfAnotherPurposeRefuses() {
|
||||
// The key may derive, but it is a data encryption key rather than a base derivation
|
||||
// key, so it is not one a DUKPT MAC key is derived from.
|
||||
PaymentCryptographyKey key =
|
||||
createKeyOf("AES_256", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", "DeriveKey");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.generateMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", hex("a message".getBytes()), "MacLength", 8,
|
||||
"GenerationAttributes", dukpt("DukptIso9797Algorithm1"))), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDukptMacUnderAnAesKeyRefuses() {
|
||||
// The derivation is over Triple DES, so a key of another family is not one.
|
||||
PaymentCryptographyKey key = createBaseDerivationKey("AES_256", "DeriveKey");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.generateMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", hex("a message".getBytes()), "MacLength", 8,
|
||||
"GenerationAttributes", dukpt("DukptIso9797Algorithm1"))), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDukptDerivationTypeTheServiceDoesNotDeriveByRefuses() {
|
||||
PaymentCryptographyKey key = createBaseDerivationKey("TDES_2KEY", "DeriveKey");
|
||||
JsonNode attributes = dukpt("DukptIso9797Algorithm1");
|
||||
((ObjectNode) attributes.path("DukptIso9797Algorithm1")).put("DukptDerivationType", "AES_256");
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.generateMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", hex("a message".getBytes()), "MacLength", 8,
|
||||
"GenerationAttributes", attributes)), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDukptMacUnderASerialNumberTheDerivationDoesNotTakeRefuses() {
|
||||
// The model takes a serial number of sixteen, twenty or twenty-four hexadecimal
|
||||
// digits, and the derivation takes one of ten bytes, so a longer one is refused by
|
||||
// the derivation and not by the model.
|
||||
PaymentCryptographyKey key = createBaseDerivationKey("TDES_2KEY", "DeriveKey");
|
||||
JsonNode attributes = dukpt("DukptIso9797Algorithm1");
|
||||
((ObjectNode) attributes.path("DukptIso9797Algorithm1"))
|
||||
.put("KeySerialNumber", "987654321098765432109876");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.generateMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", hex("a message".getBytes()), "MacLength", 8,
|
||||
"GenerationAttributes", attributes)), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("DUKPT derivation failed"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyReEncryptsUnderAnotherKey() {
|
||||
PaymentCryptographyKey incoming = createKey("Encrypt", "Decrypt");
|
||||
PaymentCryptographyKey outgoing = createKey("Encrypt", "Decrypt");
|
||||
String cipherText = (String) handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", incoming.getArn(),
|
||||
"PlainText", hex("moved over there".getBytes()),
|
||||
"EncryptionAttributes", cbc())), "us-east-1").get("CipherText");
|
||||
|
||||
Map<String, Object> reEncrypted = handler.reEncryptData(request(Map.of(
|
||||
"IncomingKeyIdentifier", incoming.getArn(),
|
||||
"OutgoingKeyIdentifier", outgoing.getArn(),
|
||||
"CipherText", cipherText,
|
||||
"IncomingEncryptionAttributes", cbc(),
|
||||
"OutgoingEncryptionAttributes", cbc())), "us-east-1");
|
||||
|
||||
Map<String, Object> decrypted = handler.decryptData(request(Map.of(
|
||||
"KeyIdentifier", outgoing.getArn(),
|
||||
"CipherText", (String) reEncrypted.get("CipherText"),
|
||||
"DecryptionAttributes", cbc())), "us-east-1");
|
||||
assertEquals(hex("moved over there".getBytes()), decrypted.get("PlainText"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theOperationsThatNeedAMaterialTheServiceDoesNotHaveAreRefused() {
|
||||
// The translation of a key's material is the one operation of these that the service
|
||||
// does not serve: the byte layout of the cryptogram is in the standard and is not
|
||||
// published, so a cryptogram the service produced would not open here.
|
||||
for (Runnable refused : new Runnable[] {
|
||||
() -> handler.translateKeyMaterial(request(Map.of()), "us-east-1")}) {
|
||||
AwsException refusal = assertThrows(AwsException.class, refused::run);
|
||||
assertEquals("ValidationException", refusal.getErrorCode());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyWithNoRestrictionsMayBeUsedForAnything() {
|
||||
PaymentCryptographyKey key = createKey("NoRestrictions");
|
||||
|
||||
Map<String, Object> encrypted = handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "PlainText", hex("xxxxxxxxxxxxxxxx".getBytes()),
|
||||
"EncryptionAttributes", cbc())), "us-east-1");
|
||||
|
||||
assertTrue(encrypted.containsKey("CipherText"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePlainTextIsTheBytesTheCallerGave() {
|
||||
PaymentCryptographyKey key = createKey("Encrypt", "Decrypt");
|
||||
byte[] plain = "a longer plaintext that spans a block boundary!!".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
String cipherText = (String) handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "PlainText", hex(plain),
|
||||
"EncryptionAttributes", cbc())), "us-east-1").get("CipherText");
|
||||
|
||||
assertEquals(hex(plain), handler.decryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "CipherText", cipherText,
|
||||
"DecryptionAttributes", cbc())), "us-east-1").get("PlainText"));
|
||||
}
|
||||
}
|
||||
+118
-22
@@ -1,11 +1,15 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import io.floci.aws.services.paymentcryptography.crypto.Ciphers;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
@@ -82,16 +86,18 @@ class PaymentCryptographyCryptoTest {
|
||||
void theEncryptionIsTheOneAnotherImplementationComputed() {
|
||||
byte[] key = PaymentCryptographyCrypto.fromHex(
|
||||
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
|
||||
byte[] plaintext = PaymentCryptographyCrypto.fromHex(
|
||||
"54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f67");
|
||||
// The cipher pads no data, so the plaintext is a whole number of blocks.
|
||||
byte[] plaintext = "The quick brown fox jumps over!!".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
byte[] blob = PaymentCryptographyCrypto.encryptCbc(key, plaintext, new FixedRandom(
|
||||
PaymentCryptographyCrypto.fromHex("101112131415161718191a1b1c1d1e1f")));
|
||||
byte[] vector = PaymentCryptographyCrypto.fromHex("101112131415161718191a1b1c1d1e1f");
|
||||
byte[] blob = PaymentCryptographyCrypto.encryptCbc(key, plaintext, vector);
|
||||
|
||||
assertEquals("101112131415161718191a1b1c1d1e1fb746e4f1bce2352d20440b8a2e0eb8fd6"
|
||||
+ "8c1fcd0d00fcac779ecaadacde7e51a41da205eac66749510362db1c9f3e6d5",
|
||||
// The ciphertext is the encrypted bytes alone: the vector travels beside it, in the
|
||||
// request's attributes. The value is the one BouncyCastle computes for the same key,
|
||||
// vector and plaintext.
|
||||
assertEquals("b746e4f1bce2352d20440b8a2e0eb8fdf67504d7488d1792588f220540ed23b4",
|
||||
PaymentCryptographyCrypto.toHex(blob));
|
||||
assertArrayEquals(plaintext, PaymentCryptographyCrypto.decryptCbc(key, blob));
|
||||
assertArrayEquals(plaintext, PaymentCryptographyCrypto.decryptCbc(key, blob, vector));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -99,28 +105,106 @@ class PaymentCryptographyCryptoTest {
|
||||
byte[] key = PaymentCryptographyCrypto.fromHex(
|
||||
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
|
||||
byte[] other = PaymentCryptographyCrypto.fromHex(
|
||||
"1f1e1d1c1b1a19181716151413121110f0e0d0c0b0a09080706050403020100");
|
||||
// The vector is fixed, so the answer is fixed: with a random one the padding of the
|
||||
// wrong key's plaintext can happen to be valid, and the test would fail now and then
|
||||
// for no reason.
|
||||
byte[] blob = PaymentCryptographyCrypto.encryptCbc(key, "hello".getBytes(),
|
||||
new FixedRandom(PaymentCryptographyCrypto.fromHex("101112131415161718191a1b1c1d1e1f")));
|
||||
"1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100");
|
||||
// The vector is fixed, so the answer is fixed.
|
||||
byte[] vector = PaymentCryptographyCrypto.fromHex("101112131415161718191a1b1c1d1e1f");
|
||||
byte[] plaintext = "a whole block ok".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] blob = PaymentCryptographyCrypto.encryptCbc(key, plaintext, vector);
|
||||
|
||||
// The right key opens it, so the refusal below is about the key and not the blob.
|
||||
assertArrayEquals("hello".getBytes(), PaymentCryptographyCrypto.decryptCbc(key, blob));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> PaymentCryptographyCrypto.decryptCbc(other, blob));
|
||||
// The right key opens it.
|
||||
assertArrayEquals(plaintext, PaymentCryptographyCrypto.decryptCbc(key, blob, vector));
|
||||
// The other key does not: the cipher pads no data, so it reads as the bytes the
|
||||
// ciphertext holds and nothing says they are the plaintext.
|
||||
assertFalse(Arrays.equals(plaintext,
|
||||
PaymentCryptographyCrypto.decryptCbc(other, blob, vector)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theEncryptionOfAnEmptyPlaintextIsTheVectorAndThePadding() {
|
||||
void theTripleDesCipherIsTheOneAnotherImplementationComputed() {
|
||||
byte[] key = PaymentCryptographyCrypto.fromHex(
|
||||
"000102030405060708090a0b0c0d0e0f0001020304050607");
|
||||
byte[] vector = PaymentCryptographyCrypto.fromHex("0102030405060708");
|
||||
byte[] plaintext = PaymentCryptographyCrypto.fromHex("00112233445566778899aabbccddeeff");
|
||||
|
||||
byte[] blob = PaymentCryptographyCrypto.tdesCbcEncrypt(key, plaintext, vector);
|
||||
|
||||
// The value is the one another implementation computes for the same key, vector and
|
||||
// plaintext.
|
||||
assertEquals("2ccf87b33cad11b72eb3ead4b7385053", PaymentCryptographyCrypto.toHex(blob));
|
||||
assertArrayEquals(plaintext, PaymentCryptographyCrypto.tdesCbcDecrypt(key, blob, vector));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theIso9797MacsAreTheOnesFipsPub113Publishes() {
|
||||
// The ISO 9797-1 worked example, with equal key halves: both algorithms collapse to
|
||||
// the single-DES CBC-MAC, so one published value pins both chains and the padding.
|
||||
byte[] key = PaymentCryptographyCrypto.fromHex("0123456789ABCDEF0123456789ABCDEF");
|
||||
byte[] message = "7654321 Now is the time for ".getBytes(StandardCharsets.US_ASCII);
|
||||
|
||||
assertEquals("f1d30f6849312ca4",
|
||||
PaymentCryptographyCrypto.toHex(Ciphers.iso9797Alg1(key, message)));
|
||||
assertEquals("f1d30f6849312ca4",
|
||||
PaymentCryptographyCrypto.toHex(Ciphers.iso9797Alg3(key, message)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theIso9797MacOfAMessageThatFillsItsBlocksIsTheOneFipsPub113Publishes() {
|
||||
// The published example pads its text with zeroes to a whole block, and that padded
|
||||
// text is the example's own fourth block. A text that already fills its blocks is
|
||||
// padded with nothing, so the two give one MAC.
|
||||
byte[] key = PaymentCryptographyCrypto.fromHex("0123456789ABCDEF0123456789ABCDEF");
|
||||
byte[] padded = PaymentCryptographyCrypto.fromHex(
|
||||
"37363534333231204e6f77206973207468652074696d6520666f722000000000");
|
||||
|
||||
assertEquals("f1d30f6849312ca4",
|
||||
PaymentCryptographyCrypto.toHex(Ciphers.iso9797Alg1(key, padded)));
|
||||
assertEquals("f1d30f6849312ca4",
|
||||
PaymentCryptographyCrypto.toHex(Ciphers.iso9797Alg3(key, padded)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theIso9797MacsAreTheOnesAnotherImplementationComputed() {
|
||||
// The two-key regression locks, which are the distinct-halves path the published
|
||||
// example does not reach.
|
||||
byte[] key = PaymentCryptographyCrypto.fromHex("0123456789ABCDEFFEDCBA9876543210");
|
||||
byte[] message = "7654321 Now is the time for ".getBytes(StandardCharsets.US_ASCII);
|
||||
|
||||
assertEquals("e5e7a413c3e3f4b5",
|
||||
PaymentCryptographyCrypto.toHex(Ciphers.iso9797Alg1(key, message)));
|
||||
assertEquals("ae4b45b1b527642f",
|
||||
PaymentCryptographyCrypto.toHex(Ciphers.iso9797Alg3(key, message)));
|
||||
// Over an empty message the algorithm 3 MAC is the Triple DES of a zero block, whose
|
||||
// leftmost three bytes are the independently documented X9.24 check value of the key.
|
||||
assertEquals("08d7b4fb629d0885",
|
||||
PaymentCryptographyCrypto.toHex(Ciphers.iso9797Alg3(key, new byte[0])));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTwoKeyTripleDesKeyIsUsedUnderTheThreeKeysItHolds() {
|
||||
byte[] two = PaymentCryptographyCrypto.fromHex("000102030405060708090a0b0c0d0e0f");
|
||||
byte[] three = PaymentCryptographyCrypto.fromHex(
|
||||
"000102030405060708090a0b0c0d0e0f0001020304050607");
|
||||
byte[] vector = PaymentCryptographyCrypto.fromHex("0102030405060708");
|
||||
byte[] plaintext = PaymentCryptographyCrypto.fromHex("00112233445566778899aabbccddeeff");
|
||||
|
||||
assertArrayEquals(PaymentCryptographyCrypto.tdesCbcEncrypt(three, plaintext, vector),
|
||||
PaymentCryptographyCrypto.tdesCbcEncrypt(two, plaintext, vector));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCipherPadsNoData() {
|
||||
byte[] key = PaymentCryptographyCrypto.fromHex(
|
||||
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
|
||||
byte[] blob = PaymentCryptographyCrypto.encryptCbc(key, new byte[0], new FixedRandom(
|
||||
PaymentCryptographyCrypto.fromHex("101112131415161718191a1b1c1d1e1f")));
|
||||
byte[] vector = PaymentCryptographyCrypto.fromHex("101112131415161718191a1b1c1d1e1f");
|
||||
|
||||
assertEquals(32, blob.length);
|
||||
assertArrayEquals(new byte[0], PaymentCryptographyCrypto.decryptCbc(key, blob));
|
||||
// A ciphertext is as long as the plaintext it holds, and the vector is not in it.
|
||||
byte[] plaintext = "a whole block ok".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] blob = PaymentCryptographyCrypto.encryptCbc(key, plaintext, vector);
|
||||
assertEquals(plaintext.length, blob.length);
|
||||
assertArrayEquals(plaintext, PaymentCryptographyCrypto.decryptCbc(key, blob, vector));
|
||||
|
||||
// An empty plaintext is an empty ciphertext: there is no padding to add.
|
||||
assertEquals(0, PaymentCryptographyCrypto.encryptCbc(key, new byte[0], vector).length);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -132,6 +216,18 @@ class PaymentCryptographyCryptoTest {
|
||||
assertNotNull(PaymentCryptographyCrypto.checkValue(material));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTripleDesCheckValueIsTheLeftmostThreeBytesOfTheEncryptedZeroes() {
|
||||
// The check value of a Triple DES key is the ANSI X9.24 one: the leftmost three
|
||||
// bytes of encrypting eight zero bytes with the key. The two-key form is widened to
|
||||
// K1||K2||K1 first, which is what the three-key cipher takes.
|
||||
assertEquals("08D7B4", PaymentCryptographyCrypto.checkValue(
|
||||
"0123456789ABCDEFFEDCBA9876543210", PaymentCryptographyKeyAlgorithm.TDES_2KEY));
|
||||
assertEquals("3FD539", PaymentCryptographyCrypto.checkValue(
|
||||
"0123456789ABCDEFFEDCBA987654321089ABCDEF01234567",
|
||||
PaymentCryptographyKeyAlgorithm.TDES_3KEY));
|
||||
}
|
||||
|
||||
private static String mac(String messageHex) {
|
||||
return PaymentCryptographyCrypto.toHex(PaymentCryptographyCrypto.cmac(
|
||||
PaymentCryptographyCrypto.fromHex(RFC4493_KEY),
|
||||
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.AwsPartition;
|
||||
import io.floci.aws.core.common.AwsPartitions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/**
|
||||
* The members that name a key, checked against the vendored constraints in every published region.
|
||||
*
|
||||
* <p>The data plane's identifier names a key by its ARN or by an alias, and the identifier of a
|
||||
* key on its own names none of them, so a request that carries one is refused.
|
||||
*/
|
||||
class PaymentCryptographyDataRequestShapesTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String KEY_ID = "0123456789abcdef0123456789abcdef";
|
||||
|
||||
/** An encryption request, which the model asks for the identifier, the plaintext and the attributes of. */
|
||||
private static ObjectNode request(String identifier) {
|
||||
ObjectNode request = MAPPER.createObjectNode();
|
||||
request.put("KeyIdentifier", identifier);
|
||||
request.put("PlainText", "00112233445566778899aabbccddeeff");
|
||||
request.putObject("EncryptionAttributes").putObject("Symmetric").put("Mode", "CBC");
|
||||
return request;
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyPublishedRegionIsTaken() {
|
||||
assertFalse(AwsPartitions.allRegionIds().isEmpty());
|
||||
for (String region : AwsPartitions.allRegionIds()) {
|
||||
AwsPartition partition = AwsPartitions.forRegion(region).orElseThrow();
|
||||
String prefix = "arn:" + partition.id() + ":payment-cryptography:" + region + ":000000000000:";
|
||||
String key = prefix + "key/" + KEY_ID;
|
||||
|
||||
assertDoesNotThrow(() -> PaymentCryptographyDataRequestShapes.check(
|
||||
"EncryptData", request(key)), key);
|
||||
assertDoesNotThrow(() -> PaymentCryptographyDataRequestShapes.check(
|
||||
"EncryptData", request(prefix + "alias/team/card-key")), region);
|
||||
assertDoesNotThrow(() -> PaymentCryptographyDataRequestShapes.check(
|
||||
"EncryptData", request("alias/team/card-key")), region);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIdentifierThatNamesNoKeyIsRefused() {
|
||||
// The identifier of a key on its own is not the ARN of a key nor an alias, and the
|
||||
// model says so.
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> PaymentCryptographyDataRequestShapes.check(
|
||||
"EncryptData", request(KEY_ID)));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package io.floci.aws.services.paymentcryptography.crypto;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HexFormat;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* The DUKPT derivation, against the vectors ANSI X9.24-1 publishes.
|
||||
*
|
||||
* <p>The vectors are the initial sequence of the standard's annex A.4.2: the device whose
|
||||
* base derivation key is the one the standard uses, over the five counters it walks
|
||||
* through. The initial key is the same for all of them, because the counter is cleared
|
||||
* before the key is derived.
|
||||
*
|
||||
* <p>The MAC of each counter is the retail MAC over the data the standard names, under
|
||||
* the MAC request key, so the vectors hold the derivation and the ISO 9797-1 algorithm 3
|
||||
* MAC the data plane computes together.
|
||||
*/
|
||||
class DukptCryptoTest {
|
||||
|
||||
/** The base derivation key of the published vectors. */
|
||||
private static final String BDK = "0123456789ABCDEFFEDCBA9876543210";
|
||||
|
||||
/** The initial key of the device, the same for every counter. */
|
||||
private static final String INITIAL_KEY = "6AC292FAA1315B4D858AB3A3D7D5933A";
|
||||
|
||||
/** The data the published MACs are taken over. */
|
||||
private static final byte[] DATA = "4012345678909D987".getBytes(StandardCharsets.US_ASCII);
|
||||
|
||||
@Test
|
||||
void theInitialKeyIsTheOneOfTheStandard() {
|
||||
assertEquals(INITIAL_KEY, hex(DukptCrypto.deriveIpek(BDK, "FFFF9876543210E00000")));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"FFFF9876543210E00001", "FFFF9876543210E00005"})
|
||||
void theInitialKeyDoesNotDependOnTheCounter(String ksn) {
|
||||
assertEquals(INITIAL_KEY, hex(DukptCrypto.deriveIpek(BDK, ksn)));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"FFFF9876543210E00001, 042666B49184CFA368DE9628D0397BC9, 9CCC78173FC4FB64",
|
||||
"FFFF9876543210E00002, C46551CEF9FD24B0AA9AD834130D3BC7, F608A9BCA6FFC311",
|
||||
"FFFF9876543210E00003, 0DF3D9422ACA56E547676D07AD6BADFA, 20B59A4FEAC937E3",
|
||||
"FFFF9876543210E00004, 279C0F6AEED0BE652B2C733E1383AE91, C7BFA6CC44161828",
|
||||
"FFFF9876543210E00005, 5F8DC6D2C845C125508DDC048093B83F, 0202B96339022058"
|
||||
})
|
||||
void theDerivedKeyAndTheMacAreTheOnesOfTheStandard(String ksn, String key, String mac) {
|
||||
assertEquals(key, hex(DukptCrypto.deriveTransactionKey(BDK, ksn)));
|
||||
|
||||
byte[] macKey = DukptCrypto.macKey(BDK, ksn);
|
||||
|
||||
assertEquals(mac, hex(Ciphers.iso9797Alg3(macKey, DATA)));
|
||||
}
|
||||
|
||||
private static String hex(byte[] bytes) {
|
||||
return HexFormat.of().withUpperCase().formatHex(bytes);
|
||||
}
|
||||
}
|
||||
@@ -170,12 +170,15 @@ CLIENTS_NOT_READ: dict[str, str] = {
|
||||
"kinesisanalytics": "Kinesis Data Analytics v1, SQL applications on the KinesisAnalytics_20150814 target, which "
|
||||
"Floci does not serve (it serves v2, kinesisanalyticsv2); its operations share v2's names and "
|
||||
"name their resources by other members",
|
||||
"payment-cryptography-data": "the Payment Cryptography data plane, REST routes such as "
|
||||
"/keys/{KeyIdentifier}/encrypt, which Floci does not serve (it serves the control "
|
||||
"plane's JSON operations); its KeyIdentifier may be an alias, read on the control "
|
||||
"plane by the handler, not by its path",
|
||||
}
|
||||
|
||||
# The namespaces whose members may name a resource of a type with a word before the type's, as
|
||||
# `IncomingKeyIdentifier` names a key: the word says which of them it is. Such a member's value may
|
||||
# be an alias, and the namespace's service resolves it to the resource the alias points at, so the
|
||||
# resource is the one the alias names. A namespace whose service cannot resolve an alias is not
|
||||
# among these: an alias would be read as the name of a resource of the type, which names nothing.
|
||||
QUALIFIED_MEMBERS = ("payment-cryptography",)
|
||||
|
||||
# The namespaces whose resources ResourceArnBuilder builds itself.
|
||||
HAND_BUILT = ("apigateway", "bedrock", "dsql", "dynamodb", "eks", "iam", "kinesis", "kms", "lambda", "logs", "pipes",
|
||||
"resource-groups", "s3", "scheduler", "secretsmanager", "sns", "sqs", "ssm", "sts")
|
||||
@@ -952,6 +955,7 @@ def resources_for(operation: str, types: list[str], formats: dict[str, str], mem
|
||||
names = {member: path for member, path in members.items() if member not in arns}
|
||||
by_arn: dict[str, list[str]] = {}
|
||||
filled: dict[str, dict[str, str]] = {}
|
||||
used: dict[str, str] = {}
|
||||
complete: dict[str, bool] = {}
|
||||
for kind in types:
|
||||
if kind not in formats:
|
||||
@@ -967,9 +971,11 @@ def resources_for(operation: str, types: list[str], formats: dict[str, str], mem
|
||||
fill: dict[str, str] = {}
|
||||
for variable in sorted(variables, key=lambda v: (kind_of(v) == "", v)):
|
||||
choice = _filling(variable, kind_stem, len(variables), {m: p for m, p in names.items() if m not in fill.values()},
|
||||
bare=not held and related(subject, kind_stem))
|
||||
bare=not held and related(subject, kind_stem),
|
||||
qualified=namespace_of(operation) in QUALIFIED_MEMBERS)
|
||||
if choice is not None:
|
||||
fill[variable] = choice
|
||||
used[kind] = choice
|
||||
fill = {variable: names[member] for variable, member in fill.items()}
|
||||
if len([path for path in fill.values() if path.endswith("[]")]) > 1:
|
||||
fill = {variable: path for variable, path in fill.items() if not path.endswith("[]")}
|
||||
@@ -987,7 +993,9 @@ def resources_for(operation: str, types: list[str], formats: dict[str, str], mem
|
||||
full = [kind for kind in kinds if complete[kind]]
|
||||
kept += kinds if len(kinds) == 1 else (full if len(full) == 1 else [])
|
||||
specs = [{"types": kinds, "arn": arns[member]} for member, kinds in sorted(by_arn.items())]
|
||||
return specs + [{"type": kind, "fill": dict(sorted(filled[kind].items()))} for kind in types if kind in kept]
|
||||
qualified = namespace_of(operation) in QUALIFIED_MEMBERS
|
||||
return specs + [{"type": kind, "fill": dict(sorted(filled[kind].items()))} for kind in types if kind in kept] + \
|
||||
also_filled(types, members, filled, kept, used, qualified)
|
||||
|
||||
|
||||
RESOURCE_PART_RE = re.compile(r"^arn:\$\{Partition}:[^:]*:[^:]*:[^:]*:([A-Za-z][A-Za-z0-9-]*)(.*)$")
|
||||
@@ -1056,7 +1064,8 @@ def by_members_key_is_empty(kinds: list[str], filled: dict[str, dict[str, str]])
|
||||
return all(not filled[kind] for kind in kinds)
|
||||
|
||||
|
||||
def _filling(variable: str, kind_stem: str, variables: int, names: dict[str, str], bare: bool) -> str | None:
|
||||
def _filling(variable: str, kind_stem: str, variables: int, names: dict[str, str], bare: bool,
|
||||
qualified: bool = False) -> str | None:
|
||||
"""The member that fills the variable: one of a compatible kind whose stem relates to the variable's,
|
||||
or, for the variable named after the type or a type's only one, a member named after the type, or,
|
||||
when `bare`, a bare `Name` or `Id`, of a compatible kind; the closest of them, and a string before a
|
||||
@@ -1066,12 +1075,48 @@ def _filling(variable: str, kind_stem: str, variables: int, names: dict[str, str
|
||||
if stem(member) and related(stem(member), variable_stem) and compatible(member, variable)]
|
||||
if not candidates and (related(variable_stem, kind_stem) or variables == 1):
|
||||
candidates = [member for member in names if compatible(member, variable)
|
||||
and ((bare and member.lower() in BARE) or (stem(member) and related(stem(member), kind_stem)))]
|
||||
and ((bare and member.lower() in BARE)
|
||||
or (stem(member) and (related(stem(member), kind_stem)
|
||||
or (qualified and names_type(member, kind_stem)))))]
|
||||
if not candidates:
|
||||
return None
|
||||
return min(candidates, key=lambda member: (stem(member) != variable_stem, names[member].endswith("[]"), len(member), member))
|
||||
|
||||
|
||||
def also_filled(types: list[str], members: dict[str, str], filled: dict[str, dict[str, str]],
|
||||
kept: list[str], used: dict[str, str], qualified: bool) -> list[dict]:
|
||||
"""The resources a request names besides the one it fills a type with, when it names several of that type and
|
||||
acts on each of them.
|
||||
|
||||
<p>A re-encryption decrypts under the key its path names and encrypts under the key its body names, so both are
|
||||
acted on and both are checked. A member that names a resource of the type, with a word before it saying which of
|
||||
them it is, fills the type's variable as well."""
|
||||
found = []
|
||||
for kind in types:
|
||||
if kind not in kept or kind not in filled or not filled[kind]:
|
||||
continue
|
||||
kind_stem = stem(kind)
|
||||
variable = next(iter(filled[kind]))
|
||||
for member in sorted(members):
|
||||
if used.get(kind) == member:
|
||||
continue
|
||||
if not qualified or not names_type(member, kind_stem):
|
||||
continue
|
||||
if not compatible(member, variable):
|
||||
continue
|
||||
found.append({"type": kind, "fill": {variable: members[member]}})
|
||||
return found
|
||||
|
||||
|
||||
def names_type(member: str, kind_stem: str) -> bool:
|
||||
"""Whether the member names a resource of the type, with a word before it saying which of them it is: an
|
||||
`IncomingKeyIdentifier` names a key, and so does an `OutgoingKeyIdentifier`.
|
||||
|
||||
<p>Only a member that identifies a resource does: a list of tag keys is no key, however its name ends."""
|
||||
member_stem = stem(member)
|
||||
return kind_of(member) == "identifier" and member_stem != kind_stem and member_stem.endswith(kind_stem)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# The vendored document
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Vendor Payment Cryptography data plane request constraints from botocore's Apache-2.0 service model.
|
||||
|
||||
`PaymentCryptographyDataRequestShapes` checks the data plane's actions against the vendored file
|
||||
through the shared `RequestConstraintCheck`: member types, required members, lengths and counts,
|
||||
patterns and enum values, as the model states them. The patterns are what settle which key a
|
||||
request may name: `KeyIdentifier` takes the ARN of a key, the ARN of an alias or the name of an
|
||||
alias, and the identifier of a key on its own names none of them.
|
||||
|
||||
The data plane is a service of its own, so its constraints are vendored in a file of their own,
|
||||
as the control plane's are.
|
||||
|
||||
Run from anywhere in the repo:
|
||||
python3 tools/aws/regen_payment_cryptography_data_shapes.py # rewrite the vendored file in place
|
||||
python3 tools/aws/regen_payment_cryptography_data_shapes.py --check # exit 1 when the vendored file is stale
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import request_shapes
|
||||
|
||||
OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/payment-cryptography-data-request-shapes.json"
|
||||
MODEL = Path("payment-cryptography-data/2022-02-03")
|
||||
OPERATIONS = (
|
||||
"EncryptData", "DecryptData", "ReEncryptData",
|
||||
"GenerateMac", "VerifyMac",
|
||||
)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT,
|
||||
description=__doc__, operations=OPERATIONS,
|
||||
prepare=request_shapes.widen_partition_and_region)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -13,15 +13,12 @@ Run from anywhere in the repo:
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from regen_partitions import resolve_botocore_data, strip_source
|
||||
from request_shapes import REPO_ROOT, build_constraints, load_model
|
||||
import request_shapes
|
||||
|
||||
OUTPUT = REPO_ROOT / "src/main/resources/aws/payment-cryptography-request-shapes.json"
|
||||
OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/payment-cryptography-request-shapes.json"
|
||||
MODEL = Path("payment-cryptography/2021-09-14")
|
||||
OPERATIONS = (
|
||||
"CreateKey", "GetKey", "ListKeys", "DeleteKey",
|
||||
@@ -29,49 +26,11 @@ OPERATIONS = (
|
||||
"TagResource", "UntagResource", "ListTagsForResource",
|
||||
)
|
||||
|
||||
# The partition the model writes in its ARN patterns, and the one the service writes in
|
||||
# every partition it serves.
|
||||
COMMERCIAL = "arn:aws:"
|
||||
EVERY_PARTITION = "arn:aws[a-z0-9-]*:"
|
||||
|
||||
# The region the model writes in its ARN patterns and on `Region`, which fits the commercial
|
||||
# partition's two-part prefix alone, and the one that fits every published region: `us-gov-west-1`
|
||||
# has a further part and `eusc-de-east-1` a longer prefix.
|
||||
COMMERCIAL_REGION = "[a-z]{2}-[a-z]{1,16}-[0-9]+"
|
||||
EVERY_REGION = "[a-z]{2,4}(-[a-z]{1,16})+-[0-9]+"
|
||||
|
||||
|
||||
def widen_partition_and_region(doc: dict) -> dict:
|
||||
"""The model's patterns, with the partition and the region they name widened to every partition's.
|
||||
|
||||
The model writes the commercial partition and regions of its shape, as the service's own model
|
||||
need not name the others, but the service mints and takes the ARN of the partition and the
|
||||
region a key is in, so the check must not refuse the ARN of a key outside the commercial one.
|
||||
"""
|
||||
for shape in doc["shapes"].values():
|
||||
pattern = shape.get("pattern")
|
||||
if pattern:
|
||||
shape["pattern"] = pattern.replace(COMMERCIAL, EVERY_PARTITION).replace(COMMERCIAL_REGION, EVERY_REGION)
|
||||
return doc
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--check", action="store_true", help="exit 1 when the vendored file differs from a fresh generation")
|
||||
parser.add_argument("--botocore-data", type=Path, help="botocore data directory")
|
||||
args = parser.parse_args(argv)
|
||||
data, provenance = resolve_botocore_data(args.botocore_data)
|
||||
doc = widen_partition_and_region(build_constraints(load_model(data, MODEL), OPERATIONS, provenance,
|
||||
"tools/aws/regen_payment_cryptography_shapes.py"))
|
||||
fresh = json.dumps(doc, indent=2) + "\n"
|
||||
if args.check:
|
||||
if not OUTPUT.exists() or strip_source(OUTPUT.read_text(encoding="utf-8")) != strip_source(fresh):
|
||||
print(f"{OUTPUT} is stale (generated from {provenance}).", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
OUTPUT.write_text(fresh, encoding="utf-8")
|
||||
print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} from {provenance}")
|
||||
return 0
|
||||
return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT,
|
||||
description=__doc__, operations=OPERATIONS,
|
||||
prepare=request_shapes.widen_partition_and_region)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -59,6 +59,8 @@ MODELS: dict[str, str] = {
|
||||
"lambda-core": "lambda",
|
||||
"lambda-microvms": "lambda",
|
||||
"opensearch": "es",
|
||||
# The data plane is signed for the service, which is one scope for both of its planes.
|
||||
"payment-cryptography-data": "payment-cryptography",
|
||||
"pipes": "pipes",
|
||||
"quicksight": "quicksight",
|
||||
"s3": "s3",
|
||||
@@ -66,6 +68,16 @@ MODELS: dict[str, str] = {
|
||||
"scheduler": "scheduler",
|
||||
}
|
||||
|
||||
# The models whose routes are rewritten onto an internal prefix, and the prefix they are rewritten
|
||||
# onto, with whether the labels in their paths hold an ARN. A service whose routes sit under such a
|
||||
# prefix has them there, and the prefix names them.
|
||||
INTERNAL_ROUTES: dict[str, tuple[str, bool]] = {
|
||||
# The Payment Cryptography data plane's routes sit under the prefix its route filter rewrites
|
||||
# them onto, and the key they name is an ARN, whose slashes the rewritten path holds: the label
|
||||
# spans them, as the controller's own path does.
|
||||
"payment-cryptography-data": ("/_paymentcryptography", True),
|
||||
}
|
||||
|
||||
|
||||
def access_denied_status(model: dict) -> int | None:
|
||||
"""The HTTP status explicitly modelled for a declared AccessDenied or AccessDeniedException error."""
|
||||
@@ -92,10 +104,16 @@ def build(models: dict[str, dict], provenance: str) -> dict:
|
||||
model = models[name]
|
||||
if model["metadata"].get("protocol") not in ("rest-json", "rest-xml"):
|
||||
raise SystemExit(f"error: {name} is not a REST model")
|
||||
prefix, arn_labels = INTERNAL_ROUTES.get(name, ("", False))
|
||||
operations = {}
|
||||
for operation in sorted(model["operations"]):
|
||||
http = model["operations"][operation]["http"]
|
||||
operations[operation] = {"method": http["method"], "requestUri": http["requestUri"]}
|
||||
request_uri = prefix + http["requestUri"]
|
||||
if arn_labels:
|
||||
# A label holding an ARN spans the slashes the ARN holds, which the rewritten path
|
||||
# holds as they are.
|
||||
request_uri = re.sub(r"\{([^}]+)\}", r"{\1+}", request_uri)
|
||||
operations[operation] = {"method": http["method"], "requestUri": request_uri}
|
||||
routes[name] = {
|
||||
"credentialScope": MODELS[name],
|
||||
"apiVersion": model["metadata"]["apiVersion"],
|
||||
|
||||
@@ -112,6 +112,32 @@ def build_constraints(model: dict, operations: tuple[str, ...], provenance: str,
|
||||
"operations": inputs, "shapes": dict(sorted(kept.items()))}
|
||||
|
||||
|
||||
# The partition the model writes in its ARN patterns, and the one the service writes in
|
||||
# every partition it serves.
|
||||
COMMERCIAL = "arn:aws:"
|
||||
EVERY_PARTITION = "arn:aws[a-z0-9-]*:"
|
||||
|
||||
# The region the model writes in its ARN patterns and on `Region`, which fits the commercial
|
||||
# partition's two-part prefix alone, and the one that fits every published region: `us-gov-west-1`
|
||||
# has a further part and `eusc-de-east-1` a longer prefix.
|
||||
COMMERCIAL_REGION = "[a-z]{2}-[a-z]{1,16}-[0-9]+"
|
||||
EVERY_REGION = "[a-z]{2,4}(-[a-z]{1,16})+-[0-9]+"
|
||||
|
||||
|
||||
def widen_partition_and_region(model: dict) -> dict:
|
||||
"""The model's patterns, with the partition and the region they name widened to every partition's.
|
||||
|
||||
The model writes the commercial partition and regions of its shape, as the service's own model
|
||||
need not name the others, but the service mints and takes the ARN of the partition and the
|
||||
region a key is in, so the check must not refuse the ARN of a key outside the commercial one.
|
||||
"""
|
||||
for shape in model["shapes"].values():
|
||||
pattern = shape.get("pattern")
|
||||
if pattern:
|
||||
shape["pattern"] = pattern.replace(COMMERCIAL, EVERY_PARTITION).replace(COMMERCIAL_REGION, EVERY_REGION)
|
||||
return model
|
||||
|
||||
|
||||
def render(doc: dict) -> str:
|
||||
return json.dumps(doc, indent=2, sort_keys=False) + "\n"
|
||||
|
||||
|
||||
@@ -389,19 +389,19 @@ def test_payment_cryptography_shapes_widen_the_partition_the_model_writes():
|
||||
doc = json.loads(regen_payment_cryptography_shapes.OUTPUT.read_text(encoding="utf-8"))
|
||||
|
||||
# The model writes the commercial partition; the service writes every partition it serves.
|
||||
assert regen_payment_cryptography_shapes.COMMERCIAL not in doc["shapes"]["KeyArn"]["pattern"]
|
||||
assert regen_payment_cryptography_shapes.EVERY_PARTITION in doc["shapes"]["KeyArn"]["pattern"]
|
||||
assert regen_payment_cryptography_shapes.EVERY_PARTITION in doc["shapes"]["ResourceArn"]["pattern"]
|
||||
assert r.COMMERCIAL not in doc["shapes"]["KeyArn"]["pattern"]
|
||||
assert r.EVERY_PARTITION in doc["shapes"]["KeyArn"]["pattern"]
|
||||
assert r.EVERY_PARTITION in doc["shapes"]["ResourceArn"]["pattern"]
|
||||
|
||||
|
||||
def test_payment_cryptography_shapes_widen_the_region_on_every_pattern_the_model_writes_it():
|
||||
doc = json.loads(regen_payment_cryptography_shapes.OUTPUT.read_text(encoding="utf-8"))
|
||||
|
||||
patterns = [shape["pattern"] for shape in doc["shapes"].values() if "pattern" in shape]
|
||||
assert not [p for p in patterns if regen_payment_cryptography_shapes.COMMERCIAL_REGION in p]
|
||||
assert doc["shapes"]["Region"]["pattern"] == regen_payment_cryptography_shapes.EVERY_REGION
|
||||
assert not [p for p in patterns if r.COMMERCIAL_REGION in p]
|
||||
assert doc["shapes"]["Region"]["pattern"] == r.EVERY_REGION
|
||||
for name in ("KeyArn", "KeyArnOrKeyAliasType", "ResourceArn"):
|
||||
assert regen_payment_cryptography_shapes.EVERY_REGION in doc["shapes"][name]["pattern"]
|
||||
assert r.EVERY_REGION in doc["shapes"][name]["pattern"]
|
||||
|
||||
|
||||
def test_payment_cryptography_shapes_take_every_published_region_of_its_partition():
|
||||
|
||||
@@ -33,6 +33,10 @@ services:
|
||||
doc: docs/services/payment-cryptography.md
|
||||
sources:
|
||||
- { path: services/paymentcryptography/PaymentCryptographyJsonHandler.java, mode: switch }
|
||||
- service: paymentcryptographydata
|
||||
doc: docs/services/payment-cryptography-data.md
|
||||
sources:
|
||||
- { path: services/paymentcryptography/PaymentCryptographyCryptoController.java, mode: rest }
|
||||
- service: applicationautoscaling
|
||||
doc: docs/services/applicationautoscaling.md
|
||||
sources:
|
||||
|
||||
Reference in new issue
Block a user