fix(core): route a Query action by its service's botocore model (#5879)

A Query request without a usable credential scope is routed by its
Action and Version, and IAM enforcement authorizes it under the service
that routing picks. The names each service routed were kept by hand in
AwsQueryController and had drifted from what the services serve: 170
names Floci dispatches, across eight services, reached no service and
fell through to SQS. They answered UnsupportedOperation in SQS's
namespace and were authorized as SQS actions.

Each Query service's API versions and operations now come from its
botocore models: tools/aws/regen_query_services.py writes them, from the
pinned botocore, to aws/query-services.json, and make aws-data-check
fails when the file is stale. Every name a service defines reaches it,
implemented here or not. Floci keeps the list of services and their
order, Cognito's names, which no Query model holds, and ElastiCache's
ValidateIamAuthToken, which no model defines.

A name several services define goes to the first of them when the
request names no Version. Ten such names get a pinned owner instead,
the service that serves them here, where the order would pick an
earlier one that does not. The routing parity test checks every
dispatched action with and without a Version and no longer needs its
list of known gaps.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-17 10:17:18 -05:00
1 parent 4f4db89d8f
commit 30d8d3ff5c
8 files changed
+2325 -705

No files matched your search

+7
View File
@@ -212,6 +212,7 @@ aws-data-sync: ## Regenerate src/main/resources/aws/*.json and the IAM managed-p
$(PYTHON) tools/aws/regen_redshift_serverless_shapes.py
$(PYTHON) tools/aws/regen_apigateway_types.py
$(PYTHON) tools/aws/regen_sesv2_shapes.py
$(PYTHON) tools/aws/regen_query_services.py
$(PYTHON) tools/aws/regen_managed_policies.py
aws-data-check: ## CI gate: the vendored AWS data must match a fresh generation
@@ -249,6 +250,12 @@ aws-data-check: ## CI gate: the vendored AWS data must match a fresh generation
echo " Run 'make aws-data-sync' and commit the result."; \
exit 1; \
}
@$(PYTHON) tools/aws/regen_query_services.py --check || { \
echo ""; \
echo "error: src/main/resources/aws/query-services.json is out of date."; \
echo " Run 'make aws-data-sync' and commit the result."; \
exit 1; \
}
@$(PYTHON) tools/aws/regen_managed_policies.py --check || { \
echo ""; \
echo "error: the IAM managed-policy catalog (src/main/resources/iam/managed-polic*) is out of date or malformed."; \
@@ -37,6 +37,7 @@ import jakarta.ws.rs.core.UriInfo;
import org.jboss.logging.Logger;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
@@ -58,174 +59,6 @@ public class AwsQueryController {
private static final Logger LOG = Logger.getLogger(AwsQueryController.class);
private static final Set<String> STS_ACTIONS = Set.of(
"AssumeRole", "AssumeRoleWithWebIdentity", "AssumeRoleWithSAML",
"GetCallerIdentity", "GetSessionToken", "GetFederationToken",
"DecodeAuthorizationMessage"
);
private static final Set<String> SNS_ACTIONS = Set.of(
"CreateTopic", "DeleteTopic", "ListTopics", "GetTopicAttributes", "SetTopicAttributes",
"Subscribe", "Unsubscribe", "ListSubscriptions", "ListSubscriptionsByTopic",
"Publish", "PublishBatch", "TagResource", "UntagResource", "ListTagsForResource",
"CreatePlatformApplication", "DeletePlatformApplication", "GetPlatformApplicationAttributes",
"SetPlatformApplicationAttributes", "ListPlatformApplications",
"CreatePlatformEndpoint", "DeleteEndpoint", "GetEndpointAttributes",
"SetEndpointAttributes", "ListEndpointsByPlatformApplication",
"CheckIfPhoneNumberIsOptedOut", "ListPhoneNumbersOptedOut",
"OptInPhoneNumber", "SetSMSAttributes", "GetSMSAttributes",
"GetSubscriptionAttributes", "SetSubscriptionAttributes", "ConfirmSubscription",
"CreateSMSSandboxPhoneNumber", "DeleteSMSSandboxPhoneNumber",
"GetSMSSandboxAccountStatus", "ListSMSSandboxPhoneNumbers",
"VerifySMSSandboxPhoneNumber", "AddPermission", "RemovePermission"
);
private static final Set<String> IAM_ACTIONS = Set.of(
"CreateUser", "GetUser", "DeleteUser", "ListUsers", "UpdateUser",
"CreateGroup", "GetGroup", "DeleteGroup", "ListGroups",
"AddUserToGroup", "RemoveUserFromGroup", "ListGroupsForUser",
"CreateRole", "GetRole", "DeleteRole", "ListRoles", "UpdateRole",
"CreateServiceLinkedRole", "DeleteServiceLinkedRole", "GetServiceLinkedRoleDeletionStatus",
"CreatePolicy", "GetPolicy", "DeletePolicy", "ListPolicies", "ListEntitiesForPolicy",
"CreatePolicyVersion", "GetPolicyVersion", "DeletePolicyVersion",
"ListPolicyVersions", "SetDefaultPolicyVersion",
"AttachUserPolicy", "DetachUserPolicy", "ListAttachedUserPolicies",
"AttachGroupPolicy", "DetachGroupPolicy", "ListAttachedGroupPolicies",
"AttachRolePolicy", "DetachRolePolicy", "ListAttachedRolePolicies",
"PutUserPolicy", "GetUserPolicy", "DeleteUserPolicy", "ListUserPolicies",
"PutRolePolicy", "GetRolePolicy", "DeleteRolePolicy", "ListRolePolicies",
"PutGroupPolicy", "GetGroupPolicy", "DeleteGroupPolicy", "ListGroupPolicies",
"CreateAccessKey", "DeleteAccessKey", "ListAccessKeys", "UpdateAccessKey",
"CreateInstanceProfile", "GetInstanceProfile", "DeleteInstanceProfile",
"ListInstanceProfiles", "AddRoleToInstanceProfile",
"RemoveRoleFromInstanceProfile", "ListInstanceProfilesForRole",
"TagUser", "UntagUser", "ListUserTags",
"TagRole", "UntagRole", "ListRoleTags",
"TagPolicy", "UntagPolicy", "ListPolicyTags",
"TagInstanceProfile", "UntagInstanceProfile", "ListInstanceProfileTags",
"CreateLoginProfile", "GetLoginProfile", "DeleteLoginProfile", "UpdateLoginProfile",
"ChangePassword",
"GenerateCredentialReport", "GetCredentialReport",
"GetAccountSummary", "GetAccountAuthorizationDetails",
"SimulatePrincipalPolicy", "SimulateCustomPolicy",
"GetContextKeysForCustomPolicy", "GetContextKeysForPrincipalPolicy",
"ListSAMLProviders", "CreateSAMLProvider", "GetSAMLProvider",
"UpdateSAMLProvider", "DeleteSAMLProvider",
"TagSAMLProvider", "UntagSAMLProvider", "ListSAMLProviderTags",
"GenerateServiceLastAccessedDetails", "GetServiceLastAccessedDetails",
"GetServiceLastAccessedDetailsWithEntities", "ListPoliciesGrantingServiceAccess",
"GenerateOrganizationsAccessReport", "GetOrganizationsAccessReport",
"UploadServerCertificate", "GetServerCertificate", "UpdateServerCertificate",
"DeleteServerCertificate", "ListServerCertificates",
"TagServerCertificate", "UntagServerCertificate", "ListServerCertificateTags",
"CreateVirtualMFADevice", "DeleteVirtualMFADevice", "ListVirtualMFADevices",
"EnableMFADevice", "DeactivateMFADevice", "ResyncMFADevice", "ListMFADevices",
"TagMFADevice", "UntagMFADevice", "ListMFADeviceTags",
"GetAccountProperties", "PutAccountProperties",
"SetSecurityTokenServicePreferences", "EnableOutboundWebIdentityFederation",
"DisableOutboundWebIdentityFederation", "GetOutboundWebIdentityFederationInfo",
"CreateServiceSpecificCredential", "ListServiceSpecificCredentials",
"UpdateServiceSpecificCredential", "ResetServiceSpecificCredential",
"DeleteServiceSpecificCredential",
"UploadSSHPublicKey", "GetSSHPublicKey", "ListSSHPublicKeys",
"UpdateSSHPublicKey", "DeleteSSHPublicKey",
"UploadSigningCertificate", "ListSigningCertificates",
"UpdateSigningCertificate", "DeleteSigningCertificate",
"CreateAccountAlias", "DeleteAccountAlias", "ListAccountAliases",
"GetAccountPasswordPolicy", "UpdateAccountPasswordPolicy", "DeleteAccountPasswordPolicy",
"GetAccessKeyLastUsed", "UpdateGroup", "UpdateAssumeRolePolicy",
"PutUserPermissionsBoundary", "DeleteUserPermissionsBoundary",
"PutRolePermissionsBoundary", "DeleteRolePermissionsBoundary",
"CreateOpenIDConnectProvider", "GetOpenIDConnectProvider",
"ListOpenIDConnectProviders", "DeleteOpenIDConnectProvider",
"AddClientIDToOpenIDConnectProvider", "RemoveClientIDFromOpenIDConnectProvider",
"UpdateOpenIDConnectProviderThumbprint", "TagOpenIDConnectProvider",
"UntagOpenIDConnectProvider", "ListOpenIDConnectProviderTags",
"ListOrganizationsFeatures",
"EnableOrganizationsRootCredentialsManagement",
"DisableOrganizationsRootCredentialsManagement",
"EnableOrganizationsRootSessions", "DisableOrganizationsRootSessions"
);
private static final Set<String> AUTOSCALING_ACTIONS = Set.of(
"CreateLaunchConfiguration", "DescribeLaunchConfigurations", "DeleteLaunchConfiguration",
"CreateAutoScalingGroup", "UpdateAutoScalingGroup", "DeleteAutoScalingGroup",
"DescribeAutoScalingGroups", "SetDesiredCapacity",
"StartInstanceRefresh", "DescribeInstanceRefreshes",
"CreateOrUpdateTags", "DeleteTags", "DescribeTags",
"DescribeAutoScalingInstances", "AttachInstances", "DetachInstances",
"TerminateInstanceInAutoScalingGroup",
"AttachLoadBalancerTargetGroups", "DetachLoadBalancerTargetGroups",
"DescribeLoadBalancerTargetGroups", "AttachLoadBalancers", "DetachLoadBalancers",
"PutLifecycleHook", "DeleteLifecycleHook", "DescribeLifecycleHooks",
"CompleteLifecycleAction", "RecordLifecycleActionHeartbeat",
"PutScalingPolicy", "DeletePolicy", "DescribePolicies",
"DescribeScalingActivities",
"DescribeAutoScalingNotificationTypes", "DescribeTerminationPolicyTypes",
"DescribeAdjustmentTypes", "DescribeAccountLimits", "DescribeLoadBalancers",
"DescribeLifecycleHookTypes", "DescribeMetricCollectionTypes",
"EnableMetricsCollection", "DisableMetricsCollection"
);
private static final Set<String> ELB_V2_ACTIONS = Set.of(
"CreateLoadBalancer", "DescribeLoadBalancers", "DeleteLoadBalancer",
"ModifyLoadBalancerAttributes", "DescribeLoadBalancerAttributes",
"SetSecurityGroups", "SetSubnets", "SetIpAddressType",
"CreateTargetGroup", "DescribeTargetGroups", "ModifyTargetGroup", "DeleteTargetGroup",
"ModifyTargetGroupAttributes", "DescribeTargetGroupAttributes",
"RegisterTargets", "DeregisterTargets", "DescribeTargetHealth",
"CreateListener", "DescribeListeners", "ModifyListener", "DeleteListener",
"AddListenerCertificates", "RemoveListenerCertificates", "DescribeListenerCertificates",
"CreateRule", "DescribeRules", "ModifyRule", "DeleteRule", "SetRulePriorities",
"AddTags", "RemoveTags", "DescribeTags",
"DescribeSSLPolicies", "DescribeAccountLimits"
);
private static final Set<String> EC2_ACTIONS = Set.of(
"RunInstances", "CreateFleet", "DescribeInstances", "TerminateInstances", "StartInstances", "StopInstances",
"RebootInstances", "DescribeInstanceStatus", "DescribeInstanceAttribute", "ModifyInstanceAttribute",
"CreateVpc", "DescribeVpcs", "DeleteVpc", "ModifyVpcAttribute", "DescribeVpcAttribute",
"DescribeVpcEndpointServices", "CreateVpcEndpoint", "DescribeVpcEndpoints", "DeleteVpcEndpoints",
"DescribePrefixLists",
"CreateDefaultVpc", "AssociateVpcCidrBlock", "DisassociateVpcCidrBlock",
"CreateSubnet", "DescribeSubnets", "DeleteSubnet", "ModifySubnetAttribute",
"CreateSecurityGroup", "DescribeSecurityGroups", "DeleteSecurityGroup",
"AuthorizeSecurityGroupIngress", "AuthorizeSecurityGroupEgress",
"RevokeSecurityGroupIngress", "RevokeSecurityGroupEgress",
"DescribeSecurityGroupRules", "ModifySecurityGroupRules",
"UpdateSecurityGroupRuleDescriptionsIngress", "UpdateSecurityGroupRuleDescriptionsEgress",
"CreateKeyPair", "DescribeKeyPairs", "DeleteKeyPair", "ImportKeyPair",
"DescribeImages", "RegisterImage", "DeregisterImage", "CreateImage", "CopyImage",
"DescribeSnapshots",
"EnableSnapshotBlockPublicAccess", "DisableSnapshotBlockPublicAccess",
"GetSnapshotBlockPublicAccessState",
"CreateTags", "DeleteTags", "DescribeTags",
"CreateInternetGateway", "DescribeInternetGateways", "DeleteInternetGateway",
"AttachInternetGateway", "DetachInternetGateway",
"CreateEgressOnlyInternetGateway", "DescribeEgressOnlyInternetGateways",
"DeleteEgressOnlyInternetGateway",
"CreateRouteTable", "DescribeRouteTables", "DeleteRouteTable",
"AssociateRouteTable", "DisassociateRouteTable", "CreateRoute", "ReplaceRoute", "DeleteRoute",
"CreateNetworkAcl", "DescribeNetworkAcls", "DeleteNetworkAcl",
"CreateNetworkAclEntry", "ReplaceNetworkAclEntry", "DeleteNetworkAclEntry",
"ReplaceNetworkAclAssociation",
"CreateNatGateway", "DescribeNatGateways", "DeleteNatGateway",
"CreateTransitGatewayPeeringAttachment", "AcceptTransitGatewayPeeringAttachment",
"DeleteTransitGatewayPeeringAttachment", "DescribeTransitGatewayPeeringAttachments",
"CreateCapacityReservation", "DescribeCapacityReservations",
"ModifyCapacityReservation", "CancelCapacityReservation",
"AllocateAddress", "AssociateAddress", "DisassociateAddress", "ReleaseAddress", "DescribeAddresses",
"DescribeAddressesAttribute",
"DescribeIamInstanceProfileAssociations",
"DescribeAvailabilityZones", "DescribeRegions", "DescribeAccountAttributes",
"DescribeInstanceTypes", "DescribeInstanceTypeOfferings", "DescribeSpotPriceHistory",
"CreateLaunchTemplate", "CreateLaunchTemplateVersion", "DescribeLaunchTemplates", "DescribeLaunchTemplateVersions",
"ModifyLaunchTemplate", "DeleteLaunchTemplate",
"DescribeNetworkInterfaces",
"CreateFlowLogs", "DescribeFlowLogs", "DeleteFlowLogs",
"CreateVolume", "DescribeVolumes", "DeleteVolume", "AttachVolume", "DetachVolume"
);
private final CloudFormationQueryHandler cloudFormationQueryHandler;
private final ElastiCacheQueryHandler elastiCacheQueryHandler;
private final RdsQueryHandler rdsQueryHandler;
@@ -531,109 +364,8 @@ public class AwsQueryController {
return Response.status(400).entity(xml).type(MediaType.APPLICATION_XML).build();
}
private static final Set<String> ELASTICACHE_ACTIONS = Set.of(
"ValidateIamAuthToken",
"CreateReplicationGroup", "DescribeReplicationGroups", "ModifyReplicationGroup", "DeleteReplicationGroup",
"CreateUser", "DescribeUsers", "ModifyUser", "DeleteUser",
"CreateUserGroup", "DescribeUserGroups", "ModifyUserGroup", "DeleteUserGroup",
"CreateServerlessCache", "DescribeServerlessCaches", "ModifyServerlessCache", "DeleteServerlessCache",
"ListTagsForResource"
);
private static final String CLOUDWATCH_API_VERSION = "2010-08-01";
private static final Set<String> CLOUDWATCH_ACTIONS = Set.of(
"PutMetricData", "ListMetrics", "GetMetricStatistics", "GetMetricData",
"PutMetricAlarm", "DescribeAlarms", "DeleteAlarms", "SetAlarmState",
"ListTagsForResource", "TagResource", "UntagResource",
"PutDashboard", "GetDashboard", "ListDashboards", "DeleteDashboards",
"PutMetricStream", "GetMetricStream", "ListMetricStreams", "DeleteMetricStream",
"StartMetricStreams", "StopMetricStreams"
);
private static final Set<String> ELASTIC_BEANSTALK_ACTIONS = Set.of(
"CreateApplication", "DescribeApplications", "UpdateApplication", "DeleteApplication",
"CreateApplicationVersion", "DescribeApplicationVersions", "DeleteApplicationVersion",
"CreateEnvironment", "DescribeEnvironments", "UpdateEnvironment", "TerminateEnvironment",
"DescribeConfigurationSettings", "CheckDNSAvailability", "ListAvailableSolutionStacks"
);
private static final Set<String> RDS_ACTIONS = Set.of(
"CreateDBInstance", "DescribeDBInstances", "DeleteDBInstance",
"ModifyDBInstance", "RebootDBInstance",
"DescribeOrderableDBInstanceOptions", "DescribeValidDBInstanceModifications",
"DescribeDBEngineVersions", "DescribeEngineDefaultParameters",
"DescribeEngineDefaultClusterParameters",
"CreateDBSubnetGroup", "DescribeDBSubnetGroups", "ModifyDBSubnetGroup", "DeleteDBSubnetGroup",
"AddTagsToResource", "ListTagsForResource", "RemoveTagsFromResource",
"CreateDBCluster", "DescribeDBClusters", "DeleteDBCluster", "ModifyDBCluster",
"AddRoleToDBCluster", "RemoveRoleFromDBCluster", "AddRoleToDBInstance", "RemoveRoleFromDBInstance",
"EnableHttpEndpoint", "DisableHttpEndpoint",
"DescribeDBLogFiles", "DownloadDBLogFilePortion",
"DescribeGlobalClusters",
"CreateDBParameterGroup", "DescribeDBParameterGroups",
"DeleteDBParameterGroup", "ModifyDBParameterGroup", "DescribeDBParameters",
"DescribeDBProxies", "CreateDBProxy", "ModifyDBProxy", "DeleteDBProxy",
"RegisterDBProxyTargets", "DeregisterDBProxyTargets",
"DescribeDBProxyTargetGroups", "ModifyDBProxyTargetGroup", "DescribeDBProxyTargets",
"CreateDBClusterParameterGroup", "DescribeDBClusterParameterGroups",
"ModifyDBClusterParameterGroup", "DeleteDBClusterParameterGroup",
"DescribeDBClusterParameters",
"CreateOptionGroup", "DescribeOptionGroups", "ModifyOptionGroup", "DeleteOptionGroup",
"DescribeDBSnapshots", "DescribeDBClusterSnapshots",
"StartExportTask", "DescribeExportTasks", "CancelExportTask"
);
private static final Set<String> CLOUDFORMATION_ACTIONS = Set.of(
"CreateStack", "DeleteStack", "UpdateStack", "DescribeStacks", "UpdateTerminationProtection",
"ContinueUpdateRollback",
"ListStacks", "ListExports", "GetTemplate", "GetTemplateSummary", "ValidateTemplate",
"CreateChangeSet", "DeleteChangeSet", "DescribeChangeSet", "ExecuteChangeSet", "ListChangeSets",
"DescribeStackEvents", "DescribeStackResources", "ListStackResources", "DescribeStackResource",
"SetStackPolicy", "GetStackPolicy",
"ListStackSets", "DescribeStackSet", "CreateStackSet", "UpdateStackSet", "DeleteStackSet",
"CreateStackInstances", "ListStackInstances", "DescribeStackInstance", "DeleteStackInstances",
"ListStackSetOperations", "DescribeStackSetOperation"
);
private static final Set<String> SES_ACTIONS = Set.of(
"VerifyEmailIdentity", "VerifyEmailAddress", "VerifyDomainIdentity",
"DeleteIdentity", "ListIdentities", "GetIdentityVerificationAttributes",
"SendEmail", "SendRawEmail", "GetSendQuota", "GetSendStatistics",
"GetAccountSendingEnabled", "ListVerifiedEmailAddresses", "DeleteVerifiedEmailAddress",
"SetIdentityNotificationTopic", "GetIdentityNotificationAttributes",
"SetIdentityFeedbackForwardingEnabled",
"SetIdentityDkimEnabled",
"VerifyDomainDkim",
"SetIdentityHeadersInNotificationsEnabled",
"SetIdentityMailFromDomain", "GetIdentityMailFromDomainAttributes",
"GetIdentityDkimAttributes",
"PutIdentityPolicy", "GetIdentityPolicies", "ListIdentityPolicies", "DeleteIdentityPolicy",
"CreateTemplate", "UpdateTemplate", "GetTemplate", "DeleteTemplate",
"ListTemplates", "SendTemplatedEmail", "SendBulkTemplatedEmail",
"TestRenderTemplate",
"CreateCustomVerificationEmailTemplate", "GetCustomVerificationEmailTemplate",
"ListCustomVerificationEmailTemplates", "UpdateCustomVerificationEmailTemplate",
"DeleteCustomVerificationEmailTemplate", "SendCustomVerificationEmail",
"CreateConfigurationSet", "DescribeConfigurationSet",
"ListConfigurationSets", "DeleteConfigurationSet",
"CreateConfigurationSetEventDestination",
"UpdateConfigurationSetEventDestination",
"DeleteConfigurationSetEventDestination",
"UpdateConfigurationSetSendingEnabled",
"CreateConfigurationSetTrackingOptions",
"UpdateConfigurationSetTrackingOptions",
"DeleteConfigurationSetTrackingOptions",
"UpdateConfigurationSetReputationMetricsEnabled",
"PutConfigurationSetDeliveryOptions",
"CreateReceiptRuleSet", "DescribeReceiptRuleSet", "ListReceiptRuleSets",
"DeleteReceiptRuleSet", "SetActiveReceiptRuleSet", "DescribeActiveReceiptRuleSet",
"ReorderReceiptRuleSet", "CloneReceiptRuleSet",
"CreateReceiptRule", "DescribeReceiptRule", "UpdateReceiptRule",
"DeleteReceiptRule", "SetReceiptRulePosition",
"CreateReceiptFilter", "ListReceiptFilters", "DeleteReceiptFilter"
);
private static final Set<String> COGNITO_ACTIONS = Set.of(
"AdminCreateUser", "AdminGetUser", "AdminDeleteUser", "AdminSetUserPassword",
"AdminUpdateUserAttributes", "AdminUserGlobalSignOut", "ListUsers",
@@ -647,21 +379,6 @@ public class AwsQueryController {
"AdminAddUserToGroup", "AdminRemoveUserFromGroup", "AdminListGroupsForUser"
);
private static final Set<String> REDSHIFT_ACTIONS = Set.of(
"CreateCluster", "DescribeClusters", "DeleteCluster",
"CreateClusterSnapshot", "DescribeClusterSnapshots", "DeleteClusterSnapshot", "RestoreFromClusterSnapshot",
"ModifyCluster", "RebootCluster",
"CreateClusterParameterGroup", "DescribeClusterParameterGroups", "DescribeClusterParameters", "DeleteClusterParameterGroup",
"ModifyClusterParameterGroup",
"CreateClusterSubnetGroup", "DescribeClusterSubnetGroups", "ModifyClusterSubnetGroup", "DeleteClusterSubnetGroup",
"CreateSnapshotCopyGrant", "DescribeSnapshotCopyGrants", "DeleteSnapshotCopyGrant",
"EnableSnapshotCopy", "DisableSnapshotCopy", "ModifySnapshotCopyRetentionPeriod",
"CreateSnapshotSchedule", "DescribeSnapshotSchedules", "ModifySnapshotSchedule",
"DeleteSnapshotSchedule", "ModifyClusterSnapshotSchedule",
"CreateTags", "DeleteTags", "DescribeTags",
"GetClusterCredentials", "GetClusterCredentialsWithIAM"
);
/** Root GET requests that can use the CloudWatch Query handler without claiming S3 traffic. */
public static boolean isCloudWatchQueryGet(String authorization, String target, String accept,
MultivaluedMap<String, String> queryParams) {
@@ -695,7 +412,7 @@ public class AwsQueryController {
version = version == null ? "2009-05-15" : version;
Set<String> actions = switch (version) {
case "2009-05-15" -> Set.of("ListMetrics", "GetMetricStatistics");
case CLOUDWATCH_API_VERSION -> CLOUDWATCH_ACTIONS;
case CLOUDWATCH_API_VERSION -> QueryServiceModels.of("monitoring").operations();
default -> Set.of();
};
if (!actions.contains(action)) {
@@ -705,70 +422,85 @@ public class AwsQueryController {
return dispatch(IamEnforcementFilter.requestAuthorization(authorization, queryParams), queryParams);
}
/**
* Tried last, so by name alone SQS takes only what no other service defines, as it takes a name
* nobody defines. Its {@code Version} is what wins back the two names SNS also defines.
*/
private static final Set<String> SQS_ACTIONS = Set.of(
"CreateQueue", "DeleteQueue", "ListQueues", "GetQueueUrl",
"GetQueueAttributes", "SetQueueAttributes", "PurgeQueue",
"SendMessage", "SendMessageBatch", "ReceiveMessage", "DeleteMessage", "DeleteMessageBatch",
"ChangeMessageVisibility", "ChangeMessageVisibilityBatch",
"TagQueue", "UntagQueue", "ListQueueTags", "ListDeadLetterSourceQueues",
"StartMessageMoveTask", "ListMessageMoveTasks", "CancelMessageMoveTask",
"AddPermission", "RemovePermission"
);
/** ELBv2's names and Classic's own. A name both APIs define is split by {@link #isElbClassicRequest}. */
private static final Set<String> ELB_ACTIONS = Stream.concat(
ELB_V2_ACTIONS.stream(), ElbClassicQueryHandler.CLASSIC_ONLY_ACTIONS.stream())
.collect(Collectors.toUnmodifiableSet());
/** A Query service, the API versions its clients declare, and the action names it serves. */
private record QueryService(String name, Set<String> apiVersions, Set<String> actions) {
/**
* A service as its botocore models define it (see {@link QueryServiceModels}), plus any
* action Floci serves that no model defines.
*/
static QueryService modeled(String name, String... floci) {
QueryServiceModels.ServiceModel model = QueryServiceModels.of(name);
return new QueryService(name, model.apiVersions(),
Stream.concat(model.operations().stream(), Stream.of(floci))
.collect(Collectors.toUnmodifiableSet()));
}
}
/**
* Every Query service, in the order they are tried when the action name alone has to decide:
* where two services define the same name, the earlier one takes it.
* where two services define the same name, the earlier one takes it, unless
* {@link #UNVERSIONED_OWNERS} names another.
*
* <p>An API version is the {@code apiVersion} of the service's model. SES and Elastic Beanstalk
* publish the same one and share no action name, so the action settles which of the two a
* request is for. Both Elastic Load Balancing APIs lead to one service here and
* {@link #isElbClassicRequest} splits them on the same field, and DocumentDB and Neptune publish
* RDS's version and are split from it in the {@code rds} case. Cognito's model is JSON only, so
* no Query client declares a version for it.
* <p>Each service's versions and actions are those of its botocore models, so a name a service
* defines reaches it whether Floci implements it or not. SES and Elastic Beanstalk publish the
* same version and share no action name, so the action settles which of the two a request is
* for. Both Elastic Load Balancing APIs lead to one service here and {@link #isElbClassicRequest}
* splits them on the same field, and DocumentDB and Neptune publish RDS's version and are split
* from it in the {@code rds} case. {@code ValidateIamAuthToken} is Floci's own ElastiCache
* action. Cognito's model is JSON only, so it has no Query model and no Query client declares a
* version for it; its names are listed by hand. SQS is tried last, so by name alone it takes only
* what no other service defines, and its {@code Version} wins back the two names SNS also
* defines.
*/
private static final List<QueryService> QUERY_SERVICES = List.of(
new QueryService("sts", Set.of("2011-06-15"), STS_ACTIONS),
new QueryService("iam", Set.of("2010-05-08"), IAM_ACTIONS),
new QueryService("sns", Set.of("2010-03-31"), SNS_ACTIONS),
new QueryService("elasticache", Set.of("2015-02-02"), ELASTICACHE_ACTIONS),
new QueryService("rds", Set.of("2014-10-31"), RDS_ACTIONS),
new QueryService("monitoring", Set.of(CLOUDWATCH_API_VERSION), CLOUDWATCH_ACTIONS),
new QueryService("cloudformation", Set.of("2010-05-15"), CLOUDFORMATION_ACTIONS),
new QueryService("email", Set.of("2010-12-01"), SES_ACTIONS),
QueryService.modeled("sts"),
QueryService.modeled("iam"),
QueryService.modeled("sns"),
QueryService.modeled("elasticache", "ValidateIamAuthToken"),
QueryService.modeled("rds"),
QueryService.modeled("monitoring"),
QueryService.modeled("cloudformation"),
QueryService.modeled("email"),
new QueryService("cognito-idp", Set.of(), COGNITO_ACTIONS),
new QueryService("ec2", Set.of("2016-11-15"), EC2_ACTIONS),
new QueryService("elasticloadbalancing",
Set.of(ELB_V2_API_VERSION, ELB_CLASSIC_API_VERSION), ELB_ACTIONS),
new QueryService("autoscaling", Set.of("2011-01-01"), AUTOSCALING_ACTIONS),
new QueryService("elasticbeanstalk", Set.of("2010-12-01"), ELASTIC_BEANSTALK_ACTIONS),
new QueryService("redshift", Set.of("2012-12-01"), REDSHIFT_ACTIONS),
new QueryService("sqs", Set.of("2012-11-05"), SQS_ACTIONS));
QueryService.modeled("ec2"),
QueryService.modeled("elasticloadbalancing"),
QueryService.modeled("autoscaling"),
QueryService.modeled("elasticbeanstalk"),
QueryService.modeled("redshift"),
QueryService.modeled("sqs"));
/**
* Where a name several services define goes when the request's {@code Version} does not decide:
* the service that serves it here, where the order would pick an earlier one that does not.
* {@code AwsQueryActionRoutingParityTest} fails when a name some service serves reaches one that
* does not.
*/
static final Map<String, String> UNVERSIONED_OWNERS = Map.ofEntries(
Map.entry("AddTagsToResource", "rds"),
Map.entry("RemoveTagsFromResource", "rds"),
Map.entry("DescribeEngineDefaultParameters", "rds"),
Map.entry("DescribeEvents", "rds"),
Map.entry("DescribeAccountAttributes", "ec2"),
Map.entry("DescribeSnapshots", "ec2"),
Map.entry("DescribeAccountLimits", "elasticloadbalancing"),
Map.entry("CreateIntegration", "redshift"),
Map.entry("DeleteIntegration", "redshift"),
Map.entry("DescribeIntegrations", "redshift"));
/**
* The service a Query request goes to when its credential scope does not name one.
*
* <p>The action name alone is ambiguous wherever two services define it, and then the earlier
* one in {@link #QUERY_SERVICES} wins. The {@code Version} every Query client sends is what
* one in {@link #QUERY_SERVICES} wins, or the one {@link #UNVERSIONED_OWNERS} names. The
* {@code Version} every Query client sends is what
* tells them apart, as {@link #isElbClassicRequest} already uses it for the two Elastic Load
* Balancing APIs: {@code CreateUser} under IAM's version is IAM's, and under ElastiCache's it
* is ElastiCache's.
*
* <p>{@code Version} only chooses among the services that serve the name. One that names a
* service without it, or none at all, leaves the order to decide, so a hand-rolled request that
* omits the field goes exactly where it went before.
* <p>{@code Version} only chooses among the services that define the name. One that names a
* service without it, or none at all, leaves the name to decide, as it does for a hand-rolled
* request that omits the field.
*/
static String inferServiceFromAction(String action, String version) {
String byName = null;
@@ -783,6 +515,9 @@ public class AwsQueryController {
byName = service.name();
}
}
if (byName != null && UNVERSIONED_OWNERS.containsKey(action)) {
return UNVERSIONED_OWNERS.get(action);
}
// A name no service defines goes to SQS, which is how a raw SQS request without an
// Authorization header gets there.
return byName != null ? byName : "sqs";
@@ -0,0 +1,74 @@
package io.github.hectorvent.floci.core.common;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
/**
* The API versions and the operations of every Query service Floci serves, read once from the
* vendored {@code aws/query-services.json}. {@link AwsQueryController} routes a request that arrives
* without a usable credential scope by them.
*
* <p>The file is generated by {@code tools/aws/regen_query_services.py} from botocore's service
* models, so a service holds every operation its model defines, implemented here or not, and the
* versions its clients declare. {@code make aws-data-check} fails when it is stale against the
* pinned botocore.
*
* <p>A missing or malformed resource is a build defect, not a runtime condition, so loading fails
* with {@link IllegalStateException} rather than degrading to no services, which would route every
* request without a credential scope to SQS.
*/
final class QueryServiceModels {
static final String RESOURCE_NAME = "aws/query-services.json";
/** One service's API versions and the operations its models define. */
record ServiceModel(Set<String> apiVersions, Set<String> operations) {
}
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final Map<String, ServiceModel> SERVICES = VendoredResources.read(RESOURCE_NAME,
"Query service models", QueryServiceModels::parse);
private QueryServiceModels() {
}
/** The model of {@code service}, as the credential scope names it. */
static ServiceModel of(String service) {
ServiceModel model = SERVICES.get(service);
if (model == null) {
throw new IllegalStateException(RESOURCE_NAME + " has no service " + service);
}
return model;
}
/** The file's services, keyed by the name the credential scope uses. */
static Map<String, ServiceModel> parse(InputStream in) throws IOException {
JsonNode services = MAPPER.readTree(in).path("services");
if (!services.isObject() || services.isEmpty()) {
throw new IllegalStateException(RESOURCE_NAME + " carries no services");
}
Map<String, ServiceModel> models = new LinkedHashMap<>();
services.properties().forEach(service -> models.put(service.getKey(), new ServiceModel(
names(service.getKey(), "apiVersions", service.getValue()),
names(service.getKey(), "operations", service.getValue()))));
return Map.copyOf(models);
}
private static Set<String> names(String service, String field, JsonNode model) {
JsonNode array = model.path(field);
if (!array.isArray() || array.isEmpty()) {
throw new IllegalStateException(RESOURCE_NAME + " has no " + field + " for " + service);
}
Set<String> names = new LinkedHashSet<>();
array.forEach(name -> names.add(name.asText()));
return Set.copyOf(names);
}
}
File diff suppressed because it is too large. Load diff
@@ -7,7 +7,6 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -20,9 +19,11 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Guards the rule that an action a Query handler dispatches is an action routing sends to that
* handler. The two lists are maintained by hand in different files, so they drift: #5032 was 28
* IAM operations that had drifted out, and the same gap exists today for most other Query
* services, which is what this test makes visible and stops growing.
* handler. Routing knows each service's actions from its botocore models
* ({@code aws/query-services.json}, generated by {@code tools/aws/regen_query_services.py}) and the
* handlers dispatch what Floci implements, so the two are kept apart; before they were generated,
* the hand-kept routing sets drifted: #5032 was 28 IAM operations that had drifted out, and 170
* names across eight services were unrouted when the sets were replaced.
*
* <p>Routing only decides anything when a request arrives without a usable credential scope,
* because otherwise the service comes from the SigV4 scope. On that path there is the action name
@@ -33,15 +34,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
* is the part worth a test.
*
* <p>Each action is routed with its own service's {@code Version}, as any Query client sends it,
* and again without one, as a hand-rolled request may leave it out. Without it a name two services
* share goes to whichever is tried first, so that path is only held to reaching a service that
* dispatches the name.
*
* <p>The known gaps live in {@code src/test/resources/query-routing-known-gaps.tsv} rather than
* here, so that fixing one is a line removed from a data file. The list is checked both ways: a new
* gap fails {@link #everyDispatchedActionRoutesToItsOwnService} or
* {@link #withoutAVersionEveryActionReachesAServiceThatDispatchesIt}, and a gap that has been fixed
* without delisting fails {@link #theKnownGapListHasNoStaleEntries}.
* and again without one, as a hand-rolled request may leave it out. Without it a name several
* services define goes to the first that defines it, or to the one
* {@code AwsQueryController.UNVERSIONED_OWNERS} names, so that path is held to reaching a service
* that dispatches the name.
*/
class AwsQueryActionRoutingParityTest {
@@ -53,27 +49,6 @@ class AwsQueryActionRoutingParityTest {
}
}
/** A heading in the gap file: what it labels, and the three counts it claims for its rows. */
private record GapHeading(String label, String line, int total, int unrouted, int claimed) {
private static GapHeading of(String label, Matcher heading, int firstCount) {
return new GapHeading(label, heading.group(),
Integer.parseInt(heading.group(firstCount)),
Integer.parseInt(heading.group(firstCount + 1)),
Integer.parseInt(heading.group(firstCount + 2)));
}
/** Records a mismatch when the unrouted and claimed rows counted under it disagree with it. */
private void check(int[] rows, List<String> wrong) {
int rowTotal = rows[0] + rows[1];
if (total != rowTotal || unrouted != rows[0] || claimed != rows[1]) {
wrong.add("the " + label + " heading says " + total + " (" + unrouted + " unrouted, "
+ claimed + " claimed) but the rows under it are " + rowTotal + " ("
+ rows[0] + " unrouted, " + rows[1] + " claimed): " + line);
}
}
}
private static final String HANDLERS_ROOT = "src/main/java/io/github/hectorvent/floci/services/";
/**
@@ -137,8 +112,6 @@ class AwsQueryActionRoutingParityTest {
Map.entry("elasticbeanstalk", "2010-12-01"),
Map.entry("redshift", "2012-12-01"));
private static final Path KNOWN_GAPS = Path.of("src/test/resources/query-routing-known-gaps.tsv");
/**
* A {@code case} arm's label list, which may carry several names and may wrap across lines.
* Only quoted labels are taken, so a {@code case} on an enum constant contributes nothing.
@@ -147,23 +120,14 @@ class AwsQueryActionRoutingParityTest {
Pattern.compile("case\\s+((?:\"[A-Za-z0-9]+\"\\s*,?\\s*)+)\\s*(?:->|:)");
private static final Pattern QUOTED_LABEL = Pattern.compile("\"([A-Za-z0-9]+)\"");
/** {@code # 189 entries: 171 unrouted, 18 claimed by another service.} */
private static final Pattern TOTAL_HEADING = Pattern.compile(
"^#\\s*(\\d+) entries: (\\d+) unrouted, (\\d+) claimed by another service\\.?$");
/** {@code # autoscaling: 17 (13 unrouted, 4 claimed elsewhere)} */
private static final Pattern SERVICE_HEADING = Pattern.compile(
"^#\\s*([a-z0-9-]+): (\\d+) \\((\\d+) unrouted, (\\d+) claimed elsewhere\\)$");
@Test
void everyDispatchedActionRoutesToItsOwnService() throws IOException {
Set<String> known = knownGaps();
List<String> unexpected = new ArrayList<>();
for (QueryHandler handler : HANDLERS) {
for (String action : dispatchedActions(handler)) {
String reached = reached(handler, action);
if (!handler.service().equals(reached)
&& !known.contains(gapKey(handler.service(), action, reached))) {
if (!handler.service().equals(reached)) {
unexpected.add(handler.service() + " dispatches " + action
+ " but a request for it reaches " + reached);
}
@@ -173,9 +137,9 @@ class AwsQueryActionRoutingParityTest {
assertTrue(unexpected.isEmpty(),
"An action a handler dispatches has to route to that handler, or a request without "
+ "a credential scope answers in the wrong namespace and is authorized "
+ "under it too. Add the name to its service's set in AwsQueryController; "
+ "a name another service also defines is then told apart by the request's "
+ "Version. New: " + unexpected);
+ "under it too. A name the service's botocore model defines comes in with "
+ "'make aws-data-sync'; one no model defines is added to its service in "
+ "AwsQueryController.QUERY_SERVICES. New: " + unexpected);
}
/**
@@ -187,15 +151,13 @@ class AwsQueryActionRoutingParityTest {
*/
@Test
void withoutAVersionEveryActionReachesAServiceThatDispatchesIt() throws IOException {
Set<String> known = knownGaps();
Map<String, Set<String>> dispatched = dispatchedByService();
List<String> unexpected = new ArrayList<>();
for (QueryHandler handler : HANDLERS) {
for (String action : dispatchedActions(handler)) {
String reached = reachedWithoutVersion(action);
if (!dispatched.getOrDefault(reached, Set.of()).contains(action)
&& !known.contains(gapKey(handler.service(), action, reached))) {
if (!dispatched.getOrDefault(reached, Set.of()).contains(action)) {
unexpected.add(handler.service() + " dispatches " + action
+ " but without a Version a request for it reaches " + reached);
}
@@ -204,39 +166,35 @@ class AwsQueryActionRoutingParityTest {
assertTrue(unexpected.isEmpty(),
"Without a Version an action has to reach a service that dispatches it, or the "
+ "request answers UnsupportedOperation in a namespace it was never for. "
+ "A set in AwsQueryController claims a name its handler does not "
+ "dispatch, ahead of the service that does: " + unexpected);
+ "request answers UnsupportedOperation from a service that does not serve "
+ "it. A service tried earlier defines the name too: name the one that "
+ "dispatches it in AwsQueryController.UNVERSIONED_OWNERS. " + unexpected);
}
/**
* The other direction, which is what keeps the list honest: once a gap is fixed its line has to
* go, or the file slowly stops describing the tree and a later regression hides behind a stale
* entry.
* An entry in {@code UNVERSIONED_OWNERS} only decides between services that all define the
* name, so it has to name one of them, and the name has to have more than one: an owner that
* does not define the name sends a request where it can never be served, and a name only one
* service defines needs no owner.
*/
@Test
void theKnownGapListHasNoStaleEntries() throws IOException {
Map<String, Set<String>> dispatched = dispatchedByService();
Set<String> live = new LinkedHashSet<>();
for (QueryHandler handler : HANDLERS) {
for (String action : dispatchedActions(handler)) {
String reached = reached(handler, action);
if (!handler.service().equals(reached)) {
live.add(gapKey(handler.service(), action, reached));
}
String reachedWithoutVersion = reachedWithoutVersion(action);
if (!dispatched.getOrDefault(reachedWithoutVersion, Set.of()).contains(action)) {
live.add(gapKey(handler.service(), action, reachedWithoutVersion));
void everyUnversionedOwnerIsOneOfTheServicesThatDefineTheName() {
List<String> wrong = new ArrayList<>();
AwsQueryController.UNVERSIONED_OWNERS.forEach((action, owner) -> {
List<String> definers = new ArrayList<>();
for (Map.Entry<String, String> service : API_VERSIONS.entrySet()) {
if (service.getKey().equals(AwsQueryController.inferServiceFromAction(action, service.getValue()))) {
definers.add(service.getKey());
}
}
}
if (!definers.contains(owner)) {
wrong.add(action + " is owned by " + owner + ", which does not define it; " + definers + " do");
} else if (definers.size() < 2) {
wrong.add(action + " is defined only by " + definers + ", so it needs no owner");
}
});
List<String> stale = new ArrayList<>(knownGaps());
stale.removeAll(live);
assertTrue(stale.isEmpty(),
"These are listed as known routing gaps but route correctly now, so the lines "
+ "should come out of " + KNOWN_GAPS + ": " + stale);
assertTrue(wrong.isEmpty(), "AwsQueryController.UNVERSIONED_OWNERS: " + wrong);
}
/**
@@ -264,77 +222,6 @@ class AwsQueryActionRoutingParityTest {
+ "Unregistered: " + unregistered);
}
/**
* The headings in the gap file count the rows under them, and a fix that removes rows makes
* them wrong. They are worth keeping, because the scale and the split between the two kinds of
* gap are the first thing a reader wants, so the test keeps them honest instead.
*
* <p>Every heading is checked, not just the total: a per-service fix is exactly the change that
* invalidates its own service heading. The headings must also be present, so deleting one
* cannot make this pass by having nothing left to compare.
*
* <p>The file is walked in order, so a service heading is held to the rows physically below it,
* up to the next heading, rather than to its service's rows wherever they sit. Each row has to
* sit under its own service's heading, and a service gets one heading, so a misplaced row or a
* section split in two fails even when every service's overall count still adds up.
*/
@Test
void theKnownGapHeadingsCountTheRowsBelowThem() throws IOException {
List<String> wrong = new ArrayList<>();
Set<String> headed = new TreeSet<>();
int[] allRows = new int[2];
GapHeading total = null;
GapHeading section = null;
int[] sectionRows = new int[2];
for (String raw : Files.readAllLines(KNOWN_GAPS)) {
String line = raw.strip();
Matcher totalHeading = TOTAL_HEADING.matcher(line);
Matcher serviceHeading = SERVICE_HEADING.matcher(line);
if (totalHeading.matches()) {
if (total != null) {
wrong.add("the total heading appears twice: " + line);
}
total = GapHeading.of("total", totalHeading, 1);
} else if (serviceHeading.matches()) {
if (section != null) {
section.check(sectionRows, wrong);
}
section = GapHeading.of(serviceHeading.group(1), serviceHeading, 2);
sectionRows = new int[2];
if (!headed.add(section.label())) {
wrong.add("the " + section.label() + " heading appears twice, splitting its rows: " + line);
}
} else if (!line.isEmpty() && !line.startsWith("#")) {
String[] columns = line.split("\t");
int column = "sqs".equals(columns[2]) ? 0 : 1;
allRows[column]++;
if (section == null) {
wrong.add(line + " comes before any service heading");
} else {
sectionRows[column]++;
if (!section.label().equals(columns[0])) {
wrong.add(line + " sits under the " + section.label() + " heading, not its own");
}
}
}
}
if (section != null) {
section.check(sectionRows, wrong);
}
if (total == null) {
wrong.add("the total heading is missing, so nothing states the overall count");
} else {
total.check(allRows, wrong);
}
assertTrue(wrong.isEmpty(),
"A heading in " + KNOWN_GAPS + " no longer counts the rows under it, or a row is not "
+ "under its own service's heading. Removing a gap means updating the heading "
+ "that counted it, including the total. " + wrong);
}
/**
* Where an unsigned request for the action goes, carrying the handler's own {@code Version} the
* way every Query client sends it.
@@ -363,23 +250,6 @@ class AwsQueryActionRoutingParityTest {
return dispatched;
}
/** One line of the known-gap file: the service, the action, and what it reaches instead. */
private static String gapKey(String service, String action, String reached) {
return service + "\t" + action + "\t" + reached;
}
private static Set<String> knownGaps() throws IOException {
Set<String> gaps = new LinkedHashSet<>();
for (String line : Files.readAllLines(KNOWN_GAPS)) {
String trimmed = line.strip();
if (trimmed.isEmpty() || trimmed.startsWith("#")) {
continue;
}
gaps.add(trimmed);
}
return gaps;
}
/**
* The action names a handler dispatches, read from its own dispatch switch and nothing else.
*
@@ -1,210 +0,0 @@
# Query actions that a handler dispatches but routing does not send to that handler.
#
# Columns: service, action, service it reaches instead.
#
# Routing only matters when a request arrives without a usable credential scope, since
# otherwise the service comes from the SigV4 scope. On that path there is the action name
# and the Version the request declares, and AwsQueryServiceResolver backs
# IamEnforcementFilter too, so an entry here is also authorized under the wrong namespace.
#
# Every entry is a name missing from its own service's routing set, and adding it there
# is the fix, as #5032 did for IAM. The third column only says where the request goes
# meanwhile: sqs when no set holds the name, since that is the default, or the service
# whose set does. A name two services define needs nothing more than being in both sets,
# because the Version a request carries decides between them.
#
# A request without a Version, which only a hand-rolled client sends, is the one other
# way to land here. A name two services define then goes to the one tried first, which
# is a gap when that one does not handle the name.
#
# 170 entries: 170 unrouted, 0 claimed by another service.
#
# Shrink this file, never grow it. Removing a line is the point; adding one needs a
# reason in the PR that adds it. AwsQueryActionRoutingParityTest fails on an entry that
# is no longer a gap, so a fix cannot leave the list stale.
# autoscaling: 13 (13 unrouted, 0 claimed elsewhere)
autoscaling AttachTrafficSources sqs
autoscaling DeleteScheduledAction sqs
autoscaling DeleteWarmPool sqs
autoscaling DescribeScheduledActions sqs
autoscaling DescribeTrafficSources sqs
autoscaling DescribeWarmPool sqs
autoscaling DetachTrafficSources sqs
autoscaling PutScheduledUpdateGroupAction sqs
autoscaling PutWarmPool sqs
autoscaling ResumeProcesses sqs
autoscaling SetInstanceHealth sqs
autoscaling SetInstanceProtection sqs
autoscaling SuspendProcesses sqs
# cloudformation: 3 (3 unrouted, 0 claimed elsewhere)
cloudformation ActivateOrganizationsAccess sqs
cloudformation DescribeOrganizationsAccess sqs
cloudformation ListStackSetAutoDeploymentTargets sqs
# ec2: 82 (82 unrouted, 0 claimed elsewhere)
ec2 AcceptVpcPeeringConnection sqs
ec2 AllocateHosts sqs
ec2 AllocateIpamPoolCidr sqs
ec2 AssociateIamInstanceProfile sqs
ec2 AssociateIpamByoasn sqs
ec2 AssociateTransitGatewayRouteTable sqs
ec2 AttachNetworkInterface sqs
ec2 CancelSpotInstanceRequests sqs
ec2 CreateIpam sqs
ec2 CreateIpamPool sqs
ec2 CreateManagedPrefixList sqs
ec2 CreateNetworkInterface sqs
ec2 CreateTransitGateway sqs
ec2 CreateTransitGatewayRoute sqs
ec2 CreateTransitGatewayRouteTable sqs
ec2 CreateTransitGatewayVpcAttachment sqs
ec2 CreateVpcPeeringConnection sqs
ec2 DeleteIpam sqs
ec2 DeleteIpamPool sqs
ec2 DeleteManagedPrefixList sqs
ec2 DeleteNetworkInterface sqs
ec2 DeleteTransitGateway sqs
ec2 DeleteTransitGatewayRoute sqs
ec2 DeleteTransitGatewayRouteTable sqs
ec2 DeleteTransitGatewayVpcAttachment sqs
ec2 DeleteVpcPeeringConnection sqs
ec2 DescribeHosts sqs
ec2 DescribeInstanceCreditSpecifications sqs
ec2 DescribeIpamByoasn sqs
ec2 DescribeIpamPools sqs
ec2 DescribeIpamScopes sqs
ec2 DescribeIpams sqs
ec2 DescribeManagedPrefixLists sqs
ec2 DescribeSpotInstanceRequests sqs
ec2 DescribeTransitGatewayAttachments sqs
ec2 DescribeTransitGatewayConnects sqs
ec2 DescribeTransitGatewayRouteTables sqs
ec2 DescribeTransitGatewayVpcAttachments sqs
ec2 DescribeTransitGateways sqs
ec2 DescribeVolumesModifications sqs
ec2 DescribeVpcPeeringConnections sqs
ec2 DescribeVpnGateways sqs
ec2 DetachNetworkInterface sqs
ec2 DisableEbsEncryptionByDefault sqs
ec2 DisableIpamOrganizationAdminAccount sqs
ec2 DisableTransitGatewayRouteTablePropagation sqs
ec2 DisassociateIamInstanceProfile sqs
ec2 DisassociateIpamByoasn sqs
ec2 DisassociateTransitGatewayRouteTable sqs
ec2 EnableEbsEncryptionByDefault sqs
ec2 EnableIpamOrganizationAdminAccount sqs
ec2 EnableTransitGatewayRouteTablePropagation sqs
ec2 ExportTransitGatewayRoutes sqs
ec2 GetEbsDefaultKmsKeyId sqs
ec2 GetEbsEncryptionByDefault sqs
ec2 GetIpamPoolAllocations sqs
ec2 GetIpamPoolCidrs sqs
ec2 GetManagedPrefixListEntries sqs
ec2 GetSecurityGroupsForVpc sqs
ec2 GetTransitGatewayRouteTableAssociations sqs
ec2 GetTransitGatewayRouteTablePropagations sqs
ec2 ModifyEbsDefaultKmsKeyId sqs
ec2 ModifyHosts sqs
ec2 ModifyInstanceMetadataOptions sqs
ec2 ModifyIpam sqs
ec2 ModifyIpamPool sqs
ec2 ModifyManagedPrefixList sqs
ec2 ModifyTransitGateway sqs
ec2 ModifyTransitGatewayVpcAttachment sqs
ec2 ModifyVolume sqs
ec2 ModifyVpcEndpoint sqs
ec2 ModifyVpcPeeringConnectionOptions sqs
ec2 MonitorInstances sqs
ec2 ProvisionIpamPoolCidr sqs
ec2 ReleaseHosts sqs
ec2 ReleaseIpamPoolAllocation sqs
ec2 ReplaceIamInstanceProfileAssociation sqs
ec2 ReplaceTransitGatewayRoute sqs
ec2 RequestSpotInstances sqs
ec2 ResetEbsDefaultKmsKeyId sqs
ec2 SearchTransitGatewayRoutes sqs
ec2 UnmonitorInstances sqs
# elasticache: 12 (12 unrouted, 0 claimed elsewhere)
elasticache CreateCacheCluster sqs
elasticache CreateCacheParameterGroup sqs
elasticache CreateCacheSubnetGroup sqs
elasticache DeleteCacheCluster sqs
elasticache DeleteCacheParameterGroup sqs
elasticache DeleteCacheSubnetGroup sqs
elasticache DescribeCacheClusters sqs
elasticache DescribeCacheParameterGroups sqs
elasticache DescribeCacheParameters sqs
elasticache DescribeCacheSubnetGroups sqs
elasticache ModifyCacheParameterGroup sqs
elasticache ModifyCacheSubnetGroup sqs
# elasticloadbalancing: 3 (3 unrouted, 0 claimed elsewhere)
elasticloadbalancing DescribeCapacityReservation sqs
elasticloadbalancing DescribeListenerAttributes sqs
elasticloadbalancing ModifyListenerAttributes sqs
# email: 1 (1 unrouted, 0 claimed elsewhere)
email UpdateAccountSendingEnabled sqs
# rds: 47 (47 unrouted, 0 claimed elsewhere)
rds AddSourceIdentifierToSubscription sqs
rds CopyDBClusterParameterGroup sqs
rds CopyDBClusterSnapshot sqs
rds CopyDBParameterGroup sqs
rds CopyDBSnapshot sqs
rds CopyOptionGroup sqs
rds CreateDBClusterEndpoint sqs
rds CreateDBClusterSnapshot sqs
rds CreateDBInstanceReadReplica sqs
rds CreateDBSnapshot sqs
rds CreateEventSubscription sqs
rds CreateGlobalCluster sqs
rds DeleteDBClusterEndpoint sqs
rds DeleteDBClusterSnapshot sqs
rds DeleteDBSnapshot sqs
rds DeleteEventSubscription sqs
rds DeleteGlobalCluster sqs
rds DescribeDBClusterEndpoints sqs
rds DescribeDBClusterSnapshotAttributes sqs
rds DescribeDBSnapshotAttributes sqs
rds DescribeEventSubscriptions sqs
rds DescribeEvents sqs
rds FailoverDBCluster sqs
rds FailoverGlobalCluster sqs
rds ModifyDBClusterEndpoint sqs
rds ModifyDBClusterSnapshotAttribute sqs
rds ModifyDBSnapshot sqs
rds ModifyDBSnapshotAttribute sqs
rds ModifyEventSubscription sqs
rds ModifyGlobalCluster sqs
rds PromoteReadReplica sqs
rds PromoteReadReplicaDBCluster sqs
rds RebootDBCluster sqs
rds RemoveFromGlobalCluster sqs
rds RemoveSourceIdentifierFromSubscription sqs
rds ResetDBClusterParameterGroup sqs
rds ResetDBParameterGroup sqs
rds RestoreDBClusterFromSnapshot sqs
rds RestoreDBClusterToPointInTime sqs
rds RestoreDBInstanceFromDBSnapshot sqs
rds RestoreDBInstanceToPointInTime sqs
rds StartDBCluster sqs
rds StartDBInstance sqs
rds StopDBCluster sqs
rds StopDBInstance sqs
rds SwitchoverGlobalCluster sqs
rds SwitchoverReadReplica sqs
# redshift: 9 (9 unrouted, 0 claimed elsewhere)
redshift CreateIntegration sqs
redshift DeleteIntegration sqs
redshift DescribeClusterVersions sqs
redshift DescribeIntegrations sqs
redshift DescribeLoggingStatus sqs
redshift DescribeOrderableClusterOptions sqs
redshift DisableLogging sqs
redshift EnableLogging sqs
redshift ModifyClusterIamRoles sqs
1 # Query actions that a handler dispatches but routing does not send to that handler.
2 #
3 # Columns: service, action, service it reaches instead.
4 #
5 # Routing only matters when a request arrives without a usable credential scope, since
6 # otherwise the service comes from the SigV4 scope. On that path there is the action name
7 # and the Version the request declares, and AwsQueryServiceResolver backs
8 # IamEnforcementFilter too, so an entry here is also authorized under the wrong namespace.
9 #
10 # Every entry is a name missing from its own service's routing set, and adding it there
11 # is the fix, as #5032 did for IAM. The third column only says where the request goes
12 # meanwhile: sqs when no set holds the name, since that is the default, or the service
13 # whose set does. A name two services define needs nothing more than being in both sets,
14 # because the Version a request carries decides between them.
15 #
16 # A request without a Version, which only a hand-rolled client sends, is the one other
17 # way to land here. A name two services define then goes to the one tried first, which
18 # is a gap when that one does not handle the name.
19 #
20 # 170 entries: 170 unrouted, 0 claimed by another service.
21 #
22 # Shrink this file, never grow it. Removing a line is the point; adding one needs a
23 # reason in the PR that adds it. AwsQueryActionRoutingParityTest fails on an entry that
24 # is no longer a gap, so a fix cannot leave the list stale.
25 # autoscaling: 13 (13 unrouted, 0 claimed elsewhere)
26 autoscaling AttachTrafficSources sqs
27 autoscaling DeleteScheduledAction sqs
28 autoscaling DeleteWarmPool sqs
29 autoscaling DescribeScheduledActions sqs
30 autoscaling DescribeTrafficSources sqs
31 autoscaling DescribeWarmPool sqs
32 autoscaling DetachTrafficSources sqs
33 autoscaling PutScheduledUpdateGroupAction sqs
34 autoscaling PutWarmPool sqs
35 autoscaling ResumeProcesses sqs
36 autoscaling SetInstanceHealth sqs
37 autoscaling SetInstanceProtection sqs
38 autoscaling SuspendProcesses sqs
39 # cloudformation: 3 (3 unrouted, 0 claimed elsewhere)
40 cloudformation ActivateOrganizationsAccess sqs
41 cloudformation DescribeOrganizationsAccess sqs
42 cloudformation ListStackSetAutoDeploymentTargets sqs
43 # ec2: 82 (82 unrouted, 0 claimed elsewhere)
44 ec2 AcceptVpcPeeringConnection sqs
45 ec2 AllocateHosts sqs
46 ec2 AllocateIpamPoolCidr sqs
47 ec2 AssociateIamInstanceProfile sqs
48 ec2 AssociateIpamByoasn sqs
49 ec2 AssociateTransitGatewayRouteTable sqs
50 ec2 AttachNetworkInterface sqs
51 ec2 CancelSpotInstanceRequests sqs
52 ec2 CreateIpam sqs
53 ec2 CreateIpamPool sqs
54 ec2 CreateManagedPrefixList sqs
55 ec2 CreateNetworkInterface sqs
56 ec2 CreateTransitGateway sqs
57 ec2 CreateTransitGatewayRoute sqs
58 ec2 CreateTransitGatewayRouteTable sqs
59 ec2 CreateTransitGatewayVpcAttachment sqs
60 ec2 CreateVpcPeeringConnection sqs
61 ec2 DeleteIpam sqs
62 ec2 DeleteIpamPool sqs
63 ec2 DeleteManagedPrefixList sqs
64 ec2 DeleteNetworkInterface sqs
65 ec2 DeleteTransitGateway sqs
66 ec2 DeleteTransitGatewayRoute sqs
67 ec2 DeleteTransitGatewayRouteTable sqs
68 ec2 DeleteTransitGatewayVpcAttachment sqs
69 ec2 DeleteVpcPeeringConnection sqs
70 ec2 DescribeHosts sqs
71 ec2 DescribeInstanceCreditSpecifications sqs
72 ec2 DescribeIpamByoasn sqs
73 ec2 DescribeIpamPools sqs
74 ec2 DescribeIpamScopes sqs
75 ec2 DescribeIpams sqs
76 ec2 DescribeManagedPrefixLists sqs
77 ec2 DescribeSpotInstanceRequests sqs
78 ec2 DescribeTransitGatewayAttachments sqs
79 ec2 DescribeTransitGatewayConnects sqs
80 ec2 DescribeTransitGatewayRouteTables sqs
81 ec2 DescribeTransitGatewayVpcAttachments sqs
82 ec2 DescribeTransitGateways sqs
83 ec2 DescribeVolumesModifications sqs
84 ec2 DescribeVpcPeeringConnections sqs
85 ec2 DescribeVpnGateways sqs
86 ec2 DetachNetworkInterface sqs
87 ec2 DisableEbsEncryptionByDefault sqs
88 ec2 DisableIpamOrganizationAdminAccount sqs
89 ec2 DisableTransitGatewayRouteTablePropagation sqs
90 ec2 DisassociateIamInstanceProfile sqs
91 ec2 DisassociateIpamByoasn sqs
92 ec2 DisassociateTransitGatewayRouteTable sqs
93 ec2 EnableEbsEncryptionByDefault sqs
94 ec2 EnableIpamOrganizationAdminAccount sqs
95 ec2 EnableTransitGatewayRouteTablePropagation sqs
96 ec2 ExportTransitGatewayRoutes sqs
97 ec2 GetEbsDefaultKmsKeyId sqs
98 ec2 GetEbsEncryptionByDefault sqs
99 ec2 GetIpamPoolAllocations sqs
100 ec2 GetIpamPoolCidrs sqs
101 ec2 GetManagedPrefixListEntries sqs
102 ec2 GetSecurityGroupsForVpc sqs
103 ec2 GetTransitGatewayRouteTableAssociations sqs
104 ec2 GetTransitGatewayRouteTablePropagations sqs
105 ec2 ModifyEbsDefaultKmsKeyId sqs
106 ec2 ModifyHosts sqs
107 ec2 ModifyInstanceMetadataOptions sqs
108 ec2 ModifyIpam sqs
109 ec2 ModifyIpamPool sqs
110 ec2 ModifyManagedPrefixList sqs
111 ec2 ModifyTransitGateway sqs
112 ec2 ModifyTransitGatewayVpcAttachment sqs
113 ec2 ModifyVolume sqs
114 ec2 ModifyVpcEndpoint sqs
115 ec2 ModifyVpcPeeringConnectionOptions sqs
116 ec2 MonitorInstances sqs
117 ec2 ProvisionIpamPoolCidr sqs
118 ec2 ReleaseHosts sqs
119 ec2 ReleaseIpamPoolAllocation sqs
120 ec2 ReplaceIamInstanceProfileAssociation sqs
121 ec2 ReplaceTransitGatewayRoute sqs
122 ec2 RequestSpotInstances sqs
123 ec2 ResetEbsDefaultKmsKeyId sqs
124 ec2 SearchTransitGatewayRoutes sqs
125 ec2 UnmonitorInstances sqs
126 # elasticache: 12 (12 unrouted, 0 claimed elsewhere)
127 elasticache CreateCacheCluster sqs
128 elasticache CreateCacheParameterGroup sqs
129 elasticache CreateCacheSubnetGroup sqs
130 elasticache DeleteCacheCluster sqs
131 elasticache DeleteCacheParameterGroup sqs
132 elasticache DeleteCacheSubnetGroup sqs
133 elasticache DescribeCacheClusters sqs
134 elasticache DescribeCacheParameterGroups sqs
135 elasticache DescribeCacheParameters sqs
136 elasticache DescribeCacheSubnetGroups sqs
137 elasticache ModifyCacheParameterGroup sqs
138 elasticache ModifyCacheSubnetGroup sqs
139 # elasticloadbalancing: 3 (3 unrouted, 0 claimed elsewhere)
140 elasticloadbalancing DescribeCapacityReservation sqs
141 elasticloadbalancing DescribeListenerAttributes sqs
142 elasticloadbalancing ModifyListenerAttributes sqs
143 # email: 1 (1 unrouted, 0 claimed elsewhere)
144 email UpdateAccountSendingEnabled sqs
145 # rds: 47 (47 unrouted, 0 claimed elsewhere)
146 rds AddSourceIdentifierToSubscription sqs
147 rds CopyDBClusterParameterGroup sqs
148 rds CopyDBClusterSnapshot sqs
149 rds CopyDBParameterGroup sqs
150 rds CopyDBSnapshot sqs
151 rds CopyOptionGroup sqs
152 rds CreateDBClusterEndpoint sqs
153 rds CreateDBClusterSnapshot sqs
154 rds CreateDBInstanceReadReplica sqs
155 rds CreateDBSnapshot sqs
156 rds CreateEventSubscription sqs
157 rds CreateGlobalCluster sqs
158 rds DeleteDBClusterEndpoint sqs
159 rds DeleteDBClusterSnapshot sqs
160 rds DeleteDBSnapshot sqs
161 rds DeleteEventSubscription sqs
162 rds DeleteGlobalCluster sqs
163 rds DescribeDBClusterEndpoints sqs
164 rds DescribeDBClusterSnapshotAttributes sqs
165 rds DescribeDBSnapshotAttributes sqs
166 rds DescribeEventSubscriptions sqs
167 rds DescribeEvents sqs
168 rds FailoverDBCluster sqs
169 rds FailoverGlobalCluster sqs
170 rds ModifyDBClusterEndpoint sqs
171 rds ModifyDBClusterSnapshotAttribute sqs
172 rds ModifyDBSnapshot sqs
173 rds ModifyDBSnapshotAttribute sqs
174 rds ModifyEventSubscription sqs
175 rds ModifyGlobalCluster sqs
176 rds PromoteReadReplica sqs
177 rds PromoteReadReplicaDBCluster sqs
178 rds RebootDBCluster sqs
179 rds RemoveFromGlobalCluster sqs
180 rds RemoveSourceIdentifierFromSubscription sqs
181 rds ResetDBClusterParameterGroup sqs
182 rds ResetDBParameterGroup sqs
183 rds RestoreDBClusterFromSnapshot sqs
184 rds RestoreDBClusterToPointInTime sqs
185 rds RestoreDBInstanceFromDBSnapshot sqs
186 rds RestoreDBInstanceToPointInTime sqs
187 rds StartDBCluster sqs
188 rds StartDBInstance sqs
189 rds StopDBCluster sqs
190 rds StopDBInstance sqs
191 rds SwitchoverGlobalCluster sqs
192 rds SwitchoverReadReplica sqs
193 # redshift: 9 (9 unrouted, 0 claimed elsewhere)
194 redshift CreateIntegration sqs
195 redshift DeleteIntegration sqs
196 redshift DescribeClusterVersions sqs
197 redshift DescribeIntegrations sqs
198 redshift DescribeLoggingStatus sqs
199 redshift DescribeOrderableClusterOptions sqs
200 redshift DisableLogging sqs
201 redshift EnableLogging sqs
202 redshift ModifyClusterIamRoles sqs
+126
View File
@@ -0,0 +1,126 @@
#!/usr/bin/env python3
"""Regenerate src/main/resources/aws/query-services.json from botocore's models.
A Query request that arrives without a usable credential scope is routed by its `Action` and the
`Version` it declares (`AwsQueryController.inferServiceFromAction`), and IAM enforcement authorizes
it under the service that routing picks. Routing therefore needs, for every Query service Floci
serves, the API versions its clients declare and every operation its model defines. This script
keeps exactly that, read from the service models, so a name a service defines reaches it whether or
not Floci implements it yet: an unimplemented one answers from the right service instead of falling
through to SQS.
Which services there are, and which botocore models each one serves, is Floci's choice and stays in
SERVICES below: the protocol field cannot pick them (SQS's model is JSON only now, CloudWatch lists
three protocols), RDS's scope also serves DocumentDB and Neptune, and Elastic Load Balancing serves
both of its APIs. The order the services are tried in is `AwsQueryController`'s.
The models are botocore's `<model>/<apiVersion>/service-2.json` (Apache-2.0,
https://github.com/boto/botocore), the latest API version of each. They are located, in order, at
`--botocore-data`, the `local/aws/botocore` checkout, then the installed `botocore` package, which
`requirements.txt` pins so CI regenerates the same bytes.
Run from anywhere in the repo:
python3 tools/aws/regen_query_services.py # rewrite the vendored file in place
python3 tools/aws/regen_query_services.py --check # exit 1 when the vendored file is stale
"""
from __future__ import annotations
import argparse
import gzip
import json
import sys
from pathlib import Path
from regen_partitions import resolve_botocore_data, strip_source
REPO_ROOT = Path(__file__).resolve().parents[2]
OUTPUT = REPO_ROOT / "src/main/resources/aws/query-services.json"
# Floci's Query service name, as the credential scope names it, and the botocore models it serves.
SERVICES: dict[str, tuple[str, ...]] = {
"autoscaling": ("autoscaling",),
"cloudformation": ("cloudformation",),
"ec2": ("ec2",),
"elasticache": ("elasticache",),
"elasticbeanstalk": ("elasticbeanstalk",),
"elasticloadbalancing": ("elbv2", "elb"),
"email": ("ses",),
"iam": ("iam",),
"monitoring": ("cloudwatch",),
"rds": ("rds", "docdb", "neptune"),
"redshift": ("redshift",),
"sns": ("sns",),
"sqs": ("sqs",),
"sts": ("sts",),
}
def latest_model_dir(data: Path, model: str) -> Path:
"""The model's directory for its latest API version, which is what current SDKs send."""
versions = sorted(path for path in (data / model).iterdir() if path.is_dir())
if not versions:
raise SystemExit(f"error: no API version of {model} under {data}")
return versions[-1]
def load_model(directory: Path) -> dict:
plain = directory / "service-2.json"
if plain.exists():
return json.loads(plain.read_text(encoding="utf-8"))
compressed = plain.with_name(plain.name + ".gz")
if compressed.exists():
with gzip.open(compressed, "rt", encoding="utf-8") as f:
return json.load(f)
raise SystemExit(f"error: {plain} not found")
def build(models: dict[str, list[dict]], provenance: str) -> dict:
"""The vendored document from each service's loaded models."""
services = {}
for name in sorted(models):
versions = sorted({model["metadata"]["apiVersion"] for model in models[name]})
operations = sorted({operation for model in models[name] for operation in model["operations"]})
services[name] = {"apiVersions": versions, "operations": operations}
return {
"_source": {
"generator": "tools/aws/regen_query_services.py",
"botocore": provenance,
},
"services": services,
}
def load_models(data: Path) -> dict[str, list[dict]]:
return {name: [load_model(latest_model_dir(data, model)) for model in models]
for name, models in SERVICES.items()}
def render(doc: dict) -> str:
return json.dumps(doc, indent=2, sort_keys=False) + "\n"
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")
parser.add_argument("--output", type=Path, default=OUTPUT, help=argparse.SUPPRESS)
args = parser.parse_args(argv)
data, provenance = resolve_botocore_data(args.botocore_data)
fresh = render(build(load_models(data), provenance))
if args.check:
current = args.output.read_text(encoding="utf-8") if args.output.exists() else ""
if strip_source(current) != strip_source(fresh):
print(f"{args.output} is stale (generated from {provenance}).", file=sys.stderr)
return 1
return 0
args.output.write_text(fresh, encoding="utf-8")
shown = args.output.relative_to(REPO_ROOT) if args.output.is_relative_to(REPO_ROOT) else args.output
print(f"wrote {shown} from {provenance}")
return 0
if __name__ == "__main__":
sys.exit(main())
+64
View File
@@ -0,0 +1,64 @@
"""Tests for regen_query_services.
Run with: pytest tools/aws -q (or: make aws-data-test)
"""
from __future__ import annotations
import json
import regen_query_services as r
def model(api_version: str, *operations: str) -> dict:
return {"metadata": {"apiVersion": api_version}, "operations": {name: {} for name in operations}}
def test_a_service_gets_every_operation_and_version_of_its_models():
doc = r.build({
"rds": [model("2014-10-31", "CreateDBCluster", "DescribeEvents"),
model("2014-10-31", "CreateDBCluster", "CreateGlobalCluster")],
"elasticloadbalancing": [model("2015-12-01", "CreateLoadBalancer", "CreateTargetGroup"),
model("2012-06-01", "CreateLoadBalancer", "ConfigureHealthCheck")],
}, "botocore test")
assert doc["_source"] == {"generator": "tools/aws/regen_query_services.py", "botocore": "botocore test"}
assert doc["services"] == {
"elasticloadbalancing": {
"apiVersions": ["2012-06-01", "2015-12-01"],
"operations": ["ConfigureHealthCheck", "CreateLoadBalancer", "CreateTargetGroup"],
},
"rds": {
"apiVersions": ["2014-10-31"],
"operations": ["CreateDBCluster", "CreateGlobalCluster", "DescribeEvents"],
},
}
def test_the_latest_api_version_is_read(tmp_path):
for version in ("2014-09-01", "2016-11-15", "2015-10-01"):
(tmp_path / "ec2" / version).mkdir(parents=True)
assert r.latest_model_dir(tmp_path, "ec2").name == "2016-11-15"
def test_check_ignores_the_provenance_and_catches_a_changed_operation(tmp_path):
data = tmp_path / "data"
for name, models in r.SERVICES.items():
for index, botocore_model in enumerate(models):
directory = data / botocore_model / "2020-01-01"
directory.mkdir(parents=True, exist_ok=True)
(directory / "service-2.json").write_text(
json.dumps(model("2020-01-01", f"{name.title()}{index}")), encoding="utf-8")
output = tmp_path / "query-services.json"
assert r.main(["--botocore-data", str(data), "--output", str(output)]) == 0
assert r.main(["--check", "--botocore-data", str(data), "--output", str(output)]) == 0
stale = json.loads(output.read_text(encoding="utf-8"))
stale["_source"]["botocore"] = "another label"
output.write_text(json.dumps(stale), encoding="utf-8")
assert r.main(["--check", "--botocore-data", str(data), "--output", str(output)]) == 0
stale["services"]["sqs"]["operations"].append("Unlisted")
output.write_text(json.dumps(stale), encoding="utf-8")
assert r.main(["--check", "--botocore-data", str(data), "--output", str(output)]) == 1