Repository: cloud-custodian/cloud-custodian

Issue:
SQS Set-Encryption Not Standard
### Describe the bug

When setting encryption via KMS for other services, you can use the default alias: `alias/aws/*service*` . This means for RDS, EBS, Lambda, EFS, S3, and others, when using the set-encryption action and use the traditional default KMS alias key as mentioned above. For SQS, for some reason the correct syntax for the KMS Key is special. I have to type out the key as: `aws/*service*` since it appends the `alias/` portion.

Because of that key string change for SQS, the KmsMasterKeyID in both console and when using API commands, it returns the KeyID instead of the alias. Even though, for human reading, it is the same default alias.

![SNS](https://user-images.githubusercontent.com/113540277/190429766-48f2424f-9043-44f9-a1ed-55f4f58e4f76.jpg)
![SQS](https://user-images.githubusercontent.com/113540277/190429770-a5e2063d-486b-4e61-9ae1-8b0ca2a0f279.jpg)

Working code for the set-encryption action:
```
policies:
  - name: sqs-queue-unencrypted-enforce
    resource: aws.sqs
     ...
     actions:
      - type: set-encryption
        key: aws/sqs
```

However when running filters that check for default KmsMasterKeyId, it flags the SQS policy as it returns a non-aliased KmsMasterKeyId. Likewise on the AWS Console (in SQS Encryption) instead shows the CMK alias key, not the Default KMS Key. 

### What did you expect to happen?

When using an action for SQS written as I would expect it to be written:
```
policies:
  - name: sqs-queue-unencrypted-enforce
    resource: aws.sqs
     ...
     actions:
      - type: set-encryption
        key: alias/aws/sqs
```
This results in the following error, ![BadOutput](https://user-images.githubusercontent.com/113540277/190430119-07892446-ba36-4d56-a533-93b699e5ce47.png)

### Cloud Provider

Amazon Web Services (AWS)

### Cloud Custodian version and dependency information

```shell
Custodian: 0.9.18
Python: 3.7.10
Platform: poxis.uname_result(sysname='Linux', ..., release='4.14.290-217.505.amzn2.x86_64', ..., machine='x86_64')
Using venv: True
Docker: False
Installed:

argcomplete==2.0.0
attrs==22.1.0
boto3==1.24.44
docutils==0.17.1
importlib-metadata==4.12.0
importlib-resource==5.9.0
jmespath==1.0.1
jsonschema==4.9.0
pkgutil-resolve-name==1.3.10
pyrsistent==0.18.1
python-dateutil==2.8.2
pyyaml==6.0
s3transfer==0.6.0
six==1.16.0
tabulate==0.8.10
typing-extensions==4.3.0
urllib3==1.26.11
zipp==3.8.1
```


### Policy

```shell
policies:
  - name: sqs-queue-unencrypted-enforce
    resource: aws.sqs
    #filters:
    # - type: value
    #   key: KmsMasterKeyId
    #   value: "alias/aws/sqs"
     actions:
      - type: set-encryption
        key: alias/aws/sqs
```


### Relevant log/traceback output

_No response_

### Extra information or context

Amazon WorkSpaces does not allow for copy and paste, will happily provide additional information/logs as needed.


Discussion:
Thanks for reporting this, good catch. I suspect that to bring some consistency without breaking existing working policies, we may need to have SQS continue to add the `alias/` prefix except in cases where `key`:

* Already starts with `alias/`
* Is an ARN
* Is a UUID (suggesting that it's a key ID rather than an alias)

Resolving patch:
diff --git a/c7n/resources/sqs.py b/c7n/resources/sqs.py
--- a/c7n/resources/sqs.py
+++ b/c7n/resources/sqs.py
@@ -3,6 +3,7 @@
 from botocore.exceptions import ClientError
 
 import json
+import re
 
 from c7n.actions import RemovePolicyBase, ModifyPolicyBase
 from c7n.filters import CrossAccountAccessFilter, MetricsFilter
@@ -32,6 +33,7 @@ def _augment(r):
                     QueueUrl=r,
                     AttributeNames=['All'])['Attributes']
                 queue['QueueUrl'] = r
+                queue['QueueName'] = queue['QueueArn'].rsplit(':', 1)[-1]
             except ClientError as e:
                 if e.response['Error']['Code'] == 'AWS.SimpleQueueService.NonExistentQueue':
                     return
@@ -331,6 +333,9 @@ def process_queue(self, client, queue):
 class SetEncryption(BaseAction):
     """Action to set encryption key on SQS queue
 
+    you can also optionally set data key 'reuse-period', or use with
+    the service managed encryption by not specifying a key.
+
     :example:
 
     .. code-block:: yaml
@@ -346,26 +351,48 @@ class SetEncryption(BaseAction):
     """
     schema = type_schema(
         'set-encryption',
-        key={'type': 'string'}, required=('key',))
+        **{
+            "enabled": {'type': 'boolean'},
+            "reuse-period": {'type': 'integer', 'minimum': 60, 'maximum': 86400},
+            "key": {'type': 'string'}}
+    )
 
     permissions = ('sqs:SetQueueAttributes',)
+    uuid_regex = re.compile('[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}')
 
     def process(self, queues):
-        # get KeyId
-        key = "alias/" + self.data.get('key')
-        session = local_session(self.manager.session_factory)
-        key_id = session.client(
-            'kms').describe_key(KeyId=key)['KeyMetadata']['KeyId']
+        # compatibility, if key is given and not arn/key id/ or prefixed with
+        # alias, add alias to it.
+        key = self.data.get('key', None)
+        if (key
+            and not key.startswith('alias')
+            and not key.startswith('arn:')
+                and not self.uuid_regex.search(key)):
+            key = "alias/" + key
+
         client = self.manager.get_client()
 
+        reuse_period = self.data.get('reuse-period', 300)
+        params = {}
+        if not self.data.get('enabled', True):
+            params['SqsManagedSseEnabled'] = 'false'
+            params['KmsMasterKeyId'] = ''
+        elif self.data.get('enable', True) and not key:
+            params['SqsManagedSseEnabled'] = 'true'
+            params['KmsMasterKeyId'] = ''
+        elif self.data.get('enable', True) and key:
+            params['SqsManagedSseEnabled'] = 'false'
+            params['KmsMasterKeyId'] = key
+            params['KmsDataKeyReusePeriodSeconds'] = str(reuse_period)
+
         for q in queues:
-            self.process_queue(client, q, key_id)
+            self.process_queue(client, q, params)
 
-    def process_queue(self, client, queue, key_id):
+    def process_queue(self, client, queue, params):
         try:
             client.set_queue_attributes(
                 QueueUrl=queue['QueueUrl'],
-                Attributes={'KmsMasterKeyId': key_id}
+                Attributes=params
             )
         except (client.exceptions.QueueDoesNotExist,) as e:
             self.log.exception(


Test patch:
diff --git a/tests/test_sqs.py b/tests/test_sqs.py
--- a/tests/test_sqs.py
+++ b/tests/test_sqs.py
@@ -91,6 +91,49 @@ def test_sqs_delete(test, sqs_delete):
         time.sleep(2)
 
 
+def test_sqs_set_encryption_options(test):
+    p = test.load_policy({
+        'name': 'set-encryption-params',
+        'resource': 'sqs',
+        'actions': [{'type': 'set-encryption'}]
+    })
+
+    set_encrypt = p.resource_manager.actions[0]
+    collected = []
+
+    def collect_params(client, queue_url, params):
+        collected.append(params)
+    set_encrypt.process_queue = collect_params
+
+    set_encrypt.data = {'enabled': False}
+    set_encrypt.process([{}])
+    assert collected.pop() == {'SqsManagedSseEnabled': 'false',
+                               'KmsMasterKeyId': ''}
+
+    set_encrypt.data = {}
+    set_encrypt.process([{}])
+    assert collected.pop() == {'SqsManagedSseEnabled': 'true',
+                               'KmsMasterKeyId': ''}
+
+    set_encrypt.data = {'key': 'xyz'}
+    set_encrypt.process([{}])
+    assert collected.pop() == {'SqsManagedSseEnabled': 'false',
+                               'KmsDataKeyReusePeriodSeconds': '300',
+                               'KmsMasterKeyId': 'alias/xyz'}
+
+    set_encrypt.data = {'key': '40753d23-0bef-459d-870e-c0963b827b51'}
+    set_encrypt.process([{}])
+    assert collected.pop() == {'SqsManagedSseEnabled': 'false',
+                               'KmsDataKeyReusePeriodSeconds': '300',
+                               'KmsMasterKeyId': '40753d23-0bef-459d-870e-c0963b827b51'}
+
+    set_encrypt.data = {'key': 'arn:aws:kms:us-east-1:1122334455:key/fb5bc39f-3cdb-438b-b959-3b812ae71628'}  # noqa
+    set_encrypt.process([{}])
+    assert collected.pop() == {'SqsManagedSseEnabled': 'false',
+                               'KmsDataKeyReusePeriodSeconds': '300',
+                               'KmsMasterKeyId': 'arn:aws:kms:us-east-1:1122334455:key/fb5bc39f-3cdb-438b-b959-3b812ae71628'}  # noqa
+
+
 @terraform('sqs_set_encryption')
 def test_sqs_set_encryption(test, sqs_set_encryption):
     session_factory = test.replay_flight_data("test_sqs_set_encryption", region='us-west-2')