mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(iam): derive the request resources without corrections (#8187)
The request-resources generator carried 106 CORRECTIONS over 22 namespaces, each a hand-written entry for one operation. They are gone, and no Floci service states what an operation acts on either: a service only looks up what it holds where an entry asks it to. Every operation the corrections covered is now read from botocore's shapes and documentation and the Service Reference, or, in two places, from a fix to the handler whose behavior the correction worked around. One table stays stated by hand, MEASURED, for what AWS was measured to check where neither botocore nor the Service Reference says it. The generator admits an entry only when it links to its measurement, names types the reference does not list for the action, and gives what the rules do not; review admits only real AWS evidence. It holds DynamoDB ListTables, on table/* (#7336's probes and AWS's recorded denial), and Step Functions SendTaskSuccess, SendTaskFailure and SendTaskHeartbeat, on the token's activity or state machine (#7277's probes and AWS's recorded denial). The generator's older hand tables (FOUND_BY, THROUGH, MINTED_IDS, UNQUALIFIED, QUALIFIED_MEMBERS, ID_TARGETS, CLIENTS_NOT_READ, READ_IN_HAND_BUILT) are unchanged. Generator rules: documentation naming the type fills it when it says the member is a name or an id as the variable is; an ARN head noun, or a name ending in ArnList, makes an ARN member; fields of a top-level structure and of the structures in a map are members; the id a create answers beside another type's ARN is that type's (RunJobFlow's JobFlowId and ClusterArn); an account-id member fills AccountId; a qualified member fills first, and a ResourceId variable is the type's own id, filled by a member named ResourceId before one named after the type. An ARN member whose pattern names another service, or which its documentation gives as the ARN of another type of the service, is not read unless named after a type the action acts on. Each SDK client's model is read apart, resources the clients disagree on carry their endpoint, and a v2 load balancer's type is picked by its Type enum and documented default. A variable no member fills is fixed to the one value of an enum named after it that the operation's name gives (CodePipeline's Custom action type owner), and a type named only by an optional member documented as holding what the operation is about is reached through that thing when the member is left out (EMR's ModifyInstanceGroups, through its instance groups). Reader and service changes: a member left out, or a JSON null, names the service's default where it has one (Athena's primary workgroup and AwsDataCatalog, EventBridge's default bus, per PutEvents entry); two types whose formats differ by one variable are told apart by whether the member names that default (EventBridge rules); a name for an id variable is found by the service (Rekognition stream processors, Logs deliveries); a bare id of the type an operation is about reaches the acted-on type through its service (the project CodeBuild holds a build under, the delivery destinations of the source a Logs DeleteDeliverySource deletes). A member given a JSON null names nothing, as the handlers read it, wherever the reader fills a variable from it, so an EMR ClusterId or an IAM Identity Center TargetId of null no longer names cluster/null or account/null. The table no longer has absent or before, and the reader refuses a resource key it does not know. Checks that change where the old correction had no evidence of AWS behind it: a Step Functions Local <stateMachineArn>#<test case> is checked as given; Macie CreateMember on member/*; IAM Identity Center ProvisionPermissionSet for ALL_PROVISIONED_ACCOUNTS on its instance and permission set alone, the request-scoped account pinning that served the account check removed; Logs DeleteDeliverySource on its delivery destinations; a CodeBuild build id of no build Floci holds on *. Handler fixes: Athena's ListDatabases, ListTableMetadata and GetTableMetadata read Glue whichever catalog was named, so they were also checked on AwsDataCatalog. They now refuse a catalog whose metadata is not the account's Glue Data Catalog with MetadataException and are checked on the catalog they name. Cost Explorer's cost reads ignored BillingViewArn, so they were checked on *. They now answer the primary billing view alone, refuse another with ResourceNotFoundException, and are checked on the view they name. The passed-roles table had drifted from the Service Reference and is regenerated. AWS now passes CreateTrainingSession's role to training-session.sagemaker alone, so its RoleArn is read rather than left unread for naming two services, and AWS lists Secrets Manager's new AssociateCrossAccountReplica, which the pinned botocore does not model yet. The generator now leaves an operation no pinned model has unread on its own, until a bump brings it in, in place of a hand-written entry for each, so the two there were are gone. The tag-on-create table had drifted too: AWS no longer lists a tagging action for Network Firewall's CreateProxy, CreateProxyConfiguration and CreateProxyRuleGroup, and lists five operations the pinned botocore does not model yet. It is regenerated.
This commit is contained in:
1 parent
fa9190e110
commit
58930c9278
40 files changed
+2358
-1153
No files matched your search
@@ -78,7 +78,11 @@ omitted, since the API reference does not document a default. The built-in
|
||||
`AwsDataCatalog` stays first, followed by registered catalogs in name order.
|
||||
`GetDataCatalog` requires `Name`; `ListDatabases`, `ListTableMetadata` and
|
||||
`GetTableMetadata` require `CatalogName`. Name `AwsDataCatalog` explicitly to
|
||||
read the built-in catalog.
|
||||
read the built-in catalog. Floci reads databases and tables from the account's
|
||||
Glue Data Catalog alone, so these three refuse a catalog whose metadata lives
|
||||
elsewhere, a `LAMBDA`, `HIVE` or `FEDERATED` one or a `GLUE` one registered for
|
||||
another account's `catalog-id`, with `MetadataException`, and a catalog that is
|
||||
not registered with `InvalidRequestException`.
|
||||
Pass the opaque `NextToken` to continue; final pages omit it. Tokens are scoped
|
||||
to the action, caller account, and request region and remain resumable after a
|
||||
cursor catalog is deleted. Malformed tokens, tokens outside the 1-to-1024
|
||||
|
||||
@@ -10,6 +10,13 @@ multiplied by the bundled AWS Pricing snapshot served by the
|
||||
so any test that mutates resources (e.g. creates a bucket, runs an instance)
|
||||
sees those changes in the next `GetCostAndUsage` call.
|
||||
|
||||
Floci answers the costs of the account as a whole, which AWS gives as the
|
||||
caller's primary billing view. AWS does not document that view's ARN, so Floci
|
||||
takes it as `arn:aws:billing::<account>:billingview/primary`. `GetCostAndUsage`, `GetCostAndUsageWithResources`, `GetDimensionValues`, `GetTags`
|
||||
and `GetCostCategories` accept that view or none in `BillingViewArn`, and refuse
|
||||
any other with `ResourceNotFoundException`, as AWS does for a view it does not
|
||||
hold. With IAM enforcement on, they are checked on the view they name.
|
||||
|
||||
## Supported Actions
|
||||
|
||||
<!-- floci:actions:start -->
|
||||
|
||||
@@ -149,8 +149,9 @@ configuration and does not deliver the source's logs.
|
||||
this account." (likewise for a Delivery Destination and a Delivery).
|
||||
- With IAM enforcement on, each action is authorized on the resources the AWS Service Authorization
|
||||
Reference lists for it: the source, destination or delivery it names, and for `CreateDelivery` the
|
||||
source, the destination and the new delivery; `DeleteDeliverySource` on the source it deletes. The
|
||||
Describe actions are authorized on `*`, as the reference lists no resource for them.
|
||||
source, the destination and the new delivery; `DeleteDeliverySource` on the delivery destinations the
|
||||
deliveries from the source it deletes send to, the type the reference lists for it, and on `*` for a source
|
||||
with none. The Describe actions are authorized on `*`, as the reference lists no resource for them.
|
||||
|
||||
Not modelled: delivery destination policies (`PutDeliveryDestinationPolicy` and its siblings), and
|
||||
record field defaults for sources other than an EventBridge event bus.
|
||||
|
||||
@@ -14,9 +14,9 @@ The listing is not filtered to the caller's individually authorized tables.
|
||||
This resource matching was checked against live AWS with isolated role sessions.
|
||||
Pagination and ignored table selectors do not change the collection being authorized.
|
||||
Other DynamoDB operations retain their own authorization resources.
|
||||
The generated IAM request-resource table records `ListTables` as a measured correction to
|
||||
the Service Reference. Other DynamoDB operations keep their existing resource builders,
|
||||
including batch, transaction and PartiQL table extraction.
|
||||
The Service Reference lists no resource type for the action, so the collection comes from that
|
||||
measurement, the one thing the generated table of request resources states by hand. Other DynamoDB
|
||||
operations keep their existing resource builders, including batch, transaction and PartiQL table extraction.
|
||||
|
||||
## Supported Actions
|
||||
|
||||
|
||||
+40
-27
@@ -1921,7 +1921,15 @@ Access Manager, CloudWatch Observability Access Manager, AWS Resource Explorer,
|
||||
Catalog, Amazon OpenSearch Service, IAM Access Analyzer, AWS Security Hub and Amazon GuardDuty they come from a table generated from AWS's Service Reference and botocore, `src/main/resources/aws/iam-request-resources.json`, which gives each
|
||||
operation's action, the resource types that action acts on with their ARN formats, and the request
|
||||
members that name them: a member holding a resource's ARN, which counts when it matches the format
|
||||
of a type the action acts on, or members filling the variables of a type's format. A member holding
|
||||
of a type the action acts on, or members filling the variables of a type's format. Nothing in it is
|
||||
stated by hand but what AWS was measured to check where neither botocore nor the Service Reference says
|
||||
it, each entry citing the measurement (a policy probe against real AWS, or AWS's own AccessDenied message
|
||||
naming the resource): DynamoDB's `ListTables` is checked on the literal `table/*` of the request's
|
||||
partition, Region and account, and Step Functions' `SendTaskSuccess`, `SendTaskFailure` and
|
||||
`SendTaskHeartbeat` on the activity or the unqualified state machine their task token belongs to, though
|
||||
the Service Reference lists no resource type for either. A service only looks up what it holds where the
|
||||
table asks it to (the resource a name finds, the one an id reaches, its default one); none says what an
|
||||
operation acts on. A member holding
|
||||
an ARN may be one inside a structure or inside each of a list's structures: `SetRulePriorities` is
|
||||
checked on the rules its `RulePriorities` name, and `CreateStateMachineAlias` on the state machine
|
||||
its routing configuration's versions are of. A variable the
|
||||
@@ -1937,30 +1945,36 @@ and answers with every repository, names no repository, and a number or a null a
|
||||
member whose botocore shape is an account id gives the account the type is in: ECR's `registryId`
|
||||
selects the registry its handler acts in, so `repository/<name>` is checked in that account, and a
|
||||
`registryId` that is no account id names no repository, while a null one is the caller's, as ECR
|
||||
reads it. `StartExecution` and
|
||||
`StartSyncExecution` take Step Functions Local's `<stateMachineArn>#<test case>` and run the
|
||||
machine before the `#`, so that machine is the one checked. `StartPipelineExecution` and
|
||||
reads it. Step Functions Local's `<stateMachineArn>#<test case>`, which `StartExecution` and
|
||||
`StartSyncExecution` take and run the machine before the `#` of, is checked as given: it is no ARN AWS has,
|
||||
and nothing botocore or the Service Reference says reads it otherwise, so a grant covering such executions
|
||||
names it (`stateMachine:<name>*`). `StartPipelineExecution` and
|
||||
`GetPipelineState` name their pipeline by a bare `name`, which is read as the pipeline's;
|
||||
`CreatePipeline` and `UpdatePipeline` by `pipeline.name`, not by `pipeline.roleArn`, which holds the
|
||||
role CodePipeline assumes; `PutWebhook` names the webhook by `webhook.name` and the pipeline it
|
||||
connects to by `webhook.targetPipeline`. A CodePipeline webhook is `webhook:<name>`, the ARN AWS
|
||||
gives it, and a custom action type `actiontype:Custom/<category>/<provider>/<version>`, its owner
|
||||
being `Custom`, which the request does not give. Cloud Map's `CreateService` is checked on the
|
||||
being `Custom`, which the request does not give and the operation's name gives as the one value of
|
||||
botocore's `ActionOwner` enum it is. Cloud Map's `CreateService` is checked on the
|
||||
namespace its `NamespaceId` names or, when it gives none or a JSON null, the one its
|
||||
`DnsConfig.NamespaceId` names, as Cloud Map reads them, and on the service it creates. A CodeBuild build is checked on its
|
||||
project, which its id names before its `:` (`<project>:<id>`), as CodeBuild authorizes
|
||||
`BatchGetBuilds`, `StopBuild`, `RetryBuild` and `BatchDeleteBuilds`. `CreateBudget` and `UpdateBudget`
|
||||
`DnsConfig.NamespaceId` names, as Cloud Map reads them, and on the service it creates. A CodeBuild build is checked on the
|
||||
project CodeBuild holds it under, as CodeBuild authorizes `BatchGetBuilds`, `StopBuild`, `RetryBuild` and
|
||||
`BatchDeleteBuilds`; an id of no build it holds names no project, as nothing botocore or the Service
|
||||
Reference says gives a build id's project, so such a request is checked on `*`. `CreateBudget` and `UpdateBudget`
|
||||
are checked on the budget their `Budget.BudgetName` or `NewBudget.BudgetName` names, and Cost and Usage
|
||||
Reports' `PutReportDefinition` and `ModifyReportDefinition` on the report their `ReportDefinition.ReportName`
|
||||
or `ReportName` names, not on the billing view ARN each may carry, which names no budget or report. An Athena request
|
||||
naming no workgroup is checked on `workgroup/primary`, where `StartQueryExecution` runs its query,
|
||||
`ListQueryExecutions` and `ListNamedQueries` list, and `GetWorkGroup` answers. Athena's
|
||||
`ListDatabases`, `ListTableMetadata` and `GetTableMetadata` are checked on the catalog their
|
||||
`CatalogName` names and on `datacatalog/AwsDataCatalog`, the Glue Data Catalog Floci reads whichever
|
||||
catalog they name, and a `GetDataCatalog` naming no catalog on `datacatalog/AwsDataCatalog`, the one it
|
||||
answers. Cost Explorer's cost and usage reads are checked on `*`, not on the billing view
|
||||
their `BillingViewArn` gives: Floci serves no billing views and answers the account's costs whichever
|
||||
one is named. Data Exports' `CreateExport` is not checked on the
|
||||
`CatalogName` names, and a `GetDataCatalog` naming no catalog on `datacatalog/AwsDataCatalog`, the one it
|
||||
answers. Floci reads their metadata from the account's Glue Data Catalog alone, so they refuse with
|
||||
`MetadataException` a catalog whose metadata is elsewhere, one of another type than `GLUE` or registered
|
||||
for another account's catalog, and read no catalog but the one checked. Cost Explorer's cost and usage
|
||||
reads are checked on the billing view their `BillingViewArn` gives, and on `*` when they give none.
|
||||
Floci answers the costs of the caller's primary billing view alone, which it takes as `billingview/primary`
|
||||
since AWS does not document that view's ARN, and refuses any other with `ResourceNotFoundException`, as AWS
|
||||
does a view it does not hold. Data Exports' `CreateExport` is not checked on the
|
||||
ARN its `Export.ExportArn` gives, which is the new export's own. CloudTrail's `StartLogging`,
|
||||
`StopLogging` and `GetTrailStatus` are checked on the trail their bare `Name` names, by name or by
|
||||
ARN, its tag operations on the resource whose ARN their `ResourceId` gives, and its dashboard
|
||||
@@ -1969,14 +1983,13 @@ Amazon EMR's requests naming a cluster by its job flow id, in `JobFlowId` or `Jo
|
||||
`cluster/<id>`, as when they name it by `ClusterId`, and `AddTags` and `RemoveTags` on the cluster their
|
||||
`ResourceId` names, the one Floci tags, not on one their `ClusterId` gives. A `ModifyInstanceGroups`
|
||||
naming its instance groups with no `ClusterId`, or a null one, is checked on the cluster each group is
|
||||
in, the one EMR finds it in. A Rekognition stream processor is checked on `streamprocessor/<name>`, the ARN its `Name`
|
||||
in, the one EMR finds it in, botocore documenting `ClusterId` as "the cluster to which the instance group
|
||||
belongs". A Rekognition stream processor is checked on `streamprocessor/<name>`, the ARN its `Name`
|
||||
gives. IAM Identity Center's `CreateAccountAssignment`, `DeleteAccountAssignment` and
|
||||
`ProvisionPermissionSet` are checked on the account their `TargetId` names, `account/<id>`, beside the
|
||||
instance and the permission set, and a `ProvisionPermissionSet` for `ALL_PROVISIONED_ACCOUNTS` on each
|
||||
account the permission set is provisioned to. AWS does not document which accounts such a request is
|
||||
authorized on, so checking each one it provisions is Floci's reading, and it provisions to the accounts it was
|
||||
checked on: one another request provisions the permission set to while it runs is left as that request
|
||||
left it. A permission set, an application or a trusted token issuer
|
||||
instance and the permission set. A `ProvisionPermissionSet` for `ALL_PROVISIONED_ACCOUNTS` names no
|
||||
account, and nothing botocore or the Service Reference says names the accounts it provisions to, so it is
|
||||
checked on its instance and permission set alone. A permission set, an application or a trusted token issuer
|
||||
a create makes has the id of the instance its `InstanceArn` names, `permissionSet/<instance id>/*`.
|
||||
Cost Explorer's `GetAnomalyMonitors` and `GetAnomalySubscriptions` are checked on each ARN their
|
||||
`MonitorArnList` or `SubscriptionArnList` gives, and Timestream for InfluxDB's `RebootDbCluster` on the
|
||||
@@ -2174,7 +2187,8 @@ Analyzer's analyzer operations, Security Hub's hub operations and GuardDuty's de
|
||||
table of request resources reading the resource they name. Every route Floci serves of AWS Lake
|
||||
Formation and Amazon Inspector is one AWS authorizes on no resource type, as is every one of Amazon Macie's but
|
||||
`CreateMember`, so those are checked by their routes alone. `CreateMember`, on `POST /members`, is checked on the
|
||||
member its `account.accountId` names, and needs `macie2:TagResource` when it carries tags. API Gateway's
|
||||
account's members, `member/*`, as nothing botocore or the Service Reference says names the member it makes by its
|
||||
`account.accountId`, and needs `macie2:TagResource` when it carries tags. API Gateway's
|
||||
routes are checked by their routes alone too, on the path Floci builds the ARN from, and the authorized
|
||||
actions list the operations AWS checks as the action their HTTP method names (above). A route whose action AWS checks on a
|
||||
resource Floci neither builds nor reads would not be checked, since checked on `*` a grant scoped to
|
||||
@@ -2416,13 +2430,12 @@ when the caller may not pass the role.
|
||||
`StartAutomationExecution`, Config `PutRemediationConfigurations`); one the Service Reference
|
||||
passes roles from to several services without saying which member goes where (EMR `RunJobFlow`,
|
||||
whose `JobFlowRole` also names an instance profile, EKS `UpdateClusterConfig`, CloudWatch Logs
|
||||
`CreateImportTask`, SageMaker `CreateTrainingSession`); one whose body is XML (S3
|
||||
`PutBucketReplication`); and one the botocore models Floci is pinned to do not have yet (SSM
|
||||
`RegisterDefaultHostManagementConfiguration`, Kinesis Analytics `ImportSnapshot`), whose role is
|
||||
read as soon as a release that has it is pinned, since the generator and its offline gate refuse
|
||||
that reason once the models carry the operation. EC2's `RequestSpotFleet` names its roles in
|
||||
EC2's own protocol, one of them as an instance profile. The REST services whose routes no rule
|
||||
maps yet, and API Gateway, which is authorized by HTTP method, are not read either.
|
||||
`CreateImportTask`); one whose body is XML (S3 `PutBucketReplication`); and one the botocore
|
||||
models Floci is pinned to do not have yet (SSM `RegisterDefaultHostManagementConfiguration`,
|
||||
Kinesis Analytics `ImportSnapshot`, Secrets Manager `AssociateCrossAccountReplica`), whose role
|
||||
the generator reads as soon as a release that has it is pinned. EC2's `RequestSpotFleet` names
|
||||
its roles in EC2's own protocol, one of them as an instance profile. The REST services whose
|
||||
routes no rule maps yet, and API Gateway, which is authorized by HTTP method, are not read either.
|
||||
|
||||
A request that names a Lambda network connector also needs `lambda:PassNetworkConnector` on it. The
|
||||
Lambda developer guide has "The caller must have `lambda:PassNetworkConnector` on the referenced
|
||||
|
||||
@@ -53,7 +53,12 @@ final class RequestResourceMembers {
|
||||
/** The one id a child type's format appends to its parent's. */
|
||||
private static final Pattern APPENDED_ID = Pattern.compile("[/:]\\$\\{\\w+}");
|
||||
/** The keys a resource found by members does not take: it is read no other way. */
|
||||
private static final List<String> FOUND_ONLY = List.of("absent", "arnOf", "fixed", "before");
|
||||
private static final List<String> FOUND_ONLY = List.of("arnOf", "fixed");
|
||||
/** The keys of a resource read from a member holding its ARN. */
|
||||
private static final Set<String> ARN_KEYS = Set.of("types", "arn", "made", "endpoint");
|
||||
/** The keys of a resource whose format's variables members fill, or its service finds by them. */
|
||||
private static final Set<String> FILL_KEYS = Set.of("type", "fill", "when", "unless", "arnOf", "account", "fixed",
|
||||
"made", "find", "endpoint", "default", "whenDefault", "unlessDefault");
|
||||
/** The keys of a resource named through a member naming another of its service's own: it is read no other way. */
|
||||
private static final Set<String> THROUGH_KEYS = Set.of("types", "through", "when", "endpoint");
|
||||
/** The keys of a resource its service acts on for a request naming none of it: it is read no other way. */
|
||||
@@ -133,19 +138,15 @@ final class RequestResourceMembers {
|
||||
* A resource a request names: by a member holding its ARN, which names a resource of one of {@code types} when
|
||||
* it matches the type's format, or by members filling the variables of one type's format, the others open,
|
||||
* only {@code when} each member named has one of its values and {@code unless} it has one of those, an empty
|
||||
* one for the member absent or given a JSON null it is not read as a value for, in the account an {@code account} member gives (ECR's {@code registryId}), or else
|
||||
* the request's. A member {@code absent} from the request, or given a JSON null, is read as the value given for
|
||||
* it (an EventBridge request naming no event bus names {@code default}), and one in {@code arnOf} may give an
|
||||
* ARN of the type named for it instead of its name, read as that type's one variable, the resource then in the
|
||||
* ARN's account and Region, or the caller's and the request's where the ARN leaves them empty. A member filling
|
||||
* a variable may be a field of each of a list's structures ({@code Entries[].EventBusName}), which names one
|
||||
* resource for each structure, read as {@code absent} gives for one that lacks it and in the account and Region
|
||||
* of the ARN that structure gives, if any. Such a member is in {@code absent} or {@code arnOf} only when it
|
||||
* fills a variable. A member filling a variable may also be a field of a structure ({@code pipeline.name}). A
|
||||
* variable no member gives may be {@code fixed} to the one value its handler uses (a CodePipeline custom action
|
||||
* type's owner, {@code Custom}). A member's value, an ARN or a variable's, is read up to the character
|
||||
* {@code before}, when there is one: Step Functions Local's handler drops a test case after {@code #}, and a
|
||||
* CodeBuild build id is {@code <project>:<id>}, a build being checked on its project. A create naming other
|
||||
* one for the member absent or given a JSON null, in the account an {@code account} member gives (ECR's
|
||||
* {@code registryId}), or else the request's. A member in {@code arnOf} may give an ARN of the type named for it
|
||||
* instead of its name, read as that type's one variable, the resource then in the ARN's account and Region, or the
|
||||
* caller's and the request's where the ARN leaves them empty. A member filling a variable may be a field of each
|
||||
* of a list's structures ({@code Entries[].EventBusName}), which names one resource for each structure, in the
|
||||
* account and Region of the ARN that structure gives, if any; a member is in {@code arnOf} only when it fills a
|
||||
* variable. A member filling a variable may also be a field of a structure ({@code pipeline.name}). A variable no
|
||||
* member gives may be {@code fixed} to the one value of its enum the operation's name gives (a CodePipeline
|
||||
* custom action type's owner, {@code Custom}). A create naming other
|
||||
* resources beside the one it makes marks that one {@code made}, where its tags go (a webhook, not the pipeline
|
||||
* it connects to). A type whose ARN is all an id its service mints is named instead by the members its service
|
||||
* finds it by, {@code find}, each one value, in the order its service reads them, filling none of its variables
|
||||
@@ -158,25 +159,34 @@ final class RequestResourceMembers {
|
||||
* instance group, by its {@code InstanceGroups[].InstanceGroupId}), {@code when} the request gives the values it
|
||||
* names, and read no other way. A resource {@code byDefault} is the one of its type its service acts on for a
|
||||
* request naming none of it, {@code when} the request leaves out the member that would (Resource Explorer's
|
||||
* {@code Search} with no {@code ViewArn}, on the Region's default view), read no other way.
|
||||
* {@code Search} with no {@code ViewArn}, on the Region's default view), read no other way. Of two types whose
|
||||
* formats differ by one variable a member fills, the one without it applies {@code whenDefault} that member is
|
||||
* absent or names its type's default resource, which the service gives, and the other {@code unlessDefault}: a
|
||||
* rule on EventBridge's default bus has no bus in its ARN. Each maps the member to that type.
|
||||
*/
|
||||
record Resource(List<String> types, Member arn, Map<String, Member> fill, Map<String, List<String>> when,
|
||||
Map<String, List<String>> unless, Map<String, String> absent, Map<String, String> arnOf,
|
||||
Member account, String before, Map<String, String> fixed, boolean made, List<Member> find,
|
||||
String endpoint, Member through, boolean byDefault) {
|
||||
Map<String, List<String>> unless, Map<String, String> arnOf, Member account,
|
||||
Map<String, String> fixed, boolean made, List<Member> find, String endpoint, Member through,
|
||||
boolean byDefault, Map<String, String> whenDefault, Map<String, String> unlessDefault) {
|
||||
|
||||
Resource(List<String> types, Member arn, Map<String, Member> fill, Map<String, List<String>> when,
|
||||
Map<String, List<String>> unless, Map<String, String> absent, Map<String, String> arnOf,
|
||||
Member account, String before, Map<String, String> fixed, boolean made, List<Member> find,
|
||||
String endpoint, Member through) {
|
||||
this(types, arn, fill, when, unless, absent, arnOf, account, before, fixed, made, find, endpoint, through,
|
||||
false);
|
||||
Map<String, List<String>> unless, Map<String, String> arnOf, Member account,
|
||||
Map<String, String> fixed, boolean made, List<Member> find, String endpoint, Member through,
|
||||
boolean byDefault) {
|
||||
this(types, arn, fill, when, unless, arnOf, account, fixed, made, find, endpoint, through, byDefault,
|
||||
Map.of(), Map.of());
|
||||
}
|
||||
|
||||
Resource(List<String> types, Member arn, Map<String, Member> fill, Map<String, List<String>> when,
|
||||
Map<String, List<String>> unless, Map<String, String> absent, Map<String, String> arnOf,
|
||||
Member account, String before, Map<String, String> fixed, boolean made, String endpoint) {
|
||||
this(types, arn, fill, when, unless, absent, arnOf, account, before, fixed, made, List.of(), endpoint, null);
|
||||
Map<String, List<String>> unless, Map<String, String> arnOf, Member account,
|
||||
Map<String, String> fixed, boolean made, List<Member> find, String endpoint, Member through) {
|
||||
this(types, arn, fill, when, unless, arnOf, account, fixed, made, find, endpoint, through, false);
|
||||
}
|
||||
|
||||
Resource(List<String> types, Member arn, Map<String, Member> fill, Map<String, List<String>> when,
|
||||
Map<String, List<String>> unless, Map<String, String> arnOf, Member account,
|
||||
Map<String, String> fixed, boolean made, String endpoint) {
|
||||
this(types, arn, fill, when, unless, arnOf, account, fixed, made, List.of(), endpoint, null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -384,10 +394,12 @@ final class RequestResourceMembers {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " serves a resource of " + operation
|
||||
+ " on no endpoint prefix");
|
||||
}
|
||||
String before = resource.has("before") ? resource.path("before").asText("") : null;
|
||||
if (before != null && before.length() != 1) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " reads a member for " + operation
|
||||
+ " before " + before + ", no one character");
|
||||
Set<String> keys = resource.has("through") ? THROUGH_KEYS : resource.has("arn") ? ARN_KEYS : FILL_KEYS;
|
||||
List<String> unknown = resource.properties().stream().map(Map.Entry::getKey)
|
||||
.filter(key -> !keys.contains(key)).toList();
|
||||
if (!unknown.isEmpty()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " gives a resource of " + operation + " " + unknown
|
||||
+ ", no key of its kind of resource");
|
||||
}
|
||||
if (resource.has("through")) {
|
||||
List<String> types = resource.path("types").valueStream().map(JsonNode::asText).toList();
|
||||
@@ -399,7 +411,7 @@ final class RequestResourceMembers {
|
||||
+ "members reading it otherwise");
|
||||
}
|
||||
return new Resource(types, null, Map.of(), values(operation, String.join(", ", types), resource.path("when")),
|
||||
Map.of(), Map.of(), Map.of(), null, null, Map.of(), false, List.of(), endpoint, through);
|
||||
Map.of(), Map.of(), null, Map.of(), false, List.of(), endpoint, through);
|
||||
}
|
||||
if (resource.has("arn")) {
|
||||
List<String> types = resource.path("types").valueStream().map(JsonNode::asText).toList();
|
||||
@@ -412,7 +424,7 @@ final class RequestResourceMembers {
|
||||
+ " and finds its resource by " + resource.path("find") + " too");
|
||||
}
|
||||
return new Resource(types, arnMember(operation, resource.path("arn").asText("")), Map.of(), Map.of(),
|
||||
Map.of(), Map.of(), Map.of(), null, before, Map.of(), made, endpoint);
|
||||
Map.of(), Map.of(), null, Map.of(), made, endpoint);
|
||||
}
|
||||
String type = resource.path("type").asText("");
|
||||
ArnFormat format = formats.get(type);
|
||||
@@ -461,15 +473,12 @@ final class RequestResourceMembers {
|
||||
+ " as its service's default, which is not for a request naming none");
|
||||
}
|
||||
Set<String> filled = Set.copyOf(fill.values().stream().map(Member::path).toList());
|
||||
Map<String, String> absent = new LinkedHashMap<>();
|
||||
resource.path("absent").properties().forEach(member -> {
|
||||
if (!readAsOne(operation, member.getKey(), filled) || !member.getValue().isTextual()
|
||||
|| member.getValue().asText().isEmpty()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " reads " + member.getKey() + " for " + operation
|
||||
+ " when absent as no value");
|
||||
}
|
||||
absent.put(member.getKey(), member.getValue().asText());
|
||||
});
|
||||
Map<String, String> whenDefault = defaultPair(operation, type, resource.path("whenDefault"), formats, null);
|
||||
Map<String, String> unlessDefault = defaultPair(operation, type, resource.path("unlessDefault"), formats, filled);
|
||||
if (!whenDefault.isEmpty() && !unlessDefault.isEmpty()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " names " + type + " for " + operation
|
||||
+ " both when and unless a member names its default");
|
||||
}
|
||||
Map<String, String> arnOf = new LinkedHashMap<>();
|
||||
resource.path("arnOf").properties().forEach(member -> {
|
||||
ArnFormat named = formats.get(member.getValue().asText(""));
|
||||
@@ -485,8 +494,37 @@ final class RequestResourceMembers {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " takes " + type + "'s account for " + operation
|
||||
+ " from " + account.name() + ", no member of one account or a type of none");
|
||||
}
|
||||
return new Resource(List.of(type), null, Map.copyOf(fill), when, unless, Map.copyOf(absent), Map.copyOf(arnOf),
|
||||
account, before, Map.copyOf(fixed), made, List.copyOf(find), endpoint, null, byDefault);
|
||||
return new Resource(List.of(type), null, Map.copyOf(fill), when, unless, Map.copyOf(arnOf), account,
|
||||
Map.copyOf(fixed), made, List.copyOf(find), endpoint, null, byDefault, whenDefault, unlessDefault);
|
||||
}
|
||||
|
||||
/**
|
||||
* A {@code whenDefault} or {@code unlessDefault}: one member and the type whose default it may name, a member the
|
||||
* resource fills for {@code unlessDefault} ({@code filled} given); empty when the resource has none.
|
||||
*/
|
||||
private static Map<String, String> defaultPair(String operation, String type, JsonNode pair,
|
||||
Map<String, ArnFormat> formats, Set<String> filled) {
|
||||
if (pair.isMissingNode()) {
|
||||
return Map.of();
|
||||
}
|
||||
if (!pair.isObject() || pair.size() != 1) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " names " + type + " for " + operation
|
||||
+ " by a default of no one member and type");
|
||||
}
|
||||
Map.Entry<String, JsonNode> entry = pair.properties().iterator().next();
|
||||
if (!formats.containsKey(entry.getValue().asText("")) || (filled != null && !filled.contains(entry.getKey()))) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " names " + type + " for " + operation + " by the default of "
|
||||
+ entry.getValue() + " " + entry.getKey() + " names, no type or no member it fills");
|
||||
}
|
||||
return Map.of(entry.getKey(), entry.getValue().asText());
|
||||
}
|
||||
|
||||
/**
|
||||
* A member of a request by its path, as {@code StoredResourceArns.actedOn} names one: {@code taskToken},
|
||||
* {@code account.accountId}, {@code InstanceGroups[].InstanceGroupId}.
|
||||
*/
|
||||
static Member selector(String path) {
|
||||
return arnMember("a service's selector", path);
|
||||
}
|
||||
|
||||
/** The values each member named in {@code when} or {@code unless} may have, an empty one for the member absent. */
|
||||
|
||||
@@ -59,7 +59,7 @@ public final class RequestResources {
|
||||
private RequestResources() {
|
||||
}
|
||||
|
||||
/** Whether the generated table owns this operation, including corrections to hand-built namespaces. */
|
||||
/** Whether the generated table owns this operation, including those of hand-built namespaces it reads. */
|
||||
public static boolean reads(String operation) {
|
||||
return operation != null && RequestResourceMembers.table().operations().containsKey(operation);
|
||||
}
|
||||
@@ -107,13 +107,14 @@ public final class RequestResources {
|
||||
}
|
||||
List<RequestResourceMembers.Resource> resources = operation == null ? null
|
||||
: served(table.operations().get(operation), ctx);
|
||||
if (resources == null || resources.isEmpty()) {
|
||||
if (resources == null) {
|
||||
return List.of();
|
||||
}
|
||||
Map<String, String> sent = IamConditionContextResolver.formParameters(ctx);
|
||||
JsonNode body = sent.isEmpty() ? located(table, operation, PassedRoles.jsonBody(ctx), ctx, labels) : null;
|
||||
Map<String, String> form = located(table, operation, sent, ctx, labels);
|
||||
return named(resources, formats(table, operation), form, body, partition, region, accountId, stored);
|
||||
return resources.isEmpty() ? List.of()
|
||||
: named(operation, resources, formats(table, operation), form, body, partition, region, accountId, stored);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -132,7 +133,7 @@ public final class RequestResources {
|
||||
if (resources == null || resources.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
return named(resources, formats(table, operation), Map.of(), body, partition, region, accountId, stored);
|
||||
return named(operation, resources, formats(table, operation), Map.of(), body, partition, region, accountId, stored);
|
||||
}
|
||||
|
||||
/** Whether the table holds the operation as one with no resource of its own, which is checked on {@code *}. */
|
||||
@@ -177,18 +178,20 @@ public final class RequestResources {
|
||||
}
|
||||
|
||||
/** The ARNs of the resources the request names, as {@link #of} reads them. */
|
||||
private static List<String> named(List<RequestResourceMembers.Resource> resources,
|
||||
private static List<String> named(String operation, List<RequestResourceMembers.Resource> resources,
|
||||
Map<String, RequestResourceMembers.ArnFormat> formats, Map<String, String> form,
|
||||
JsonNode body, String partition, String region, String accountId,
|
||||
StoredResourceArns stored) {
|
||||
Set<String> arns = new LinkedHashSet<>();
|
||||
for (RequestResourceMembers.Resource resource : resources) {
|
||||
if (!applies(resource, form, body, formats)) {
|
||||
if (!applies(resource, form, body, formats) || !onDefault(resource, form, body, formats, region, stored)) {
|
||||
continue;
|
||||
}
|
||||
if (resource.arn() != null) {
|
||||
for (String value : values(form, body, resource.arn())) {
|
||||
String named = before(value, resource.before());
|
||||
for (String named : values(form, body, resource.arn())) {
|
||||
if (longerFormat(named, resource.types(), formats)) {
|
||||
continue;
|
||||
}
|
||||
// An ARN fitting a customer's format and one AWS owns is AWS's: the account `aws` tells them apart.
|
||||
resource.types().stream().map(formats::get).filter(format -> format.pattern().matcher(named).matches())
|
||||
.min(Comparator.comparing(format -> !format.awsOwned()))
|
||||
@@ -262,16 +265,12 @@ public final class RequestResources {
|
||||
Map<String, String> form = located(table, operation, sent, ctx, labels);
|
||||
Map<String, RequestResourceMembers.ArnFormat> formats = formats(table, operation);
|
||||
if (creates == null) {
|
||||
return named(made, formats, form, body, partition, region, accountId, null);
|
||||
return named(operation, made, formats, form, body, partition, region, accountId, null);
|
||||
}
|
||||
Set<String> arns = new LinkedHashSet<>();
|
||||
for (RequestResourceMembers.Created created : creates) {
|
||||
String separator = table.operations().getOrDefault(operation, List.of()).stream()
|
||||
.filter(resource -> created.arn().equals(resource.arn()) && resource.before() != null)
|
||||
.map(RequestResourceMembers.Resource::before).findFirst().orElse(null);
|
||||
RequestResourceMembers.ArnFormat parentFormat = formats.get(created.parent());
|
||||
for (String value : values(form, body, created.arn())) {
|
||||
String named = before(value, separator);
|
||||
for (String named : values(form, body, created.arn())) {
|
||||
if (!parentFormat.pattern().matcher(named).matches()) {
|
||||
continue;
|
||||
}
|
||||
@@ -376,10 +375,48 @@ public final class RequestResources {
|
||||
|| resource.endpoint().equals(endpoint)).toList();
|
||||
}
|
||||
|
||||
/** The value up to {@code separator}, which its handler drops the rest after; the whole value without one. */
|
||||
private static String before(String value, String separator) {
|
||||
int at = separator == null ? -1 : value.indexOf(separator);
|
||||
return at < 0 ? value : value.substring(0, at);
|
||||
/**
|
||||
* Whether an ARN fits the format of a type of the namespace the resource does not read, longer than every one of
|
||||
* its own that it fits: an endpoint group's ARN under its accelerator's, {@code accelerator/<id>/listener/...},
|
||||
* is the endpoint group's, not the accelerator's.
|
||||
*/
|
||||
private static boolean longerFormat(String arn, List<String> types,
|
||||
Map<String, RequestResourceMembers.ArnFormat> formats) {
|
||||
List<RequestResourceMembers.ArnFormat> fits = types.stream().map(formats::get)
|
||||
.filter(format -> format != null && format.pattern().matcher(arn).matches()).toList();
|
||||
// A type checked without its qualifier takes the longer ARNs of its versions and aliases on purpose.
|
||||
if (fits.stream().anyMatch(RequestResourceMembers.ArnFormat::unqualified)) {
|
||||
return false;
|
||||
}
|
||||
int own = fits.stream().mapToInt(format -> format.format().length()).max().orElse(Integer.MAX_VALUE);
|
||||
return formats.entrySet().stream().anyMatch(other -> !types.contains(other.getKey())
|
||||
&& other.getValue().format().length() > own && other.getValue().pattern().matcher(arn).matches());
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a resource marked {@code whenDefault} or {@code unlessDefault} applies: the one without the variable when
|
||||
* its member is absent or names the default resource of its type, which the service gives ({@code findDefault}),
|
||||
* the other otherwise; true for a resource marked neither. With no service, only an absent member is the default.
|
||||
*/
|
||||
private static boolean onDefault(RequestResourceMembers.Resource resource, Map<String, String> form, JsonNode body,
|
||||
Map<String, RequestResourceMembers.ArnFormat> formats, String region,
|
||||
StoredResourceArns stored) {
|
||||
Map<String, String> pair = resource.whenDefault().isEmpty() ? resource.unlessDefault() : resource.whenDefault();
|
||||
if (pair.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
Map.Entry<String, String> member = pair.entrySet().iterator().next();
|
||||
RequestResourceMembers.ArnFormat format = formats.get(member.getValue());
|
||||
List<String> given = isNull(body, new RequestResourceMembers.Member(member.getKey(), false)) ? List.of()
|
||||
: values(form, body, new RequestResourceMembers.Member(member.getKey(), false));
|
||||
String value = given.isEmpty() ? "" : given.getFirst();
|
||||
if (format != null && format.pattern().matcher(value).matches()) {
|
||||
value = format.variable(value);
|
||||
}
|
||||
Optional<String> fallback = stored == null ? Optional.empty() : stored.findDefault(member.getValue(), region);
|
||||
boolean isDefault = value.isEmpty() || fallback.map(arn -> format != null && format.pattern().matcher(arn).matches()
|
||||
? format.variable(arn) : arn).filter(value::equals).isPresent();
|
||||
return resource.whenDefault().isEmpty() != isDefault;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -405,7 +442,7 @@ public final class RequestResources {
|
||||
private static String first(RequestResourceMembers.Resource resource, Map<String, String> form, JsonNode body,
|
||||
String member, Map<String, RequestResourceMembers.ArnFormat> formats) {
|
||||
RequestResourceMembers.Member read = new RequestResourceMembers.Member(member, false);
|
||||
if (!resource.absent().containsKey(member) && isNull(body, read)) {
|
||||
if (isNull(body, read)) {
|
||||
return "";
|
||||
}
|
||||
List<String> given = given(resource, form, body, read, formats);
|
||||
@@ -413,32 +450,25 @@ public final class RequestResources {
|
||||
}
|
||||
|
||||
/**
|
||||
* The values a request gives a member as the resource reads them, as {@link #read} gives them, and, for a member
|
||||
* that may give an ARN of a type instead of its name, that type's one variable of such an ARN.
|
||||
* The values a request gives a member, and, for a member that may give an ARN of a type instead of its name, that
|
||||
* type's one variable of such an ARN.
|
||||
*/
|
||||
private static List<String> given(RequestResourceMembers.Resource resource, Map<String, String> form,
|
||||
JsonNode body, RequestResourceMembers.Member member,
|
||||
Map<String, RequestResourceMembers.ArnFormat> formats) {
|
||||
RequestResourceMembers.ArnFormat named = arnOf(resource, member.path(), formats);
|
||||
List<String> values = read(resource, form, body, member);
|
||||
List<String> values = values(form, body, member);
|
||||
return named == null ? values : values.stream()
|
||||
.map(value -> named.pattern().matcher(value).matches() ? named.variable(value) : value).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* The values a request gives a member: the one the resource reads for the member absent or given a JSON null,
|
||||
* as a handler reading it with {@code asText(null)} does (EventBridge's {@code EventBusName}), and, for a field
|
||||
* of each of a list's structures, one for each structure, that one for a structure lacking it (a
|
||||
* {@code PutEvents} entry naming no event bus is published to the default one), none for no structures.
|
||||
*/
|
||||
private static List<String> read(RequestResourceMembers.Resource resource, Map<String, String> form,
|
||||
JsonNode body, RequestResourceMembers.Member member) {
|
||||
String absent = resource.absent().get(member.path());
|
||||
if (absent != null && member.eachElement()) {
|
||||
return eachElement(form, body, member, absent);
|
||||
/** The values of a member, a JSON null, or one in an element of a list, giving none. */
|
||||
private static List<String> namingNoneWhenNull(Map<String, String> form, JsonNode body,
|
||||
RequestResourceMembers.Member member) {
|
||||
if (member.eachElement()) {
|
||||
return eachElement(form, body, member, "").stream().filter(value -> !value.isEmpty()).toList();
|
||||
}
|
||||
List<String> values = absent != null && isNull(body, member) ? List.of() : values(form, body, member);
|
||||
return values.isEmpty() && absent != null ? List.of(absent) : values;
|
||||
return isNull(body, member) ? List.of() : values(form, body, member);
|
||||
}
|
||||
|
||||
/** The format of the type whose ARN a member of the resource may give instead of its name; null for none. */
|
||||
@@ -489,11 +519,11 @@ public final class RequestResources {
|
||||
* handler then acts on the caller's resource of that name, and it is named as an ARN the request gives is; for
|
||||
* a member naming one resource for each of a list's structures, each in the account and Region of the ARN its
|
||||
* structure gives, the request's for a name (a {@code PutEvents} entry, on the bus it names). Each value is read
|
||||
* up to the resource's {@code before} character, when it has one (a CodeBuild build id's project), and without the
|
||||
* type's own path when it begins with one, as Route 53 returns its ids ({@code /hostedzone/Z1} names hosted zone
|
||||
* {@code Z1}). A value filling a {@code ...WithoutLeadingSlash} variable is a Parameter Store name instead, read
|
||||
* as {@link #asVariable} reads it. A value rendered past a type's format, when its service checks the
|
||||
* type without a qualifier, is cut where the format ends, as an ARN given is. A type
|
||||
* without the type's own path when it begins with one, as Route 53 returns its ids ({@code /hostedzone/Z1} names
|
||||
* hosted zone {@code Z1}). A value filling a {@code ...WithoutLeadingSlash} variable is a Parameter Store name
|
||||
* instead, read as {@link #asVariable} reads it. A value rendered past a type's format, when its service checks
|
||||
* the type without a qualifier, is cut where the format ends, as an ARN given is. A variable no member fills
|
||||
* takes the value the resource gives it {@code fixed}. A type
|
||||
* whose service mints an id after its name is the caller's resource {@code stored} finds under that name, or
|
||||
* else has that id open.
|
||||
*/
|
||||
@@ -508,14 +538,23 @@ public final class RequestResources {
|
||||
}
|
||||
AwsArnUtils.Arn fromRequest = arnGiven(resource, form, body, formats);
|
||||
List<Filling> fillings = new ArrayList<>(List.of(new Filling(resource.fixed(), fromRequest)));
|
||||
// A member that is a JSON null names none, as a request leaving it out and as a handler reading it with
|
||||
// asText(null) does: an EventBridge rule with a null EventBusName is on the default bus, and an EMR request
|
||||
// with a null ClusterId names no cluster of its own.
|
||||
boolean given = false;
|
||||
for (Map.Entry<String, RequestResourceMembers.Member> variable : resource.fill().entrySet()) {
|
||||
List<String> values = read(resource, form, body, variable.getValue()).stream()
|
||||
.map(value -> before(value, resource.before()))
|
||||
List<String> values = namingNoneWhenNull(form, body, variable.getValue()).stream()
|
||||
.map(value -> variable.getKey().endsWith(WITHOUT_LEADING_SLASH)
|
||||
? asVariable(variable.getKey(), value)
|
||||
: withoutTypePath(value, resource.types().getFirst()))
|
||||
.toList();
|
||||
// An element of a list naming no resource names its service's default (a PutEvents entry with no bus).
|
||||
if (variable.getValue().eachElement() && stored != null && resource.fill().size() == 1) {
|
||||
List<String> elements = eachElement(form, body, variable.getValue(), "");
|
||||
if (elements.contains("")) {
|
||||
stored.findDefault(resource.types().getFirst(), region).ifPresent(arns::add);
|
||||
}
|
||||
}
|
||||
if (values.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
@@ -543,6 +582,12 @@ public final class RequestResources {
|
||||
fillings = next;
|
||||
}
|
||||
if (!resource.fill().isEmpty() && !given) {
|
||||
// A request leaving out every member naming the resource acts on the one its service uses then; a list's
|
||||
// elements each name their own (above), so a list of none names nothing (a PutEvents of no entries).
|
||||
boolean perElement = resource.fill().values().stream().anyMatch(RequestResourceMembers.Member::eachElement);
|
||||
if (stored != null && account.equals(accountId) && !perElement) {
|
||||
stored.findDefault(resource.types().getFirst(), region).ifPresent(arns::add);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (Filling filling : fillings) {
|
||||
|
||||
@@ -23,6 +23,10 @@ import java.util.Optional;
|
||||
* permission sets are provisioned to; Resource Explorer, for its default view; OAM and RAM, for the sinks,
|
||||
* invitations and shares of other accounts they act on); looked up lazily by {@code ResourceArnBuilder} through {@code Instance<StoredResourceArns>}
|
||||
* for the namespace a request is of, so IAM never depends on that service directly.</p>
|
||||
*
|
||||
* <p>Each answer is a lookup of what the service holds, asked for by an entry of the generated table ({@code find},
|
||||
* {@code through}, a default): never a fact about what an operation acts on, which the table alone says, from
|
||||
* botocore and the Service Reference, or from AWS behaviour measured where neither carries it.</p>
|
||||
*/
|
||||
public interface StoredResourceArns {
|
||||
|
||||
|
||||
@@ -199,15 +199,18 @@ public class AthenaJsonHandler {
|
||||
}
|
||||
case "ListDatabases" -> {
|
||||
String catalog = catalogName(request);
|
||||
athenaService.requireGlueCatalog(region, catalog);
|
||||
yield Response.ok(Map.of("DatabaseList", athenaService.listDatabases(catalog))).build();
|
||||
}
|
||||
case "ListTableMetadata" -> {
|
||||
String catalog = catalogName(request);
|
||||
athenaService.requireGlueCatalog(region, catalog);
|
||||
String database = request.path("DatabaseName").asText(request.path("Database").asText(""));
|
||||
yield Response.ok(Map.of("TableMetadataList", athenaService.listTableMetadata(catalog, database))).build();
|
||||
}
|
||||
case "GetTableMetadata" -> {
|
||||
String catalog = catalogName(request);
|
||||
athenaService.requireGlueCatalog(region, catalog);
|
||||
String database = request.path("DatabaseName").asText(request.path("Database").asText(""));
|
||||
String tableName = request.get("TableName").asText();
|
||||
yield Response.ok(Map.of("TableMetadata", athenaService.getTableMetadata(catalog, database, tableName))).build();
|
||||
|
||||
@@ -942,6 +942,23 @@ public class AthenaService {
|
||||
"WorkGroup " + name + " is not found.", 400));
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses a metadata read of a data catalog whose metadata is not the account's Glue Data Catalog, which Floci
|
||||
* reads them from: a catalog of another type, or a Glue one registered for another account's catalog. Athena
|
||||
* answers {@code MetadataException} when it cannot read a catalog's metastore, and {@code InvalidRequestException}
|
||||
* for one it does not hold.
|
||||
*/
|
||||
public void requireGlueCatalog(String region, String name) {
|
||||
if (DEFAULT_CATALOG.equals(name)) {
|
||||
return;
|
||||
}
|
||||
DataCatalog catalog = requireDataCatalog(region, name);
|
||||
String catalogId = catalog.getParameters() == null ? null : catalog.getParameters().get("catalog-id");
|
||||
if (!"GLUE".equals(catalog.getType()) || (catalogId != null && !catalogId.equals(regionResolver.getAccountId()))) {
|
||||
throw new AwsException("MetadataException", "Unable to read the metadata of data catalog " + name + ".", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private DataCatalog requireDataCatalog(String region, String name) {
|
||||
return dataCatalogStore.get(catalogKey(region, name))
|
||||
.orElseThrow(() -> new AwsException("InvalidRequestException",
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package io.floci.aws.services.athena;
|
||||
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.StoredResourceArns;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* What IAM asks Athena of the resources a request names: the workgroup and the data catalog its handlers use for a
|
||||
* request naming none, {@code primary} and {@code AwsDataCatalog}.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class AthenaStoredResourceArns implements StoredResourceArns {
|
||||
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
public AthenaStoredResourceArns(RegionResolver regionResolver) {
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String namespace() {
|
||||
return "athena";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> findDefault(String type, String region) {
|
||||
return switch (type) {
|
||||
case "workgroup" -> Optional.of(regionResolver.buildArn("athena", region, "workgroup/primary"));
|
||||
case "datacatalog" -> Optional.of(regionResolver.buildArn("athena", region,
|
||||
"datacatalog/" + AthenaService.DEFAULT_CATALOG));
|
||||
default -> Optional.empty();
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,15 @@ package io.floci.aws.services.ce;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.floci.aws.core.common.AwsErrorResponse;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* JSON 1.1 handler for AWS Cost Explorer operations.
|
||||
* Dispatches {@code X-Amz-Target: AWSInsightsIndexService.*} actions to
|
||||
@@ -18,18 +22,28 @@ import org.jboss.logging.Logger;
|
||||
public class CostExplorerJsonHandler {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CostExplorerJsonHandler.class);
|
||||
/** The reads that take a {@code BillingViewArn}, which they answer the costs of. */
|
||||
private static final Set<String> BILLING_VIEW_READS = Set.of("GetCostAndUsage", "GetCostAndUsageWithResources",
|
||||
"GetDimensionValues", "GetTags", "GetCostCategories");
|
||||
|
||||
private final CostExplorerService service;
|
||||
private final CostAnomalyService anomalies;
|
||||
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
public CostExplorerJsonHandler(CostExplorerService service, CostAnomalyService anomalies) {
|
||||
public CostExplorerJsonHandler(CostExplorerService service, CostAnomalyService anomalies,
|
||||
RegionResolver regionResolver) {
|
||||
this.service = service;
|
||||
this.anomalies = anomalies;
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
public Response handle(String action, JsonNode request, String region) {
|
||||
LOG.debugv("CostExplorer action: {0}", action);
|
||||
if (BILLING_VIEW_READS.contains(action)) {
|
||||
requireServedBillingView(request);
|
||||
}
|
||||
return switch (action) {
|
||||
case "GetCostAndUsage" -> Response.ok(service.getCostAndUsage(request, region)).build();
|
||||
case "GetCostAndUsageWithResources" -> Response.ok(service.getCostAndUsageWithResources(request, region)).build();
|
||||
@@ -69,4 +83,21 @@ public class CostExplorerJsonHandler {
|
||||
.build();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses a billing view other than the caller's primary one, the costs of the whole account, the only view Floci
|
||||
* answers the costs of: AWS answers {@code ResourceNotFoundException}, "The specified ARN in the request doesn't
|
||||
* exist.", for a view it does not hold. AWS does not document the primary view's ARN; Floci takes it as
|
||||
* {@code billingview/primary}. The view is that ARN exactly, of AWS Billing, global, in the request's partition
|
||||
* and account, as IAM checks it: one of another service or with a Region names no view IAM could check.
|
||||
*/
|
||||
private void requireServedBillingView(JsonNode request) {
|
||||
String view = request.path("BillingViewArn").asText("");
|
||||
if (view.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
if (!regionResolver.buildGlobalArn("billing", "billingview/primary").equals(view)) {
|
||||
throw new AwsException("ResourceNotFoundException", "The specified ARN in the request doesn't exist.", 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -229,6 +229,13 @@ public class CloudWatchLogsDeliveryService {
|
||||
deliveries.delete(key(region, id));
|
||||
}
|
||||
|
||||
/** The ARNs of the delivery destinations the deliveries from the delivery source of that name send to. */
|
||||
public List<String> destinationArnsFrom(String sourceName, String region) {
|
||||
return deliveries.scan(k -> k.startsWith(prefix(region))).stream()
|
||||
.filter(delivery -> sourceName.equals(delivery.getDeliverySourceName()))
|
||||
.map(Delivery::getDeliveryDestinationArn).distinct().toList();
|
||||
}
|
||||
|
||||
/** Every delivery, or those from one of {@code deliverySourceNames}. */
|
||||
public PaginatedResult<Delivery> describeDeliveries(Integer limit, String nextToken,
|
||||
List<String> deliverySourceNames, String region) {
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package io.floci.aws.services.cloudwatch.logs;
|
||||
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.StoredResourceArns;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* What IAM asks CloudWatch Logs of the resources a request names: the caller's delivery of the id it was created
|
||||
* with, and the delivery destinations the deliveries from a delivery source send to, which the Service Reference
|
||||
* checks a {@code DeleteDeliverySource} on.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CloudWatchLogsStoredResourceArns implements StoredResourceArns {
|
||||
|
||||
private final CloudWatchLogsDeliveryService deliveries;
|
||||
|
||||
@Inject
|
||||
public CloudWatchLogsStoredResourceArns(CloudWatchLogsDeliveryService deliveries) {
|
||||
this.deliveries = deliveries;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String namespace() {
|
||||
return "logs";
|
||||
}
|
||||
|
||||
/** The ARN of the caller's delivery of the id {@code names} gives, as the service stored it; empty for none. */
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
if (!"delivery".equals(type) || names.size() != 1) {
|
||||
return Optional.empty();
|
||||
}
|
||||
try {
|
||||
return Optional.ofNullable(deliveries.getDelivery(names.getFirst(), region).getArn());
|
||||
} catch (AwsException notFound) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
/** The delivery destinations the caller's deliveries from the delivery source a {@code name} names send to. */
|
||||
@Override
|
||||
public List<String> through(String member, String value, String region) {
|
||||
return "name".equals(member) ? deliveries.destinationArnsFrom(value, region) : List.of();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package io.floci.aws.services.codebuild;
|
||||
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.StoredResourceArns;
|
||||
import io.floci.aws.services.codebuild.model.Build;
|
||||
import io.floci.aws.services.codebuild.model.Project;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* What IAM asks CodeBuild of the resources a request names: the project the caller's build of an id belongs to, as
|
||||
* the service stores them, which CodeBuild checks a call naming the build on.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CodeBuildStoredResourceArns implements StoredResourceArns {
|
||||
|
||||
private final CodeBuildService codeBuild;
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
public CodeBuildStoredResourceArns(CodeBuildService codeBuild, RegionResolver regionResolver) {
|
||||
this.codeBuild = codeBuild;
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String namespace() {
|
||||
return "codebuild";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/** The project of the caller's build of the id an {@code id} or {@code ids[]} gives; empty for one it has none of. */
|
||||
@Override
|
||||
public List<String> through(String member, String value, String region) {
|
||||
if (!"ids[]".equals(member) && !"id".equals(member)) {
|
||||
return List.of();
|
||||
}
|
||||
return codeBuild.batchGetBuilds(region, regionResolver.getAccountId(), List.of(value)).stream()
|
||||
.map(Build::getProjectName)
|
||||
.flatMap(name -> codeBuild.batchGetProjects(region, List.of(name)).stream())
|
||||
.map(Project::getArn)
|
||||
.distinct()
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
@@ -661,13 +661,20 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
|
||||
/**
|
||||
* The cluster an instance group a {@code ModifyInstanceGroups} names by its id alone is in, the one
|
||||
* {@link #modifyInstanceGroups} finds it in and changes it there, read under the service's lock, as
|
||||
* {@code addInstanceGroups} adds to a cluster's groups.
|
||||
* {@code addInstanceGroups} adds to a cluster's groups; and the cluster a tag call's {@code ResourceId} names.
|
||||
*/
|
||||
@Override
|
||||
public List<String> through(String member, String value, String region) {
|
||||
return "InstanceGroups[].InstanceGroupId".equals(member)
|
||||
? call(() -> clusterWithGroup(region, value).map(EmrCluster::getClusterArn).stream().toList())
|
||||
: List.of();
|
||||
return switch (member) {
|
||||
case "InstanceGroups[].InstanceGroupId" ->
|
||||
call(() -> clusterWithGroup(region, value).map(EmrCluster::getClusterArn).stream().toList());
|
||||
// A tag call's ResourceId is a cluster's id, or a Studio's, which Floci does not serve: the cluster the
|
||||
// tag handlers find by it (findCluster), one recorded with no Region included.
|
||||
case "ResourceId" -> call(() -> clusterStore.get(value)
|
||||
.filter(cluster -> cluster.getRegion() == null || cluster.getRegion().equals(region))
|
||||
.map(EmrCluster::getClusterArn).stream().toList());
|
||||
default -> List.of();
|
||||
};
|
||||
}
|
||||
|
||||
public List<EmrInstanceGroup> listInstanceGroups(String clusterId) {
|
||||
|
||||
@@ -1917,6 +1917,13 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
|
||||
return "events";
|
||||
}
|
||||
|
||||
/** The Region's default event bus, which a request naming no bus acts on. */
|
||||
@Override
|
||||
public Optional<String> findDefault(String type, String region) {
|
||||
return "event-bus".equals(type) ? Optional.of(regionResolver.buildArn("events", region, "event-bus/default"))
|
||||
: Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARN of the caller's connection or API destination of the one name in the Region, which follows the name
|
||||
* with the id it was minted with, as its handlers look it up.
|
||||
|
||||
@@ -234,9 +234,9 @@ public class QuickSightService implements Resettable, StoredResourceArns {
|
||||
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
if ("user".equals(type) && names.size() == 3) {
|
||||
if (("user".equals(type) || "group".equals(type)) && names.size() == 3) {
|
||||
return Optional.of(regions.buildArn("quicksight", region, names.getFirst(),
|
||||
"user/" + names.get(1) + "/" + names.get(2)));
|
||||
type + "/" + names.get(1) + "/" + names.get(2)));
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package io.floci.aws.services.rekognition;
|
||||
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.StoredResourceArns;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* What IAM asks Rekognition of the resources a request names: a stream processor by the name it was created with,
|
||||
* which its ARN ends in.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class RekognitionStoredResourceArns implements StoredResourceArns {
|
||||
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
public RekognitionStoredResourceArns(RegionResolver regionResolver) {
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String namespace() {
|
||||
return "rekognition";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
return "streamprocessor".equals(type) && names.size() == 1
|
||||
? Optional.of(regionResolver.buildArn("rekognition", region, "streamprocessor/" + names.getFirst()))
|
||||
: Optional.empty();
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package io.floci.aws.services.ssoadmin;
|
||||
|
||||
import jakarta.enterprise.context.RequestScoped;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* What this request found, kept for the request.
|
||||
*
|
||||
* <p>A {@code ProvisionPermissionSet} for {@code ALL_PROVISIONED_ACCOUNTS} provisions a permission set to every
|
||||
* account it is provisioned to, and the permission check finds those accounts and checks each one. Another request
|
||||
* may provision the permission set to one more account while this one is running, with an assignment of its own,
|
||||
* and the request must provision to the accounts it was checked on: an account found again afterwards could be one
|
||||
* no policy was checked against.
|
||||
*/
|
||||
@RequestScoped
|
||||
public class SsoAdminRequestContext {
|
||||
|
||||
/** The accounts a permission set was provisioned to, by the permission set's ARN. */
|
||||
private final Map<String, List<String>> provisionedAccounts = new HashMap<>();
|
||||
|
||||
/**
|
||||
* The accounts the permission set was provisioned to when this request found them, and null when this request
|
||||
* has not looked for them yet.
|
||||
*/
|
||||
List<String> provisionedAccounts(String permissionSetArn) {
|
||||
return provisionedAccounts.get(permissionSetArn);
|
||||
}
|
||||
|
||||
/** Remembers the accounts the permission set is provisioned to, so that the request provisions to those. */
|
||||
void pinProvisionedAccounts(String permissionSetArn, List<String> accountIds) {
|
||||
provisionedAccounts.put(permissionSetArn, List.copyOf(accountIds));
|
||||
}
|
||||
}
|
||||
@@ -140,7 +140,6 @@ public class SsoAdminService implements Resettable, StoredResourceArns {
|
||||
private final StorageBackend<String, String> trustedTokenIssuerClientTokens;
|
||||
private final IdentityStoreService identityStoreService;
|
||||
private final OrganizationsService organizationsService;
|
||||
private final SsoAdminRequestContext requestContext;
|
||||
private final String defaultAccountId;
|
||||
private final String defaultRegion;
|
||||
/** The seeded instance lives in the deployment's home region, so its ARN takes that partition. */
|
||||
@@ -150,8 +149,7 @@ public class SsoAdminService implements Resettable, StoredResourceArns {
|
||||
|
||||
@Inject
|
||||
public SsoAdminService(StorageFactory storageFactory, IdentityStoreService identityStoreService,
|
||||
OrganizationsService organizationsService, SsoAdminRequestContext requestContext,
|
||||
EmulatorConfig config) {
|
||||
OrganizationsService organizationsService, EmulatorConfig config) {
|
||||
this(
|
||||
storageFactory.create("ssoadmin", "ssoadmin-permission-sets.json", new TypeReference<Map<String, PermissionSet>>() {}),
|
||||
storageFactory.create("ssoadmin", "ssoadmin-assignments.json", new TypeReference<Map<String, Assignment>>() {}),
|
||||
@@ -180,7 +178,6 @@ public class SsoAdminService implements Resettable, StoredResourceArns {
|
||||
storageFactory.create("ssoadmin", "ssoadmin-trusted-token-issuer-client-tokens.json", new TypeReference<Map<String, String>>() {}),
|
||||
identityStoreService,
|
||||
organizationsService,
|
||||
requestContext,
|
||||
config.defaultAccountId(),
|
||||
config.defaultRegion(),
|
||||
Clock.systemUTC());
|
||||
@@ -213,7 +210,6 @@ public class SsoAdminService implements Resettable, StoredResourceArns {
|
||||
StorageBackend<String, String> trustedTokenIssuerClientTokens,
|
||||
IdentityStoreService identityStoreService,
|
||||
OrganizationsService organizationsService,
|
||||
SsoAdminRequestContext requestContext,
|
||||
String defaultAccountId,
|
||||
String defaultRegion,
|
||||
Clock clock) {
|
||||
@@ -245,7 +241,6 @@ public class SsoAdminService implements Resettable, StoredResourceArns {
|
||||
this.trustedTokenIssuerClientTokens = trustedTokenIssuerClientTokens;
|
||||
this.identityStoreService = identityStoreService;
|
||||
this.organizationsService = organizationsService;
|
||||
this.requestContext = requestContext;
|
||||
this.defaultAccountId = defaultAccountId;
|
||||
this.defaultRegion = defaultRegion;
|
||||
this.bootstrapInstanceArn = globalArn("sso", defaultRegion, "", BOOTSTRAP_INSTANCE);
|
||||
@@ -1921,25 +1916,13 @@ public class SsoAdminService implements Resettable, StoredResourceArns {
|
||||
return operation;
|
||||
}
|
||||
|
||||
/**
|
||||
* The accounts the permission set is provisioned to, as this request found them.
|
||||
*
|
||||
* <p>They are found once for the request, and kept: the permission check of a {@code ProvisionPermissionSet} for
|
||||
* {@code ALL_PROVISIONED_ACCOUNTS} finds them and checks each one, and the request must provision to those.
|
||||
* Another request may provision the permission set to one more account in between, and an account found again
|
||||
* afterwards could be one no policy was checked against.
|
||||
*/
|
||||
/** The accounts the permission set is provisioned to. */
|
||||
private List<String> provisionedAccounts(String permissionSetArn) {
|
||||
List<String> accountIds = requestContext.provisionedAccounts(permissionSetArn);
|
||||
if (accountIds == null) {
|
||||
accountIds = permissionSetProvisionings.scan(key -> true).stream()
|
||||
.filter(provisioning -> permissionSetArn.equals(provisioning.permissionSetArn()))
|
||||
.map(PermissionSetProvisioning::accountId)
|
||||
.distinct()
|
||||
.toList();
|
||||
requestContext.pinProvisionedAccounts(permissionSetArn, accountIds);
|
||||
}
|
||||
return accountIds;
|
||||
return permissionSetProvisionings.scan(key -> true).stream()
|
||||
.filter(provisioning -> permissionSetArn.equals(provisioning.permissionSetArn()))
|
||||
.map(PermissionSetProvisioning::accountId)
|
||||
.distinct()
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -1952,22 +1935,6 @@ public class SsoAdminService implements Resettable, StoredResourceArns {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* The accounts a permission set is provisioned to, in its partition, which a {@code ProvisionPermissionSet} for
|
||||
* {@code ALL_PROVISIONED_ACCOUNTS} provisions it to again, as {@link #provisionPermissionSet} does: the same
|
||||
* ones, found once for the request.
|
||||
*/
|
||||
@Override
|
||||
public List<String> through(String member, String value, String region) {
|
||||
if (!"PermissionSetArn".equals(member) || !AwsArnUtils.isArn(value)) {
|
||||
return List.of();
|
||||
}
|
||||
String partition = AwsArnUtils.parse(value).partition();
|
||||
return provisionedAccounts(value).stream()
|
||||
.map(accountId -> AwsArnUtils.Arn.global(partition, "sso", "", "account/" + accountId).toString())
|
||||
.toList();
|
||||
}
|
||||
|
||||
private void ensurePermissionSetProvisioned(String permissionSetArn, String accountId) {
|
||||
String key = permissionSetArn + "::" + accountId;
|
||||
permissionSetProvisionings.put(key, new PermissionSetProvisioning(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"_source": {"generator": "tools/aws/regen_iam_passed_roles.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.43.118 (installed package)", "retrieved": "2026-11-12", "note": "make iam-passed-roles-check re-derives every member from botocore; make iam-passed-roles-verify checks every operation against AWS."},
|
||||
"_source": {"generator": "tools/aws/regen_iam_passed_roles.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.43.118 (installed package)", "retrieved": "2026-11-13", "note": "make iam-passed-roles-check re-derives every member from botocore; make iam-passed-roles-verify checks every operation against AWS."},
|
||||
"namespaces": {"application-autoscaling": ["application-autoscaling"], "athena": ["athena"], "autoscaling": ["autoscaling"], "budgets": ["budgets"], "cloudformation": ["cloudcontrol", "cloudformation"], "cloudtrail": ["cloudtrail"], "cloudwatch": ["cloudwatch", "cloudwatchomni"], "codebuild": ["codebuild"], "codedeploy": ["codedeploy"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "comprehend": ["comprehend"], "config": ["config"], "datasync": ["datasync"], "dms": ["dms"], "dsql": ["dsql"], "ec2": ["ec2"], "ecr": ["ecr"], "ecs": ["ecs"], "eks": ["eks"], "elasticmapreduce": ["emr"], "emr-serverless": ["emr-serverless"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "glue": ["glue"], "iam": ["iam"], "kinesis": ["kinesis"], "kinesisanalytics": ["kinesisanalytics", "kinesisanalyticsv2"], "lambda": ["lambda", "lambda-core", "lambda-microvms", "lambda-web"], "logs": ["logs"], "pipes": ["pipes"], "rds": ["docdb", "neptune", "rds"], "redshift": ["redshift"], "redshift-serverless": ["redshift-serverless"], "rekognition": ["rekognition"], "resource-groups": ["resource-groups"], "s3": ["s3", "s3control"], "sagemaker": ["sagemaker"], "scheduler": ["scheduler"], "secretsmanager": ["secretsmanager"], "servicecatalog": ["servicecatalog"], "ses": ["mailmanager", "pinpoint-email", "ses", "sesv2"], "sns": ["sns"], "ssm": ["ssm"], "states": ["stepfunctions"], "swf": ["swf"], "textract": ["textract"], "transcribe": ["transcribe"], "transfer": ["transfer"], "translate": ["translate"]},
|
||||
"notCovered": {"access-analyzer": "REST routes no rule maps yet", "airflow": "REST routes no rule maps yet", "apigateway": "authorized by HTTP method, so no request is checked as one of these operations", "appconfig": "REST routes no rule maps yet", "appsync": "REST routes no rule maps yet", "aps": "REST routes no rule maps yet", "aws-marketplace": "REST routes no rule maps yet", "backup": "REST routes no rule maps yet", "batch": "REST routes no rule maps yet", "bedrock": "REST routes no rule maps yet", "bedrock-agentcore": "REST routes no rule maps yet", "cloudfront": "REST routes no rule maps yet", "dlm": "REST routes no rule maps yet", "elasticfilesystem": "REST routes no rule maps yet", "es": "REST routes no rule maps yet", "fis": "REST routes no rule maps yet", "guardduty": "REST routes no rule maps yet", "iot": "REST routes no rule maps yet", "kafka": "REST routes no rule maps yet", "macie2": "REST routes no rule maps yet", "mq": "REST routes no rule maps yet", "quicksight": "metadata-only REST subset; role passing and iam:PassRole checks are not implemented", "rum": "REST routes no rule maps yet", "s3tables": "REST routes no rule maps yet"},
|
||||
"otherNamespaces": ["agent-registry", "aidevops", "aiops", "airflow-serverless", "amplify", "aoss", "appflow", "appmesh", "apprunner", "appstream", "arc-region-switch", "backup-gateway", "backup-search", "bcm-dashboards", "braket", "chatbot", "chime", "cleanrooms", "cleanrooms-ml", "codeconnections", "codestar-connections", "cognito-sync", "comprehendmedical", "databrew", "dataexchange", "datapipeline", "datazone", "dax", "deadline", "devicefarm", "elemental-inference", "emr-containers", "entityresolution", "fms", "forecast", "frauddetector", "gamelift", "gameliftstreams", "geo", "grafana", "greengrass", "groundstation", "health-agent", "healthlake", "imagebuilder", "iotdeviceadvisor", "iotfleetwise", "iotmanagedintegrations", "iotsitewise", "iottwinmaker", "iotwireless", "kafkaconnect", "kendra", "lex", "lookoutequipment", "m2", "machinelearning", "mediaconnect", "mediaconvert", "medialive", "mediapackage", "mediapackage-vod", "mediapackagev2", "mediastore", "medical-imaging", "mobiletargeting", "neptune-graph", "observabilityadmin", "odb", "omics", "opensearch", "osis", "partnercentral", "pcs", "personalize", "profile", "proton", "qbusiness", "repostspace", "resiliencehub", "rolesanywhere", "s3files", "sagemaker-geospatial", "securityagent", "securitylake", "shield", "sms-voice", "snowball", "social-messaging", "ssm-incidents", "ssm-quicksetup", "storagegateway", "supportapp", "synthetics", "timestream", "voiceid", "wellarchitected", "wisdom", "workmail", "workspaces"],
|
||||
@@ -840,7 +840,9 @@
|
||||
"sagemaker:CreateTrainingJob": {"passedTo": ["sagemaker"], "roles": [
|
||||
{"member": "RoleArn", "passedTo": "sagemaker"}
|
||||
]},
|
||||
"sagemaker:CreateTrainingSession": {"passedTo": ["sagemaker", "training-session.sagemaker"], "notRead": "the reference passes the role to sagemaker or training-session.sagemaker and nothing says which"},
|
||||
"sagemaker:CreateTrainingSession": {"passedTo": ["training-session.sagemaker"], "roles": [
|
||||
{"member": "RoleArn", "passedTo": "training-session.sagemaker"}
|
||||
]},
|
||||
"sagemaker:CreateTransformJob": {"passedTo": ["sagemaker"], "notRead": "no member of the request names a role"},
|
||||
"sagemaker:CreateUserProfile": {"passedTo": ["sagemaker"], "roles": [
|
||||
{"member": "UserSettings.CanvasAppSettings.EmrServerlessSettings.ExecutionRoleArn", "passedTo": "sagemaker"},
|
||||
@@ -885,6 +887,7 @@
|
||||
]},
|
||||
"scheduler:CreateSchedule": {"passedTo": ["scheduler"], "byHand": "the target's role"},
|
||||
"scheduler:UpdateSchedule": {"passedTo": ["scheduler"], "byHand": "the target's role"},
|
||||
"secretsmanager:AssociateCrossAccountReplica": {"passedTo": ["secretsmanager"], "notRead": "the pinned botocore does not have the operation yet, so its request cannot be read"},
|
||||
"secretsmanager:RotateSecret": {"passedTo": ["secretsmanager"], "roles": [
|
||||
{"member": "ExternalSecretRotationRoleArn", "passedTo": "secretsmanager"}
|
||||
]},
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"_source": {"generator": "tools/aws/regen_iam_tag_on_create.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.43.118 (installed package)", "retrieved": "2026-11-12", "note": "make iam-tag-on-create-check re-derives every member from botocore; make iam-tag-on-create-verify checks every operation against AWS."},
|
||||
"_source": {"generator": "tools/aws/regen_iam_tag_on_create.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.43.118 (installed package)", "retrieved": "2026-11-13", "note": "make iam-tag-on-create-check re-derives every member from botocore; make iam-tag-on-create-verify checks every operation against AWS."},
|
||||
"namespaces": {"access-analyzer": ["accessanalyzer"], "acm": ["acm"], "application-autoscaling": ["application-autoscaling"], "athena": ["athena"], "autoscaling": ["autoscaling"], "bcm-data-exports": ["bcm-data-exports"], "bcm-pricing-calculator": ["bcm-pricing-calculator"], "budgets": ["budgets"], "ce": ["ce"], "cloudformation": ["cloudformation"], "cloudhsm": ["cloudhsmv2"], "cloudtrail": ["cloudtrail"], "cloudwatch": ["cloudwatch", "cloudwatchomni"], "codedeploy": ["codedeploy"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "comprehend": ["comprehend"], "config": ["config"], "controltower": ["controltower"], "cur": ["cur"], "datasync": ["datasync"], "dms": ["dms"], "dsql": ["dsql"], "dynamodb": ["dynamodb"], "ec2": ["ec2"], "ecr": ["ecr"], "ecs": ["ecs"], "eks": ["eks"], "elasticache": ["elasticache"], "elasticloadbalancing": ["elb", "elbv2"], "elasticmapreduce": ["emr"], "emr-serverless": ["emr-serverless"], "es": ["es", "opensearch"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "fis": ["fis"], "globalaccelerator": ["globalaccelerator"], "glue": ["glue"], "guardduty": ["guardduty"], "iam": ["iam"], "kinesis": ["kinesis"], "kinesisanalytics": ["kinesisanalytics", "kinesisanalyticsv2"], "kms": ["kms"], "lambda": ["lambda", "lambda-core", "lambda-microvms", "lambda-web"], "lightsail": ["lightsail"], "logs": ["logs"], "macie2": ["macie2"], "memorydb": ["memorydb"], "network-firewall": ["network-firewall"], "oam": ["oam"], "organizations": ["organizations"], "payment-cryptography": ["payment-cryptography"], "pipes": ["pipes"], "ram": ["ram"], "rds": ["docdb", "neptune", "rds"], "redshift": ["redshift"], "redshift-serverless": ["redshift-serverless"], "rekognition": ["rekognition"], "resource-explorer-2": ["resource-explorer-2"], "resource-groups": ["resource-groups"], "route53resolver": ["route53resolver"], "sagemaker": ["sagemaker"], "scheduler": ["scheduler"], "secretsmanager": ["secretsmanager"], "securityhub": ["securityhub"], "servicediscovery": ["servicediscovery"], "ses": ["mailmanager", "pinpoint-email", "ses", "sesv2"], "signer": ["signer"], "sns": ["sns"], "sqs": ["sqs"], "ssm": ["ssm"], "sso": ["sso-admin"], "states": ["stepfunctions"], "sts": ["sts"], "swf": ["swf"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "transcribe": ["transcribe"], "transfer": ["transfer"], "translate": ["translate"], "wafv2": ["wafv2"], "xray": ["xray"]},
|
||||
"notCovered": {"airflow": "REST routes no rule maps yet", "app-integrations": "REST routes no rule maps yet", "appconfig": "REST routes no rule maps yet", "appsync": "REST routes no rule maps yet", "aps": "REST routes no rule maps yet", "aws-marketplace": "REST routes no rule maps yet", "backup": "REST routes no rule maps yet", "batch": "REST routes no rule maps yet", "bedrock": "REST routes no rule maps yet", "bedrock-agentcore": "REST routes no rule maps yet", "cloudfront": "its creation tags are a Tags structure holding Items, which this file does not read yet", "codeguru-reviewer": "REST routes no rule maps yet", "connect": "REST routes no rule maps yet", "detective": "REST routes no rule maps yet", "dlm": "REST routes no rule maps yet", "elasticfilesystem": "REST routes no rule maps yet", "inspector2": "REST routes no rule maps yet", "iot": "REST routes no rule maps yet", "kafka": "REST routes no rule maps yet", "mq": "REST routes no rule maps yet", "quicksight": "metadata-only REST subset; creation-tag IAM authorization is not implemented", "rum": "REST routes no rule maps yet", "s3": "authorized by route; S3 checks s3:PutObjectTagging for an object it creates with tags itself", "s3tables": "REST routes no rule maps yet", "servicecatalog": "its operations that tag are AppRegistry's, whose REST routes no rule maps yet"},
|
||||
"otherNamespaces": ["account-access", "acm-pca", "aco-automation", "agent-registry", "aidevops", "aiops", "airflow-serverless", "amplify", "amplifyuibuilder", "aoss", "appfabric", "appflow", "application-signals", "applicationinsights", "appmesh", "apprunner", "appstream", "arc-region-switch", "artifact", "auditmanager", "b2bi", "backup-gateway", "backup-search", "bcm-dashboards", "billing", "billingconductor", "braket", "cases", "cassandra", "chatbot", "chime", "cleanrooms", "cleanrooms-ml", "cloud9", "codecommit", "codeconnections", "codeguru-profiler", "codeguru-security", "codestar-connections", "codestar-notifications", "connect-campaigns", "databrew", "dataexchange", "datapipeline", "datazone", "dax", "deadline", "directconnect", "docdb-elastic", "drs", "ds", "ebs", "ecr-public", "elemental-inference", "emr-containers", "entityresolution", "evs", "fms", "forecast", "frauddetector", "fsx", "gamelift", "gameliftstreams", "geo", "grafana", "greengrass", "groundstation", "health-agent", "healthlake", "imagebuilder", "interconnect", "internetmonitor", "invoicing", "iotdeviceadvisor", "iotfleetwise", "iotmanagedintegrations", "iotsitewise", "iottwinmaker", "iotwireless", "ivs", "ivschat", "kafkaconnect", "kendra", "kendra-ranking", "kinesisvideo", "launchwizard", "lex", "license-manager", "license-manager-linux-subscriptions", "license-manager-user-subscriptions", "lookoutequipment", "m2", "managedblockchain", "mediaconnect", "mediaconvert", "medialive", "mediapackage", "mediapackage-vod", "mediapackagev2", "mediastore", "mediatailor", "medical-imaging", "mgn", "migrationhub-orchestrator", "mobiletargeting", "mpa", "neptune-graph", "network-security-manager", "networkflowmonitor", "networkmanager", "networkmonitor", "notifications", "notifications-contacts", "observabilityadmin", "odb", "omics", "opensearch", "osis", "outposts", "partnercentral", "pca-connector-ad", "pca-connector-scep", "pcs", "personalize", "pi", "polly", "profile", "proton", "qbusiness", "rbin", "refactor-spaces", "repostspace", "resiliencehub", "rolesanywhere", "route53-recovery-control-config", "route53-recovery-readiness", "route53globalresolver", "route53profiles", "rtbfabric", "s3files", "sagemaker-geospatial", "savingsplans", "schemas", "scn", "security-ir", "securityagent", "securitylake", "shield", "sms-voice", "snow-device-management", "social-messaging", "ssm-contacts", "ssm-incidents", "ssm-quicksetup", "ssm-sap", "storagegateway", "supportauthz", "synthetics", "thinclient", "timestream", "voiceid", "vpc-lattice", "waf", "waf-regional", "wellarchitected", "wickr", "wisdom", "workspaces", "workspaces-instances", "workspaces-web"],
|
||||
@@ -51,6 +51,7 @@
|
||||
"cloudwatch:PutInsightRule": {"tagging": ["cloudwatch:TagResource"], "requestTags": true, "tags": [{"member": "Tags[]", "key": "Key", "value": "Value"}]},
|
||||
"cloudwatch:PutLogAlarm": {"tagging": ["cloudwatch:TagResource"], "requestTags": true, "tags": [{"member": "Tags[]", "key": "Key", "value": "Value"}]},
|
||||
"cloudwatch:PutMetricAlarm": {"tagging": ["cloudwatch:TagResource"], "requestTags": true, "tags": [{"member": "Tags[]", "key": "Key", "value": "Value"}]},
|
||||
"cloudwatch:PutMetricDataQueryDefinition": {"tagging": ["cloudwatch:TagResource"], "requestTags": true, "notRead": "the pinned botocore does not have the operation yet, so its request cannot be read"},
|
||||
"cloudwatch:PutMetricStream": {"tagging": ["cloudwatch:TagResource"], "requestTags": true, "tags": [{"member": "Tags[]", "key": "Key", "value": "Value"}]},
|
||||
"codedeploy:CreateApplication": {"tagging": ["codedeploy:TagResource"], "requestTags": true, "tags": [{"member": "tags[]", "key": "Key", "value": "Value"}]},
|
||||
"codedeploy:CreateDeploymentGroup": {"tagging": ["codedeploy:TagResource"], "requestTags": true, "tags": [{"member": "tags[]", "key": "Key", "value": "Value"}]},
|
||||
@@ -172,11 +173,13 @@
|
||||
"ec2:CreateLocalGatewayVirtualInterfaceGroup": {"tagging": ["ec2:CreateTags"], "createAction": true, "requestTags": true, "tags": [{"member": "TagSpecification[item].Tag[item]", "key": "Key", "value": "Value", "resourceType": "ResourceType"}]},
|
||||
"ec2:CreateMacSystemIntegrityProtectionModificationTask": {"tagging": ["ec2:CreateTags"], "createAction": true, "requestTags": true, "tags": [{"member": "TagSpecification[item].Tag[item]", "key": "Key", "value": "Value", "resourceType": "ResourceType"}]},
|
||||
"ec2:CreateManagedPrefixList": {"tagging": ["ec2:CreateTags"], "createAction": true, "requestTags": true, "tags": [{"member": "TagSpecification[item].Tag[item]", "key": "Key", "value": "Value", "resourceType": "ResourceType"}]},
|
||||
"ec2:CreateMetricCategory": {"tagging": ["ec2:CreateTags"], "createAction": true, "notRead": "the pinned botocore does not have the operation yet, so its request cannot be read"},
|
||||
"ec2:CreateNatGateway": {"tagging": ["ec2:CreateTags"], "createAction": true, "requestTags": true, "tags": [{"member": "TagSpecification[item].Tag[item]", "key": "Key", "value": "Value", "resourceType": "ResourceType"}]},
|
||||
"ec2:CreateNetworkAcl": {"tagging": ["ec2:CreateTags"], "createAction": true, "requestTags": true, "tags": [{"member": "TagSpecification[item].Tag[item]", "key": "Key", "value": "Value", "resourceType": "ResourceType"}]},
|
||||
"ec2:CreateNetworkInsightsAccessScope": {"tagging": ["ec2:CreateTags"], "createAction": true, "requestTags": true, "tags": [{"member": "TagSpecification[item].Tag[item]", "key": "Key", "value": "Value", "resourceType": "ResourceType"}]},
|
||||
"ec2:CreateNetworkInsightsPath": {"tagging": ["ec2:CreateTags"], "createAction": true, "requestTags": true, "tags": [{"member": "TagSpecification[item].Tag[item]", "key": "Key", "value": "Value", "resourceType": "ResourceType"}]},
|
||||
"ec2:CreateNetworkInterface": {"tagging": ["ec2:CreateTags"], "createAction": true, "requestTags": true, "tags": [{"member": "TagSpecification[item].Tag[item]", "key": "Key", "value": "Value", "resourceType": "ResourceType"}]},
|
||||
"ec2:CreateNetworkingFlexCostAllocationPolicy": {"tagging": ["ec2:CreateTags"], "createAction": true, "notRead": "the pinned botocore does not have the operation yet, so its request cannot be read"},
|
||||
"ec2:CreatePlacementGroup": {"tagging": ["ec2:CreateTags"], "createAction": true, "requestTags": true, "tags": [{"member": "TagSpecification[item].Tag[item]", "key": "Key", "value": "Value", "resourceType": "ResourceType"}]},
|
||||
"ec2:CreatePublicIpv4Pool": {"tagging": ["ec2:CreateTags"], "createAction": true, "requestTags": true, "tags": [{"member": "TagSpecification[item].Tag[item]", "key": "Key", "value": "Value", "resourceType": "ResourceType"}]},
|
||||
"ec2:CreateReplaceRootVolumeTask": {"tagging": ["ec2:CreateTags"], "createAction": true, "requestTags": true, "tags": [{"member": "TagSpecification[item].Tag[item]", "key": "Key", "value": "Value", "resourceType": "ResourceType"}]},
|
||||
@@ -345,6 +348,7 @@
|
||||
"lambda:CreateFunction": {"tagging": ["lambda:TagResource"], "requestTags": true, "tags": [{"member": "Tags{}"}]},
|
||||
"lambda:CreateMicrovmImage": {"tagging": ["lambda:TagResource"], "requestTags": true, "tags": [{"member": "tags{}"}]},
|
||||
"lambda:CreateNetworkConnector": {"tagging": ["lambda:TagResource"], "requestTags": true, "tags": [{"member": "Tags{}"}]},
|
||||
"lambda:CreateRuntime": {"tagging": ["lambda:TagResource"], "notRead": "the pinned botocore does not have the operation yet, so its request cannot be read"},
|
||||
"lambda:CreateWebFunction": {"tagging": ["lambda:TagResource"], "requestTags": true, "tags": [{"member": "tags{}"}]},
|
||||
"lightsail:CreateBucket": {"tagging": ["lightsail:TagResource"], "requestTags": true, "tags": [{"member": "tags[]", "key": "key", "value": "value"}]},
|
||||
"lightsail:CreateCertificate": {"tagging": ["lightsail:TagResource"], "requestTags": true, "tags": [{"member": "tags[]", "key": "key", "value": "value"}]},
|
||||
@@ -363,6 +367,7 @@
|
||||
"lightsail:CreateRelationalDatabase": {"tagging": ["lightsail:TagResource"], "requestTags": true, "tags": [{"member": "tags[]", "key": "key", "value": "value"}]},
|
||||
"lightsail:CreateRelationalDatabaseFromSnapshot": {"tagging": ["lightsail:TagResource"], "requestTags": true, "tags": [{"member": "tags[]", "key": "key", "value": "value"}]},
|
||||
"lightsail:CreateRelationalDatabaseSnapshot": {"tagging": ["lightsail:TagResource"], "requestTags": true, "tags": [{"member": "tags[]", "key": "key", "value": "value"}]},
|
||||
"lightsail:CreateSubdomain": {"tagging": ["lightsail:TagResource"], "notRead": "the pinned botocore does not have the operation yet, so its request cannot be read"},
|
||||
"lightsail:PutAlarm": {"tagging": ["lightsail:TagResource"], "requestTags": true, "tags": [{"member": "tags[]", "key": "key", "value": "value"}]},
|
||||
"logs:CreateDelivery": {"tagging": ["logs:TagResource"], "requestTags": true, "tags": [{"member": "tags{}"}]},
|
||||
"logs:CreateLogAnomalyDetector": {"tagging": ["logs:TagResource"], "requestTags": true, "tags": [{"member": "tags{}"}]},
|
||||
@@ -390,9 +395,6 @@
|
||||
"network-firewall:CreateFirewall": {"tagging": ["network-firewall:TagResource"], "requestTags": true, "tags": [{"member": "Tags[]", "key": "Key", "value": "Value"}]},
|
||||
"network-firewall:CreateFirewallPolicy": {"tagging": ["network-firewall:TagResource"], "requestTags": true, "tags": [{"member": "Tags[]", "key": "Key", "value": "Value"}]},
|
||||
"network-firewall:CreateFirewallPolicyV2": {"tagging": ["network-firewall:TagResource"], "requestTags": true, "notRead": "the pinned botocore does not have the operation yet, so its request cannot be read"},
|
||||
"network-firewall:CreateProxy": {"tagging": ["network-firewall:TagResource"], "requestTags": true, "tags": [{"member": "Tags[]", "key": "Key", "value": "Value"}]},
|
||||
"network-firewall:CreateProxyConfiguration": {"tagging": ["network-firewall:TagResource"], "requestTags": true, "tags": [{"member": "Tags[]", "key": "Key", "value": "Value"}]},
|
||||
"network-firewall:CreateProxyRuleGroup": {"tagging": ["network-firewall:TagResource"], "requestTags": true, "tags": [{"member": "Tags[]", "key": "Key", "value": "Value"}]},
|
||||
"network-firewall:CreateRuleGroup": {"tagging": ["network-firewall:TagResource"], "requestTags": true, "tags": [{"member": "Tags[]", "key": "Key", "value": "Value"}]},
|
||||
"network-firewall:CreateTLSInspectionConfiguration": {"tagging": ["network-firewall:TagResource"], "requestTags": true, "tags": [{"member": "Tags[]", "key": "Key", "value": "Value"}]},
|
||||
"network-firewall:CreateVpcEndpointAssociation": {"tagging": ["network-firewall:TagResource"], "requestTags": true, "tags": [{"member": "Tags[]", "key": "Key", "value": "Value"}]},
|
||||
|
||||
@@ -99,12 +99,13 @@ class RequestResourceMembersTest {
|
||||
"UpdateDeliveryConfiguration", "DeleteDelivery", "DescribeDeliveries")
|
||||
.map(operation -> "logs:" + operation).collect(Collectors.toSet());
|
||||
Set<String> expected = new HashSet<>(logsDelivery);
|
||||
expected.add("dynamodb:ListTables");
|
||||
expected.add("logs:PutDestination");
|
||||
// What AWS was measured to check where the Service Reference lists no resource type (MEASURED).
|
||||
expected.add("dynamodb:ListTables");
|
||||
assertEquals(expected, table.operations().keySet().stream()
|
||||
.filter(operation -> table.handBuilt().contains(operation.substring(0, operation.indexOf(':'))))
|
||||
.collect(Collectors.toSet()),
|
||||
"only explicit corrections and the operations listed to read override hand-built operations");
|
||||
"only the operations listed to read override hand-built operations");
|
||||
assertTrue(table.namespaces().stream().noneMatch(table.notCovered()::contains));
|
||||
assertTrue(table.otherNamespaces().stream().noneMatch(table.notCovered()::contains));
|
||||
table.operations().forEach((operation, resources) -> {
|
||||
@@ -178,7 +179,7 @@ class RequestResourceMembersTest {
|
||||
@Test
|
||||
void aDataApiSessionNamesTheClusterOrWorkgroupItRunsOnThroughItsSessionId() {
|
||||
Resource session = new Resource(List.of("cluster", "workgroup"), null, Map.of(), Map.of(), Map.of(), Map.of(),
|
||||
Map.of(), null, null, Map.of(), false, List.of(), null, new Member("SessionId", false));
|
||||
null, Map.of(), false, List.of(), null, new Member("SessionId", false));
|
||||
for (String operation : List.of("ExecuteStatement", "BatchExecuteStatement")) {
|
||||
assertEquals(session, RequestResourceMembers.table().operations().get("redshift-data:" + operation)
|
||||
.getLast(), operation);
|
||||
@@ -234,31 +235,31 @@ class RequestResourceMembersTest {
|
||||
assertThrows(IllegalStateException.class, () -> parse(document(formats,
|
||||
"{\"type\":\"thing\",\"fill\":{\"ThingName\":\"" + bad + "\"}}")), bad);
|
||||
}
|
||||
// A field of each of a list's structures fills a variable, read as given when absent or as an ARN, which
|
||||
// only a member filling a variable is.
|
||||
// A field of each of a list's structures fills a variable, read as given or as an ARN, which only a member
|
||||
// filling a variable is.
|
||||
Member each = new Member("A", true, new Member("Name", false));
|
||||
assertEquals(List.of(new Resource(List.of("thing"), null, Map.of("ThingName", each), Map.of(), Map.of(),
|
||||
Map.of("A[].Name", "default"), Map.of("A[].Name", "thing"), null, null, Map.of(), false, null)),
|
||||
Map.of("A[].Name", "thing"), null, Map.of(), false, null)),
|
||||
parseUnchecked(document(formats, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"A[].Name\"},"
|
||||
+ "\"absent\":{\"A[].Name\":\"default\"},\"arnOf\":{\"A[].Name\":\"thing\"}}"))
|
||||
+ "\"arnOf\":{\"A[].Name\":\"thing\"}}"))
|
||||
.operations().get("a:Op"));
|
||||
assertEquals("A[].Name", each.path());
|
||||
for (String bad : List.of("\"absent\":{\"A[].Name\":\"default\"}", "\"arnOf\":{\"A[].Name\":\"thing\"}")) {
|
||||
for (String bad : List.of("\"arnOf\":{\"A[].Name\":\"thing\"}")) {
|
||||
assertThrows(IllegalStateException.class, () -> parse(document(formats,
|
||||
"{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Name\"}," + bad + "}")), bad);
|
||||
}
|
||||
// A field of a structure fills a variable, as one value.
|
||||
Member field = new Member("A", false, new Member("Name", false));
|
||||
assertEquals(List.of(new Resource(List.of("thing"), null, Map.of("ThingName", field), Map.of(), Map.of(),
|
||||
Map.of("A.Name", "default"), Map.of(), null, null, Map.of(), false, null)),
|
||||
parseUnchecked(document(formats, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"A.Name\"},"
|
||||
+ "\"absent\":{\"A.Name\":\"default\"}}")).operations().get("a:Op"));
|
||||
Map.of(), null, Map.of(), false, null)),
|
||||
parseUnchecked(document(formats, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"A.Name\"}}"))
|
||||
.operations().get("a:Op"));
|
||||
assertEquals("A.Name", field.path());
|
||||
// A variable fixed to the one value its handler uses, and one fixed that is no variable, that a member fills,
|
||||
// or to no value.
|
||||
String owned = "\"arnFormats\":{\"a\":{\"thing\":\"arn:${Partition}:a:${Region}:${Account}:thing/${Owner}/${ThingName}\"}}";
|
||||
assertEquals(List.of(new Resource(List.of("thing"), null, Map.of("ThingName", new Member("Name", false)), Map.of(),
|
||||
Map.of(), Map.of(), Map.of(), null, null, Map.of("Owner", "Custom"), false, null)),
|
||||
Map.of(), Map.of(), null, Map.of("Owner", "Custom"), false, null)),
|
||||
parseUnchecked(document(owned, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Name\"},"
|
||||
+ "\"fixed\":{\"Owner\":\"Custom\"}}")).operations().get("a:Op"));
|
||||
for (String bad : List.of("{\"Other\":\"Custom\"}", "{\"ThingName\":\"Custom\"}", "{\"Owner\":\"\"}",
|
||||
@@ -276,16 +277,15 @@ class RequestResourceMembersTest {
|
||||
"{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Name\"},\"made\":" + bad + "}")), bad);
|
||||
}
|
||||
assertEquals(List.of(new Resource(List.of("thing"), new Member("A", true, new Member("ThingArns", true)), Map.of(),
|
||||
Map.of(), Map.of(), Map.of(), Map.of(), null, null, Map.of(), false, null)), parseUnchecked(document(formats, "{\"types\":[\"thing\"],\"arn\":\"A[].ThingArns[]\"}"))
|
||||
Map.of(), Map.of(), Map.of(), null, Map.of(), false, null)), parseUnchecked(document(formats, "{\"types\":[\"thing\"],\"arn\":\"A[].ThingArns[]\"}"))
|
||||
.operations().get("a:Op"));
|
||||
// A member read before more than one character, holding an ARN or filling a variable.
|
||||
assertThrows(IllegalStateException.class, () -> parse(document(formats,
|
||||
"{\"types\":[\"thing\"],\"arn\":\"ThingArn\",\"before\":\"##\"}")));
|
||||
assertThrows(IllegalStateException.class, () -> parse(document(formats,
|
||||
"{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Id\"},\"before\":\"##\"}")));
|
||||
// A member filling a variable read up to a character, as a CodeBuild build id names its project.
|
||||
assertEquals(":", parseUnchecked(document(formats, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Id\"},"
|
||||
+ "\"before\":\":\"}")).operations().get("a:Op").getFirst().before());
|
||||
// A key no resource of its kind has, as one the table no longer writes, fails rather than being ignored.
|
||||
for (String bad : List.of("{\"types\":[\"thing\"],\"arn\":\"ThingArn\",\"before\":\"#\"}",
|
||||
"{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Id\"},\"before\":\":\"}",
|
||||
"{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Name\"},\"absent\":{\"Name\":\"default\"}}",
|
||||
"{\"types\":[\"thing\"],\"arn\":\"ThingArn\",\"when\":{\"Type\":[\"a\"]}}")) {
|
||||
assertThrows(IllegalStateException.class, () -> parse(document(formats, bad)), bad);
|
||||
}
|
||||
// An account from a list, or for a type whose format has no account.
|
||||
assertThrows(IllegalStateException.class, () -> parse(document(formats,
|
||||
"{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Name\"},\"account\":\"Ids[]\"}")));
|
||||
@@ -306,22 +306,21 @@ class RequestResourceMembersTest {
|
||||
}
|
||||
assertTrue(parseUnchecked("{\"namespaces\":{\"a\":[]}," + parts + ",\"mintedIds\":{\"a\":[\"thing\"]},"
|
||||
+ "\"operations\":{\"a:Op\":{\"resources\":[]}}}").formats().get("a").get("thing").minted());
|
||||
// A member read when absent as no value, or as an ARN of a type with no format or of more than one variable.
|
||||
for (String bad : List.of("\"absent\":{\"Bus\":\"\"}", "\"absent\":{\"Bus[]\":\"default\"}",
|
||||
"\"arnOf\":{\"Bus\":\"other\"}", "\"arnOf\":{\"Bus\":\"part\"}", "\"unless\":{\"Bus\":[]}")) {
|
||||
// A member read as an ARN of a type with no format or of more than one variable.
|
||||
for (String bad : List.of("\"arnOf\":{\"Bus\":\"other\"}", "\"arnOf\":{\"Bus\":\"part\"}",
|
||||
"\"unless\":{\"Bus\":[]}")) {
|
||||
assertThrows(IllegalStateException.class, () -> parse(document("\"arnFormats\":{\"a\":{"
|
||||
+ "\"thing\":\"arn:${Partition}:a:${Region}:${Account}:thing/${ThingName}\","
|
||||
+ "\"part\":\"arn:${Partition}:a:${Region}:${Account}:part/${ThingName}/${PartId}\"}}",
|
||||
"{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Name\"}," + bad + "}")), bad);
|
||||
}
|
||||
assertEquals(List.of(new Resource(List.of("thing"), null, Map.of("ThingName", new Member("Name", false)),
|
||||
Map.of(), Map.of("Bus", List.of("default")), Map.of("Bus", "default"), Map.of("Bus", "thing"), null, null,
|
||||
Map.of(), false, null)),
|
||||
Map.of(), Map.of("Bus", List.of("default")), Map.of("Bus", "thing"), null, Map.of(), false, null)),
|
||||
parseUnchecked(document(formats, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Name\"},"
|
||||
+ "\"unless\":{\"Bus\":[\"default\"]},\"absent\":{\"Bus\":\"default\"},"
|
||||
+ "\"arnOf\":{\"Bus\":\"thing\"}}")).operations().get("a:Op"));
|
||||
+ "\"unless\":{\"Bus\":[\"default\"]},\"arnOf\":{\"Bus\":\"thing\"}}"))
|
||||
.operations().get("a:Op"));
|
||||
assertEquals(List.of(new Resource(List.of("thing"), null, Map.of("ThingName", new Member("Names", true)), Map.of(),
|
||||
Map.of(), Map.of(), Map.of(), new Member("registryId", false), null, Map.of(), false, null)),
|
||||
Map.of(), Map.of(), new Member("registryId", false), Map.of(), false, null)),
|
||||
parseUnchecked(document(formats, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Names[]\"},"
|
||||
+ "\"account\":\"registryId\"}")).operations().get("a:Op"));
|
||||
}
|
||||
@@ -342,7 +341,7 @@ class RequestResourceMembersTest {
|
||||
// The resource a create acting on no type makes, of its variables alone; and none for a create acting on one.
|
||||
String makes = "\"makes\":[{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Name\"}}]";
|
||||
assertEquals(List.of(new Resource(List.of("thing"), null, Map.of("ThingName", new Member("Name", false)), Map.of(),
|
||||
Map.of(), Map.of(), Map.of(), null, null, Map.of(), false, null)),
|
||||
Map.of(), Map.of(), null, Map.of(), false, null)),
|
||||
parseUnchecked("{\"namespaces\":{\"a\":[]}," + formats + ",\"operations\":{\"a:Op\":{\"types\":[],"
|
||||
+ "\"resources\":[]," + makes + "}}}").makes().get("a:Op"));
|
||||
for (String bad : List.of("\"types\":[\"thing\"],\"resources\":[]," + makes, "\"types\":[],\"resources\":[],"
|
||||
@@ -354,7 +353,7 @@ class RequestResourceMembersTest {
|
||||
// A field of each of a map's structure values fills a variable, one value for each.
|
||||
Member each = new Member("A", false, new Member("Name", false), true);
|
||||
assertEquals(List.of(new Resource(List.of("thing"), null, Map.of("ThingName", each), Map.of(), Map.of(), Map.of(),
|
||||
Map.of(), null, null, Map.of(), false, null)),
|
||||
null, Map.of(), false, null)),
|
||||
parseUnchecked(document(formats, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"A{}.Name\"}}"))
|
||||
.operations().get("a:Op"));
|
||||
assertEquals("A{}.Name", each.path());
|
||||
@@ -555,6 +554,12 @@ class RequestResourceMembersTest {
|
||||
}
|
||||
Map<String, String> values = given.entrySet().stream()
|
||||
.collect(Collectors.toMap(entry -> entry.getKey().name(), Map.Entry::getValue, (a, b) -> a));
|
||||
// Of a pair whose formats differ by one variable, the one without it applies when its member is absent (the
|
||||
// test's services give no default), the other when the request gives it.
|
||||
if (resource.whenDefault().keySet().stream().anyMatch(values::containsKey)
|
||||
|| resource.unlessDefault().keySet().stream().anyMatch(member -> !values.containsKey(member))) {
|
||||
return false;
|
||||
}
|
||||
return resource.when().entrySet().stream()
|
||||
.allMatch(when -> when.getValue().contains(values.getOrDefault(when.getKey(), "")))
|
||||
&& resource.unless().entrySet().stream()
|
||||
|
||||
@@ -30,6 +30,25 @@ class RequestResourcesTest {
|
||||
|
||||
private static final ObjectMapper CBOR = new ObjectMapper(new CBORFactory());
|
||||
private static final String MACHINE = "arn:aws:states:us-east-1:000000000000:stateMachine:orders";
|
||||
private static final RegionResolver US_EAST_1 = new RegionResolver("us-east-1", "000000000000");
|
||||
/** EventBridge as it answers the reader: the Region's default bus, {@code event-bus/default}. */
|
||||
private static final StoredResourceArns EVENTS = new StoredResourceArns() {
|
||||
@Override
|
||||
public String namespace() {
|
||||
return "events";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> findDefault(String type, String region) {
|
||||
return "event-bus".equals(type) ? Optional.of("arn:aws:events:" + region + ":000000000000:event-bus/default")
|
||||
: Optional.empty();
|
||||
}
|
||||
};
|
||||
|
||||
@Test
|
||||
void inferredLandingZoneIdentifiersKeepRawContextAcrossOperations() {
|
||||
@@ -136,12 +155,15 @@ class RequestResourcesTest {
|
||||
"000000000000", null));
|
||||
}
|
||||
|
||||
/**
|
||||
* DynamoDB is built by hand, but the table reads {@code ListTables}: AWS was measured to check it on the literal
|
||||
* {@code table/*} of the request's partition, Region and account, whatever table its request names, though the
|
||||
* Service Reference lists no resource type for it (the generator's {@code MEASURED}).
|
||||
*/
|
||||
@Test
|
||||
void listTablesCorrectionReadsTheCollectionAndLeavesOtherDynamoOperationsHandBuilt() {
|
||||
void listTablesIsCheckedOnTheTableCollectionAwsWasMeasuredToCheck() {
|
||||
assertTrue(RequestResources.reads("dynamodb:ListTables"));
|
||||
assertFalse(RequestResources.reads("dynamodb:BatchWriteItem"));
|
||||
assertFalse(RequestResources.reads("dynamodb:ExecuteStatement"));
|
||||
assertFalse(RequestResources.reads(null));
|
||||
assertFalse(RequestResources.reads("dynamodb:DescribeLimits"));
|
||||
for (String body : List.of("{}", "{\"TableName\":\"ignored\",\"ExclusiveStartTableName\":\"cursor\"}")) {
|
||||
assertEquals(List.of("arn:aws-us-gov:dynamodb:us-gov-west-1:111122223333:table/*"),
|
||||
RequestResources.of("dynamodb:ListTables", json(body), "aws-us-gov", "us-gov-west-1",
|
||||
@@ -448,18 +470,17 @@ class RequestResourcesTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code StartExecution} takes Step Functions Local's {@code <stateMachineArn>#<test case>} and runs the
|
||||
* machine the part before the {@code #} names, so that machine is checked; other operations read it whole.
|
||||
* Step Functions Local's {@code <stateMachineArn>#<test case>} is no ARN AWS has, and neither botocore nor the
|
||||
* Service Reference says to read it otherwise, so a request giving one is checked on it as given.
|
||||
*/
|
||||
@Test
|
||||
void aStateMachinesTestCaseIsCheckedOnTheMachineItRuns() {
|
||||
assertEquals(List.of(MACHINE), of("states:StartExecution",
|
||||
void aStateMachinesTestCaseIsCheckedAsGiven() {
|
||||
assertEquals(List.of(MACHINE + "#HappyPath"), of("states:StartExecution",
|
||||
json("{\"stateMachineArn\":\"" + MACHINE + "#HappyPath\"}")));
|
||||
assertEquals(List.of(MACHINE), of("states:StartSyncExecution", json("{\"stateMachineArn\":\"" + MACHINE + "#\"}")));
|
||||
assertEquals(List.of(MACHINE + "#x"), of("states:DescribeStateMachine",
|
||||
json("{\"stateMachineArn\":\"" + MACHINE + "#x\"}")));
|
||||
assertEquals(List.of("arn:aws:states:us-east-1:000000000000:execution:orders:*"), created("states:StartExecution",
|
||||
json("{\"stateMachineArn\":\"" + MACHINE + "#HappyPath\"}")));
|
||||
json("{\"stateMachineArn\":\"" + MACHINE + "\"}")));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -474,7 +495,7 @@ class RequestResourcesTest {
|
||||
json("{\"stateMachineVersionArn\":\"" + MACHINE + ":3\"}")));
|
||||
assertEquals(List.of(MACHINE), of("states:DescribeStateMachine", json("{\"stateMachineArn\":\"" + MACHINE + ":1\"}")));
|
||||
assertEquals(List.of(MACHINE), of("states:StartExecution",
|
||||
json("{\"stateMachineArn\":\"" + MACHINE + ":PROD#HappyPath\"}")));
|
||||
json("{\"stateMachineArn\":\"" + MACHINE + ":PROD\"}")));
|
||||
assertEquals(List.of("arn:aws:states:us-east-1:000000000000:execution:orders:*"), created("states:StartExecution",
|
||||
json("{\"stateMachineArn\":\"" + MACHINE + ":PROD\"}")));
|
||||
String execution = "arn:aws:states:us-east-1:000000000000:execution:orders:run-1";
|
||||
@@ -515,27 +536,27 @@ class RequestResourcesTest {
|
||||
@Test
|
||||
void aRuleIsOnTheEventBusItsRequestNames() {
|
||||
String events = "arn:aws:events:us-east-1:000000000000:";
|
||||
assertEquals(List.of(events + "rule/r"), of("events:DescribeRule", json("{\"Name\":\"r\"}")));
|
||||
assertEquals(List.of(events + "rule/r"), of("events:DescribeRule", json("{\"Name\":\"r\"}"), EVENTS));
|
||||
assertEquals(List.of(events + "rule/r"), of("events:DescribeRule",
|
||||
json("{\"Name\":\"r\",\"EventBusName\":\"default\"}")));
|
||||
json("{\"Name\":\"r\",\"EventBusName\":\"default\"}"), EVENTS));
|
||||
assertEquals(List.of(events + "rule/orders/r"), of("events:DescribeRule",
|
||||
json("{\"Name\":\"r\",\"EventBusName\":\"orders\"}")));
|
||||
json("{\"Name\":\"r\",\"EventBusName\":\"orders\"}"), EVENTS));
|
||||
assertEquals(List.of(events + "rule/orders/r"), of("events:DescribeRule",
|
||||
json("{\"Name\":\"r\",\"EventBusName\":\"" + events + "event-bus/orders\"}")));
|
||||
json("{\"Name\":\"r\",\"EventBusName\":\"" + events + "event-bus/orders\"}"), EVENTS));
|
||||
assertEquals(List.of(events + "rule/r"), of("events:DescribeRule",
|
||||
json("{\"Name\":\"r\",\"EventBusName\":\"" + events + "event-bus/default\"}")));
|
||||
json("{\"Name\":\"r\",\"EventBusName\":\"" + events + "event-bus/default\"}"), EVENTS));
|
||||
assertEquals(List.of("arn:aws:events:eu-west-1:111122223333:rule/orders/r",
|
||||
"arn:aws:events:us-east-1:111122223333:rule/orders/r", "arn:aws:events:eu-west-1:000000000000:rule/orders/r",
|
||||
events + "rule/orders/r"), of("events:DescribeRule", json("{\"Name\":\"r\",\"EventBusName\":"
|
||||
+ "\"arn:aws:events:eu-west-1:111122223333:event-bus/orders\"}")));
|
||||
+ "\"arn:aws:events:eu-west-1:111122223333:event-bus/orders\"}"), EVENTS));
|
||||
// A target's rule is named by Rule.
|
||||
assertEquals(List.of(events + "rule/orders/r"), of("events:PutTargets", json("{\"Rule\":\"r\","
|
||||
+ "\"EventBusName\":\"orders\",\"Targets\":[{\"Id\":\"1\",\"Arn\":\"arn:aws:sqs:us-east-1:000000000000:q\"}]}")));
|
||||
+ "\"EventBusName\":\"orders\",\"Targets\":[{\"Id\":\"1\",\"Arn\":\"arn:aws:sqs:us-east-1:000000000000:q\"}]}"), EVENTS));
|
||||
// A request naming no event bus describes the default one.
|
||||
assertEquals(List.of(events + "event-bus/default"), of("events:DescribeEventBus", json("{}")));
|
||||
assertEquals(List.of(events + "event-bus/orders"), of("events:DescribeEventBus", json("{\"Name\":\"orders\"}")));
|
||||
assertEquals(List.of(events + "event-bus/default"), of("events:DescribeEventBus", json("{}"), EVENTS));
|
||||
assertEquals(List.of(events + "event-bus/orders"), of("events:DescribeEventBus", json("{\"Name\":\"orders\"}"), EVENTS));
|
||||
assertEquals(List.of(events + "event-bus/orders"), of("events:DescribeEventBus",
|
||||
json("{\"Name\":\"" + events + "event-bus/orders\"}")));
|
||||
json("{\"Name\":\"" + events + "event-bus/orders\"}"), EVENTS));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -547,14 +568,14 @@ class RequestResourcesTest {
|
||||
String events = "arn:aws:events:us-east-1:000000000000:";
|
||||
assertEquals(List.of("arn:aws:events:us-east-1:111122223333:rule/r", events + "rule/r"),
|
||||
of("events:DescribeRule", json("{\"Name\":\"r\",\"EventBusName\":"
|
||||
+ "\"arn:aws:events:us-east-1:111122223333:event-bus/default\"}")));
|
||||
+ "\"arn:aws:events:us-east-1:111122223333:event-bus/default\"}"), EVENTS));
|
||||
assertEquals(List.of(events + "rule/orders/r"), of("events:DescribeRule",
|
||||
json("{\"Name\":\"r\",\"EventBusName\":\"arn:aws:events:::event-bus/orders\"}")));
|
||||
json("{\"Name\":\"r\",\"EventBusName\":\"arn:aws:events:::event-bus/orders\"}"), EVENTS));
|
||||
assertEquals(List.of(events + "rule/r"), of("events:DescribeRule",
|
||||
json("{\"Name\":\"r\",\"EventBusName\":null}")));
|
||||
json("{\"Name\":\"r\",\"EventBusName\":null}"), EVENTS));
|
||||
assertEquals(List.of(events + "event-bus/orders"), of("events:DescribeEventBus",
|
||||
json("{\"Name\":\"arn:aws:events:::event-bus/orders\"}")));
|
||||
assertEquals(List.of(events + "event-bus/default"), of("events:DescribeEventBus", json("{\"Name\":null}")));
|
||||
json("{\"Name\":\"arn:aws:events:::event-bus/orders\"}"), EVENTS));
|
||||
assertEquals(List.of(events + "event-bus/default"), of("events:DescribeEventBus", json("{\"Name\":null}"), EVENTS));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -565,11 +586,12 @@ class RequestResourcesTest {
|
||||
@Test
|
||||
void eachEntryIsOnTheEventBusItNames() {
|
||||
String events = "arn:aws:events:us-east-1:000000000000:";
|
||||
assertEquals(List.of(events + "event-bus/orders", events + "event-bus/default", events + "event-bus/audit"),
|
||||
// An entry naming no bus is on the default one, which EventBridge gives (StoredResourceArns.findDefault).
|
||||
assertEquals(List.of(events + "event-bus/default", events + "event-bus/orders", events + "event-bus/audit"),
|
||||
of("events:PutEvents", json("{\"Entries\":[{\"EventBusName\":\"orders\"},{\"Source\":\"s\"},"
|
||||
+ "{\"EventBusName\":\"audit\"},{\"EventBusName\":\"orders\"}]}")));
|
||||
+ "{\"EventBusName\":\"audit\"},{\"EventBusName\":\"orders\"}]}"), EVENTS));
|
||||
assertEquals(List.of(events + "event-bus/default"), of("events:PutEvents",
|
||||
json("{\"Entries\":[{\"EventBusName\":null},{\"EventBusName\":\"\"},{\"EventBusName\":\" \"}]}")));
|
||||
json("{\"Entries\":[{\"EventBusName\":null},{\"EventBusName\":\"\"},{\"EventBusName\":\" \"}]}"), EVENTS));
|
||||
// Each ARN puts its entry's bus in its own account and Region, checked as the caller's too.
|
||||
assertEquals(List.of("arn:aws:events:eu-west-1:111122223333:event-bus/orders",
|
||||
"arn:aws:events:us-east-1:111122223333:event-bus/orders",
|
||||
@@ -578,15 +600,15 @@ class RequestResourcesTest {
|
||||
events + "event-bus/billing"), of("events:PutEvents", json("{\"Entries\":["
|
||||
+ "{\"EventBusName\":\"arn:aws:events:eu-west-1:111122223333:event-bus/orders\"},"
|
||||
+ "{\"EventBusName\":\"audit\"},"
|
||||
+ "{\"EventBusName\":\"arn:aws:events:us-east-1:444455556666:event-bus/billing\"}]}")));
|
||||
+ "{\"EventBusName\":\"arn:aws:events:us-east-1:444455556666:event-bus/billing\"}]}"), EVENTS));
|
||||
assertEquals(List.of(events + "event-bus/orders"), of("events:PutEvents",
|
||||
json("{\"Entries\":[{\"EventBusName\":\"arn:aws:events:::event-bus/orders\"}]}")));
|
||||
assertEquals(List.of(), of("events:PutEvents", json("{\"Entries\":[]}")));
|
||||
assertEquals(List.of(), of("events:PutEvents", json("{}")));
|
||||
json("{\"Entries\":[{\"EventBusName\":\"arn:aws:events:::event-bus/orders\"}]}"), EVENTS));
|
||||
assertEquals(List.of(), of("events:PutEvents", json("{\"Entries\":[]}"), EVENTS));
|
||||
assertEquals(List.of(), of("events:PutEvents", json("{}"), EVENTS));
|
||||
// A form's entries run from 1 to the first it gives nothing of.
|
||||
assertEquals(List.of(events + "event-bus/orders", events + "event-bus/default"), of("events:PutEvents",
|
||||
assertEquals(List.of(events + "event-bus/default", events + "event-bus/orders"), of("events:PutEvents",
|
||||
form("Action=PutEvents&Entries.member.1.EventBusName=orders&Entries.member.2.Source=s"
|
||||
+ "&Entries.member.4.EventBusName=late")));
|
||||
+ "&Entries.member.4.EventBusName=late"), EVENTS));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -899,10 +921,11 @@ class RequestResourcesTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* An EMR request modifying instance groups without its {@code ClusterId} is on the cluster each group is in, as its
|
||||
* service finds it, and none for a group in no cluster; with one, on that cluster alone, and with a null one as
|
||||
* with none. A permission set provisioned to all the accounts it is provisioned to is on each of them, a null
|
||||
* {@code TargetId} naming none, and one provisioned to an account on that account alone.
|
||||
* An EMR request modifying instance groups without its {@code ClusterId}, documented as "the cluster to which the
|
||||
* instance group belongs", is on the cluster each group is in, as its service finds it, and none for a group in no
|
||||
* cluster; with one, on that cluster alone, and with a null one as with none. A permission set provisioned to an
|
||||
* account is on that account; provisioned to all the accounts it is provisioned to, on its instance and itself,
|
||||
* since nothing botocore or the Service Reference says names those accounts.
|
||||
*/
|
||||
@Test
|
||||
void aResourceIsNamedThroughEachValueOfAListAndOnlyWhenTheRequestNamesItNoOtherWay() {
|
||||
@@ -924,6 +947,7 @@ class RequestResourcesTest {
|
||||
return "InstanceGroups[].InstanceGroupId".equals(member)
|
||||
? Optional.ofNullable(groups.get(value)).stream().toList() : List.of();
|
||||
}
|
||||
|
||||
};
|
||||
String modified = "\"InstanceGroups\":[{\"InstanceGroupId\":\"ig-A\",\"InstanceCount\":2},"
|
||||
+ "{\"InstanceGroupId\":\"ig-B\",\"InstanceCount\":2},{\"InstanceGroupId\":\"ig-none\"}]";
|
||||
@@ -962,12 +986,10 @@ class RequestResourcesTest {
|
||||
}
|
||||
};
|
||||
String provisioned = "{\"InstanceArn\":\"" + instance + "\",\"PermissionSetArn\":\"" + permissionSet + "\",";
|
||||
assertEquals(List.of(instance, permissionSet, "arn:aws:sso:::account/111111111111",
|
||||
"arn:aws:sso:::account/222222222222"), RequestResources.of("sso:ProvisionPermissionSet",
|
||||
assertEquals(List.of(instance, permissionSet), RequestResources.of("sso:ProvisionPermissionSet",
|
||||
json(provisioned + "\"TargetType\":\"ALL_PROVISIONED_ACCOUNTS\"}"), "aws", "us-east-1",
|
||||
"000000000000", sso));
|
||||
assertEquals(List.of(instance, permissionSet, "arn:aws:sso:::account/111111111111",
|
||||
"arn:aws:sso:::account/222222222222"), RequestResources.of("sso:ProvisionPermissionSet",
|
||||
assertEquals(List.of(instance, permissionSet), RequestResources.of("sso:ProvisionPermissionSet",
|
||||
json(provisioned + "\"TargetType\":\"ALL_PROVISIONED_ACCOUNTS\",\"TargetId\":null}"), "aws",
|
||||
"us-east-1", "000000000000", sso));
|
||||
assertEquals(List.of(instance, permissionSet, "arn:aws:sso:::account/333333333333"), RequestResources.of(
|
||||
@@ -1022,7 +1044,10 @@ class RequestResourcesTest {
|
||||
json("{\"webhook\":{\"name\":\"w\",\"targetPipeline\":\"p\"}}")));
|
||||
}
|
||||
|
||||
/** A custom action type is {@code Custom}'s, the owner CodePipeline gives every one, which its request does not. */
|
||||
/**
|
||||
* A custom action type is {@code Custom}'s: the request gives no owner, and the operation's name gives the one
|
||||
* value of the {@code ActionOwner} enum it is (the table's {@code fixed}).
|
||||
*/
|
||||
@Test
|
||||
void aCustomActionTypeIsCustoms() {
|
||||
assertEquals(List.of("arn:aws:codepipeline:us-east-1:000000000000:actiontype:Custom/Build/MyProvider/1"),
|
||||
@@ -1055,14 +1080,34 @@ class RequestResourcesTest {
|
||||
json("{\"Name\":\"s\",\"NamespaceId\":\"ns-a\"}")));
|
||||
}
|
||||
|
||||
/** A CodeBuild build is checked on its project, which its id names before its {@code :}. */
|
||||
/** A CodeBuild build is checked on the project its service holds it under, and none for an id it holds none of. */
|
||||
@Test
|
||||
void aBuildIsCheckedOnItsProject() {
|
||||
String project = "arn:aws:codebuild:us-east-1:000000000000:project/";
|
||||
assertEquals(List.of(project + "a"), of("codebuild:StopBuild", json("{\"id\":\"a:1\"}")));
|
||||
Map<String, String> builds = Map.of("a:1", project + "a", "b:2", project + "b", "a:3", project + "a");
|
||||
StoredResourceArns codeBuild = new StoredResourceArns() {
|
||||
@Override
|
||||
public String namespace() {
|
||||
return "codebuild";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> through(String member, String value, String region) {
|
||||
return "id".equals(member) || "ids[]".equals(member)
|
||||
? Optional.ofNullable(builds.get(value)).stream().toList() : List.of();
|
||||
}
|
||||
};
|
||||
assertEquals(List.of(project + "a"), of("codebuild:StopBuild", json("{\"id\":\"a:1\"}"), codeBuild));
|
||||
assertEquals(List.of(project + "a", project + "b"), of("codebuild:BatchGetBuilds",
|
||||
json("{\"ids\":[\"a:1\",\"b:2\",\"a:3\"]}")));
|
||||
assertEquals(List.of(project + "a"), of("codebuild:RetryBuild", form("Action=RetryBuild&id=a:1")));
|
||||
json("{\"ids\":[\"a:1\",\"b:2\",\"a:3\"]}"), codeBuild));
|
||||
assertEquals(List.of(project + "a"), of("codebuild:RetryBuild", form("Action=RetryBuild&id=a:1"), codeBuild));
|
||||
// An id of no build it holds names none.
|
||||
assertEquals(List.of(), of("codebuild:StopBuild", json("{\"id\":\"orphan\"}"), codeBuild));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1206,6 +1251,10 @@ class RequestResourcesTest {
|
||||
return RequestResources.of(operation, request, "aws", "us-east-1", "000000000000");
|
||||
}
|
||||
|
||||
private static List<String> of(String operation, ContainerRequestContext request, StoredResourceArns stored) {
|
||||
return RequestResources.of(operation, request, "aws", "us-east-1", "000000000000", stored);
|
||||
}
|
||||
|
||||
private static ContainerRequestContext json(String body) {
|
||||
return request("application/x-amz-json-1.1", body);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.floci.aws.services.athena;
|
||||
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
@@ -500,4 +501,65 @@ class AthenaDataCatalogIntegrationTest {
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidRequestException"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Floci reads databases and tables from the account's Glue Data Catalog alone, so the metadata reads refuse a
|
||||
* catalog whose metadata is elsewhere: one of another type, or a Glue one registered for another account.
|
||||
*/
|
||||
@Test
|
||||
@Order(20)
|
||||
void metadataReadsRefuseACatalogThatIsNotTheAccountsGlueCatalog() {
|
||||
String federated = "floci-metadata-federated";
|
||||
String foreignGlue = "floci-metadata-foreign-glue";
|
||||
String ownGlue = "floci-metadata-own-glue";
|
||||
createCatalog(federated, "FEDERATED", "\"connection-type\": \"MYSQL\", "
|
||||
+ "\"connection-arn\": \"arn:aws:glue:us-east-1:000000000000:connection/mysql\"");
|
||||
createCatalog(foreignGlue, "GLUE", "\"catalog-id\": \"111122223333\"");
|
||||
createCatalog(ownGlue, "GLUE", "\"catalog-id\": \"000000000000\"");
|
||||
try {
|
||||
for (String catalog : new String[] {federated, foreignGlue}) {
|
||||
for (String read : new String[] {"ListDatabases", "ListTableMetadata", "GetTableMetadata"}) {
|
||||
metadataRead(read, catalog)
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("MetadataException"));
|
||||
}
|
||||
}
|
||||
for (String catalog : new String[] {ownGlue, "AwsDataCatalog"}) {
|
||||
metadataRead("ListDatabases", catalog).statusCode(200);
|
||||
}
|
||||
metadataRead("ListDatabases", "floci-metadata-absent")
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidRequestException"));
|
||||
} finally {
|
||||
for (String catalog : new String[] {federated, foreignGlue, ownGlue}) {
|
||||
given()
|
||||
.header("X-Amz-Target", "AmazonAthena.DeleteDataCatalog")
|
||||
.contentType(CONTENT_TYPE)
|
||||
.body("{ \"Name\": \"" + catalog + "\" }")
|
||||
.when()
|
||||
.post("/");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void createCatalog(String name, String type, String parameters) {
|
||||
given()
|
||||
.header("X-Amz-Target", "AmazonAthena.CreateDataCatalog")
|
||||
.contentType(CONTENT_TYPE)
|
||||
.body("{ \"Name\": \"" + name + "\", \"Type\": \"" + type + "\", \"Parameters\": { " + parameters + " } }")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private static ValidatableResponse metadataRead(String operation, String catalog) {
|
||||
return given()
|
||||
.header("X-Amz-Target", "AmazonAthena." + operation)
|
||||
.contentType(CONTENT_TYPE)
|
||||
.body("{ \"CatalogName\": \"" + catalog + "\", \"DatabaseName\": \"default\", \"TableName\": \"t\" }")
|
||||
.when()
|
||||
.post("/")
|
||||
.then();
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package io.floci.aws.services.ce;
|
||||
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -61,6 +62,35 @@ class CostExplorerIntegrationTest {
|
||||
.body("ResultsByTime", hasSize(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
void costReadsAnswerThePrimaryBillingViewAndRefuseAnother() {
|
||||
String views = "arn:aws:billing::000000000000:billingview/";
|
||||
costRead("GetCostAndUsage", views + "primary").statusCode(200).body("ResultsByTime", hasSize(1));
|
||||
// A view Floci does not hold, a custom one or another account's primary one, does not exist, nor does the
|
||||
// primary one's path under another service or with a Region.
|
||||
for (String view : new String[] {views + "custom-view", "arn:aws:billing::111122223333:billingview/primary",
|
||||
"arn:aws:ce::000000000000:billingview/primary", "arn:aws:billing:us-east-1:000000000000:billingview/primary",
|
||||
"not-an-arn"}) {
|
||||
costRead("GetCostAndUsage", view).statusCode(400).body("__type", equalTo("ResourceNotFoundException"))
|
||||
.body("message", equalTo("The specified ARN in the request doesn't exist."));
|
||||
}
|
||||
costRead("GetDimensionValues", views + "custom-view").statusCode(400)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
private static ValidatableResponse costRead(String action, String billingViewArn) {
|
||||
return given()
|
||||
.contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", "AWSInsightsIndexService." + action)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.body("{\"TimePeriod\":{\"Start\":\"2026-01-01\",\"End\":\"2026-02-01\"},\"Granularity\":\"MONTHLY\","
|
||||
+ "\"Metrics\":[\"UnblendedCost\"],\"Dimension\":\"SERVICE\",\"BillingViewArn\":\""
|
||||
+ billingViewArn + "\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then();
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCostAndUsage_hourlyGranularityEmitsHourBuckets() {
|
||||
given()
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package io.floci.aws.services.codebuild;
|
||||
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.services.codebuild.model.Build;
|
||||
import io.floci.aws.services.codebuild.model.Project;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** What IAM asks CodeBuild of a build a request names: the project CodeBuild holds the build under. */
|
||||
class CodeBuildStoredResourceArnsTest {
|
||||
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String PROJECT = "arn:aws:codebuild:us-east-1:000000000000:project/web";
|
||||
|
||||
@Test
|
||||
void aBuildReachesTheProjectItIsHeldUnderAndAnIdOfNoBuildReachesNone() {
|
||||
CodeBuildService codeBuild = mock(CodeBuildService.class);
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn(ACCOUNT);
|
||||
Build build = new Build();
|
||||
build.setId("web:1");
|
||||
build.setProjectName("web");
|
||||
Project project = new Project();
|
||||
project.setArn(PROJECT);
|
||||
when(codeBuild.batchGetBuilds("us-east-1", ACCOUNT, List.of("web:1"))).thenReturn(List.of(build));
|
||||
when(codeBuild.batchGetProjects("us-east-1", List.of("web"))).thenReturn(List.of(project));
|
||||
CodeBuildStoredResourceArns stored = new CodeBuildStoredResourceArns(codeBuild, regionResolver);
|
||||
|
||||
assertEquals(List.of(PROJECT), stored.through("id", "web:1", "us-east-1"));
|
||||
assertEquals(List.of(PROJECT), stored.through("ids[]", "web:1", "us-east-1"));
|
||||
// An id of no build it holds, whatever project it seems to name, reaches none, nor does another member.
|
||||
assertEquals(List.of(), stored.through("id", "web:2", "us-east-1"));
|
||||
assertEquals(List.of(), stored.through("projectName", "web:1", "us-east-1"));
|
||||
}
|
||||
}
|
||||
@@ -175,7 +175,7 @@ final class EmrServiceFixture {
|
||||
// The docker runner mode's step threads, not yet run.
|
||||
private final List<Runnable> stepThreads = new ArrayList<>();
|
||||
private boolean waking;
|
||||
private final InMemoryStorageFactory storage;
|
||||
final InMemoryStorageFactory storage;
|
||||
private final SparkJobRunner runner;
|
||||
private final BootstrapRunner bootstrap;
|
||||
// The docker runner mode's; null in the immediate one.
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package io.floci.aws.services.emr;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.services.emr.model.EmrCluster;
|
||||
import io.floci.aws.services.emr.model.EmrInstanceFleet;
|
||||
import io.floci.aws.services.emr.model.EmrInstanceGroup;
|
||||
@@ -45,6 +47,28 @@ class EmrServiceTest {
|
||||
+ "\"Rules\":[{\"Name\":\"scale-out\",\"Action\":{},\"Trigger\":{}}]}";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
/**
|
||||
* A tag call's {@code ResourceId} is the cluster the tag handlers find by it: one in the request's Region, or one
|
||||
* stored with no Region, which they find in any.
|
||||
*/
|
||||
@Test
|
||||
void aTagCallsResourceIdIsTheClusterTheTagHandlersFind() {
|
||||
EmrServiceFixture fixture = new EmrServiceFixture(0, 0, 0);
|
||||
EmrService service = fixture.service;
|
||||
EmrCluster cluster = service.runJobFlow(cluster("tagged", true), REGION);
|
||||
|
||||
assertEquals(List.of(cluster.getClusterArn()), service.through("ResourceId", cluster.getId(), REGION));
|
||||
assertEquals(List.of(), service.through("ResourceId", cluster.getId(), "eu-west-1"));
|
||||
assertEquals(List.of(), service.through("ResourceId", "j-UNKNOWN", REGION));
|
||||
|
||||
AccountAwareStorageBackend<EmrCluster> clusters = fixture.storage.create("emr", "emr-clusters.json",
|
||||
new TypeReference<Map<String, EmrCluster>>() {});
|
||||
EmrCluster regionless = clusters.get(cluster.getId()).orElseThrow();
|
||||
regionless.setRegion(null);
|
||||
clusters.put(cluster.getId(), regionless);
|
||||
assertEquals(List.of(cluster.getClusterArn()), service.through("ResourceId", cluster.getId(), "eu-west-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterIsStartingThenBootstrappingUntilItIsReady() {
|
||||
EmrServiceFixture fixture = new EmrServiceFixture(10, 0, 0);
|
||||
|
||||
+87
-51
@@ -232,19 +232,22 @@ class IamRequestResourceEnforcementIntegrationTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code StartExecution} runs the machine before a Step Functions Local test case's {@code #}, so a grant on
|
||||
* that machine allows a start that names a test case, and a deny on it holds.
|
||||
* A Step Functions Local {@code <stateMachineArn>#<test case>} is checked as given: it is no ARN AWS has, and
|
||||
* nothing botocore or the Service Reference says reads it otherwise. So a grant on the machine alone does not
|
||||
* reach a start naming a test case, a grant covering it does, and a deny on the machine alone does not apply.
|
||||
*/
|
||||
@Test
|
||||
void aStateMachinesTestCaseIsCheckedOnTheMachineItRuns() {
|
||||
void aStateMachinesTestCaseIsCheckedAsGiven() {
|
||||
String arn = createStateMachine("res-tc-" + suffix());
|
||||
User user = user("res-tc");
|
||||
user.policy(allowOn("states:StartExecution", arn));
|
||||
refusedJson(startExecution(user, arn + "#"), "states:StartExecution");
|
||||
user.policy(allowOn("states:StartExecution", arn + "*"));
|
||||
startExecution(user, arn + "#").statusCode(200);
|
||||
|
||||
user.policy(allowOn("states:StartExecution", "*") + ",{\"Effect\":\"Deny\",\"Action\":\"states:StartExecution\","
|
||||
+ "\"Resource\":\"" + arn + "\"}");
|
||||
refusedJson(startExecution(user, arn + "#"), "states:StartExecution");
|
||||
startExecution(user, arn + "#").statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -867,11 +870,12 @@ class IamRequestResourceEnforcementIntegrationTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* A build is checked on its project, which its id names before its {@code :}, as CodeBuild authorizes builds,
|
||||
* and a project on the ARN its name gives, a list naming it by name and by ARN alike.
|
||||
* A build is checked on the project CodeBuild holds it under, and one it holds none of on {@code *}: nothing
|
||||
* botocore or the Service Reference says gives a build id's project. A project is checked on the ARN its name
|
||||
* gives, a list naming it by name and by ARN alike.
|
||||
*/
|
||||
@Test
|
||||
void aBuildIsCheckedOnTheProjectItsIdNames() {
|
||||
void aBuildIsCheckedOnTheProjectItIsHeldUnder() {
|
||||
String project = "res-project-" + suffix();
|
||||
String arn = adminJson("codebuild", "CodeBuild_20161006.CreateProject").body("{\"name\":\"" + project
|
||||
+ "\",\"source\":{\"type\":\"NO_SOURCE\",\"buildspec\":\"version: 0.2\"},\"artifacts\":{\"type\":"
|
||||
@@ -887,12 +891,14 @@ class IamRequestResourceEnforcementIntegrationTest {
|
||||
+ allowOn("codebuild:StopBuild", arn));
|
||||
codeBuild(user, "BatchGetProjects", "{\"names\":[\"" + project + "\"]}").statusCode(200);
|
||||
codeBuild(user, "BatchGetProjects", "{\"names\":[\"" + project + "\",\"" + arn + "\"]}").statusCode(200);
|
||||
codeBuild(user, "BatchGetBuilds", "{\"ids\":[\"" + project + ":1\"]}").statusCode(200);
|
||||
refusedJson(codeBuild(user, "BatchGetBuilds", "{\"ids\":[\"" + project + ":1\",\"" + project + "-other:1\"]}"),
|
||||
"codebuild:BatchGetBuilds");
|
||||
codeBuild(user, "StopBuild", "{\"id\":\"" + project + ":1\"}").statusCode(400)
|
||||
// CodeBuild holds no build of these ids, so none names a project and each request is checked on *.
|
||||
refusedJson(codeBuild(user, "BatchGetBuilds", "{\"ids\":[\"" + project + ":1\"]}"), "codebuild:BatchGetBuilds");
|
||||
refusedJson(codeBuild(user, "StopBuild", "{\"id\":\"" + project + ":1\"}"), "codebuild:StopBuild");
|
||||
User any = user("res-build-any");
|
||||
any.policy(allowOn("codebuild:BatchGetBuilds", "*") + "," + allowOn("codebuild:StopBuild", "*"));
|
||||
codeBuild(any, "BatchGetBuilds", "{\"ids\":[\"" + project + ":1\"]}").statusCode(200);
|
||||
codeBuild(any, "StopBuild", "{\"id\":\"" + project + ":1\"}").statusCode(400)
|
||||
.body(containsString("ResourceNotFoundException"));
|
||||
refusedJson(codeBuild(user, "StopBuild", "{\"id\":\"" + project + "-other:1\"}"), "codebuild:StopBuild");
|
||||
}
|
||||
|
||||
/** A Managed Service for Apache Flink application is checked on the ARN its name gives. */
|
||||
@@ -942,21 +948,35 @@ class IamRequestResourceEnforcementIntegrationTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* An Athena catalog read is checked on the catalog its {@code CatalogName} names and on {@code AwsDataCatalog},
|
||||
* the Glue Data Catalog Floci reads whichever it names, so a grant on another catalog alone does not reach it.
|
||||
* An Athena catalog read is checked on the catalog its {@code CatalogName} names, and Floci reads the metadata of
|
||||
* none but the account's Glue Data Catalog: a catalog of another type is refused, so a grant on it does not reach
|
||||
* the Glue data, nor does one on a Glue catalog reach {@code AwsDataCatalog}'s grant.
|
||||
*/
|
||||
@Test
|
||||
void aCatalogReadIsCheckedOnTheGlueCatalogFlociReads() {
|
||||
void aCatalogReadIsCheckedOnTheCatalogItNamesAndReadsNoOther() {
|
||||
String catalogs = "arn:aws:athena:" + REGION + ":" + ACCOUNT + ":datacatalog/";
|
||||
User both = user("res-catalogs");
|
||||
both.policy(allowOn("athena:ListDatabases", catalogs + "AwsDataCatalog") + ","
|
||||
+ allowOn("athena:ListDatabases", catalogs + "res-allowed"));
|
||||
send(both, "athena", "AmazonAthena.ListDatabases", "1.1", "{\"CatalogName\":\"res-allowed\"}").statusCode(200);
|
||||
refusedJson(send(both, "athena", "AmazonAthena.ListDatabases", "1.1", "{\"CatalogName\":\"res-other\"}"),
|
||||
String glue = "res-glue-" + suffix();
|
||||
String lambda = "res-lambda-" + suffix();
|
||||
for (String catalog : List.of("{\"Name\":\"" + glue + "\",\"Type\":\"GLUE\",\"Parameters\":{\"catalog-id\":\""
|
||||
+ ACCOUNT + "\"}}",
|
||||
"{\"Name\":\"" + lambda + "\",\"Type\":\"LAMBDA\",\"Parameters\":{\"function\":\"arn:aws:lambda:"
|
||||
+ REGION + ":" + ACCOUNT + ":function:meta\"}}")) {
|
||||
adminJson("athena", "AmazonAthena.CreateDataCatalog").body(catalog).post("/").then().statusCode(200);
|
||||
}
|
||||
for (String name : List.of(glue, lambda)) {
|
||||
cleanup.register(() -> adminJson("athena", "AmazonAthena.DeleteDataCatalog")
|
||||
.body("{\"Name\":\"" + name + "\"}").post("/"));
|
||||
}
|
||||
User user = user("res-catalogs");
|
||||
user.policy(allowOn("athena:ListDatabases", catalogs + glue) + ","
|
||||
+ allowOn("athena:ListDatabases", catalogs + lambda));
|
||||
send(user, "athena", "AmazonAthena.ListDatabases", "1.1", "{\"CatalogName\":\"" + glue + "\"}")
|
||||
.statusCode(200);
|
||||
send(user, "athena", "AmazonAthena.ListDatabases", "1.1", "{\"CatalogName\":\"" + lambda + "\"}")
|
||||
.statusCode(400).body("__type", equalTo("MetadataException"));
|
||||
refusedJson(send(user, "athena", "AmazonAthena.ListDatabases", "1.1", "{\"CatalogName\":\"AwsDataCatalog\"}"),
|
||||
"athena:ListDatabases");
|
||||
User named = user("res-catalog");
|
||||
named.policy(allowOn("athena:ListDatabases", catalogs + "res-allowed"));
|
||||
refusedJson(send(named, "athena", "AmazonAthena.ListDatabases", "1.1", "{\"CatalogName\":\"res-allowed\"}"),
|
||||
refusedJson(send(user, "athena", "AmazonAthena.ListDatabases", "1.1", "{\"CatalogName\":\"res-other\"}"),
|
||||
"athena:ListDatabases");
|
||||
}
|
||||
|
||||
@@ -1069,17 +1089,34 @@ class IamRequestResourceEnforcementIntegrationTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* A Cost Explorer cost read is checked on {@code *}, not on the billing view its {@code BillingViewArn} gives:
|
||||
* Floci serves no billing views and answers the account's costs whichever it names.
|
||||
* A Cost Explorer cost read is checked on the billing view its {@code BillingViewArn} gives, and Floci answers the
|
||||
* costs of none but the caller's primary view: another is refused, so a grant on it does not reach the account's
|
||||
* costs, nor does one on the primary view reach another's.
|
||||
*/
|
||||
@Test
|
||||
void aBillingViewGrantDoesNotReachTheAccountsCosts() {
|
||||
String view = "arn:aws:billing::" + ACCOUNT + ":billingview/res-view";
|
||||
void aCostReadIsCheckedOnTheBillingViewItNamesAndAnswersNoOther() {
|
||||
String views = "arn:aws:billing::" + ACCOUNT + ":billingview/";
|
||||
User user = user("res-view");
|
||||
user.policy(allowOn("ce:GetCostAndUsage", view));
|
||||
refusedJson(send(user, "ce", "AWSInsightsIndexService.GetCostAndUsage", "1.1", "{\"TimePeriod\":{\"Start\":"
|
||||
+ "\"2026-01-01\",\"End\":\"2026-02-01\"},\"Granularity\":\"MONTHLY\",\"Metrics\":[\"UnblendedCost\"],"
|
||||
+ "\"BillingViewArn\":\"" + view + "\"}"), "ce:GetCostAndUsage");
|
||||
user.policy(allowOn("ce:GetCostAndUsage", views + "primary") + ","
|
||||
+ allowOn("ce:GetCostAndUsage", views + "res-view"));
|
||||
send(user, "ce", "AWSInsightsIndexService.GetCostAndUsage", "1.1", costs(views + "primary")).statusCode(200);
|
||||
send(user, "ce", "AWSInsightsIndexService.GetCostAndUsage", "1.1", costs(views + "res-view")).statusCode(400)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
refusedJson(send(user, "ce", "AWSInsightsIndexService.GetCostAndUsage", "1.1", costs(views + "res-other")),
|
||||
"ce:GetCostAndUsage");
|
||||
User primary = user("res-view-primary");
|
||||
primary.policy(allowOn("ce:GetCostAndUsage", views + "primary"));
|
||||
refusedJson(send(primary, "ce", "AWSInsightsIndexService.GetCostAndUsage", "1.1", costs(views + "res-view")),
|
||||
"ce:GetCostAndUsage");
|
||||
// A deny on the primary view is not sidestepped by naming it under another service, which IAM checks as *.
|
||||
User denied = user("res-view-denied");
|
||||
denied.policy(allowOn("ce:GetCostAndUsage", "*") + ",{\"Effect\":\"Deny\",\"Action\":\"ce:GetCostAndUsage\","
|
||||
+ "\"Resource\":\"" + views + "primary\"}");
|
||||
refusedJson(send(denied, "ce", "AWSInsightsIndexService.GetCostAndUsage", "1.1", costs(views + "primary")),
|
||||
"ce:GetCostAndUsage");
|
||||
send(denied, "ce", "AWSInsightsIndexService.GetCostAndUsage", "1.1",
|
||||
costs("arn:aws:ce::" + ACCOUNT + ":billingview/primary")).statusCode(400)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1556,12 +1593,12 @@ class IamRequestResourceEnforcementIntegrationTest {
|
||||
/** An assignment of the permission set to a group, in the account. */
|
||||
/**
|
||||
* An IAM Identity Center permission set provisioned to all the accounts it is provisioned to, with no
|
||||
* {@code TargetId}, or a null one, is checked on each of those accounts, so a grant on one does not reach the
|
||||
* others, a deny on one holds, and a grant on all of them lets it through. Each request finds the accounts
|
||||
* afresh, so one provisioned to since is checked too.
|
||||
* {@code TargetId} or a null one, is checked on its instance and itself: nothing botocore or the Service Reference
|
||||
* says names those accounts, so a grant on the instance and the permission set lets it through and a deny on one of
|
||||
* its accounts does not apply. One provisioned to an account is checked on that account too.
|
||||
*/
|
||||
@Test
|
||||
void aPermissionSetProvisionedToAllItsAccountsIsCheckedOnEachOfThem() {
|
||||
void aPermissionSetProvisionedToAllItsAccountsIsCheckedOnItsInstanceAndItself() {
|
||||
String instance = ssoInstance();
|
||||
String permissionSet = permissionSet(instance);
|
||||
for (String account : List.of("111111111111", "222222222222")) {
|
||||
@@ -1576,26 +1613,19 @@ class IamRequestResourceEnforcementIntegrationTest {
|
||||
String one = provision + "\"TargetType\":\"AWS_ACCOUNT\",\"TargetId\":\"111111111111\"}";
|
||||
|
||||
User user = user("res-sso-provision");
|
||||
user.policy(allowOn("sso:ProvisionPermissionSet", instance) + ","
|
||||
+ allowOn("sso:ProvisionPermissionSet", permissionSet));
|
||||
ssoAdmin(user, "ProvisionPermissionSet", all).statusCode(200);
|
||||
ssoAdmin(user, "ProvisionPermissionSet", provision + "\"TargetType\":\"ALL_PROVISIONED_ACCOUNTS\","
|
||||
+ "\"TargetId\":null}").statusCode(200);
|
||||
refusedJson(ssoAdmin(user, "ProvisionPermissionSet", one), "sso:ProvisionPermissionSet");
|
||||
user.policy(allowOn("sso:ProvisionPermissionSet", "*") + ",{\"Effect\":\"Deny\","
|
||||
+ "\"Action\":\"sso:ProvisionPermissionSet\",\"Resource\":\"arn:aws:sso:::account/222222222222\"}");
|
||||
ssoAdmin(user, "ProvisionPermissionSet", all).statusCode(200);
|
||||
user.policy(allowOn("sso:ProvisionPermissionSet", instance) + ","
|
||||
+ allowOn("sso:ProvisionPermissionSet", permissionSet) + ","
|
||||
+ allowOn("sso:ProvisionPermissionSet", "arn:aws:sso:::account/111111111111"));
|
||||
ssoAdmin(user, "ProvisionPermissionSet", one).statusCode(200);
|
||||
refusedJson(ssoAdmin(user, "ProvisionPermissionSet", all), "sso:ProvisionPermissionSet");
|
||||
user.policy(allowOn("sso:ProvisionPermissionSet", "*") + ",{\"Effect\":\"Deny\","
|
||||
+ "\"Action\":\"sso:ProvisionPermissionSet\",\"Resource\":\"arn:aws:sso:::account/222222222222\"}");
|
||||
refusedJson(ssoAdmin(user, "ProvisionPermissionSet", all), "sso:ProvisionPermissionSet");
|
||||
ssoAdmin(user, "ProvisionPermissionSet", one).statusCode(200);
|
||||
// A grant on both accounts covers it, a null TargetId naming no account of its own.
|
||||
user.policy(allowOn("sso:ProvisionPermissionSet", instance) + ","
|
||||
+ allowOn("sso:ProvisionPermissionSet", permissionSet) + ","
|
||||
+ allowOn("sso:ProvisionPermissionSet", "arn:aws:sso:::account/111111111111") + ","
|
||||
+ allowOn("sso:ProvisionPermissionSet", "arn:aws:sso:::account/222222222222"));
|
||||
ssoAdmin(user, "ProvisionPermissionSet", provision + "\"TargetType\":\"ALL_PROVISIONED_ACCOUNTS\","
|
||||
+ "\"TargetId\":null}").statusCode(200);
|
||||
String third = assignment(instance, permissionSet, "333333333333");
|
||||
adminJson("sso", "SWBExternalService.CreateAccountAssignment").body(third).post("/").then().statusCode(200);
|
||||
cleanup.register(() -> adminJson("sso", "SWBExternalService.DeleteAccountAssignment").body(third).post("/"));
|
||||
refusedJson(ssoAdmin(user, "ProvisionPermissionSet", all), "sso:ProvisionPermissionSet");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1782,6 +1812,12 @@ class IamRequestResourceEnforcementIntegrationTest {
|
||||
.formParam("SnapshotClusterIdentifier", snapshotCluster).post("/").then();
|
||||
}
|
||||
|
||||
/** A month's unblended cost of the billing view. */
|
||||
private static String costs(String billingViewArn) {
|
||||
return "{\"TimePeriod\":{\"Start\":\"2026-01-01\",\"End\":\"2026-02-01\"},\"Granularity\":\"MONTHLY\","
|
||||
+ "\"Metrics\":[\"UnblendedCost\"],\"BillingViewArn\":\"" + billingViewArn + "\"}";
|
||||
}
|
||||
|
||||
private static String budget(String name, String billingViewArn) {
|
||||
return "{\"BudgetName\":\"" + name + "\",\"BudgetType\":\"COST\",\"TimeUnit\":\"MONTHLY\",\"BudgetLimit\":"
|
||||
+ "{\"Amount\":\"100\",\"Unit\":\"USD\"}" + (billingViewArn == null ? ""
|
||||
|
||||
+14
-11
@@ -603,22 +603,25 @@ class IamRestRouteEnforcementIntegrationTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* Macie's {@code CreateMember} is checked on the member its {@code account.accountId} names: a grant scoped to the
|
||||
* member lets the request reach Macie, which answers that this account has no session, a request naming another
|
||||
* member is refused, and a deny on the member holds under an allow on everything.
|
||||
* Macie's {@code CreateMember} is checked on the account's members, {@code member/*}: nothing botocore or the
|
||||
* Service Reference says names the member it makes by its {@code account.accountId}, so a grant scoped to one
|
||||
* member does not reach it, a grant on the members lets the request reach Macie, which answers that this account
|
||||
* has no session, and a deny on them holds under an allow on everything.
|
||||
*/
|
||||
@Test
|
||||
void macieCreateMemberIsCheckedOnTheMemberItNames() {
|
||||
void macieCreateMemberIsCheckedOnTheAccountsMembers() {
|
||||
String user = user("route-macie-member");
|
||||
String member = "arn:aws:macie2:us-east-1:" + ACCOUNT + ":member/111122223333";
|
||||
String members = "arn:aws:macie2:us-east-1:" + ACCOUNT + ":member/*";
|
||||
|
||||
policy(user, allow("macie2:CreateMember", member));
|
||||
createMember(user, "111122223333", null).statusCode(404);
|
||||
refused(createMember(user, "444455556666", null), "macie2:CreateMember");
|
||||
|
||||
policy(user, allow("macie2:CreateMember", "*") + "," + deny("macie2:CreateMember", member));
|
||||
policy(user, allow("macie2:CreateMember", "arn:aws:macie2:us-east-1:" + ACCOUNT + ":member/111122223333"));
|
||||
refused(createMember(user, "111122223333", null), "macie2:CreateMember");
|
||||
|
||||
policy(user, allow("macie2:CreateMember", members));
|
||||
createMember(user, "111122223333", null).statusCode(404);
|
||||
createMember(user, "444455556666", null).statusCode(404);
|
||||
|
||||
policy(user, allow("macie2:CreateMember", "*") + "," + deny("macie2:CreateMember", members));
|
||||
refused(createMember(user, "111122223333", null), "macie2:CreateMember");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -628,7 +631,7 @@ class IamRestRouteEnforcementIntegrationTest {
|
||||
@Test
|
||||
void macieCreateMemberIsCheckedWithTheTagsItCarries() {
|
||||
String user = user("route-macie-tags");
|
||||
String member = "arn:aws:macie2:us-east-1:" + ACCOUNT + ":member/111122223333";
|
||||
String member = "arn:aws:macie2:us-east-1:" + ACCOUNT + ":member/*";
|
||||
|
||||
policy(user, allow("macie2:CreateMember", member));
|
||||
createMember(user, "111122223333", null).statusCode(404);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.AwsProtocolClaimFilter;
|
||||
import io.floci.aws.core.common.AwsRegions;
|
||||
import io.floci.aws.core.common.ProtocolClaim;
|
||||
@@ -10,6 +11,9 @@ import io.floci.aws.core.common.StoredResourceArns;
|
||||
import io.floci.aws.core.common.WireProtocol;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsDeliveryService;
|
||||
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsStoredResourceArns;
|
||||
import io.floci.aws.services.cloudwatch.logs.model.Delivery;
|
||||
import io.floci.aws.services.eks.EksService;
|
||||
import io.floci.aws.services.iam.model.AccessKey;
|
||||
import io.floci.aws.services.iam.model.IamGroup;
|
||||
@@ -947,11 +951,29 @@ class ResourceArnBuilderTest {
|
||||
@Test
|
||||
void deliveryActionsAreAuthorizedOnTheSourceDestinationOrDeliveryTheyName() {
|
||||
String prefix = "arn:aws:logs:us-east-1:" + ACCOUNT + ":";
|
||||
for (String action : List.of("logs:PutDeliverySource", "logs:GetDeliverySource", "logs:DeleteDeliverySource")) {
|
||||
// A delivery is the one CloudWatch Logs holds under its id; a deleted delivery source is checked on the
|
||||
// delivery destinations its deliveries send to, the type the Service Reference gives DeleteDeliverySource.
|
||||
CloudWatchLogsDeliveryService deliveries = mock(CloudWatchLogsDeliveryService.class);
|
||||
Delivery delivery = new Delivery();
|
||||
delivery.setArn(prefix + "delivery:AbCdEfGh12345678");
|
||||
when(deliveries.getDelivery("AbCdEfGh12345678", "us-east-1")).thenReturn(delivery);
|
||||
when(deliveries.getDelivery("gone", "us-east-1"))
|
||||
.thenThrow(new AwsException("ResourceNotFoundException", "Delivery not found", 400));
|
||||
when(deliveries.destinationArnsFrom("bus-source", "us-east-1"))
|
||||
.thenReturn(List.of(prefix + "delivery-destination:bus-logs"));
|
||||
ResourceArnBuilder builder = reading(new CloudWatchLogsStoredResourceArns(deliveries));
|
||||
for (String action : List.of("logs:PutDeliverySource", "logs:GetDeliverySource")) {
|
||||
setJsonBody("{\"name\":\"bus-source\"}");
|
||||
assertEquals(List.of(prefix + "delivery-source:bus-source"),
|
||||
builder.buildLogResources(action, ctx, "us-east-1", ACCOUNT, "aws"));
|
||||
}
|
||||
setJsonBody("{\"name\":\"bus-source\"}");
|
||||
assertEquals(List.of(prefix + "delivery-destination:bus-logs"),
|
||||
builder.buildLogResources("logs:DeleteDeliverySource", ctx, "us-east-1", ACCOUNT, "aws"));
|
||||
// A source with no deliveries reaches no destination, so the request names none of its resource type.
|
||||
setJsonBody("{\"name\":\"idle-source\"}");
|
||||
assertEquals(List.of("*"), builder.buildLogResources("logs:DeleteDeliverySource", ctx, "us-east-1", ACCOUNT,
|
||||
"aws"));
|
||||
for (String action : List.of("logs:PutDeliveryDestination", "logs:GetDeliveryDestination",
|
||||
"logs:DeleteDeliveryDestination")) {
|
||||
setJsonBody("{\"name\":\"bus-logs\"}");
|
||||
@@ -962,6 +984,10 @@ class ResourceArnBuilderTest {
|
||||
setJsonBody("{\"id\":\"AbCdEfGh12345678\"}");
|
||||
assertEquals(List.of(prefix + "delivery:AbCdEfGh12345678"),
|
||||
builder.buildLogResources(action, ctx, "us-east-1", ACCOUNT, "aws"));
|
||||
// One it holds none of has its id open.
|
||||
setJsonBody("{\"id\":\"gone\"}");
|
||||
assertEquals(List.of(prefix + "delivery:*"),
|
||||
builder.buildLogResources(action, ctx, "us-east-1", ACCOUNT, "aws"));
|
||||
}
|
||||
setJsonBody("{\"deliverySourceName\":\"bus-source\",\"deliveryDestinationArn\":\""
|
||||
+ prefix + "delivery-destination:bus-logs\"}");
|
||||
@@ -1046,6 +1072,7 @@ class ResourceArnBuilderTest {
|
||||
|
||||
@Test
|
||||
void listTablesUsesTheCollectionInTheRequestPartitionRegionAndAccount() {
|
||||
// The collection AWS was measured to check ListTables on, the Service Reference giving its action no type.
|
||||
for (String body : List.of("{}", "{\"ExclusiveStartTableName\":\"page-start\"}",
|
||||
"{\"TableName\":\"decoy\",\"ResourceArn\":\"decoy\"}")) {
|
||||
setJsonBody(body);
|
||||
@@ -1380,11 +1407,11 @@ class ResourceArnBuilderTest {
|
||||
return new ResourceArnBuilder(new ObjectMapper(), null, null, null, null, instance);
|
||||
}
|
||||
|
||||
/** A builder reading the stored ARNs of a namespace, for a request of that namespace. */
|
||||
/** A builder reading the stored ARNs of a namespace, for every request of that namespace. */
|
||||
private static ResourceArnBuilder reading(StoredResourceArns stored) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Instance<StoredResourceArns> instance = mock(Instance.class);
|
||||
when(instance.iterator()).thenReturn(List.of(stored).iterator());
|
||||
when(instance.iterator()).thenAnswer(invocation -> List.of(stored).iterator());
|
||||
return new ResourceArnBuilder(new ObjectMapper(), null, null, null, null, null, instance);
|
||||
}
|
||||
|
||||
|
||||
@@ -94,7 +94,6 @@ class SsoAdminServiceTest {
|
||||
new InMemoryStorage<String, String>(),
|
||||
identityStoreService,
|
||||
organizationsService,
|
||||
new SsoAdminRequestContext(),
|
||||
ACCOUNT_ID,
|
||||
"us-east-1",
|
||||
clock);
|
||||
@@ -1593,41 +1592,6 @@ class SsoAdminServiceTest {
|
||||
() -> accountInstanceService.listAssignmentsForPrincipal(accountInstanceRequest, ACCOUNT_ID));
|
||||
}
|
||||
|
||||
/**
|
||||
* A {@code ProvisionPermissionSet} for {@code ALL_PROVISIONED_ACCOUNTS} provisions the permission set to the
|
||||
* accounts its permission check found it provisioned to, not to one another request provisioned it to in between:
|
||||
* a permission set change then leaves that account not provisioned, and this request was not checked on it.
|
||||
*/
|
||||
@Test
|
||||
void allProvisionedAccountsAreTheOnesThePermissionCheckFound() {
|
||||
PermissionSet permissionSet = createPermissionSet("PinnedAccounts");
|
||||
service.createAssignment(assignmentRequest(permissionSet.arn()));
|
||||
assertEquals(List.of("arn:aws:sso:::account/" + ACCOUNT_ID),
|
||||
service.through("PermissionSetArn", permissionSet.arn(), "us-east-1"));
|
||||
|
||||
ObjectNode other = assignmentRequest(permissionSet.arn());
|
||||
other.put("TargetId", "222222222222");
|
||||
service.createAssignment(other);
|
||||
service.attachPolicy(service.getInstanceArn(), permissionSet.arn(), "arn:aws:iam::aws:policy/ReadOnlyAccess");
|
||||
ObjectNode all = mapper.createObjectNode();
|
||||
all.put("InstanceArn", service.getInstanceArn());
|
||||
all.put("PermissionSetArn", permissionSet.arn());
|
||||
all.put("TargetType", "ALL_PROVISIONED_ACCOUNTS");
|
||||
service.provisionPermissionSet(all);
|
||||
|
||||
assertEquals(List.of(ACCOUNT_ID), accountsProvisioned(permissionSet.arn(), "LATEST_PERMISSION_SET_PROVISIONED"));
|
||||
assertEquals(List.of("222222222222"),
|
||||
accountsProvisioned(permissionSet.arn(), "LATEST_PERMISSION_SET_NOT_PROVISIONED"));
|
||||
}
|
||||
|
||||
private List<String> accountsProvisioned(String permissionSetArn, String status) {
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
request.put("InstanceArn", service.getInstanceArn());
|
||||
request.put("PermissionSetArn", permissionSetArn);
|
||||
request.put("ProvisioningStatus", status);
|
||||
return service.listAccountsForProvisionedPermissionSet(request).items();
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionPermissionSetSupportsSingleAndAllProvisionedAccounts() {
|
||||
PermissionSet permissionSet = createPermissionSet("ProvisionAdmins");
|
||||
@@ -1962,7 +1926,6 @@ class SsoAdminServiceTest {
|
||||
new InMemoryStorage<String, String>(),
|
||||
identityStoreService,
|
||||
organizationsService,
|
||||
new SsoAdminRequestContext(),
|
||||
"999999999999",
|
||||
defaultRegion,
|
||||
Clock.systemUTC());
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
# without a reason.
|
||||
account the one ARN it builds is the member account an IAM check names, in the partition of the caller's organization's own ARN, and it never reaches the wire, so a case has nothing to assert
|
||||
appintegrations no non-commercial partition publishes the service, so a case would be skipped in every partition
|
||||
athena the only ARNs it builds are the default workgroup and data catalog an IAM check names for a request naming none, in the request Region's partition, and they never reach the wire, so a case has nothing to assert
|
||||
cloudformation covered by PartitionArnMintingIntegrationTest (all partitions)
|
||||
cloudhsmv2 the only ARN on the wire is the automatic backup's, and a backup is never removed (DeleteBackup only marks it), so a case would leak state into the shared emulator
|
||||
cloudtrail covered by CloudTrailSelfDeliveryTest (one partition)
|
||||
|
||||
|
@@ -246,8 +246,8 @@ BY_HAND.update({
|
||||
NO_ROLE_MEMBER = "no member of the request names a role"
|
||||
# For an operation no botocore release models, as a legacy one the SDKs dropped.
|
||||
NO_SUCH_OPERATION = "botocore's model has no such operation"
|
||||
# For an operation AWS has shipped since the botocore pin. It lasts until a bump brings the operation in,
|
||||
# when entry_for refuses it, so that the role its request names is read.
|
||||
# For an operation the reference lists that no model of the pinned botocore has, one AWS has shipped since the
|
||||
# pin. It lasts until a bump brings the operation in, when entry_for reads the role its request names.
|
||||
NOT_IN_BOTOCORE = "the pinned botocore does not have the operation yet, so its request cannot be read"
|
||||
RUNBOOK_PARAMETER = "the role is a parameter of the runbook it runs, not a member of the request"
|
||||
XML_BODY = "the request body is XML, which PassedRoles does not read"
|
||||
@@ -268,7 +268,6 @@ NOT_READ = {
|
||||
"elasticmapreduce:UpdateStudio": NO_ROLE_MEMBER,
|
||||
"glue:GetJob": NO_ROLE_MEMBER,
|
||||
"glue:GetJobs": NO_ROLE_MEMBER,
|
||||
"kinesisanalytics:ImportSnapshot": NOT_IN_BOTOCORE,
|
||||
"lambda:AddEventSource": NO_SUCH_OPERATION,
|
||||
"logs:CreateImportTask": "the reference passes the role to cloudtrail or logs and nothing says which",
|
||||
"logs:StartQuery": NO_ROLE_MEMBER,
|
||||
@@ -277,14 +276,11 @@ NOT_READ = {
|
||||
"s3:PutBucketReplication": XML_BODY,
|
||||
"redshift:ModifyLakehouseConfiguration": NO_ROLE_MEMBER,
|
||||
"redshift-serverless:UpdateLakehouseConfiguration": NO_ROLE_MEMBER,
|
||||
"sagemaker:CreateTrainingSession": "the reference passes the role to sagemaker or training-session.sagemaker "
|
||||
"and nothing says which",
|
||||
"sagemaker:CreateTransformJob": NO_ROLE_MEMBER,
|
||||
"sagemaker:ImportHubContent": NO_ROLE_MEMBER,
|
||||
"ssm:CreateDocument": NO_ROLE_MEMBER,
|
||||
"ssm:DescribeAutomationStepExecutions": NO_ROLE_MEMBER,
|
||||
"ssm:GetAutomationExecution": NO_ROLE_MEMBER,
|
||||
"ssm:RegisterDefaultHostManagementConfiguration": NOT_IN_BOTOCORE,
|
||||
"ssm:StartAutomationExecution": RUNBOOK_PARAMETER,
|
||||
"ssm:StartChangeRequestExecution": RUNBOOK_PARAMETER,
|
||||
"ssm:UpdateDocument": NO_ROLE_MEMBER,
|
||||
@@ -588,9 +584,9 @@ def entry_for(operation: str, passed_to: list[str], models: dict[str, dict]) ->
|
||||
return {"passedTo": passed_to, "byHand": BY_HAND[operation]}
|
||||
name = operation.split(":", 1)[1]
|
||||
if operation in NOT_READ:
|
||||
if NOT_READ[operation] == NOT_IN_BOTOCORE and any(name in model["operations"] for model in models.values()):
|
||||
raise ValueError(f"{operation}: the pinned botocore has it now, so take it out of NOT_READ")
|
||||
return {"passedTo": passed_to, "notRead": NOT_READ[operation]}
|
||||
if not any(name in model["operations"] for model in models.values()):
|
||||
return {"passedTo": passed_to, "notRead": NOT_IN_BOTOCORE}
|
||||
members: dict[str, bool] = {}
|
||||
for model in models.values():
|
||||
for path, by_name in role_members(model, name).items():
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -218,13 +218,12 @@ def test_an_operation_naming_no_role_must_say_why(corrections):
|
||||
|
||||
|
||||
def test_an_operation_botocore_does_not_have_yet_is_not_read_until_a_bump_brings_it(corrections):
|
||||
corrections.setattr(r, "NOT_READ", {"svc:CreateThing": r.NOT_IN_BOTOCORE})
|
||||
before = {"svc": model({"CreateOther": "In"}, {"In": structure(Name="String")})}
|
||||
assert r.entry_for("svc:CreateThing", ["svc"], before) == {"passedTo": ["svc"],
|
||||
"notRead": r.NOT_IN_BOTOCORE}
|
||||
bumped = {"svc": model({"CreateThing": "In"}, {"In": structure(RoleArn="String")})}
|
||||
with pytest.raises(ValueError, match="take it out of NOT_READ"):
|
||||
r.entry_for("svc:CreateThing", ["svc"], bumped)
|
||||
assert r.entry_for("svc:CreateThing", ["svc"], bumped) == {"passedTo": ["svc"],
|
||||
"roles": [{"member": "RoleArn", "passedTo": "svc"}]}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
@@ -87,6 +87,17 @@ def test_a_create_makes_its_own_type_whatever_a_member_holding_the_resources_it_
|
||||
{"types": ["pool"], "arn": "resourceArns[]"}]
|
||||
|
||||
|
||||
def test_a_creates_bare_name_fills_what_it_makes_only_when_the_type_says_its_a_name_or_an_id():
|
||||
# CreateResourceShare's share is `resource-share/${ResourcePath}`, a path RAM mints, which no name fills.
|
||||
formats = {"share": "arn:${Partition}:svc:${Region}:${Account}:share/${ResourcePath}", "thing": FORMATS["thing"]}
|
||||
assert r.resources_for("svc:CreateShare", ["share", "thing"], formats, members("name", "resourceArns[]")) == [
|
||||
{"types": ["share", "thing"], "arn": "resourceArns[]"}, {"type": "share", "fill": {}}]
|
||||
# A type whose variable is a name or an id takes the create's bare one.
|
||||
named = {"share": "arn:${Partition}:svc:${Region}:${Account}:share/${ShareName}", "thing": FORMATS["thing"]}
|
||||
assert r.resources_for("svc:CreateShare", ["share", "thing"], named, members("name", "resourceArns[]")) == [
|
||||
{"types": ["share", "thing"], "arn": "resourceArns[]"}, {"type": "share", "fill": {"ShareName": "name"}}]
|
||||
|
||||
|
||||
def test_an_optional_arn_member_of_a_type_without_variables_names_it_when_absent():
|
||||
named = [{"types": ["catalog", "thing"], "arn": "CatalogArn"}]
|
||||
assert r.with_absent_arn(named, FORMATS, {"CatalogArn"}) == named + [
|
||||
@@ -127,7 +138,7 @@ def test_a_create_whose_action_acts_on_no_type_makes_the_one_named_as_it_is():
|
||||
assert r.makes_for("svc:CreatePool", [], VIEWS, {}) == []
|
||||
|
||||
|
||||
def test_a_built_document_with_what_a_create_makes_a_default_and_a_maps_ids_validates(corrections, tmp_path):
|
||||
def test_a_built_document_with_what_a_create_makes_a_default_and_a_maps_ids_validates(isolated, tmp_path):
|
||||
service = model({"CreateThing": {"ThingName": "String"}, "ListThings": {"ThingArn": "String"}, "ApplySteps": {}})
|
||||
service["shapes"]["Step"] = {"type": "structure", "members": {"poolId": {"shape": "String"},
|
||||
"note": {"shape": "String"}}}
|
||||
@@ -355,12 +366,12 @@ def model(operations: dict[str, dict[str, str]], protocol: str = "json") -> dict
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def corrections(monkeypatch):
|
||||
def isolated(monkeypatch):
|
||||
monkeypatch.setattr(r, "NAMESPACES", ("svc",))
|
||||
monkeypatch.setattr(r, "HAND_BUILT", ("hand",))
|
||||
monkeypatch.setattr(r, "NOT_COVERED", {"later": "a later batch"})
|
||||
monkeypatch.setattr(r, "CORRECTIONS", {})
|
||||
monkeypatch.setattr(r, "READ_IN_HAND_BUILT", {})
|
||||
monkeypatch.setattr(r, "MEASURED", {})
|
||||
monkeypatch.setattr(r, "UNQUALIFIED", {})
|
||||
monkeypatch.setattr(r, "MINTED_IDS", {})
|
||||
monkeypatch.setattr(r, "FOUND_BY", {})
|
||||
@@ -381,7 +392,7 @@ DOCUMENTS = [reference("svc", {"GetThing": ["thing"], "ListThings": []}, {"thing
|
||||
reference("later", {"Op": ["y"]}, {"y": "arn:${Partition}:later:::y"})]
|
||||
|
||||
|
||||
def test_a_built_document_validates_matches_botocore_and_names_the_namespaces_it_does_not_read(corrections, tmp_path):
|
||||
def test_a_built_document_validates_matches_botocore_and_names_the_namespaces_it_does_not_read(isolated, tmp_path):
|
||||
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}})})
|
||||
document = r.build(DOCUMENTS, "test", tmp_path, "botocore test")
|
||||
assert r.validate(document) == []
|
||||
@@ -393,7 +404,7 @@ def test_a_built_document_validates_matches_botocore_and_names_the_namespaces_it
|
||||
assert json.loads(r.render(document)) == document
|
||||
|
||||
|
||||
def test_a_member_holding_an_account_id_gives_the_account_of_the_types_named_by_variables(corrections, tmp_path):
|
||||
def test_a_member_holding_an_account_id_gives_the_account_of_the_types_named_by_variables(isolated, tmp_path):
|
||||
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String", "registryId": "AccountId"},
|
||||
"ListThings": {"registryId": "AccountId"}})})
|
||||
document = r.build(DOCUMENTS, "test", tmp_path, "botocore test")
|
||||
@@ -515,7 +526,7 @@ def test_a_format_whose_account_is_an_account_id_variable_takes_the_account_ever
|
||||
"thing": FORMATS["thing"]}}
|
||||
|
||||
|
||||
def test_a_file_that_is_not_json_is_reported_and_not_read(corrections, tmp_path, capsys):
|
||||
def test_a_file_that_is_not_json_is_reported_and_not_read(isolated, tmp_path, capsys):
|
||||
output = tmp_path / "iam-request-resources.json"
|
||||
output.write_text("{not json", encoding="utf-8")
|
||||
|
||||
@@ -524,7 +535,7 @@ def test_a_file_that_is_not_json_is_reported_and_not_read(corrections, tmp_path,
|
||||
assert "could not be read" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_a_file_that_cannot_be_read_is_reported(corrections, tmp_path, capsys):
|
||||
def test_a_file_that_cannot_be_read_is_reported(isolated, tmp_path, capsys):
|
||||
output = tmp_path / "iam-request-resources.json"
|
||||
output.write_text("{}", encoding="utf-8")
|
||||
|
||||
@@ -532,12 +543,12 @@ def test_a_file_that_cannot_be_read_is_reported(corrections, tmp_path, capsys):
|
||||
raise PermissionError(13, "Permission denied")
|
||||
|
||||
# The read is refused rather than the file made unreadable, which a run as root could read anyway.
|
||||
corrections.setattr(Path, "read_text", refuse)
|
||||
isolated.setattr(Path, "read_text", refuse)
|
||||
assert r.main(["--check", "--output", str(output)]) == 1
|
||||
assert "could not be read" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_a_hand_edited_entry_does_not_match_botocore(corrections, tmp_path):
|
||||
def test_a_hand_edited_entry_does_not_match_botocore(isolated, tmp_path):
|
||||
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}})})
|
||||
document = r.build(DOCUMENTS, "test", tmp_path, "botocore test")
|
||||
document["operations"]["svc:GetThing"]["resources"] = []
|
||||
@@ -545,35 +556,35 @@ def test_a_hand_edited_entry_does_not_match_botocore(corrections, tmp_path):
|
||||
assert len(r.derive(document, tmp_path)) == 1
|
||||
|
||||
|
||||
def test_a_type_checked_without_a_qualifier_is_recorded_and_must_be_one_the_file_reads(corrections, tmp_path):
|
||||
def test_a_type_checked_without_a_qualifier_is_recorded_and_must_be_one_the_file_reads(isolated, tmp_path):
|
||||
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}})})
|
||||
corrections.setattr(r, "UNQUALIFIED", {"svc:thing": "its service checks a qualified ARN without the qualifier"})
|
||||
isolated.setattr(r, "UNQUALIFIED", {"svc:thing": "its service checks a qualified ARN without the qualifier"})
|
||||
document = r.build(DOCUMENTS, "test", tmp_path, "botocore test")
|
||||
assert document["unqualified"] == {"svc": ["thing"]}
|
||||
assert r.validate(document) == [] and r.derive(document, tmp_path) == []
|
||||
# A hand edit no longer matches, and a type the file has no format for fails the build.
|
||||
document["unqualified"] = {}
|
||||
assert r.validate(document) == [] and len(r.derive(document, tmp_path)) == 1
|
||||
corrections.setattr(r, "UNQUALIFIED", {"svc:gone": "no longer there"})
|
||||
isolated.setattr(r, "UNQUALIFIED", {"svc:gone": "no longer there"})
|
||||
with pytest.raises(ValueError, match="svc:gone"):
|
||||
r.build(DOCUMENTS, "test", tmp_path, "botocore test")
|
||||
|
||||
|
||||
def test_a_type_whose_service_mints_an_id_after_its_name_is_recorded_and_must_be_one_the_file_reads(corrections, tmp_path):
|
||||
def test_a_type_whose_service_mints_an_id_after_its_name_is_recorded_and_must_be_one_the_file_reads(isolated, tmp_path):
|
||||
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}})})
|
||||
corrections.setattr(r, "MINTED_IDS", {"svc:thing": "its service follows the name with an id it mints"})
|
||||
isolated.setattr(r, "MINTED_IDS", {"svc:thing": "its service follows the name with an id it mints"})
|
||||
document = r.build(DOCUMENTS, "test", tmp_path, "botocore test")
|
||||
assert document["mintedIds"] == {"svc": ["thing"]}
|
||||
assert r.validate(document) == [] and r.derive(document, tmp_path) == []
|
||||
# A hand edit no longer matches, and a type the file has no format for fails the build.
|
||||
document["mintedIds"] = {}
|
||||
assert r.validate(document) == [] and len(r.derive(document, tmp_path)) == 1
|
||||
corrections.setattr(r, "MINTED_IDS", {"svc:gone": "no longer there"})
|
||||
isolated.setattr(r, "MINTED_IDS", {"svc:gone": "no longer there"})
|
||||
with pytest.raises(ValueError, match="svc:gone"):
|
||||
r.build(DOCUMENTS, "test", tmp_path, "botocore test")
|
||||
|
||||
|
||||
def test_a_type_whose_arn_is_all_an_id_its_service_mints_is_found_by_the_members_naming_it(corrections, tmp_path):
|
||||
def test_a_type_whose_arn_is_all_an_id_its_service_mints_is_found_by_the_members_naming_it(isolated, tmp_path):
|
||||
documents = [reference("svc", {"PutTarget": ["target"], "TagTarget": ["target"], "GetByResource": ["target"],
|
||||
"RunOn": ["target", "group"]},
|
||||
{"target": "arn:${Partition}:svc:${Region}:${Account}:target/${ResourceId}",
|
||||
@@ -583,7 +594,7 @@ def test_a_type_whose_arn_is_all_an_id_its_service_mints_is_found_by_the_members
|
||||
"TagTarget": {"ResourceArn": "String"},
|
||||
"GetByResource": {"ResourceId": "String"},
|
||||
"RunOn": {"GroupName": "String"}})})
|
||||
corrections.setattr(r, "FOUND_BY", {"svc:target": (["Namespace", "ResourceId", "Dimension"], "its service mints the id"),
|
||||
isolated.setattr(r, "FOUND_BY", {"svc:target": (["Namespace", "ResourceId", "Dimension"], "its service mints the id"),
|
||||
"svc:group": (["GroupName"], "its service mints the id")})
|
||||
document = r.build(documents, "test", tmp_path, "botocore test")
|
||||
assert r.validate(document) == [] and r.derive(document, tmp_path) == []
|
||||
@@ -599,19 +610,19 @@ def test_a_type_whose_arn_is_all_an_id_its_service_mints_is_found_by_the_members
|
||||
# A hand edit no longer matches, and a type the file has no format for fails the build.
|
||||
operations["svc:PutTarget"]["resources"] = [{"type": "target", "fill": {"ResourceId": "ResourceId"}}]
|
||||
assert r.validate(document) == [] and len(r.derive(document, tmp_path)) == 1
|
||||
corrections.setattr(r, "FOUND_BY", {"svc:gone": (["Namespace"], "no longer there")})
|
||||
isolated.setattr(r, "FOUND_BY", {"svc:gone": (["Namespace"], "no longer there")})
|
||||
with pytest.raises(ValueError, match="svc:gone"):
|
||||
r.build(documents, "test", tmp_path, "botocore test")
|
||||
|
||||
|
||||
def test_a_member_naming_a_resource_of_no_type_names_the_one_it_runs_on_through_it(corrections, tmp_path):
|
||||
def test_a_member_naming_a_resource_of_no_type_names_the_one_it_runs_on_through_it(isolated, tmp_path):
|
||||
documents = [reference("svc", {"Run": ["cluster", "group"], "RunOnGroup": ["group"], "RunOnCluster": ["cluster"],
|
||||
"ListSessions": []},
|
||||
{"cluster": "arn:${Partition}:svc:${Region}:${Account}:cluster:${ClusterName}",
|
||||
"group": "arn:${Partition}:svc:${Region}:${Account}:group/${GroupId}"})]
|
||||
write_models(tmp_path, {"svc": model({"Run": {"SessionId": "String"}, "RunOnGroup": {"SessionId": "String"},
|
||||
"RunOnCluster": {"Sql": "String"}, "ListSessions": {"SessionId": "String"}})})
|
||||
corrections.setattr(r, "THROUGH", {"svc:SessionId": (["cluster", "group"], "a session runs on one")})
|
||||
isolated.setattr(r, "THROUGH", {"svc:SessionId": (["cluster", "group"], "a session runs on one")})
|
||||
document = r.build(documents, "test", tmp_path, "botocore test")
|
||||
assert r.validate(document) == [] and r.derive(document, tmp_path) == []
|
||||
operations = document["operations"]
|
||||
@@ -624,13 +635,13 @@ def test_a_member_naming_a_resource_of_no_type_names_the_one_it_runs_on_through_
|
||||
# A hand edit no longer matches, and a type the file has no format for fails the build.
|
||||
operations["svc:Run"]["resources"] = []
|
||||
assert r.validate(document) == [] and len(r.derive(document, tmp_path)) == 1
|
||||
corrections.setattr(r, "THROUGH", {"svc:SessionId": (["gone"], "no longer there")})
|
||||
isolated.setattr(r, "THROUGH", {"svc:SessionId": (["gone"], "no longer there")})
|
||||
with pytest.raises(ValueError, match="svc:gone"):
|
||||
r.build(documents, "test", tmp_path, "botocore test")
|
||||
|
||||
|
||||
def test_a_client_not_read_gives_no_members_and_aws_listing_it_is_no_untrue_claim(corrections, tmp_path):
|
||||
corrections.setattr(r, "CLIENTS_NOT_READ", {"svcv2": "a second API Floci does not serve"})
|
||||
def test_a_client_not_read_gives_no_members_and_aws_listing_it_is_no_untrue_claim(isolated, tmp_path):
|
||||
isolated.setattr(r, "CLIENTS_NOT_READ", {"svcv2": "a second API Floci does not serve"})
|
||||
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}}),
|
||||
"svcv2": model({"GetThing": {"ThingArn": "String"}})})
|
||||
documents = [dict(DOCUMENTS[0], Operations=[dict(op, SDK=op["SDK"] + [{"Name": "svcv2", "Package": "Boto3"}])
|
||||
@@ -672,17 +683,11 @@ def test_a_field_of_each_of_a_lists_structures_taking_an_arn_before_a_name_is_re
|
||||
# Only a list's structures give one value for each, so a lone structure's field is not read.
|
||||
assert r.name_or_arn_members(models, "PutEvents") == {"Entries[].BusName": "bus"}
|
||||
formats = {"bus": "arn:${Partition}:svc:${Region}:${Account}:bus/${BusName}"}
|
||||
buses = [{"type": "bus", "fill": {"BusName": "Entries[].BusName"}, "absent": {"Entries[].BusName": "default"}}]
|
||||
buses = [{"type": "bus", "fill": {"BusName": "Entries[].BusName"}}]
|
||||
assert r.with_arn_of(buses, formats, r.name_or_arn_members(models, "PutEvents")) == [
|
||||
dict(buses[0], arnOf={"Entries[].BusName": "bus"})]
|
||||
|
||||
|
||||
def test_a_correction_for_an_operation_the_file_does_not_read_fails(corrections, tmp_path):
|
||||
corrections.setattr(r, "CORRECTIONS", {"svc:Gone": ([], "no longer there")})
|
||||
with pytest.raises(ValueError, match="svc:Gone"):
|
||||
r.build(DOCUMENTS, "test", tmp_path, "botocore test")
|
||||
|
||||
|
||||
def good_document() -> dict:
|
||||
return {"namespaces": {"svc": ["svc"]}, "clientsNotRead": {"svcv2": "not served"}, "handBuilt": ["hand"],
|
||||
"notCovered": {"later": "a later batch"},
|
||||
@@ -700,22 +705,18 @@ def test_a_well_formed_document_validates():
|
||||
document["operations"]["svc:B"]["resources"][0]["when"] = {"Type": ["application", None]}
|
||||
document["operations"]["svc:B"]["resources"][0]["account"] = "registryId"
|
||||
document["operations"]["svc:B"]["resources"][0]["unless"] = {"Bus": ["default"]}
|
||||
document["operations"]["svc:B"]["resources"][0]["absent"] = {"Bus": "default"}
|
||||
document["operations"]["svc:B"]["resources"][0]["arnOf"] = {"Bus": "thing"}
|
||||
document["operations"]["svc:A"]["resources"][0]["before"] = "#"
|
||||
# A member filling a variable read up to a character, as a CodeBuild build id names its project before ':'.
|
||||
document["operations"]["svc:B"]["resources"][0]["before"] = ":"
|
||||
assert r.validate(document) == []
|
||||
assert r.validate(with_a_create()) == []
|
||||
# A field of each of a list's structures fills a variable, read as given when absent, or as an ARN.
|
||||
# A field of each of a list's structures fills a variable, read as given, or as an ARN.
|
||||
document = good_document()
|
||||
document["operations"]["svc:B"]["resources"][0].update(
|
||||
fill={"GroupName": "Groups[].Name"}, absent={"Groups[].Name": "default"}, arnOf={"Groups[].Name": "thing"})
|
||||
fill={"GroupName": "Groups[].Name"}, arnOf={"Groups[].Name": "thing"})
|
||||
assert r.validate(document) == []
|
||||
# A field of a structure fills a variable, read as one value, and a variable no member fills may be fixed.
|
||||
document = good_document()
|
||||
document["operations"]["svc:B"]["resources"][0].update(
|
||||
fill={"GroupName": "Group.Name"}, absent={"Group.Name": "default"}, fixed={"GroupId": "g-1"}, made=True)
|
||||
fill={"GroupName": "Group.Name"}, fixed={"GroupId": "g-1"}, made=True)
|
||||
document["operations"]["svc:A"]["resources"][0]["made"] = True
|
||||
assert r.validate(document) == []
|
||||
# A type whose ARN is all an id its service mints, found by the members naming it.
|
||||
@@ -766,7 +767,6 @@ def with_a_create() -> dict:
|
||||
(lambda d: d["operations"]["svc:A"]["resources"][0].update(made="true"), "not true"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0]["fill"].update(GroupName="Groups[].Names[]"), "no variables"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0]["fill"].update(GroupId="Groups[].Id"), "more than one list"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0].update(absent={"Groups[].Name": "default"}), "absent members"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0].update(arnOf={"Groups[].Name": "thing"}), "types of one variable"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0]["fill"].update(Other="Name"), "no variables"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0]["fill"].update(GroupId="Ids[]"), "more than one list"),
|
||||
@@ -779,17 +779,15 @@ def with_a_create() -> dict:
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0].update(when={"Type": []}), "no member's values"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0].update(when={"Types[]": ["a"]}), "no member's values"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0].update(when={"Type": [1]}), "no member's values"),
|
||||
(lambda d: d["operations"]["svc:A"]["resources"][0].update(before="##"), "no one character"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0].update(before="##"), "no one character"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0].update(before=":", fill={"GroupName": "Names[]"}) or
|
||||
d["operations"]["svc:B"]["resources"][0].update(before=1), "no one character"),
|
||||
# A value read as given for a member left out, or up to a character, is no key of a resource any more.
|
||||
(lambda d: d["operations"]["svc:A"]["resources"][0].update(before="#"), "neither an ARN member"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0].update(before=":"), "neither an ARN member"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0].update(absent={"Bus": "default"}), "neither an ARN member"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0].update(account="Ids[]"), "no account of its ARN"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0].update(account="a.b"), "no account of its ARN"),
|
||||
(lambda d: d["arnFormats"]["svc"].update(group="arn:${Partition}:svc:::group/${GroupName}")
|
||||
or d["operations"]["svc:B"]["resources"][0].update(account="registryId"), "no account of its ARN"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0].update(unless={"Type": []}), "no member's values"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0].update(absent={"Bus": ""}), "absent members"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0].update(absent={"Bus[]": "default"}), "absent members"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0].update(arnOf={"Bus": "pool"}), "types of one variable"),
|
||||
(lambda d: d["arnFormats"]["svc"].update(group="arn:${Partition}:svc:${Region}:${Account}:group/${GroupName}/${Id}")
|
||||
or d["operations"]["svc:B"]["resources"][0].update(arnOf={"Bus": "group"}), "types of one variable"),
|
||||
@@ -807,7 +805,7 @@ def with_a_create() -> dict:
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fill={}, find=[]), "beside a fill"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fill={}, find=["Ids[]"]), "beside a fill"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fill={}, find="Namespace"), "beside a fill"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fill={}, find=["Namespace"], absent={"Namespace": "ecs"}),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fill={}, find=["Namespace"], fixed={"GroupId": "g"}),
|
||||
"beside a fill"),
|
||||
(lambda d: d["operations"]["svc:A"]["resources"][0].update(find=["Namespace"]), "neither an ARN member"),
|
||||
])
|
||||
@@ -843,25 +841,6 @@ def test_verify_fails_on_an_action_type_or_format_aws_does_not_give_and_reports_
|
||||
assert added == ["svc:D"]
|
||||
|
||||
|
||||
def test_every_correction_is_the_vendored_entry_of_an_operation_the_file_reads():
|
||||
operations = json.loads(r.OUTPUT.read_text(encoding="utf-8"))["operations"]
|
||||
assert r.CORRECTIONS
|
||||
for operation, (resources, reason) in r.CORRECTIONS.items():
|
||||
assert operation in operations and reason, operation
|
||||
# Derived metadata may extend a correction; metadata explicitly supplied by the correction must survive.
|
||||
actual = operations[operation]["resources"]
|
||||
assert len(actual) == len(resources), operation
|
||||
for resource, correction in zip(actual, resources, strict=True):
|
||||
assert {key: value for key, value in resource.items()
|
||||
if key not in ("account", "arnOf", "made") or key in correction} == correction, operation
|
||||
|
||||
|
||||
def test_a_correction_gives_the_operation_its_resources(corrections):
|
||||
corrections.setattr(r, "CORRECTIONS", {"svc:GetThing": ([{"type": "thing", "fill": {}}], "a reason")})
|
||||
entry = r.entry_for("svc:GetThing", {"action": "svc:GetThing", "types": ["thing"]}, FORMATS, {})
|
||||
assert entry["resources"] == [{"type": "thing", "fill": {}}]
|
||||
|
||||
|
||||
def test_the_vendored_file_is_well_formed():
|
||||
document = json.loads(r.OUTPUT.read_text(encoding="utf-8"))
|
||||
assert r.validate(document) == []
|
||||
@@ -875,31 +854,31 @@ def test_the_vendored_file_is_well_formed():
|
||||
assert operations["ecr:BatchGetRepositoryScanningConfiguration"]["resources"] == [
|
||||
{"type": "repository", "fill": {"RepositoryName": "repositoryNames[]"}}]
|
||||
assert operations["cognito-idp:DescribeUserPool"]["resources"] == [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]
|
||||
# StartExecution's name is the execution's, so only its state machine ARN is read, up to a test case's #.
|
||||
assert operations["states:StartExecution"]["resources"] == [
|
||||
{"types": ["statemachine"], "arn": "stateMachineArn", "before": "#"}]
|
||||
# StartExecution's name is the execution's, so only its state machine ARN is read; Step Functions drops a test
|
||||
# case's `#` from it at runtime (StoredResourceArns.canonical).
|
||||
assert operations["states:StartExecution"]["resources"] == [{"types": ["statemachine"], "arn": "stateMachineArn"}]
|
||||
# An ARN inside a structure or each of a list's structures.
|
||||
assert operations["elasticloadbalancing:SetRulePriorities"]["resources"] == [
|
||||
{"types": ["listener-rule/app", "listener-rule/net"], "arn": "RulePriorities[].RuleArn"}]
|
||||
assert operations["states:CreateStateMachineAlias"]["resources"] == [
|
||||
{"types": ["statemachine"], "arn": "routingConfiguration[].stateMachineVersionArn"}]
|
||||
# An EventBridge rule is on the bus EventBusName names, by name or ARN, or the default one when it names none.
|
||||
# An EventBridge rule is on the bus EventBusName names, by name or ARN; a rule on the default bus, the one a
|
||||
# request naming none acts on, which EventBridge gives at runtime, has no bus in its ARN, and a default bus's ARN
|
||||
# puts it in that ARN's account.
|
||||
assert operations["events:DescribeRule"]["resources"] == [
|
||||
{"type": "rule-on-default-event-bus", "fill": {"RuleName": "Name"}, "when": {"EventBusName": ["default"]},
|
||||
"absent": {"EventBusName": "default"}, "arnOf": {"EventBusName": "event-bus"}},
|
||||
{"type": "rule-on-custom-event-bus", "fill": {"EventBusName": "EventBusName", "RuleName": "Name"},
|
||||
"unless": {"EventBusName": ["default"]}, "absent": {"EventBusName": "default"}, "arnOf": {"EventBusName": "event-bus"}}]
|
||||
"arnOf": {"EventBusName": "event-bus"}, "unlessDefault": {"EventBusName": "event-bus"}},
|
||||
{"type": "rule-on-default-event-bus", "fill": {"RuleName": "Name"}, "whenDefault": {"EventBusName": "event-bus"},
|
||||
"arnOf": {"EventBusName": "event-bus"}}]
|
||||
assert operations["events:DescribeEventBus"]["resources"] == [
|
||||
{"types": ["event-busv2"], "arn": "EventBusArn", "endpoint": "eventsv2"},
|
||||
{"type": "event-bus", "fill": {"EventBusName": "Name"}, "absent": {"Name": "default"}, "endpoint": "events",
|
||||
"arnOf": {"Name": "event-bus"}}]
|
||||
# Each PutEvents entry is on the bus it names, by name or ARN, or the default one when it names none; an
|
||||
# EventBridge V2 request is on the one bus its EventBusArn names.
|
||||
{"type": "event-bus", "fill": {"EventBusName": "Name"}, "arnOf": {"Name": "event-bus"}, "endpoint": "events"}]
|
||||
# Each PutEvents entry is on the bus it names, by name or ARN (the default one, which EventBridge gives, when it
|
||||
# names none); an EventBridge V2 request is on the one bus its EventBusArn names.
|
||||
assert operations["events:PutEvents"]["resources"] == [
|
||||
{"types": ["event-busv2"], "arn": "EventBusArn", "endpoint": "eventsv2"},
|
||||
{"type": "event-bus", "fill": {"EventBusName": "Entries[].EventBusName"},
|
||||
"absent": {"Entries[].EventBusName": "default"}, "endpoint": "events",
|
||||
"arnOf": {"Entries[].EventBusName": "event-bus"}}]
|
||||
"arnOf": {"Entries[].EventBusName": "event-bus"}, "endpoint": "events"}]
|
||||
# EventBridge V2 is read beside EventBridge, and where both name an operation's resources, which one applies is
|
||||
# the endpoint serving the request, never a member a caller could add.
|
||||
assert document["namespaces"]["events"] == ["eventbridgev2", "events"]
|
||||
@@ -908,11 +887,11 @@ def test_the_vendored_file_is_well_formed():
|
||||
assert operations["events:DeleteEventBus"]["resources"] == [
|
||||
{"types": ["event-busv2"], "arn": "EventBusArn", "endpoint": "eventsv2"},
|
||||
{"type": "event-bus", "fill": {"EventBusName": "Name"}, "endpoint": "events"}]
|
||||
assert operations["events:CreateEventBus"]["resources"][1:] == [
|
||||
{"type": "event-bus", "fill": {"EventBusName": "Name"}, "endpoint": "events", "made": True},
|
||||
{"type": "event-busv2", "fill": {"EventBusName": "Name"}, "endpoint": "eventsv2"}]
|
||||
created = operations["events:CreateEventBus"]["resources"]
|
||||
assert {"type": "event-bus", "fill": {"EventBusName": "Name"}, "endpoint": "events", "made": True} in created
|
||||
assert {"type": "event-busv2", "fill": {"EventBusName": "Name"}, "endpoint": "eventsv2"} in created
|
||||
# A create's tags are checked on what it makes: not a dead-letter target or the bus a subscriber is made on.
|
||||
assert "made" not in operations["events:CreateEventBus"]["resources"][0]
|
||||
assert [resource for resource in created if "arn" in resource and resource.get("made")] == []
|
||||
assert [resource for resource in operations["events:CreateSubscriber"]["resources"] if resource.get("made")] == [
|
||||
{"type": "subscriber", "fill": {"SubscriberName": "Name"}, "made": True}]
|
||||
assert not any("when" in resource or "unless" in resource
|
||||
@@ -947,47 +926,8 @@ def test_the_vendored_file_is_well_formed():
|
||||
"type": "loadbalancer/app/", "fill": {"LoadBalancerName": "Name"}, "when": {"Type": ["application", None]}}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("operation", ["SendTaskSuccess", "SendTaskFailure", "SendTaskHeartbeat"])
|
||||
def test_callback_resources_are_resolved_from_the_token(operation):
|
||||
resources, reason = r.CORRECTIONS[f"states:{operation}"]
|
||||
assert resources == [{"type": kind, "fill": {}, "find": ["taskToken"]}
|
||||
for kind in ("activity", "statemachine")]
|
||||
assert "2026-11-02" in reason
|
||||
assert "no resource types" in reason
|
||||
|
||||
|
||||
def test_list_tables_correction_names_the_literal_collection_without_selectors():
|
||||
resources, reason = r.CORRECTIONS["dynamodb:ListTables"]
|
||||
assert resources == [{"type": "table", "fill": {}}]
|
||||
assert "table/?" in reason
|
||||
formats = {"table": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}"}
|
||||
assert not r._resource_problems("dynamodb:ListTables", resources[0], [], formats)
|
||||
assert r._resource_problems("dynamodb:OtherOperation", resources[0], [], formats)
|
||||
assert r.reads("dynamodb:ListTables")
|
||||
assert not r.reads("dynamodb:BatchWriteItem")
|
||||
assert not r.reads("dynamodb:ExecuteStatement")
|
||||
|
||||
|
||||
def test_hand_built_correction_is_generated_without_claiming_other_operations(corrections, tmp_path):
|
||||
corrections.setattr(r, "CORRECTIONS", {"hand:ListThings": ([{"type": "thing", "fill": {}}], "measured collection")})
|
||||
documents = DOCUMENTS + [reference("hand", {"ListThings": [], "PutThing": ["thing"]},
|
||||
{"thing": "arn:${Partition}:hand:${Region}:${Account}:thing/${ThingName}"})]
|
||||
hand = model({"ListThings": {}, "PutThing": {"ThingName": "String"}})
|
||||
hand["metadata"]["endpointPrefix"] = "hand"
|
||||
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}}), "hand": hand})
|
||||
document = r.build(documents, "test", tmp_path, "botocore test")
|
||||
assert document["operations"]["hand:ListThings"] == {
|
||||
"action": "hand:ListThings", "types": [], "resources": [{"type": "thing", "fill": {}}]}
|
||||
assert "hand:PutThing" not in document["operations"]
|
||||
assert document["namespaces"]["hand"] == ["hand"]
|
||||
assert document["handBuilt"] == ["hand"]
|
||||
assert r.validate(document) == []
|
||||
assert r.derive(document, tmp_path) == []
|
||||
assert r.verify_against(document, r.checked_actions(documents), document["arnFormats"]) == ([], [])
|
||||
|
||||
|
||||
def test_hand_built_operations_listed_to_read_follow_the_rule(corrections, tmp_path):
|
||||
corrections.setattr(r, "READ_IN_HAND_BUILT", {"hand:GetThing": "a family the rule reads"})
|
||||
def test_hand_built_operations_listed_to_read_follow_the_rule(isolated, tmp_path):
|
||||
isolated.setattr(r, "READ_IN_HAND_BUILT", {"hand:GetThing": "a family the rule reads"})
|
||||
documents = DOCUMENTS + [reference("hand", {"GetThing": ["thing"], "PutThing": ["thing"]},
|
||||
{"thing": "arn:${Partition}:hand:${Region}:${Account}:thing/${ThingName}"})]
|
||||
hand = model({"GetThing": {"ThingName": "String"}, "PutThing": {"ThingName": "String"}})
|
||||
@@ -1001,21 +941,86 @@ def test_hand_built_operations_listed_to_read_follow_the_rule(corrections, tmp_p
|
||||
assert r.validate(document) == []
|
||||
|
||||
|
||||
def test_operations_listed_to_read_must_exist_and_be_hand_built(corrections, tmp_path):
|
||||
def test_operations_listed_to_read_must_exist_and_be_hand_built(isolated, tmp_path):
|
||||
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}})})
|
||||
corrections.setattr(r, "READ_IN_HAND_BUILT", {"hand:Gone": "no longer there"})
|
||||
isolated.setattr(r, "READ_IN_HAND_BUILT", {"hand:Gone": "no longer there"})
|
||||
with pytest.raises(ValueError, match="READ_IN_HAND_BUILT names hand:Gone, which the reference does not give"):
|
||||
r.build(DOCUMENTS, "test", tmp_path, "botocore test")
|
||||
|
||||
|
||||
def test_measured_callback_correction_retains_action_metadata_and_rejects_unlisted_resources():
|
||||
formats = {"activity": "arn:${Partition}:states:${Region}:${Account}:activity:${ActivityName}",
|
||||
"statemachine": "arn:${Partition}:states:${Region}:${Account}:stateMachine:${StateMachineName}"}
|
||||
resource = {"type": "activity", "fill": {}, "find": ["taskToken"]}
|
||||
assert not r._resource_problems("states:SendTaskSuccess", resource, [], formats)
|
||||
assert r._resource_problems("states:SendTaskSuccess", {**resource, "find": ["otherToken"]}, [], formats)
|
||||
assert r._resource_problems("states:OtherOperation", resource, [], formats)
|
||||
assert r._resource_problems("states:SendTaskSuccess", resource, [], {})
|
||||
MEASURED_FORMATS = {"thing": "arn:${Partition}:hand:${Region}:${Account}:thing/${ThingName}"}
|
||||
PROBED = "real AWS probes in https://example.com/probes accept an allow and enforce a deny on thing/*"
|
||||
|
||||
|
||||
def measured_documents(tmp_path, listed: list[str]) -> list[dict]:
|
||||
hand = model({"ListThings": {"StartName": "String"}})
|
||||
hand["metadata"]["endpointPrefix"] = "hand"
|
||||
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}}), "hand": hand})
|
||||
return DOCUMENTS + [reference("hand", {"ListThings": listed}, MEASURED_FORMATS)]
|
||||
|
||||
|
||||
def test_a_measured_operation_takes_the_resources_aws_was_measured_to_check_where_the_reference_lists_none(
|
||||
isolated, tmp_path):
|
||||
isolated.setattr(r, "MEASURED", {"hand:ListThings": ([{"type": "thing", "fill": {}}], PROBED)})
|
||||
document = r.build(measured_documents(tmp_path, []), "test", tmp_path, "botocore test")
|
||||
# Read in a namespace otherwise built by hand, keeping the reference's empty types.
|
||||
assert document["operations"]["hand:ListThings"] == {
|
||||
"action": "hand:ListThings", "types": [], "resources": [{"type": "thing", "fill": {}}]}
|
||||
assert r.reads("hand:ListThings")
|
||||
assert r.validate(document) == []
|
||||
assert r.derive(document, tmp_path) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("measured, listed, problem", [
|
||||
# No link to the measurement it rests on.
|
||||
(([{"type": "thing", "fill": {}}], "probed against AWS, results not published"), [], "no link to the measurement"),
|
||||
# A type the reference lists for the action: the rules read it, so a measurement of it belongs in a rule.
|
||||
(([{"type": "thing", "fill": {}}], PROBED), ["thing"], "which the Service Reference lists for its action"),
|
||||
# A type with no ARN format.
|
||||
(([{"type": "gadget", "fill": {}}], PROBED), [], "no ARN format"),
|
||||
# What the rules already give: an entry a later rule or reference update makes redundant is taken out.
|
||||
(([], PROBED), [], "what the rules already give"),
|
||||
])
|
||||
def test_a_measured_entry_is_refused_unless_it_cites_aws_for_what_the_metadata_does_not_say(
|
||||
isolated, tmp_path, measured, listed, problem):
|
||||
isolated.setattr(r, "MEASURED", {"hand:ListThings": measured})
|
||||
with pytest.raises(ValueError, match=problem):
|
||||
r.build(measured_documents(tmp_path, listed), "test", tmp_path, "botocore test")
|
||||
|
||||
|
||||
def test_a_measured_entry_must_name_an_operation_the_file_reads(isolated, tmp_path):
|
||||
isolated.setattr(r, "MEASURED", {"hand:Gone": ([{"type": "thing", "fill": {}}], PROBED)})
|
||||
with pytest.raises(ValueError, match="MEASURED gives hand:Gone, which the file does not read"):
|
||||
r.build(measured_documents(tmp_path, []), "test", tmp_path, "botocore test")
|
||||
|
||||
|
||||
def test_a_variable_no_member_fills_takes_the_one_value_of_its_enum_the_operations_name_gives():
|
||||
formats = {"actiontype": "arn:${Partition}:svc:${Region}:${Account}:actiontype:${Owner}/${Category}"}
|
||||
owners = model({"CreateCustomActionType": {"category": "String"}})
|
||||
owners["shapes"]["ActionOwner"] = {"type": "string", "enum": ["AWS", "ThirdParty", "Custom"]}
|
||||
named = [{"type": "actiontype", "fill": {"Category": "category"}}]
|
||||
assert r.with_enum_named("svc:CreateCustomActionType", named, formats, {"svc": owners}) == [
|
||||
dict(named[0], fixed={"Owner": "Custom"})]
|
||||
# A name giving none of its values, or a word inside another, fixes nothing.
|
||||
assert r.with_enum_named("svc:CreateActionType", named, formats, {"svc": owners}) == named
|
||||
assert r.with_enum_named("svc:CreateCustomizedActionType", named, formats, {"svc": owners}) == named
|
||||
|
||||
|
||||
def test_a_type_named_by_a_member_documented_as_holding_the_operations_subject_is_reached_through_it_when_left_out():
|
||||
groups = model({"ModifyInstanceGroups": {"ClusterId": "String"}})
|
||||
groups["shapes"]["ModifyInstanceGroupsIn"]["members"]["ClusterId"]["documentation"] = \
|
||||
"<p>The ID of the cluster to which the instance group belongs.</p>"
|
||||
named = [{"type": "cluster", "fill": {"ClusterId": "ClusterId"}}]
|
||||
fields = {"InstanceGroups[].InstanceGroupId": "InstanceGroupId"}
|
||||
assert r.with_subject_through("svc:ModifyInstanceGroups", named, {"ClusterId": "ClusterId"}, fields,
|
||||
{"ClusterId"}, {"svc": groups}) == named + [
|
||||
{"types": ["cluster"], "through": "InstanceGroups[].InstanceGroupId", "when": {"ClusterId": [None]}}]
|
||||
# A member that must be given, or one not documented as holding the subject, is all that names the type.
|
||||
assert r.with_subject_through("svc:ModifyInstanceGroups", named, {"ClusterId": "ClusterId"}, fields,
|
||||
set(), {"svc": groups}) == named
|
||||
groups["shapes"]["ModifyInstanceGroupsIn"]["members"]["ClusterId"]["documentation"] = "<p>The cluster.</p>"
|
||||
assert r.with_subject_through("svc:ModifyInstanceGroups", named, {"ClusterId": "ClusterId"}, fields,
|
||||
{"ClusterId"}, {"svc": groups}) == named
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -1032,7 +1037,7 @@ def rest_model(operations: dict[str, dict[str, str]], located: dict[str, dict[st
|
||||
return built
|
||||
|
||||
|
||||
def test_a_rest_request_reads_its_path_and_query_members_and_records_where_the_ones_it_reads_are(corrections, tmp_path):
|
||||
def test_a_rest_request_reads_its_path_and_query_members_and_records_where_the_ones_it_reads_are(isolated, tmp_path):
|
||||
svc = rest_model({"GetThing": {"ThingName": "String", "Marker": "String"}, "ListThings": {"Marker": "String"}},
|
||||
{"GetThing": {"ThingName": "uri:Name", "Marker": "querystring:marker"},
|
||||
"ListThings": {"Marker": "querystring:marker"}})
|
||||
@@ -1053,7 +1058,7 @@ def test_a_member_two_clients_locate_apart_is_an_error():
|
||||
r.located_members({"one": one, "two": two}, "GetThing")
|
||||
|
||||
|
||||
def test_a_located_member_must_be_a_path_label_or_a_query_parameter(corrections, tmp_path):
|
||||
def test_a_located_member_must_be_a_path_label_or_a_query_parameter(isolated, tmp_path):
|
||||
write_models(tmp_path, {"svc": rest_model({"GetThing": {"ThingName": "String"}, "ListThings": {}},
|
||||
{"GetThing": {"ThingName": "uri:ThingName"}})})
|
||||
document = r.build(DOCUMENTS, "test", tmp_path, "botocore test")
|
||||
@@ -1068,8 +1073,8 @@ SPLIT = [reference("svc", {"GetThing": ["thing"], "ListThings": []}, {"thing": F
|
||||
SPLIT[0]["Actions"].append({"Name": "DescribeThing", "Resources": [{"Name": "thing"}]})
|
||||
|
||||
|
||||
def test_a_rest_models_operations_the_reference_lists_for_no_client_take_their_own_actions(corrections):
|
||||
corrections.setattr(r, "REST_MODELS", {"svc-v2": "svc"})
|
||||
def test_a_rest_models_operations_the_reference_lists_for_no_client_take_their_own_actions(isolated):
|
||||
isolated.setattr(r, "REST_MODELS", {"svc-v2": "svc"})
|
||||
found = r.with_rest_operations(r.checked_actions(SPLIT), SPLIT, {"svc-v2": {"GetThing", "DescribeThing", "Gone"}})
|
||||
assert found["svc:GetThing"]["clients"] == ["svc", "svc-v2"]
|
||||
assert found["svc:DescribeThing"] == {"action": "svc:DescribeThing", "types": ["thing"], "clients": ["svc-v2"]}
|
||||
@@ -1077,8 +1082,8 @@ def test_a_rest_models_operations_the_reference_lists_for_no_client_take_their_o
|
||||
assert "svc:Gone" not in found
|
||||
|
||||
|
||||
def test_a_namespace_reads_the_operations_of_the_rest_models_floci_routes_under_it(corrections, tmp_path):
|
||||
corrections.setattr(r, "REST_MODELS", {"svc-v2": "svc"})
|
||||
def test_a_namespace_reads_the_operations_of_the_rest_models_floci_routes_under_it(isolated, tmp_path):
|
||||
isolated.setattr(r, "REST_MODELS", {"svc-v2": "svc"})
|
||||
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}}),
|
||||
"svc-v2": rest_model({"DescribeThing": {"ThingName": "String"}},
|
||||
{"DescribeThing": {"ThingName": "uri:ThingName"}})})
|
||||
@@ -1097,8 +1102,8 @@ def test_a_namespace_reads_the_operations_of_the_rest_models_floci_routes_under_
|
||||
assert r.main(["--verify", "--source-dir", str(sources), "--output", str(output)]) == 0
|
||||
|
||||
|
||||
def test_verify_reports_a_rest_models_operation_whose_action_aws_no_longer_has(corrections, tmp_path):
|
||||
corrections.setattr(r, "REST_MODELS", {"svc-v2": "svc"})
|
||||
def test_verify_reports_a_rest_models_operation_whose_action_aws_no_longer_has(isolated, tmp_path):
|
||||
isolated.setattr(r, "REST_MODELS", {"svc-v2": "svc"})
|
||||
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}}),
|
||||
"svc-v2": rest_model({"DescribeThing": {"ThingName": "String"}},
|
||||
{"DescribeThing": {"ThingName": "uri:ThingName"}})})
|
||||
@@ -1209,7 +1214,6 @@ def test_controltower_entries_are_derived_without_operation_corrections(operatio
|
||||
from regen_partitions import resolve_botocore_data
|
||||
|
||||
key = "controltower:" + operation
|
||||
assert key not in r.CORRECTIONS
|
||||
document = json.loads(r.OUTPUT.read_text())
|
||||
data, _ = resolve_botocore_data(None)
|
||||
model = r.load_models(data, {"controltower"})
|
||||
@@ -1262,8 +1266,6 @@ def test_no_inferred_identifier_metadata_or_withdrawn_redshift_rows():
|
||||
document = json.loads(r.OUTPUT.read_text())
|
||||
resource = document["operations"]["redshift:DescribeClusters"]["resources"][0]
|
||||
assert "arnOf" not in resource
|
||||
assert "redshift:CreateCluster" not in r.CORRECTIONS
|
||||
assert "redshift:AssociateDataShareConsumer" not in r.CORRECTIONS
|
||||
|
||||
|
||||
def test_sso_access_scope_does_not_authorize_target_applications():
|
||||
@@ -1295,14 +1297,14 @@ def test_a_member_whose_enum_lists_two_of_the_actions_types_picks_the_type():
|
||||
"hostedzone": "arn:${Partition}:route53:::hostedzone/${Id}"}
|
||||
members = {"ResourceType": "ResourceType", "ResourceId": "ResourceId"}
|
||||
enums = {"ResourceType": {"healthcheck", "hostedzone"}}
|
||||
assert r.picked_by_enum(["healthcheck", "hostedzone"], formats, members, enums) == [
|
||||
assert r.picked_by_enum("route53:TagResource", ["healthcheck", "hostedzone"], formats, members, enums) == [
|
||||
{"type": "healthcheck", "fill": {"Id": "ResourceId"}, "when": {"ResourceType": ["healthcheck"]}},
|
||||
{"type": "hostedzone", "fill": {"Id": "ResourceId"}, "when": {"ResourceType": ["hostedzone"]}}]
|
||||
# An enum listing one of the action's types, or none of them, picks nothing.
|
||||
assert r.picked_by_enum(["hostedzone"], formats, members, enums) is None
|
||||
assert r.picked_by_enum(["healthcheck", "hostedzone"], formats, members, {"ResourceType": {"other"}}) is None
|
||||
assert r.picked_by_enum("route53:TagResource", ["hostedzone"], formats, members, enums) is None
|
||||
assert r.picked_by_enum("route53:TagResource", ["healthcheck", "hostedzone"], formats, members, {"ResourceType": {"other"}}) is None
|
||||
# Without a member naming the resource, the request names none of them.
|
||||
assert r.picked_by_enum(["healthcheck", "hostedzone"], formats, {"ResourceType": "ResourceType"}, enums) is None
|
||||
assert r.picked_by_enum("route53:TagResource", ["healthcheck", "hostedzone"], formats, {"ResourceType": "ResourceType"}, enums) is None
|
||||
|
||||
|
||||
def test_an_enum_value_picks_a_type_ignoring_case_and_hyphens_and_the_resource_id_fills_it():
|
||||
@@ -1311,7 +1313,8 @@ def test_an_enum_value_picks_a_type_ignoring_case_and_hyphens_and_the_resource_i
|
||||
"parameter": "arn:${Partition}:ssm:${Region}:${Account}:parameter/${ParameterNameWithoutLeadingSlash}"}
|
||||
members = {"ResourceType": "ResourceType", "ResourceId": "ResourceId"}
|
||||
enums = {"ResourceType": {"Document", "ManagedInstance", "Parameter", "Automation"}}
|
||||
assert r.picked_by_enum(["document", "managed-instance", "parameter"], formats, members, enums) == [
|
||||
assert r.picked_by_enum("ssm:AddTagsToResource", ["document", "managed-instance", "parameter"], formats, members,
|
||||
enums) == [
|
||||
{"type": "document", "fill": {"DocumentName": "ResourceId"}, "when": {"ResourceType": ["Document"]}},
|
||||
{"type": "managed-instance", "fill": {"InstanceId": "ResourceId"},
|
||||
"when": {"ResourceType": ["ManagedInstance"]}},
|
||||
@@ -1328,3 +1331,239 @@ def test_a_member_whose_shape_is_named_after_the_type_names_it():
|
||||
assert r.resources_for("svc:GetPoolsByPath", ["pool"], FORMATS, members("Path"), shapes={"Path": "PoolName"}) == []
|
||||
assert r.resources_for("svc:GetThingsByPath", ["thing"], FORMATS, members("Paths[]"),
|
||||
shapes={"Paths": "ThingName"}) == []
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# What botocore's documentation and shapes say a member names
|
||||
# --------------------------------------------------------------------------- #
|
||||
def documented(operation: str, fields: dict[str, tuple[str, str]], output: dict[str, str] | None = None,
|
||||
protocol: str = "json") -> dict:
|
||||
"""A model whose operation takes the members given, each a shape name and its documentation."""
|
||||
shapes = {"String": {"type": "string"}, "Strings": {"type": "list", "member": {"shape": "String"}},
|
||||
"AccountId": {"type": "string", "pattern": "\\d{12}"},
|
||||
"RoleArn": {"type": "string", "pattern": "arn:aws(-[\\w]+)*:iam::[0-9]{12}:role/.*"}}
|
||||
shapes["In"] = {"type": "structure", "members": {name: {"shape": shape, "documentation": f"<p>{doc}</p>"}
|
||||
for name, (shape, doc) in fields.items()}}
|
||||
spec = {"input": {"shape": "In"}}
|
||||
if output:
|
||||
shapes["Out"] = {"type": "structure", "members": {name: {"shape": shape} for name, shape in output.items()}}
|
||||
spec["output"] = {"shape": "Out"}
|
||||
return {"metadata": {"protocol": protocol, "endpointPrefix": "svc"}, "operations": {operation: spec}, "shapes": shapes}
|
||||
|
||||
|
||||
DOCUMENTED = {"pipeline": "arn:${Partition}:svc:${Region}:${Account}:pipeline/${PipelineName}",
|
||||
"processor": "arn:${Partition}:svc:${Region}:${Account}:processor/${ProcessorId}",
|
||||
"trail": "arn:${Partition}:svc:${Region}:${Account}:trail/${TrailName}",
|
||||
"dashboard": "arn:${Partition}:svc:${Region}:${Account}:dashboard/${DashboardName}"}
|
||||
|
||||
|
||||
def test_a_member_whose_documentation_names_the_type_fills_it_or_is_found_by_its_service():
|
||||
starts = {"svc": documented("StartPipelineExecution", {"name": ("String", "The name of the pipeline to start.")})}
|
||||
assert r.with_documented("svc:StartPipelineExecution", ["pipeline"], DOCUMENTED, starts, []) == [
|
||||
{"type": "pipeline", "fill": {"PipelineName": "name"}}]
|
||||
# A name for an id variable: the type's service finds the resource by it, its id open when it finds none.
|
||||
stops = {"svc": documented("StopProcessor", {"Name": ("String", "The name of the processor to stop.")})}
|
||||
assert r.with_documented("svc:StopProcessor", ["processor"], DOCUMENTED, stops, []) == [
|
||||
{"type": "processor", "fill": {}, "find": ["Name"]}]
|
||||
# A type named only past the word the documentation stops at names nothing: a pipeline execution is no pipeline.
|
||||
runs = {"svc": documented("GetRun", {"id": ("String", "The ID of the pipeline execution.")})}
|
||||
assert r.with_documented("svc:GetRun", ["pipeline"], DOCUMENTED, runs, []) == []
|
||||
# A type an ARN member of the request already holds takes no other member: an update's Name is the new name.
|
||||
held = [{"types": ["pipeline"], "arn": "PipelineArn"}]
|
||||
updates = {"svc": documented("UpdatePipeline", {"Name": ("String", "The name of the pipeline."),
|
||||
"PipelineArn": ("String", "The ARN of the pipeline.")})}
|
||||
assert r.with_documented("svc:UpdatePipeline", ["pipeline"], DOCUMENTED, updates, held) == held
|
||||
|
||||
|
||||
def test_a_member_whose_documentation_says_it_is_an_arn_holds_one():
|
||||
tags = {"svc": documented("AddTags", {"ResourceId": ("String", "Specifies the ARN of the trail or dashboard to "
|
||||
"which one or more tags will be added.")})}
|
||||
assert r.with_documented("svc:AddTags", ["dashboard", "trail"], DOCUMENTED, tags, []) == [
|
||||
{"types": ["dashboard", "trail"], "arn": "ResourceId"}]
|
||||
# A name or an ARN is a name, and an ARN of something else is no ARN of the action's types.
|
||||
named = {"svc": documented("GetTrail", {"Name": ("String", "Specifies the name or the ARN of the trail.")})}
|
||||
assert r.with_documented("svc:GetTrail", ["trail"], DOCUMENTED, named, []) == [
|
||||
{"type": "trail", "fill": {"TrailName": "Name"}}]
|
||||
keys = {"svc": documented("UntagResource", {"ResourceTagKeys": ("Strings", "The tag keys associated with the "
|
||||
"resource ARN.")})}
|
||||
assert r.with_documented("svc:UntagResource", ["trail"], DOCUMENTED, keys, []) == []
|
||||
assert r.doc_head("the amazon resource name (arn) for which you want to describe the tags") == (
|
||||
"the amazon resource name (arn)", None)
|
||||
|
||||
|
||||
def test_an_arn_member_whose_pattern_takes_another_services_arns_names_none_of_the_actions_resources():
|
||||
models = {"svc": documented("CreatePipeline", {"roleArn": ("RoleArn", "The role it assumes.")})}
|
||||
assert r.with_documented("svc:CreatePipeline", ["pipeline"], DOCUMENTED, models,
|
||||
[{"types": ["pipeline"], "arn": "roleArn"}]) == []
|
||||
# A pattern whose ARN is optional, in a group of its own: CUR's billing view ARN.
|
||||
views = documented("PutPipeline", {"viewArn": ("ViewArn", "The billing view.")})
|
||||
views["shapes"]["ViewArn"] = {"type": "string",
|
||||
"pattern": "(arn:aws(-cn)?:billing::[0-9]{12}:billingview/)?[a-zA-Z0-9_\\+=\\.\\-@].{1,30}"}
|
||||
assert r.with_documented("svc:PutPipeline", ["pipeline"], DOCUMENTED, {"svc": views},
|
||||
[{"types": ["pipeline"], "arn": "viewArn"}]) == []
|
||||
|
||||
|
||||
def test_an_arn_member_documented_as_another_types_names_none_of_the_actions_resources():
|
||||
# CreateExport's `Export.ExportArn`, "the ARN for this export", is the export's, of no type the action acts on.
|
||||
model_ = documented("CreateTrailExport", {})
|
||||
model_["shapes"]["Export"] = {"type": "structure", "members": {
|
||||
"ExportArn": {"shape": "String", "documentation": "<p>The Amazon Resource Name (ARN) for this dashboard.</p>"}}}
|
||||
model_["shapes"]["In"]["members"]["Export"] = {"shape": "Export"}
|
||||
assert r.with_documented("svc:CreateTrailExport", ["trail"], DOCUMENTED, {"svc": model_},
|
||||
[{"types": ["trail"], "arn": "Export.ExportArn"}]) == []
|
||||
# One documented as an acted-on type's is kept, and so is one named after it, whatever its documentation says.
|
||||
model_["shapes"]["Export"]["members"]["ExportArn"]["documentation"] = "<p>The ARN of the trail.</p>"
|
||||
assert r.with_documented("svc:CreateTrailExport", ["trail"], DOCUMENTED, {"svc": model_},
|
||||
[{"types": ["trail"], "arn": "Export.ExportArn"}]) == [{"types": ["trail"], "arn": "Export.ExportArn"}]
|
||||
named = documented("PutTrailSetting", {"trailArn": ("String", "The Amazon Resource Name (ARN) of the dashboard.")})
|
||||
assert r.with_documented("svc:PutTrailSetting", ["trail"], DOCUMENTED, {"svc": named},
|
||||
[{"types": ["trail"], "arn": "trailArn"}]) == [{"types": ["trail"], "arn": "trailArn"}]
|
||||
|
||||
|
||||
def test_a_structures_field_and_each_lists_element_name_the_type_they_are_named_after():
|
||||
model_ = documented("CreateBudget", {})
|
||||
model_["shapes"]["Budget"] = {"type": "structure", "members": {"BudgetName": {"shape": "String"},
|
||||
"BillingViewArn": {"shape": "String"}}}
|
||||
model_["shapes"]["In"]["members"]["Budget"] = {"shape": "Budget"}
|
||||
formats = {"budget": "arn:${Partition}:svc::${Account}:budget/${BudgetName}"}
|
||||
assert r.with_documented("svc:CreateBudget", ["budget"], formats, {"svc": model_},
|
||||
[{"type": "budget", "fill": {}}]) == [{"type": "budget", "fill": {"BudgetName": "Budget.BudgetName"}}]
|
||||
# A field of each element of a list of structures, as of each value of a map.
|
||||
entries = documented("PutEvents", {})
|
||||
entries["shapes"]["Entry"] = {"type": "structure", "members": {"BusName": {"shape": "String"}}}
|
||||
entries["shapes"]["Entries"] = {"type": "list", "member": {"shape": "Entry"}}
|
||||
entries["shapes"]["In"]["members"]["Entries"] = {"shape": "Entries"}
|
||||
assert r.map_fields({"svc": entries}, "PutEvents") == {"Entries[].BusName": "BusName"}
|
||||
|
||||
|
||||
def test_the_id_a_create_answers_beside_another_types_arn_is_that_types():
|
||||
model_ = documented("TerminateJobFlows", {"JobFlowIds": ("Strings", "A list of job flows to be shut down.")})
|
||||
model_["operations"]["RunJobFlow"] = {"input": {"shape": "In"}, "output": {"shape": "RunOut"}}
|
||||
model_["shapes"]["RunOut"] = {"type": "structure", "members": {"JobFlowId": {"shape": "String"},
|
||||
"ClusterArn": {"shape": "String"}}}
|
||||
assert r.created_aliases({"svc": model_}) == {"jobflow": "cluster"}
|
||||
formats = {"cluster": "arn:${Partition}:svc:${Region}:${Account}:cluster/${ClusterId}"}
|
||||
assert r.with_documented("svc:TerminateJobFlows", ["cluster"], formats, {"svc": model_}, []) == [
|
||||
{"type": "cluster", "fill": {"ClusterId": "JobFlowIds[]"}}]
|
||||
|
||||
|
||||
def test_an_account_id_member_fills_an_account_id_variable():
|
||||
models = {"svc": documented("CreateAssignment", {"TargetId": ("AccountId", "TargetID is an account identifier.")})}
|
||||
formats = {"Account": "arn:${Partition}:svc:::account/${AccountId}"}
|
||||
assert r.with_documented("svc:CreateAssignment", ["Account"], formats, models, []) == [
|
||||
{"type": "Account", "fill": {"AccountId": "TargetId"}}]
|
||||
|
||||
|
||||
def test_a_non_create_about_a_type_its_action_does_not_act_on_reaches_the_acted_types_through_its_service():
|
||||
formats = {"build": "arn:${Partition}:svc:${Region}:${Account}:build/${BuildId}",
|
||||
"project": "arn:${Partition}:svc:${Region}:${Account}:project/${ProjectName}"}
|
||||
gets = {"svc": documented("BatchGetBuilds", {"ids": ("Strings", "The IDs of the builds.")})}
|
||||
assert r.with_documented("svc:BatchGetBuilds", ["project"], formats, gets, []) == [
|
||||
{"types": ["project"], "through": "ids[]"}]
|
||||
# A create's bare name is the new resource's.
|
||||
creates = {"svc": documented("CreateBuild", {"name": ("String", "The name of the build.")})}
|
||||
assert r.with_documented("svc:CreateBuild", ["project"], formats, creates, []) == []
|
||||
|
||||
|
||||
def test_an_enum_value_the_word_setting_two_formats_apart_abbreviates_picks_the_type():
|
||||
formats = {"loadbalancer": "arn:${Partition}:svc:${Region}:${Account}:loadbalancer/${LoadBalancerName}",
|
||||
"loadbalancer/app/": "arn:${Partition}:svc:${Region}:${Account}:loadbalancer/app/${LoadBalancerName}/${LoadBalancerId}",
|
||||
"loadbalancer/gwy/": "arn:${Partition}:svc:${Region}:${Account}:loadbalancer/gwy/${LoadBalancerName}/${LoadBalancerId}"}
|
||||
models = {"svc": documented("CreateLoadBalancer", {"Name": ("String", "The name of the load balancer."),
|
||||
"Type": ("String", "The type of load balancer. The default is application.")})}
|
||||
picked = r.picked_by_enum("svc:CreateLoadBalancer", ["loadbalancer/app/", "loadbalancer/gwy/"], formats,
|
||||
{"Name": "Name", "Type": "Type"}, {"Type": {"application", "gateway", "network"}}, models)
|
||||
assert picked == [
|
||||
{"type": "loadbalancer/app/", "fill": {"LoadBalancerName": "Name"}, "when": {"Type": ["application", None]}},
|
||||
{"type": "loadbalancer/gwy/", "fill": {"LoadBalancerName": "Name"}, "when": {"Type": ["gateway"]}}]
|
||||
|
||||
|
||||
def test_two_types_differing_by_one_variable_are_marked_for_the_default_its_service_gives():
|
||||
formats = {"rule-on-default-bus": "arn:${Partition}:svc:${Region}:${Account}:rule/${RuleName}",
|
||||
"rule-on-custom-bus": "arn:${Partition}:svc:${Region}:${Account}:rule/${BusName}/${RuleName}",
|
||||
"bus": "arn:${Partition}:svc:${Region}:${Account}:bus/${BusName}"}
|
||||
resources = [{"type": "rule-on-custom-bus", "fill": {"BusName": "BusName", "RuleName": "Name"}},
|
||||
{"type": "rule-on-default-bus", "fill": {"RuleName": "Name"}}]
|
||||
assert r.with_default_pairs(resources, formats, {"BusName"}) == [
|
||||
dict(resources[0], unlessDefault={"BusName": "bus"}), dict(resources[1], whenDefault={"BusName": "bus"})]
|
||||
# A required member always names its bus.
|
||||
assert r.with_default_pairs(resources, formats, set()) == resources
|
||||
|
||||
|
||||
def test_a_resource_one_optional_member_qualifies_is_named_only_when_the_request_gives_it():
|
||||
resources = [{"type": "dbname", "fill": {"ClusterName": "ClusterIdentifier", "DbName": "DbName"}},
|
||||
{"type": "dbuser", "fill": {"ClusterName": "ClusterIdentifier", "DbUser": "DbUser"}}]
|
||||
assert r.with_optional_qualifier(resources, {"ClusterIdentifier", "DbName"}) == [
|
||||
dict(resources[0], unless={"DbName": [None]}), resources[1]]
|
||||
assert r.with_optional_qualifier(resources, {"ClusterIdentifier"}) == resources
|
||||
|
||||
|
||||
def test_an_arn_patterns_type_words_and_a_clients_versioned_twin():
|
||||
assert r.pattern_words("arn:aws:svc:[a-z0-9-]+:([0-9]{12}):(bus-v2|subscriber|source-v2\\/(a|b))\\/[A-Za-z]+") == {
|
||||
"bus-v2", "subscriber", "source-v2"}
|
||||
assert r.pattern_words("(arn:aws[\\w-]*:svc:[a-z]+:[0-9]{12}:bus\\/)?[A-Za-z]+") == {"bus"}
|
||||
formats = {"bus": "arn:${Partition}:svc:${Region}:${Account}:bus/${BusName}",
|
||||
"busv2": "arn:${Partition}:svc:${Region}:${Account}:busv2/${BusName}/${OpaqueId}"}
|
||||
model_ = documented("CreateBus", {"Name": ("String", "The name of the bus.")})
|
||||
# A client whose patterns name only the versioned type reads the other as it.
|
||||
assert r.narrowed([{"type": "bus", "fill": {"BusName": "Name"}}], {"busv2"}, model_, "CreateBus", formats) == [
|
||||
{"type": "busv2", "fill": {"BusName": "Name"}}]
|
||||
assert r.narrowed([{"type": "bus", "fill": {"BusName": "Name"}}], {"bus", "busv2"}, model_, "CreateBus", formats) == [
|
||||
{"type": "bus", "fill": {"BusName": "Name"}}]
|
||||
|
||||
|
||||
def test_a_lone_resource_id_in_a_rest_request_is_found_by_its_path_labels_and_the_member_named_after_it():
|
||||
model_ = documented("DescribeUser", {"AwsAccountId": ("String", "The account."), "Namespace": ("String", "The namespace."),
|
||||
"UserName": ("String", "The name of the user that you want to describe.")},
|
||||
protocol="rest-json")
|
||||
model_["operations"]["DescribeUser"]["http"] = {
|
||||
"method": "GET", "requestUri": "/accounts/{AwsAccountId}/namespaces/{Namespace}/users/{UserName}"}
|
||||
for name in ("AwsAccountId", "Namespace", "UserName"):
|
||||
model_["shapes"]["In"]["members"][name].update(location="uri", locationName=name)
|
||||
formats = {"user": "arn:${Partition}:svc:${Region}:${Account}:user/${ResourceId}"}
|
||||
assert r.with_documented("svc:DescribeUser", ["user"], formats, {"svc": model_}, []) == [
|
||||
{"type": "user", "fill": {}, "find": ["AwsAccountId", "Namespace", "UserName"]}]
|
||||
# A member holding the user's ARN names it by that ARN, and its service has nothing to find.
|
||||
embeds = documented("GenerateEmbedUrlForRegisteredUser", {"AwsAccountId": ("String", "The account."),
|
||||
"UserArn": ("String", "The ARN of the user.")},
|
||||
protocol="rest-json")
|
||||
embeds["operations"]["GenerateEmbedUrlForRegisteredUser"]["http"] = {
|
||||
"method": "POST", "requestUri": "/accounts/{AwsAccountId}/embed-url/registered-user"}
|
||||
embeds["shapes"]["In"]["members"]["AwsAccountId"].update(location="uri", locationName="AwsAccountId")
|
||||
held = [{"types": ["user"], "arn": "UserArn"}]
|
||||
assert r.with_documented("svc:GenerateEmbedUrlForRegisteredUser", ["user"], formats, {"svc": embeds}, held) == held
|
||||
# A label after the member's own names something inside it: a membership's member is not its group's.
|
||||
members_ = documented("DescribeGroupMembership", {name: ("String", "A label.") for name in
|
||||
("AwsAccountId", "Namespace", "GroupName", "MemberName")},
|
||||
protocol="rest-json")
|
||||
members_["operations"]["DescribeGroupMembership"]["http"] = {
|
||||
"method": "GET",
|
||||
"requestUri": "/accounts/{AwsAccountId}/namespaces/{Namespace}/groups/{GroupName}/members/{MemberName}"}
|
||||
for name in ("AwsAccountId", "Namespace", "GroupName", "MemberName"):
|
||||
members_["shapes"]["In"]["members"][name].update(location="uri", locationName=name)
|
||||
groups = {"group": "arn:${Partition}:svc:${Region}:${Account}:group/${ResourceId}"}
|
||||
found = [{"type": "group", "fill": {}, "find": ["GroupName"]}]
|
||||
assert r.with_documented("svc:DescribeGroupMembership", ["group"], groups, {"svc": members_}, found) == [
|
||||
{"type": "group", "fill": {}, "find": ["AwsAccountId", "Namespace", "GroupName"]}]
|
||||
|
||||
|
||||
def test_a_resource_id_naming_whatever_the_action_acts_on_reaches_it_through_its_service():
|
||||
formats = {"cluster": "arn:${Partition}:svc:${Region}:${Account}:cluster/${ClusterId}",
|
||||
"studio": "arn:${Partition}:svc:${Region}:${Account}:studio/${StudioId}"}
|
||||
models = {"svc": documented("AddTags", {"ResourceId": ("String", "The resource identifier to tag."),
|
||||
"ClusterId": ("String", "The cluster that scopes the call.")})}
|
||||
# Another member then scopes the call rather than names a resource.
|
||||
assert r.with_documented("svc:AddTags", ["cluster", "studio"], formats, models,
|
||||
[{"type": "cluster", "fill": {"ClusterId": "ClusterId"}}]) == [
|
||||
{"types": ["cluster", "studio"], "through": "ResourceId"}]
|
||||
|
||||
|
||||
def test_a_resource_id_variable_takes_a_member_named_so_and_a_bare_id_the_member_named_after_the_type():
|
||||
# CreateOpsMetadata names `opsmetadata/${ResourceId}` by its `ResourceId`.
|
||||
assert r._filling("ResourceId", "opsmetadata", 1, {"ResourceId": "ResourceId", "Tags": "Tags[]"}, set()) == \
|
||||
"ResourceId"
|
||||
# A QuickSight ingestion's `ResourceId` is its `IngestionId` when no member is named so.
|
||||
assert r._filling("ResourceId", "ingestion", 1, {"IngestionId": "IngestionId"}, set()) == "IngestionId"
|
||||
# A bare `Id` is whatever the operation is about: the tenant's is its `DistributionTenantId`.
|
||||
assert r._filling("Id", "distributiontenant", 1, {"Id": "Id", "DistributionTenantId": "DistributionTenantId"},
|
||||
{"Id"}) == "DistributionTenantId"
|
||||
Reference in new issue
Block a user