fix(iam): check an SQS redrive as the actions its guide gives each queue (#9743)

StartMessageMoveTask was checked as sqs:StartMessageMoveTask alone, on both its SourceArn and its DestinationArn, so a
caller granted the permissions AWS requires was refused on the destination, and one granted the action alone on the
dead-letter queue was let through. ListMessageMoveTasks was checked as its own action alone.

The Amazon SQS developer guide's table of a dead-letter queue redrive's minimum permissions gives each task's actions
of each queue: "Add the sqs:StartMessageMoveTask, sqs:ReceiveMessage, sqs:DeleteMessage, and sqs:GetQueueAttributes
of the dead-letter queue", "Add the sqs:SendMessage of the destination queue", and "Add the sqs:ListMessageMoveTasks
and sqs:GetQueueAttributes of the dead-letter queue". The API reference names each queue's parameter: SourceArn "only
ARNs of dead-letter queues (DLQs)", DestinationArn "specify the destination queue". AWS's own fidelity check
(iam__sqs__sts/check_start_message_move_task_requires_composite_source_and_destination_permissions in
aws/aws-emulator-evaluation-suite) refuses a caller granted sqs:StartMessageMoveTask alone on the dead-letter queue,
naming sqs:ReceiveMessage on it, and lets the call through once the five are granted.

tools/aws/fetch_sqs_redrive_permissions.py copies the table's rows and those parameter sentences into
tools/aws/sources/sqs-redrive-permissions.json, a new PERMISSION_SOURCES entry, and the request-resources generator's
task_permission_resources reads it: the row naming the operation's own action, each action on the resource the rules
read from the parameter naming its queue, a queue the request names by no such parameter being the one the row names
the operation's own action of. --verify checks each row's actions against the Service Reference's AuthorizedActions.
Only StartMessageMoveTask and ListMessageMoveTasks change; CancelMessageMoveTask names its task by handle and keeps
its reading.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-29 11:22:57 -04:00
1 parent a98a43d519
commit 1c84d5eccf
12 files changed
+718 -13

No files matched your search

+3
View File
@@ -82,6 +82,9 @@ on:
- 'tools/aws/fetch_ssm_session_permissions.py'
- 'tools/aws/sources/ssm-session-permissions.json'
- 'tools/aws/test_fetch_ssm_session_permissions.py'
- 'tools/aws/fetch_sqs_redrive_permissions.py'
- 'tools/aws/sources/sqs-redrive-permissions.json'
- 'tools/aws/test_fetch_sqs_redrive_permissions.py'
- 'src/main/resources/aws/dynamodb-condition-keys.json'
- 'tools/aws/regen_dynamodb_condition_keys.py'
- 'tools/aws/test_regen_dynamodb_condition_keys.py'
+2
View File
@@ -672,6 +672,8 @@ IAM_REQUEST_RESOURCES_PATHS := src/main/resources/aws/iam-request-resources.json
tools/aws/sources/ec2-id-examples.json tools/aws/fetch_ec2_id_examples.py tools/aws/test_fetch_ec2_id_examples.py \
tools/aws/sources/ssm-session-permissions.json tools/aws/fetch_ssm_session_permissions.py \
tools/aws/test_fetch_ssm_session_permissions.py \
tools/aws/sources/sqs-redrive-permissions.json tools/aws/fetch_sqs_redrive_permissions.py \
tools/aws/test_fetch_sqs_redrive_permissions.py \
tools/aws/sources/required-resource-types.json tools/aws/fetch_required_resource_types.py \
tools/aws/test_fetch_required_resource_types.py
CLOUDTRAIL_S3_DATA_EVENTS_PATHS := src/main/resources/aws/cloudtrail-s3-data-events.json \
+5 -1
View File
@@ -2957,7 +2957,11 @@ new environment's, so its tags go on `application/<app>/environment/*`, and `Ass
is checked in the account its `domain-owner` names, where its handler looks the domain up. `CopyPackageVersions` is
checked as the CodeArtifact user guide says, which its own script vendors (`tools/aws/fetch_codeartifact_permissions.py`):
`codeartifact:ReadFromRepository` on its source repository and `codeartifact:CopyPackageVersions` on its destination
repository. A package a request names with no `namespace` is checked with its namespace empty, as the guide writes
repository. An SQS message move task is checked as the SQS developer guide's table of a redrive's minimum permissions
gives it, which its own script vendors with the API reference's sentences naming each queue
(`tools/aws/fetch_sqs_redrive_permissions.py`): `StartMessageMoveTask` on its `SourceArn` as its own action and
`sqs:ReceiveMessage`, `sqs:DeleteMessage` and `sqs:GetQueueAttributes`, and on its `DestinationArn` as
`sqs:SendMessage`; `ListMessageMoveTasks` on its `SourceArn` as its own action and `sqs:GetQueueAttributes`. A package a request names with no `namespace` is checked with its namespace empty, as the guide writes
such an ARN (`package/my_domain/my_repo/npm//react`), and a package group by its pattern percent-encoded as
CodeArtifact writes it into the group's ARN (`/npm/team/*` is `/npm/team/%2a`): a variable the reference names
`Encoded` and a botocore shape's name is filled from the member of that shape and encoded as its service encodes it.
+16
View File
@@ -224,6 +224,22 @@ describes. Within one account either the policy or the caller's identity policie
and an explicit `Deny` in either refuses it. A `QueueUrl` whose path names another account is a
cross-account call: the queue's policy and the caller's identity policies both have to allow it.
A dead-letter queue redrive is checked as the
[developer guide's](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-configure-dead-letter-queue-redrive.html)
table of its minimum permissions gives each task, each action on the queue the table names it of:
- `StartMessageMoveTask` as `sqs:StartMessageMoveTask`, `sqs:ReceiveMessage`, `sqs:DeleteMessage` and
`sqs:GetQueueAttributes` on the dead-letter queue its `SourceArn` names, and as `sqs:SendMessage` alone on the
destination queue its `DestinationArn` names. AWS refuses a caller granted only `sqs:StartMessageMoveTask` on the
dead-letter queue, naming `sqs:ReceiveMessage`, and so does Floci.
- `ListMessageMoveTasks` as `sqs:ListMessageMoveTasks` and `sqs:GetQueueAttributes` on the queue its `SourceArn`
names.
`CancelMessageMoveTask` names its task by `TaskHandle` alone, so the dead-letter queue its actions are checked on is
not read yet, and it stays checked as `sqs:CancelMessageMoveTask` as before. A `StartMessageMoveTask` with no
`DestinationArn`, which moves the messages back to their original source queues, is not checked for
`sqs:SendMessage` on them, and the KMS permissions the guide gives for an encrypted queue are not checked either.
## Storage write failures
When the message backend reports a failed write, the queue retains its previously acknowledged
@@ -7706,7 +7706,7 @@
"sqs:GetQueueAttributes": {"action": "sqs:GetQueueAttributes", "types": ["queue"], "resources": [{"type": "queue", "fill": {}, "find": ["QueueUrl"], "apis": ["json/2012-11-05"]}]},
"sqs:GetQueueUrl": {"action": "sqs:GetQueueUrl", "types": ["queue"], "resources": [{"type": "queue", "fill": {"QueueName": "QueueName"}, "apis": ["json/2012-11-05"]}]},
"sqs:ListDeadLetterSourceQueues": {"action": "sqs:ListDeadLetterSourceQueues", "types": ["queue"], "resources": [{"type": "queue", "fill": {}, "find": ["QueueUrl"], "apis": ["json/2012-11-05"]}]},
"sqs:ListMessageMoveTasks": {"action": "sqs:ListMessageMoveTasks", "types": ["queue"], "resources": [{"types": ["queue"], "arn": "SourceArn", "apis": ["json/2012-11-05"]}]},
"sqs:ListMessageMoveTasks": {"action": "sqs:ListMessageMoveTasks", "types": ["queue"], "actions": {"sqs:ListMessageMoveTasks": ["queue"], "sqs:GetQueueAttributes": ["queue"]}, "resources": [{"types": ["queue"], "arn": "SourceArn", "action": "sqs:ListMessageMoveTasks", "apis": ["json/2012-11-05"]}, {"types": ["queue"], "arn": "SourceArn", "action": "sqs:GetQueueAttributes", "apis": ["json/2012-11-05"]}]},
"sqs:ListQueueTags": {"action": "sqs:ListQueueTags", "types": ["queue"], "resources": [{"type": "queue", "fill": {}, "find": ["QueueUrl"], "apis": ["json/2012-11-05"]}]},
"sqs:ListQueues": {"action": "sqs:ListQueues", "types": [], "resources": []},
"sqs:PurgeQueue": {"action": "sqs:PurgeQueue", "types": ["queue"], "resources": [{"type": "queue", "fill": {}, "find": ["QueueUrl"], "apis": ["json/2012-11-05"]}]},
@@ -7715,7 +7715,7 @@
"sqs:SendMessage": {"action": "sqs:SendMessage", "types": ["queue"], "resources": [{"type": "queue", "fill": {}, "find": ["QueueUrl"], "apis": ["json/2012-11-05"]}]},
"sqs:SendMessageBatch": {"action": "sqs:SendMessage", "types": ["queue"], "resources": [{"type": "queue", "fill": {}, "find": ["QueueUrl"], "apis": ["json/2012-11-05"]}]},
"sqs:SetQueueAttributes": {"action": "sqs:SetQueueAttributes", "types": ["queue"], "resources": [{"type": "queue", "fill": {}, "find": ["QueueUrl"], "apis": ["json/2012-11-05"]}]},
"sqs:StartMessageMoveTask": {"action": "sqs:StartMessageMoveTask", "types": ["queue"], "resources": [{"types": ["queue"], "arn": "DestinationArn", "apis": ["json/2012-11-05"]}, {"types": ["queue"], "arn": "SourceArn", "apis": ["json/2012-11-05"]}]},
"sqs:StartMessageMoveTask": {"action": "sqs:StartMessageMoveTask", "types": ["queue"], "actions": {"sqs:StartMessageMoveTask": ["queue"], "sqs:ReceiveMessage": ["queue"], "sqs:DeleteMessage": ["queue"], "sqs:GetQueueAttributes": ["queue"], "sqs:SendMessage": ["queue"]}, "resources": [{"types": ["queue"], "arn": "SourceArn", "action": "sqs:StartMessageMoveTask", "apis": ["json/2012-11-05"]}, {"types": ["queue"], "arn": "SourceArn", "action": "sqs:ReceiveMessage", "apis": ["json/2012-11-05"]}, {"types": ["queue"], "arn": "SourceArn", "action": "sqs:DeleteMessage", "apis": ["json/2012-11-05"]}, {"types": ["queue"], "arn": "SourceArn", "action": "sqs:GetQueueAttributes", "apis": ["json/2012-11-05"]}, {"types": ["queue"], "arn": "DestinationArn", "action": "sqs:SendMessage", "apis": ["json/2012-11-05"]}]},
"sqs:TagQueue": {"action": "sqs:TagQueue", "types": ["queue"], "resources": [{"type": "queue", "fill": {}, "find": ["QueueUrl"], "apis": ["json/2012-11-05"]}]},
"sqs:UntagQueue": {"action": "sqs:UntagQueue", "types": ["queue"], "resources": [{"type": "queue", "fill": {}, "find": ["QueueUrl"], "apis": ["json/2012-11-05"]}]},
"ssm:AddTagsToResource": {"action": "ssm:AddTagsToResource", "types": ["association", "automation-execution", "cloud-connector", "document", "instance", "maintenancewindow", "managed-instance", "opsitem", "opsmetadata", "parameter", "patchbaseline", "task"], "resources": [{"type": "association", "fill": {"AssociationId": "ResourceId"}, "when": {"ResourceType": ["Association"]}, "apis": ["json/2014-11-06"]}, {"type": "cloud-connector", "fill": {"CloudConnectorId": "ResourceId"}, "when": {"ResourceType": ["CloudConnector"]}, "apis": ["json/2014-11-06"]}, {"type": "document", "fill": {"DocumentName": "ResourceId"}, "when": {"ResourceType": ["Document"]}, "apis": ["json/2014-11-06"]}, {"type": "maintenancewindow", "fill": {"ResourceId": "ResourceId"}, "when": {"ResourceType": ["MaintenanceWindow"]}, "apis": ["json/2014-11-06"]}, {"type": "managed-instance", "fill": {"InstanceId": "ResourceId"}, "when": {"ResourceType": ["ManagedInstance"]}, "apis": ["json/2014-11-06"]}, {"type": "opsitem", "fill": {"ResourceId": "ResourceId"}, "when": {"ResourceType": ["OpsItem"]}, "apis": ["json/2014-11-06"]}, {"type": "opsmetadata", "fill": {"ResourceId": "ResourceId"}, "when": {"ResourceType": ["OpsMetadata"]}, "apis": ["json/2014-11-06"]}, {"type": "parameter", "fill": {"ParameterNameWithoutLeadingSlash": "ResourceId"}, "when": {"ResourceType": ["Parameter"]}, "apis": ["json/2014-11-06"]}, {"type": "patchbaseline", "fill": {"PatchBaselineIdResourceId": "ResourceId"}, "when": {"ResourceType": ["PatchBaseline"]}, "apis": ["json/2014-11-06"]}]},
@@ -1782,20 +1782,31 @@ class ResourceArnBuilderTest {
}
/**
* StartMessageMoveTask is checked for its own action on each queue ARN it carries, a named destination included,
* and on the dead-letter queue alone when it names none.
* StartMessageMoveTask is checked as the SQS developer guide's table gives a redrive's actions: its own
* action, sqs:ReceiveMessage, sqs:DeleteMessage and sqs:GetQueueAttributes on the dead-letter queue its
* SourceArn names, and sqs:SendMessage on the destination queue its DestinationArn names, which a request
* naming none is not checked for.
*/
@Test
void sqsChecksAMoveTaskOnTheQueueArnsItCarries() {
void sqsChecksAMoveTaskAsTheActionsOfEachQueueItCarries() {
ResourceArnBuilder builder = sqsHolding(ACCOUNT, "orders-dlq", "orders");
String dlq = "arn:aws:sqs:us-east-1:000000000000:orders-dlq";
String destination = "arn:aws:sqs:us-east-1:000000000000:orders";
List<String> onTheDeadLetterQueue = List.of("sqs:StartMessageMoveTask", "sqs:ReceiveMessage",
"sqs:DeleteMessage", "sqs:GetQueueAttributes");
setJsonBody("{\"SourceArn\":\"" + dlq + "\",\"DestinationArn\":\"" + destination + "\"}");
assertEquals(List.of(destination, dlq),
builder.buildResources("sqs", "sqs:StartMessageMoveTask", ctx, "us-east-1", ACCOUNT, "aws"));
List<RequestResources.Target> targets = builder.targets("sqs", "sqs:StartMessageMoveTask", ctx, "us-east-1",
ACCOUNT, "aws");
assertEquals(List.of("sqs:StartMessageMoveTask", "sqs:ReceiveMessage", "sqs:DeleteMessage",
"sqs:GetQueueAttributes", "sqs:SendMessage"),
targets.stream().map(RequestResources.Target::action).toList());
assertEquals(List.of(List.of(dlq), List.of(dlq), List.of(dlq), List.of(dlq), List.of(destination)),
targets.stream().map(RequestResources.Target::resources).toList());
setJsonBody("{\"SourceArn\":\"" + dlq + "\"}");
assertEquals(List.of(dlq),
builder.buildResources("sqs", "sqs:StartMessageMoveTask", ctx, "us-east-1", ACCOUNT, "aws"));
targets = builder.targets("sqs", "sqs:StartMessageMoveTask", ctx, "us-east-1", ACCOUNT, "aws");
assertEquals(onTheDeadLetterQueue, targets.stream().map(RequestResources.Target::action).toList());
assertEquals(List.of(List.of(dlq), List.of(dlq), List.of(dlq), List.of(dlq)),
targets.stream().map(RequestResources.Target::resources).toList());
}
/**
@@ -0,0 +1,164 @@
package io.floci.aws.services.iam;
import io.floci.aws.testing.EnforcementFixtures;
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.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.net.URI;
import java.util.UUID;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.notNullValue;
/**
* A dead-letter queue redrive is checked as the actions the Amazon SQS developer guide's table of minimum permissions
* gives each task, each on the queue it names: "Add the sqs:StartMessageMoveTask, sqs:ReceiveMessage,
* sqs:DeleteMessage, and sqs:GetQueueAttributes of the dead-letter queue", "Add the sqs:SendMessage of the destination
* queue", and "Add the sqs:ListMessageMoveTasks and sqs:GetQueueAttributes of the dead-letter queue". AWS's own
* fidelity check, verified against two sandboxed accounts
* (behavioral/iam__sqs__sts/check_start_message_move_task_requires_composite_source_and_destination_permissions.py in
* aws/aws-emulator-evaluation-suite), refuses a caller granted sqs:StartMessageMoveTask alone on the dead-letter queue,
* naming sqs:ReceiveMessage on it, and lets the same call through once the five are granted, sqs:SendMessage on the
* destination queue alone. The grants name each queue's ARN, so an allowed call is one checked on those queues.
*/
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class SqsMessageMoveTaskEnforcementIntegrationTest {
private static final String ACCOUNT_ID = "000000000000";
@TestHTTPResource("/")
static URI baseUri;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void startMessageMoveTaskAloneOnTheDeadLetterQueueIsRefusedOnItsReceiveMessage() {
Queues queues = queues();
String caller = userWithPolicy(allow("sqs:StartMessageMoveTask", queues.deadLetter()));
startMessageMoveTask(caller, queues)
.statusCode(400)
.body(containsString("AccessDenied"))
.body(containsString("not authorized to perform: sqs:ReceiveMessage"));
}
@Test
void theGuidesGrantStartsTheTaskWithSendMessageAloneOnTheDestination() {
Queues queues = queues();
String caller = userWithPolicy(allow("sqs:StartMessageMoveTask", queues.deadLetter()) + ","
+ allow("sqs:ReceiveMessage", queues.deadLetter()) + ","
+ allow("sqs:DeleteMessage", queues.deadLetter()) + ","
+ allow("sqs:GetQueueAttributes", queues.deadLetter()) + ","
+ allow("sqs:SendMessage", queues.destination()));
startMessageMoveTask(caller, queues)
.statusCode(200)
.body("TaskHandle", notNullValue());
}
@Test
void theDestinationIsCheckedAsSendMessage() {
Queues queues = queues();
String caller = userWithPolicy(allow("sqs:StartMessageMoveTask", queues.deadLetter()) + ","
+ allow("sqs:ReceiveMessage", queues.deadLetter()) + ","
+ allow("sqs:DeleteMessage", queues.deadLetter()) + ","
+ allow("sqs:GetQueueAttributes", queues.deadLetter()) + ","
+ allow("sqs:StartMessageMoveTask", queues.destination()));
startMessageMoveTask(caller, queues)
.statusCode(400)
.body(containsString("not authorized to perform: sqs:SendMessage"));
}
@Test
void listMessageMoveTasksNeedsGetQueueAttributesOfTheDeadLetterQueue() {
Queues queues = queues();
String listing = userWithPolicy(allow("sqs:ListMessageMoveTasks", queues.deadLetter()));
String reading = userWithPolicy(allow("sqs:ListMessageMoveTasks", queues.deadLetter()) + ","
+ allow("sqs:GetQueueAttributes", queues.deadLetter()));
sqs(listing, "ListMessageMoveTasks", """
{"SourceArn": "%s"}""".formatted(queues.deadLetter()))
.statusCode(400)
.body(containsString("not authorized to perform: sqs:GetQueueAttributes"));
sqs(reading, "ListMessageMoveTasks", """
{"SourceArn": "%s"}""".formatted(queues.deadLetter()))
.statusCode(200);
}
/** A dead-letter queue, a queue whose redrive policy targets it, and a destination queue, by their ARNs. */
private record Queues(String deadLetter, String destination) {
}
private Queues queues() {
String deadLetter = queueArn(createQueue("move-dlq-", "{}"));
createQueue("move-source-", """
{"Attributes": {"RedrivePolicy": "{\\"deadLetterTargetArn\\":\\"%s\\",\\"maxReceiveCount\\":2}"}}"""
.formatted(deadLetter));
return new Queues(deadLetter, queueArn(createQueue("move-destination-", "{}")));
}
private String createQueue(String prefix, String attributes) {
String name = prefix + UUID.randomUUID().toString().substring(0, 8);
String body = attributes.equals("{}") ? """
{"QueueName": "%s"}""".formatted(name)
: attributes.replaceFirst("^\\{", "{\"QueueName\": \"" + name + "\", ");
String queueUrl = sqs(ACCOUNT_ID, "CreateQueue", body).statusCode(200).extract().path("QueueUrl");
cleanup.register(() -> sqs(ACCOUNT_ID, "DeleteQueue", """
{"QueueUrl": "%s"}""".formatted(queueUrl)).statusCode(200));
return queueUrl;
}
private static String queueArn(String queueUrl) {
return sqs(ACCOUNT_ID, "GetQueueAttributes", """
{"QueueUrl": "%s", "AttributeNames": ["QueueArn"]}""".formatted(queueUrl))
.statusCode(200).extract().path("Attributes.QueueArn");
}
private static String allow(String action, String resource) {
return """
{"Effect":"Allow","Action":"%s","Resource":"%s"}""".formatted(action, resource);
}
private String userWithPolicy(String statements) {
String userName = "mover-" + UUID.randomUUID().toString().substring(0, 8);
String accessKeyId = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(ACCOUNT_ID, "iam"),
userName).accessKeyId();
EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(ACCOUNT_ID, "iam"), userName, "only",
"{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
return accessKeyId;
}
private static ValidatableResponse startMessageMoveTask(String accessKeyId, Queues queues) {
return sqs(accessKeyId, "StartMessageMoveTask", """
{"SourceArn": "%s", "DestinationArn": "%s"}""".formatted(queues.deadLetter(), queues.destination()));
}
private static ValidatableResponse sqs(String accessKeyId, String operation, String body) {
return given()
.header("Authorization", auth(accessKeyId, "sqs"))
.header("X-Amz-Target", "AmazonSQS." + operation)
.contentType("application/x-amz-json-1.0")
.body(body)
.when()
.post("/")
.then();
}
}
+190
View File
@@ -0,0 +1,190 @@
#!/usr/bin/env python3
"""Vendor what the Amazon SQS developer guide and API reference say a dead-letter queue redrive is checked as into
tools/aws/sources/sqs-redrive-permissions.json, a source of the IAM tables.
The Service Reference lists the actions each message move task operation is authorized by, StartMessageMoveTask by
sqs:StartMessageMoveTask, sqs:ReceiveMessage, sqs:DeleteMessage, sqs:GetQueueAttributes and sqs:SendMessage, without
saying which queue of the request each is checked on, and botocore does not say it either. The developer guide's
table of the minimum permissions for a redrive does, a row for each task:
To start a message redrive: Add the sqs:StartMessageMoveTask, sqs:ReceiveMessage, sqs:DeleteMessage, and
sqs:GetQueueAttributes of the dead-letter queue. ... Add the sqs:SendMessage of the destination queue.
https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-configure-dead-letter-queue-redrive.html
and the API reference's pages on the operations say which parameter names each queue:
SourceArn: The ARN of the queue that contains the messages to be moved to another queue. Currently, only ARNs of
dead-letter queues (DLQs) whose sources are other Amazon SQS queues are accepted.
DestinationArn: The ARN of the queue that receives the moved messages. You can use this field to specify the
destination queue where you would like to redrive messages.
https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_StartMessageMoveTask.html
This script copies each row of the table as it stands, with each action it names and the queue it names it of, and
each parameter sentence of the pages naming a queue the table names, with its operation and parameter. A sentence of
a row naming no sqs: action, as its KMS ones, is copied with the row but not read. Nothing in the output is written by
hand, and the generator reads it against botocore's requests.
Run from anywhere in the repo:
python3 tools/aws/fetch_sqs_redrive_permissions.py # rewrite the vendored file from the pages
python3 tools/aws/fetch_sqs_redrive_permissions.py --verify # online: the file still says what the pages do
"""
from __future__ import annotations
import argparse
import html
import json
import re
import sys
import urllib.request
from datetime import datetime, timezone
from pathlib import Path
GUIDE_PAGE = ("https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/"
"sqs-configure-dead-letter-queue-redrive.html")
API_PAGES = {operation: f"https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_{operation}.html"
for operation in ("CancelMessageMoveTask", "ListMessageMoveTasks", "StartMessageMoveTask")}
REPO_ROOT = Path(__file__).resolve().parents[2]
OUTPUT = REPO_ROOT / "tools/aws/sources/sqs-redrive-permissions.json"
# The table's header, which says what its rows give.
HEADER = ("Minimum Permissions", "Required API methods")
# A sentence of a row giving the sqs: actions of a queue the request names.
ADD_RE = re.compile(r"\bAdd the (?P<actions>sqs:[A-Za-z]+(?:, sqs:[A-Za-z]+)*(?:,? and sqs:[A-Za-z]+)?) of the "
r"(?P<queue>[a-z-]+(?: [a-z-]+)* queue)\.")
# The sentences of a parameter's description naming the queue it holds, as the table names that queue.
QUEUE_SENTENCES = (
re.compile(r"\bCurrently, only ARNs of (?P<queue>dead-letter queue)s \(DLQs\) whose sources are other Amazon SQS "
r"queues are accepted\."),
re.compile(r"\bYou can use this field to specify the (?P<queue>destination queue) where you would like to "
r"redrive messages\."),
)
OPERATION_RE = re.compile(r'<h1 class="topictitle" id="API_(?P<operation>[A-Za-z]+)">(?P=operation)</h1>')
REQUEST_PARAMETERS_RE = re.compile(r'<h2 id="API_[A-Za-z]+_RequestParameters">(?P<section>.*?)(?:<h2|$)', re.S)
# A parameter of the section: its name in bold in its term, then its description.
PARAMETER_RE = re.compile(r'<dt[^>]*><span class="term">\s*<b>\s*(?:<a[^>]*>)?(?P<member>[A-Za-z0-9]+)(?:</a>)?\s*</b>'
r'\s*</span></dt>(?:\s*<dt>(?:(?!<dd>).)*?</dt>)*\s*<dd>(?P<description>.*?)</dd>', re.S)
def text(fragment: str) -> str:
"""A fragment of a page as text, spaces collapsed, and none left before a mark an inline tag ends ahead of."""
collapsed = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", fragment))).strip()
return re.sub(r" (?=[.,;)])", "", re.sub(r"\( ", "(", collapsed))
def body(page: str) -> str:
"""The page's own content, its navigation left out."""
match = re.search(r'<div id="main-col-body">(?P<body>.*?)(?:<div class="prev-next"|$)', page, re.S)
return match.group("body") if match else page
def read_tasks(page: str) -> list[dict]:
"""Each row of the guide's table of a redrive's minimum permissions, with each sqs: action a sentence of it names
and the queue it names it of, in the row's order."""
for table in re.findall(r"<table.*?</table>", body(page), re.S):
rows = [[text(cell) for cell in re.findall(r"<t[hd][^>]*>(.*?)</t[hd]>", row, re.S)]
for row in re.findall(r"<tr>(.*?)</tr>", table, re.S)]
if not rows or tuple(rows[0]) != HEADER:
continue
tasks = []
for row in rows[1:]:
if len(row) != 2:
raise ValueError(f"{GUIDE_PAGE}'s table of minimum permissions has a row of {len(row)} cells: its "
f"layout changed")
permissions = [{"action": action, "queue": added.group("queue")}
for added in ADD_RE.finditer(row[1])
for action in re.split(r",? and |, ", added.group("actions"))]
if not permissions:
raise ValueError(f"{GUIDE_PAGE} says '{row[1]}' for '{row[0]}', which names no sqs: action of a "
f"queue: its wording changed")
tasks.append({"task": row[0], "sentence": row[1], "permissions": permissions})
return tasks
raise ValueError(f"{GUIDE_PAGE} has no table of a redrive's minimum permissions: its layout changed")
def read_queues(operation: str, page: str) -> list[dict]:
"""Each request parameter of the operation's page whose description names a queue the guide's table names."""
titled = OPERATION_RE.search(body(page))
if titled is None or titled.group("operation") != operation:
raise ValueError(f"{API_PAGES[operation]} is not the page of {operation}: its layout changed")
section = REQUEST_PARAMETERS_RE.search(body(page))
if section is None:
raise ValueError(f"{API_PAGES[operation]} has no request parameters: its layout changed")
found = []
for parameter in PARAMETER_RE.finditer(section.group("section")):
description = text(parameter.group("description"))
for sentence in QUEUE_SENTENCES:
named = sentence.search(description)
if named is not None:
found.append({"operation": operation, "member": parameter.group("member"),
"queue": named.group("queue"), "sentence": named.group(0)})
return found
def build(guide_page: str, *api_pages: str) -> dict:
tasks = read_tasks(guide_page)
queues = [found for operation, page in zip(API_PAGES, api_pages) for found in read_queues(operation, page)]
if not queues:
raise ValueError(f"{' and '.join(API_PAGES.values())} name no queue of the guide's table: their wording "
f"changed")
return {
"_source": {
"pages": [GUIDE_PAGE, *API_PAGES.values()],
"fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)),
"retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
"note": "Each row of the developer guide's table of a dead-letter queue redrive's minimum permissions, "
"copied as it stands, with each sqs: action it names and the queue it names it of; the operation "
"of each of the API reference's message move task pages; and each parameter sentence of those "
"pages naming one of the queues, with its operation and parameter.",
},
"operations": list(API_PAGES),
"tasks": tasks,
"queues": queues,
}
def fetch_url(url: str) -> str:
request = urllib.request.Request(url, headers={"User-Agent": "floci-tools"})
with urllib.request.urlopen(request, timeout=60) as response:
return response.read().decode("utf-8")
def fetch_all(fetch=fetch_url) -> tuple[str, ...]:
"""The guide's page and each operation's API reference page, in `API_PAGES`' order."""
return (fetch(GUIDE_PAGE), *(fetch(url) for url in API_PAGES.values()))
def stale(vendored: dict, guide_page: str, *api_pages: str) -> bool:
"""Whether the pages now give something other than the vendored file, its date aside."""
built = build(guide_page, *api_pages)
return any(vendored.get(key) != built[key] for key in built if key != "_source")
def main(argv: list[str] | None = None, fetch=fetch_url) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--verify", action="store_true", help="online: the vendored file matches the pages")
args = parser.parse_args(argv)
try:
pages = fetch_all(fetch)
except OSError as e:
print(f"error: could not read the Amazon SQS documentation ({e})", file=sys.stderr)
return 2
if args.verify:
vendored = json.loads(OUTPUT.read_text(encoding="utf-8"))
if stale(vendored, *pages):
print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what the Amazon SQS developer guide and API "
f"reference do: run tools/aws/fetch_sqs_redrive_permissions.py and then make "
f"iam-request-resources-sync", file=sys.stderr)
return 1
print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the Amazon SQS developer guide and API reference")
return 0
built = build(*pages)
OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8")
print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['tasks'])} tasks, {len(built['queues'])} parameters)")
return 0
if __name__ == "__main__":
sys.exit(main())
+82 -3
View File
@@ -354,6 +354,7 @@ import fetch_ec2_id_examples
import fetch_iam_identifiers
import fetch_kms_api_permissions
import fetch_required_resource_types
import fetch_sqs_redrive_permissions
import fetch_ssm_session_permissions
from regen_iam_authorized_actions import (ROUTES as ROUTES_FILE, authorized_actions, fetch_references,
load_s3_required, s3_query_parameters, s3_version_choices,
@@ -582,9 +583,14 @@ PATH_SOURCES: dict[str, Path] = {
# CopyPackageVersions permission on the destination repository"), and the ARN of a package with no namespace ("The ARN
# for an npm package without a scope has the empty string for the namespace field": `package/my_domain/my_repo/npm//
# react`); tools/aws/fetch_codeartifact_permissions.py vendors those pages and `caller_permission_resources` and
# `with_empty_variables` read them. Each file is
# written by its own script from the pages, unchanged, and the generator only reads it: nothing about an operation is
# stated here.
# `with_empty_variables` read them. Amazon SQS's developer guide gives, in its table of a dead-letter queue redrive's
# minimum permissions, the actions each message move task needs of each queue ("Add the sqs:StartMessageMoveTask,
# sqs:ReceiveMessage, sqs:DeleteMessage, and sqs:GetQueueAttributes of the dead-letter queue", "Add the sqs:SendMessage
# of the destination queue"), and its API reference the parameter naming each queue (SourceArn: "only ARNs of
# dead-letter queues (DLQs) whose sources are other Amazon SQS queues are accepted"; DestinationArn: "specify the
# destination queue"); tools/aws/fetch_sqs_redrive_permissions.py vendors those pages and `task_permission_resources`
# reads them. Each file is written by its own script from the pages, unchanged, and the generator only reads it:
# nothing about an operation is stated here.
# ---------------------------------------------------------------------------------------------------------------------
PERMISSION_SOURCES: dict[str, Path] = {
"codeartifact": REPO_ROOT / "tools/aws/sources/codeartifact-permissions.json",
@@ -592,6 +598,7 @@ PERMISSION_SOURCES: dict[str, Path] = {
"dynamodb": REPO_ROOT / "tools/aws/sources/dynamodb-permissions.json",
"iam": REPO_ROOT / "tools/aws/sources/iam-identifiers.json",
"ssm": REPO_ROOT / "tools/aws/sources/ssm-session-permissions.json",
"sqs": REPO_ROOT / "tools/aws/sources/sqs-redrive-permissions.json",
}
# The script that writes each namespace's permission source, whose pages `verify_sources` reads it against.
PERMISSION_FETCHERS = {
@@ -600,6 +607,7 @@ PERMISSION_FETCHERS = {
"dynamodb": fetch_dynamodb_permissions,
"iam": fetch_iam_identifiers,
"ssm": fetch_ssm_session_permissions,
"sqs": fetch_sqs_redrive_permissions,
}
# Fetched API response examples supplement the identifier prefixes in botocore.
@@ -3188,6 +3196,8 @@ def entry_for(operation: str, upstream: dict, formats: dict[str, str], models: d
if source is not None and "callerPermissions" in source:
resources, actions = caller_permission_resources(operation, resources, source["callerPermissions"], known,
formats, models)
if source is not None and "tasks" in source:
resources, actions = task_permission_resources(operation, upstream["action"], resources, source, known)
if source is not None and "arnExamples" in source:
resources = with_empty_variables(resources, source["arnExamples"], formats)
if source is not None and "partiql" in source:
@@ -3835,6 +3845,74 @@ def caller_permission_resources(operation: str, resources: list[dict], rows: lis
return found, {permission["action"]: known[permission["action"]] for permission in row["permissions"]}
def task_permission_resources(operation: str, checked_as: str, resources: list[dict], source: dict,
known: dict[str, list[str]]) -> tuple[list[dict], dict | None]:
"""The resources of an operation whose namespace's vendored permissions give a table of tasks, each naming the
actions it needs of each queue of its request (`tasks`), and those actions, each with the types the Service
Reference gives it (`known`); the resources as they are and none for an operation no page of the source is for
(`operations`). The task is the one naming the action the operation is checked as ("Add the sqs:StartMessageMoveTask, sqs:ReceiveMessage,
sqs:DeleteMessage, and sqs:GetQueueAttributes of the dead-letter queue"). Each action is checked on the resource
the rules read from the member the vendored API reference names its queue by (`queues`: StartMessageMoveTask's
SourceArn, "only ARNs of dead-letter queues (DLQs)"; its DestinationArn, "specify the destination queue"), and a
queue the request names by no such member is the one the task names the operation's own action of, checked on
the resources the rules read for the operation (ListMessageMoveTasks' SourceArn). They replace what the rules
read, as an operation checked as several actions is checked on those alone. An operation the rules read no
resource of the queue for keeps their reading (CancelMessageMoveTask, whose request names its task by handle)."""
name = operation.split(":", 1)[1]
if name not in source["operations"]:
return resources, None
tasks = [task for task in source["tasks"] if any(found["action"] == checked_as for found in task["permissions"])]
if not tasks:
raise ValueError(f"{operation}: the vendored permissions name {checked_as} in no task")
if len(tasks) > 1:
raise ValueError(f"{operation}: the vendored permissions name {checked_as} in {len(tasks)} tasks, not one")
permissions = tasks[0]["permissions"]
own = next(found["queue"] for found in permissions if found["action"] == checked_as)
members = {found["queue"]: found["member"] for found in source["queues"] if found["operation"] == name}
held = set(members.values())
based = []
for permission in permissions:
queue = permission["queue"]
if queue in members:
base = [resource for resource in resources if resource.get("arn") == members[queue]]
if len(base) != 1:
raise ValueError(f"{operation}: the vendored API reference names the {queue} by {members[queue]}, "
f"which no resource the rules read is named by")
elif queue == own:
base = [resource for resource in resources if resource.get("arn") not in held]
else:
raise ValueError(f"{operation}: the vendored permissions name the {queue}, which no member of its "
f"request names")
if not base:
return resources, None
based.append((permission["action"], base))
rows = []
for action, base in based:
if action not in known:
raise ValueError(f"{operation}: the vendored permissions check {action}, which the Service Reference does "
f"not have")
for resource in base:
if not set(_kinds(resource)) & set(known[action]):
raise ValueError(f"{operation}: the vendored permissions check {action} on {_kinds(resource)}, no "
f"type the Service Reference gives that action")
rows.append({**resource, "action": action})
return rows, {action: known[action] for action in dict.fromkeys(action for action, _ in based)}
def verify_task_actions(vendored: dict, documents: list[dict]) -> list[str]:
"""An operation the vendored task tables give actions to whose actions the Service Reference no longer lists as
the ones it is authorized by: the guide's row for a task names the same actions as the reference does."""
authorized = authorized_by(documents)
untrue = []
for operation, entry in sorted(vendored["operations"].items()):
source = load_permission_source(namespace_of(operation)) if "actions" in entry else None
if source is None or "tasks" not in source or set(entry["actions"]) == authorized.get(operation, set()):
continue
untrue.append(f"AWS lists {sorted(authorized.get(operation, set()))} as the actions {operation} is authorized "
f"by, not {sorted(entry['actions'])} as its vendored task gives")
return untrue
def with_empty_variables(resources: list[dict], examples: list[dict], formats: dict[str, str]) -> list[dict]:
"""The resources, each filling a variable from an optional member, named only when the request gives it
(`unless`), followed, where the vendored pages give an example ARN of its type with that variable empty, by the
@@ -5988,6 +6066,7 @@ def main(argv: list[str] | None = None) -> int:
untrue.append("resourceKeys differ from AWS Service Reference and botocore")
untrue += verify_forwarded(document, documents)
untrue += verify_permission_actions(document, documents)
untrue += verify_task_actions(document, documents)
try:
untrue += verify_statements(document, documents)
untrue += verify_path_sources()
@@ -0,0 +1,96 @@
{
"_source": {
"pages": [
"https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-configure-dead-letter-queue-redrive.html",
"https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_CancelMessageMoveTask.html",
"https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ListMessageMoveTasks.html",
"https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_StartMessageMoveTask.html"
],
"fetcher": "tools/aws/fetch_sqs_redrive_permissions.py",
"retrieved": "2026-11-29",
"note": "Each row of the developer guide's table of a dead-letter queue redrive's minimum permissions, copied as it stands, with each sqs: action it names and the queue it names it of; the operation of each of the API reference's message move task pages; and each parameter sentence of those pages naming one of the queues, with its operation and parameter."
},
"operations": [
"CancelMessageMoveTask",
"ListMessageMoveTasks",
"StartMessageMoveTask"
],
"tasks": [
{
"task": "To start a message redrive",
"sentence": "Add the sqs:StartMessageMoveTask, sqs:ReceiveMessage, sqs:DeleteMessage, and sqs:GetQueueAttributes of the dead-letter queue. If either the dead-letter queue or the original source queue are encrypted (also known as an SSE queue), kms:Decrypt for any KMS key that has been used to encrypt the messages is also required. Add the sqs:SendMessage of the destination queue. If the destination queue is encrypted, kms:GenerateDataKey and kms:Decrypt are also required.",
"permissions": [
{
"action": "sqs:StartMessageMoveTask",
"queue": "dead-letter queue"
},
{
"action": "sqs:ReceiveMessage",
"queue": "dead-letter queue"
},
{
"action": "sqs:DeleteMessage",
"queue": "dead-letter queue"
},
{
"action": "sqs:GetQueueAttributes",
"queue": "dead-letter queue"
},
{
"action": "sqs:SendMessage",
"queue": "destination queue"
}
]
},
{
"task": "To cancel an in-progress message redrive",
"sentence": "Add the sqs:CancelMessageMoveTask, sqs:ReceiveMessage, sqs:DeleteMessage, and sqs:GetQueueAttributes of the dead-letter queue. If the dead-letter queue is encrypted (also known as an SSE queue), kms:Decrypt is also required.",
"permissions": [
{
"action": "sqs:CancelMessageMoveTask",
"queue": "dead-letter queue"
},
{
"action": "sqs:ReceiveMessage",
"queue": "dead-letter queue"
},
{
"action": "sqs:DeleteMessage",
"queue": "dead-letter queue"
},
{
"action": "sqs:GetQueueAttributes",
"queue": "dead-letter queue"
}
]
},
{
"task": "To show a message move status",
"sentence": "Add the sqs:ListMessageMoveTasks and sqs:GetQueueAttributes of the dead-letter queue.",
"permissions": [
{
"action": "sqs:ListMessageMoveTasks",
"queue": "dead-letter queue"
},
{
"action": "sqs:GetQueueAttributes",
"queue": "dead-letter queue"
}
]
}
],
"queues": [
{
"operation": "StartMessageMoveTask",
"member": "DestinationArn",
"queue": "destination queue",
"sentence": "You can use this field to specify the destination queue where you would like to redrive messages."
},
{
"operation": "StartMessageMoveTask",
"member": "SourceArn",
"queue": "dead-letter queue",
"sentence": "Currently, only ARNs of dead-letter queues (DLQs) whose sources are other Amazon SQS queues are accepted."
}
]
}
@@ -0,0 +1,83 @@
#!/usr/bin/env python3
"""Tests for fetch_sqs_redrive_permissions.py, on pages in the Amazon SQS developer guide's and API reference's
markup."""
from __future__ import annotations
import pytest
import fetch_sqs_redrive_permissions as f
START = ("Add the <code>sqs:StartMessageMoveTask</code>, <code>sqs:ReceiveMessage</code>, "
"<code>sqs:DeleteMessage</code>, and <code>sqs:GetQueueAttributes</code> of the dead-letter queue. If either the "
"dead-letter queue or the original source queue are encrypted, <code>kms:Decrypt</code> is also required. "
"Add the <code>sqs:SendMessage</code> of the destination queue.")
LIST = "Add the <code>sqs:ListMessageMoveTasks</code> and <code>sqs:GetQueueAttributes</code> of the dead-letter queue."
def guide(*rows: tuple[str, str], header: tuple[str, str] = f.HEADER) -> str:
listed = rows or (("To start a message redrive", START), ("To show a message move status", LIST))
cells = "".join(f"<tr><td><p>{task}</p></td><td><p>{sentence}</p></td></tr>" for task, sentence in listed)
return (f'<div id="main-col-body"><h1>Redrive</h1><table><tr><th>{header[0]}</th><th>{header[1]}</th></tr>'
f'{cells}</table></div><div class="prev-next"></div>')
def parameter(member: str, description: str) -> str:
return (f'<dt id="SQS-x-request-{member}"><span class="term">\n <b>\n <a href="#syntax">{member}</a>\n </b>\n'
f' </span></dt>\n<dd><p>{description}</p><p>Type: String</p></dd>')
SOURCE = parameter("SourceArn", "The ARN of the queue that contains the messages to be moved to another queue. "
"Currently, only ARNs of dead-letter queues (DLQs) whose sources are other Amazon SQS "
"queues are accepted.")
DESTINATION = parameter("DestinationArn", "The ARN of the queue that receives the moved messages. You can use this "
"field to specify the destination queue where you would like to redrive "
"messages.")
RATE = parameter("MaxNumberOfMessagesPerSecond", "The number of messages to be moved per second.")
def api(operation: str, *parameters: str) -> str:
return (f'<div id="main-col-body"><h1 class="topictitle" id="API_{operation}">{operation}</h1>'
f'<h2 id="API_{operation}_RequestParameters">Request Parameters</h2><dl>{"".join(parameters)}</dl>'
f'<h2 id="API_{operation}_Errors">Errors</h2></div><div class="prev-next"></div>')
def pages(guide_page: str | None = None, start: str | None = None) -> tuple[str, ...]:
return (guide_page or guide(), api("CancelMessageMoveTask", parameter("TaskHandle", "An identifier.")),
api("ListMessageMoveTasks", parameter("SourceArn", "The ARN of the queue whose tasks are listed.")),
start or api("StartMessageMoveTask", SOURCE, DESTINATION, RATE))
def test_each_task_names_its_actions_of_each_queue_and_each_parameter_naming_a_queue_is_read():
built = f.build(*pages())
assert built["operations"] == ["CancelMessageMoveTask", "ListMessageMoveTasks", "StartMessageMoveTask"]
start, listing = built["tasks"]
assert start["task"] == "To start a message redrive"
# The row's KMS sentence names no sqs: action and is copied with the row, not read.
assert [(found["action"], found["queue"]) for found in start["permissions"]] == [
("sqs:StartMessageMoveTask", "dead-letter queue"), ("sqs:ReceiveMessage", "dead-letter queue"),
("sqs:DeleteMessage", "dead-letter queue"), ("sqs:GetQueueAttributes", "dead-letter queue"),
("sqs:SendMessage", "destination queue")]
assert [(found["action"], found["queue"]) for found in listing["permissions"]] == [
("sqs:ListMessageMoveTasks", "dead-letter queue"), ("sqs:GetQueueAttributes", "dead-letter queue")]
# A parameter naming no queue, as the rate or the other pages' SourceArn, is not read.
assert [(found["operation"], found["member"], found["queue"]) for found in built["queues"]] == [
("StartMessageMoveTask", "SourceArn", "dead-letter queue"),
("StartMessageMoveTask", "DestinationArn", "destination queue")]
def test_a_page_whose_layout_or_wording_changed_is_refused():
with pytest.raises(ValueError, match="no table of a redrive's minimum permissions"):
f.build(*pages(guide(header=("Permissions", "Methods"))))
with pytest.raises(ValueError, match="names no sqs: action of a queue"):
f.build(*pages(guide(("To start a message redrive", START.replace("Add the", "Grant the")))))
with pytest.raises(ValueError, match="name no queue of the guide's table"):
f.build(*pages(start=api("StartMessageMoveTask", RATE)))
with pytest.raises(ValueError, match="is not the page of StartMessageMoveTask"):
f.build(*pages(start=api("CancelMessageMoveTask", SOURCE)))
def test_the_file_is_stale_when_a_page_says_something_else():
vendored = f.build(*pages())
assert not f.stale(vendored, *pages())
assert f.stale(vendored, *pages(guide(("To start a message redrive", START.replace(
"<code>sqs:SendMessage</code> of the destination", "<code>sqs:SendMessageBatch</code> of the destination")))))
@@ -4096,6 +4096,63 @@ def test_the_callers_permissions_check_each_action_on_the_repository_their_words
r.caller_permission_resources("svc:CopyPackageVersions", read, missing, known, REPOSITORIES, {"svc": copy})
REDRIVE = {"operations": ["CancelMessageMoveTask", "ListMessageMoveTasks", "StartMessageMoveTask"], "tasks": [
{"task": "To start a message redrive", "permissions": [
{"action": "svc:StartMessageMoveTask", "queue": "dead-letter queue"},
{"action": "svc:ReceiveMessage", "queue": "dead-letter queue"},
{"action": "svc:SendMessage", "queue": "destination queue"}]},
{"task": "To cancel an in-progress message redrive", "permissions": [
{"action": "svc:CancelMessageMoveTask", "queue": "dead-letter queue"},
{"action": "svc:ReceiveMessage", "queue": "dead-letter queue"}]},
{"task": "To show a message move status", "permissions": [
{"action": "svc:ListMessageMoveTasks", "queue": "dead-letter queue"},
{"action": "svc:GetQueueAttributes", "queue": "dead-letter queue"}]}],
"queues": [{"operation": "StartMessageMoveTask", "member": "SourceArn", "queue": "dead-letter queue"},
{"operation": "StartMessageMoveTask", "member": "DestinationArn", "queue": "destination queue"}]}
QUEUE_ACTIONS = {f"svc:{name}": ["queue"] for name in ("StartMessageMoveTask", "CancelMessageMoveTask",
"ListMessageMoveTasks", "ReceiveMessage", "SendMessage",
"GetQueueAttributes")}
def test_a_tasks_actions_are_each_checked_on_the_queue_its_row_names_them_of():
read = [{"types": ["queue"], "arn": "DestinationArn"}, {"types": ["queue"], "arn": "SourceArn"}]
assert r.task_permission_resources("svc:StartMessageMoveTask", "svc:StartMessageMoveTask", read, REDRIVE,
QUEUE_ACTIONS) == (
[{"types": ["queue"], "arn": "SourceArn", "action": "svc:StartMessageMoveTask"},
{"types": ["queue"], "arn": "SourceArn", "action": "svc:ReceiveMessage"},
{"types": ["queue"], "arn": "DestinationArn", "action": "svc:SendMessage"}],
{"svc:StartMessageMoveTask": ["queue"], "svc:ReceiveMessage": ["queue"], "svc:SendMessage": ["queue"]})
# A queue no parameter of the request is named after is the one the task names the operation's own action of.
listed = [{"types": ["queue"], "arn": "SourceArn"}]
assert r.task_permission_resources("svc:ListMessageMoveTasks", "svc:ListMessageMoveTasks", listed, REDRIVE,
QUEUE_ACTIONS)[0] == [
{"types": ["queue"], "arn": "SourceArn", "action": "svc:ListMessageMoveTasks"},
{"types": ["queue"], "arn": "SourceArn", "action": "svc:GetQueueAttributes"}]
def test_an_operation_the_rules_read_no_queue_of_or_no_page_is_for_keeps_its_reading():
assert r.task_permission_resources("svc:CancelMessageMoveTask", "svc:CancelMessageMoveTask", [], REDRIVE,
QUEUE_ACTIONS) == ([], None)
read = [{"type": "queue", "fill": {}, "find": ["QueueUrl"]}]
assert r.task_permission_resources("svc:ReceiveMessage", "svc:ReceiveMessage", read, REDRIVE,
QUEUE_ACTIONS) == (read, None)
def test_a_task_naming_what_the_request_or_the_reference_does_not_have_is_refused():
read = [{"types": ["queue"], "arn": "SourceArn"}]
with pytest.raises(ValueError, match="names the destination queue by DestinationArn"):
r.task_permission_resources("svc:StartMessageMoveTask", "svc:StartMessageMoveTask", read, REDRIVE,
QUEUE_ACTIONS)
read = [{"types": ["queue"], "arn": "DestinationArn"}, {"types": ["queue"], "arn": "SourceArn"}]
known = {action: kinds for action, kinds in QUEUE_ACTIONS.items() if action != "svc:ReceiveMessage"}
with pytest.raises(ValueError, match="check svc:ReceiveMessage, which the Service Reference does not have"):
r.task_permission_resources("svc:StartMessageMoveTask", "svc:StartMessageMoveTask", read, REDRIVE, known)
unnamed = {**REDRIVE, "tasks": REDRIVE["tasks"][:1]}
with pytest.raises(ValueError, match="in no task"):
r.task_permission_resources("svc:ListMessageMoveTasks", "svc:ListMessageMoveTasks", read, unnamed,
QUEUE_ACTIONS)
def test_an_example_arn_with_a_variable_empty_names_it_empty_for_a_request_leaving_its_member_out():
package = {"type": "package", "fill": {"DomainName": "domain", "PackageFormat": "format", "PackageName": "package",
"PackageNamespace": "namespace", "RepositoryName": "repository"},