mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(iam): check a Redshift Data statement in a session on the target the session runs on (#7300)
Under IAM enforcement, an ExecuteStatement or BatchExecuteStatement
naming only its SessionId was checked on `*`. A policy allowing one
cluster's or workgroup's ARN let a statement open a session there and
refused the next statement in it, and a deny on that ARN under an
allow on `*` let every statement after the first through.
A session runs on the cluster or serverless workgroup it was opened
on: ListSessions filters sessions "by session status, compute target
(cluster or serverless workgroup), or database", and the SessionId
"can then be used in subsequent ExecuteStatement and
BatchExecuteStatement operations". The Service Reference gives a
session no resource type, so the generator's new THROUGH names the
members a request names a resource through, with the types that
resource may be of: redshift-data:SessionId, on a cluster or a
workgroup. Each operation whose request has the member, and whose
action acts on one of those types, gets a generated
`{"types": [...], "through": "SessionId"}` entry, so there are no hand
corrections. The generator's validation and the Java loader reject a
`through` that is not one top-level member, or that sits beside any
other reading key.
For such an entry the reader asks the namespace's StoredResourceArns
through(member, value, region) for the ARN of the caller's resource
at the other end, and keeps it when it matches one of the types. When
there is none, as for a session that is closed, expired or another
caller's, it names nothing and the request stays on `*`; the Data API
then refuses it. RedshiftDataService now implements StoredResourceArns
for redshift-data, since it owns the sessions and builds their owner
scope: through gives the target ARN of the caller's open session,
through RedshiftDataSessions.targetArn, which find now shares; find
still gives the workgroup a name or an ARN finds, through the
resolver.
ExecuteStatement and BatchExecuteStatement gain the entry (1095
operations over 27 namespaces, unchanged). ListSessions takes a
SessionId too, but the Service Reference gives it no resource type,
so it stays on `*`. iam.md's sentence on EventBridge V2, which said
Floci does not serve it, now says how its requests are read.
This commit is contained in:
1 parent
db3efe8186
commit
c84e9249c9
15 files changed
+416
-42
No files matched your search
@@ -1711,8 +1711,10 @@ on `scalable-target/*` when there is none yet, as for a `RegisterScalableTarget`
|
||||
its tag operations name it by its ARN. A Redshift Data API request is checked on the cluster its
|
||||
`ClusterIdentifier` names, or on the ARN of the Redshift Serverless workgroup its `WorkgroupName`
|
||||
names by name or by ARN, which ends in the id Redshift Serverless gives it, `workgroup/<id>`, and on
|
||||
`workgroup/*` when there is no such workgroup; one naming only its session, by `SessionId`, is
|
||||
checked on `*`. EventBridge V2's API, which Floci does not serve, is not read. A
|
||||
`workgroup/*` when there is no such workgroup; one naming its session, by `SessionId`, on the
|
||||
cluster or workgroup the caller's session runs on, and on `*` when the caller has no such session.
|
||||
EventBridge V2's requests are read beside EventBridge's, each checked on the resources the API serving
|
||||
it names (an EventBridge V2 `PutEvents` on the bus its `EventBusArn` names). A
|
||||
state machine's version or alias
|
||||
(`stateMachine:<name>:<qualifier>`) is checked on the state machine's ARN, as Step Functions
|
||||
authorizes it, so a grant or a deny on `stateMachine:<name>` covers its versions and aliases, and
|
||||
|
||||
@@ -44,7 +44,7 @@ A request identifies its target cluster or serverless workgroup one of three way
|
||||
|
||||
A statement run against a workgroup reports `WorkgroupName` and omits `ClusterIdentifier`, and the reverse holds for a cluster statement. `ListDatabases`, `ListSchemas`, `ListTables` and `DescribeTable` accept `WorkgroupName` the same way.
|
||||
|
||||
Under IAM enforcement, `ExecuteStatement`, `BatchExecuteStatement`, `ListDatabases`, `ListSchemas`, `ListTables` and `DescribeTable` are checked on the cluster's ARN, or on the ARN of the workgroup `WorkgroupName` names, `workgroup/<id>`, whichever form it takes; a workgroup that does not exist is checked on `workgroup/*`, and a request naming only a `SessionId` on `*`.
|
||||
Under IAM enforcement, `ExecuteStatement`, `BatchExecuteStatement`, `ListDatabases`, `ListSchemas`, `ListTables` and `DescribeTable` are checked on the cluster's ARN, or on the ARN of the workgroup `WorkgroupName` names, `workgroup/<id>`, whichever form it takes; a workgroup that does not exist is checked on `workgroup/*`. `ExecuteStatement` and `BatchExecuteStatement` naming a `SessionId` are checked on the cluster or workgroup the caller's session runs on, so a grant or a deny on that target covers every statement in the session, and on `*` when the caller has no such session.
|
||||
|
||||
## Session reuse
|
||||
|
||||
|
||||
@@ -49,6 +49,8 @@ final class RequestResourceMembers {
|
||||
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, in the caller's account. */
|
||||
private static final List<String> FOUND_ONLY = List.of("absent", "arnOf", "account", "fixed", "before");
|
||||
/** 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", "endpoint");
|
||||
|
||||
/**
|
||||
* A top-level request member that holds a string, or a list of them when {@code list}, or, with a
|
||||
@@ -131,17 +133,19 @@ final class RequestResourceMembers {
|
||||
* and read no other way, in the caller's account (a scalable target by its service namespace, resource id and
|
||||
* scalable dimension). A resource with an {@code endpoint} applies only to a request the service of that endpoint
|
||||
* prefix serves, where two APIs share the operation's name and nothing in a request tells them apart
|
||||
* (EventBridge's {@code events} and EventBridge V2's {@code eventsv2}); null for every request.
|
||||
* (EventBridge's {@code events} and EventBridge V2's {@code eventsv2}); null for every request. A resource of one
|
||||
* of {@code types} may be named {@code through} a member of one value naming a resource of its service's own the
|
||||
* table gives no type, which runs on it (a Data API session, by its {@code SessionId}), and read no other way.
|
||||
*/
|
||||
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) {
|
||||
String endpoint, Member through) {
|
||||
|
||||
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);
|
||||
this(types, arn, fill, when, unless, absent, arnOf, account, before, fixed, made, List.of(), endpoint, null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -260,6 +264,18 @@ final class RequestResourceMembers {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " reads a member for " + operation
|
||||
+ " before " + before + ", no one character");
|
||||
}
|
||||
if (resource.has("through")) {
|
||||
List<String> types = resource.path("types").valueStream().map(JsonNode::asText).toList();
|
||||
Member through = member(operation, resource.path("through").asText(""));
|
||||
if (types.isEmpty() || !formats.keySet().containsAll(types) || through.list() || resource.properties()
|
||||
.stream().map(Map.Entry::getKey).anyMatch(key -> !THROUGH_KEYS.contains(key))) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " names a resource of " + operation + " through "
|
||||
+ resource.path("through") + ", no member of one value naming types with a format, or beside "
|
||||
+ "members reading it otherwise");
|
||||
}
|
||||
return new Resource(types, null, Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), null, null, Map.of(),
|
||||
false, List.of(), endpoint, through);
|
||||
}
|
||||
if (resource.has("arn")) {
|
||||
List<String> types = resource.path("types").valueStream().map(JsonNode::asText).toList();
|
||||
if (types.isEmpty() || !formats.keySet().containsAll(types)) {
|
||||
@@ -338,7 +354,7 @@ final class RequestResourceMembers {
|
||||
+ " 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);
|
||||
account, before, Map.copyOf(fixed), made, List.copyOf(find), endpoint, null);
|
||||
}
|
||||
|
||||
/** The values each member named in {@code when} or {@code unless} may have, an empty one for the member absent. */
|
||||
|
||||
@@ -64,7 +64,8 @@ public final class RequestResources {
|
||||
/**
|
||||
* As {@link #of(String, ContainerRequestContext, String, String, String)}, a resource of a type whose service
|
||||
* mints an id after its name, or as all of its ARN, being the one {@code stored} finds for the caller under the
|
||||
* name or the members the request gives, or else its ARN with that id open, as it is with no {@code stored}.
|
||||
* name or the members the request gives, or else its ARN with that id open, as it is with no {@code stored}; and
|
||||
* one a request names through another of its service's own, the one {@code stored} gives, or none.
|
||||
*/
|
||||
public static List<String> of(String operation, ContainerRequestContext ctx, String partition, String region,
|
||||
String accountId, StoredResourceArns stored) {
|
||||
@@ -96,6 +97,8 @@ public final class RequestResources {
|
||||
.findFirst().ifPresent(format -> addNamed(arns, format.checked(named), partition, region,
|
||||
accountId));
|
||||
}
|
||||
} else if (resource.through() != null) {
|
||||
through(arns, resource, formats, form, body, region, stored);
|
||||
} else if (!resource.find().isEmpty()) {
|
||||
found(arns, resource, formats, form, body, partition, region, accountId, stored);
|
||||
} else {
|
||||
@@ -368,6 +371,24 @@ public final class RequestResources {
|
||||
arns.add(found.orElseGet(() -> render(formats.get(type).format(), Map.of(), partition, region, accountId)));
|
||||
}
|
||||
|
||||
/**
|
||||
* The resource of one of the types a request names through a member naming another of its service's own, which
|
||||
* runs on it ({@code through}), when the request gives it one value: the ARN {@code stored} gives for the caller's
|
||||
* resource of that name; none when there is no such resource, which its handler refuses.
|
||||
*/
|
||||
private static void through(Set<String> arns, RequestResourceMembers.Resource resource,
|
||||
Map<String, RequestResourceMembers.ArnFormat> formats, Map<String, String> form,
|
||||
JsonNode body, String region, StoredResourceArns stored) {
|
||||
List<String> values = values(form, body, resource.through());
|
||||
if (stored == null || isNull(body, resource.through()) || values.size() != 1) {
|
||||
return;
|
||||
}
|
||||
stored.through(resource.through().name(), values.getFirst(), region)
|
||||
.filter(arn -> resource.types().stream().map(formats::get)
|
||||
.anyMatch(format -> format.pattern().matcher(arn).matches()))
|
||||
.ifPresent(arns::add);
|
||||
}
|
||||
|
||||
/** Whether a member that may give an ARN of a type instead of its name gives one. */
|
||||
private static boolean isArnOf(RequestResourceMembers.ArnFormat named, String value) {
|
||||
return named != null && named.pattern().matcher(value).matches();
|
||||
|
||||
@@ -8,7 +8,8 @@ import java.util.Optional;
|
||||
* service knows: after the name a request gives ({@code connection/<name>/<id>}), or as all of it, a request naming
|
||||
* the resource by members its ARN does not hold
|
||||
* ({@code scalable-target/<id>}, named by its service namespace, resource id and scalable dimension;
|
||||
* {@code workgroup/<id>}, named by its name).
|
||||
* {@code workgroup/<id>}, named by its name). Also the ARN of a resource a request names through another of its
|
||||
* service's own, which the table gives no type (the cluster or workgroup a Data API session runs on).
|
||||
*
|
||||
* <p>The reader asks for every type of the namespace, not only for the ones whose ARN carries an id the service
|
||||
* mints, so a service may answer for a type whose ARN it does not mint: a key an alias names is the key the alias
|
||||
@@ -16,10 +17,9 @@ import java.util.Optional;
|
||||
*
|
||||
* <p>Implemented by the service that owns such resources or whose requests name them (EventBridge, for its
|
||||
* connections and API destinations; Application Auto Scaling, for its scalable targets; Redshift Data, for the
|
||||
* Redshift Serverless workgroups it runs statements on; Payment Cryptography, for the key an alias names);
|
||||
* 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>
|
||||
* Redshift Serverless workgroups it runs statements on and the targets of its sessions; Payment Cryptography, for
|
||||
* the key an alias names); 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>
|
||||
*/
|
||||
public interface StoredResourceArns {
|
||||
|
||||
@@ -33,4 +33,13 @@ public interface StoredResourceArns {
|
||||
* type is not one it finds.
|
||||
*/
|
||||
Optional<String> find(String type, List<String> names, String region);
|
||||
|
||||
/**
|
||||
* The ARN of the resource the caller's resource named by {@code value} in its {@code member} runs on in the
|
||||
* Region, as a request naming it runs there (the cluster or workgroup of a Data API session, by its
|
||||
* {@code SessionId}); empty when the caller has none of that name, or the member is not one it reads.
|
||||
*/
|
||||
default Optional<String> through(String member, String value, String region) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
+2
-9
@@ -6,7 +6,6 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.DatabaseSecretCredentials;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.StoredResourceArns;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftCredentialBroker;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftService;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
@@ -25,7 +24,7 @@ import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@ApplicationScoped
|
||||
class RedshiftDataResourceResolver implements StoredResourceArns {
|
||||
class RedshiftDataResourceResolver {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RedshiftDataResourceResolver.class);
|
||||
|
||||
@@ -51,14 +50,8 @@ class RedshiftDataResourceResolver implements StoredResourceArns {
|
||||
this.serverlessService = serverlessService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String namespace() {
|
||||
return "redshift-data";
|
||||
}
|
||||
|
||||
/** The ARN of the serverless workgroup a request names by its name or ARN, as {@link #resolve} reads it. */
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
Optional<String> find(String type, List<String> names, String region) {
|
||||
if (!"workgroup".equals(type) || names.size() != 1) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
+19
-1
@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.common.EpochSeconds;
|
||||
import io.github.hectorvent.floci.core.common.RequestContext;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.core.common.SqlParameterParser.ParsedSql;
|
||||
import io.github.hectorvent.floci.core.common.StoredResourceArns;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftAuditLogPublisher;
|
||||
@@ -42,6 +43,7 @@ import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
@@ -50,7 +52,7 @@ import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ApplicationScoped
|
||||
public class RedshiftDataService implements Resettable {
|
||||
public class RedshiftDataService implements Resettable, StoredResourceArns {
|
||||
|
||||
private static final int PAGE_SIZE = 1000;
|
||||
static final Pattern AUTO_COMMIT_SQL = Pattern.compile(
|
||||
@@ -220,6 +222,22 @@ public class RedshiftDataService implements Resettable {
|
||||
return new RedshiftDataSessionListing(objectMapper, sessions).list(request, sessionScope(region, null));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String namespace() {
|
||||
return "redshift-data";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
return resolver.find(type, names, region);
|
||||
}
|
||||
|
||||
/** The cluster or workgroup the caller's open session runs on, named by its {@code SessionId}, as it reads it. */
|
||||
@Override
|
||||
public Optional<String> through(String member, String value, String region) {
|
||||
return "SessionId".equals(member) ? sessions.targetArn(sessionScope(region, null), value) : Optional.empty();
|
||||
}
|
||||
|
||||
private Admission replay(RedshiftDataIdempotencyStore.Receipt receipt, RedshiftDataIdempotencyStore.Scope scope,
|
||||
RedshiftDataSessions.Scope owner, String principal) {
|
||||
if (receipt.sessionOwner != null) {
|
||||
|
||||
+13
-3
@@ -19,6 +19,7 @@ import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executors;
|
||||
@@ -78,17 +79,26 @@ class RedshiftDataSessions implements AutoCloseable {
|
||||
}
|
||||
|
||||
Session find(Scope owner, String id) {
|
||||
return open(owner, id).orElseThrow(RedshiftDataSessions::missing);
|
||||
}
|
||||
|
||||
/** The ARN of the cluster or workgroup the owner's open session of that id runs on; empty when it has none. */
|
||||
Optional<String> targetArn(Scope owner, String id) {
|
||||
return open(owner, id).map(session -> session.target.arn());
|
||||
}
|
||||
|
||||
private Optional<Session> open(Scope owner, String id) {
|
||||
Session session = sessions.get(id);
|
||||
if (session == null || !session.owner.equals(owner)) {
|
||||
throw missing();
|
||||
return Optional.empty();
|
||||
}
|
||||
synchronized (session) {
|
||||
if (!session.closed && !expired(session)) {
|
||||
return session;
|
||||
return Optional.of(session);
|
||||
}
|
||||
}
|
||||
retire(session);
|
||||
throw missing();
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
Reservation reserve(Scope owner, JsonNode request, RedshiftDataResourceResolver.DatabaseTarget target) {
|
||||
|
||||
@@ -931,11 +931,11 @@
|
||||
"payment-cryptography:VerifyCardValidationData": {"action": "payment-cryptography:VerifyCardValidationData", "types": ["alias", "key"], "resources": []},
|
||||
"payment-cryptography:VerifyMac": {"action": "payment-cryptography:VerifyMac", "types": ["alias", "key"], "resources": []},
|
||||
"payment-cryptography:VerifyPinData": {"action": "payment-cryptography:VerifyPinData", "types": ["alias", "key"], "resources": []},
|
||||
"redshift-data:BatchExecuteStatement": {"action": "redshift-data:BatchExecuteStatement", "types": ["cluster", "workgroup"], "resources": [{"types": ["cluster", "workgroup"], "arn": "SecretArn"}, {"type": "cluster", "fill": {"ClusterName": "ClusterIdentifier"}}, {"type": "workgroup", "fill": {}, "find": ["WorkgroupName"]}]},
|
||||
"redshift-data:BatchExecuteStatement": {"action": "redshift-data:BatchExecuteStatement", "types": ["cluster", "workgroup"], "resources": [{"types": ["cluster", "workgroup"], "arn": "SecretArn"}, {"type": "cluster", "fill": {"ClusterName": "ClusterIdentifier"}}, {"type": "workgroup", "fill": {}, "find": ["WorkgroupName"]}, {"types": ["cluster", "workgroup"], "through": "SessionId"}]},
|
||||
"redshift-data:CancelStatement": {"action": "redshift-data:CancelStatement", "types": [], "resources": []},
|
||||
"redshift-data:DescribeStatement": {"action": "redshift-data:DescribeStatement", "types": [], "resources": []},
|
||||
"redshift-data:DescribeTable": {"action": "redshift-data:DescribeTable", "types": ["cluster", "workgroup"], "resources": [{"types": ["cluster", "workgroup"], "arn": "SecretArn"}, {"type": "cluster", "fill": {"ClusterName": "ClusterIdentifier"}}, {"type": "workgroup", "fill": {}, "find": ["WorkgroupName"]}]},
|
||||
"redshift-data:ExecuteStatement": {"action": "redshift-data:ExecuteStatement", "types": ["cluster", "workgroup"], "resources": [{"types": ["cluster", "workgroup"], "arn": "SecretArn"}, {"type": "cluster", "fill": {"ClusterName": "ClusterIdentifier"}}, {"type": "workgroup", "fill": {}, "find": ["WorkgroupName"]}]},
|
||||
"redshift-data:ExecuteStatement": {"action": "redshift-data:ExecuteStatement", "types": ["cluster", "workgroup"], "resources": [{"types": ["cluster", "workgroup"], "arn": "SecretArn"}, {"type": "cluster", "fill": {"ClusterName": "ClusterIdentifier"}}, {"type": "workgroup", "fill": {}, "find": ["WorkgroupName"]}, {"types": ["cluster", "workgroup"], "through": "SessionId"}]},
|
||||
"redshift-data:GetStatementResult": {"action": "redshift-data:GetStatementResult", "types": [], "resources": []},
|
||||
"redshift-data:GetStatementResultV2": {"action": "redshift-data:GetStatementResult", "types": [], "resources": []},
|
||||
"redshift-data:ListDatabases": {"action": "redshift-data:ListDatabases", "types": ["cluster", "workgroup"], "resources": [{"types": ["cluster", "workgroup"], "arn": "SecretArn"}, {"type": "cluster", "fill": {"ClusterName": "ClusterIdentifier"}}, {"type": "workgroup", "fill": {}, "find": ["WorkgroupName"]}]},
|
||||
|
||||
+56
-7
@@ -17,6 +17,7 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
@@ -109,6 +110,31 @@ class RequestResourceMembersTest {
|
||||
"{\"types\":[\"target\"],\"arn\":\"TargetArn\",\"find\":[\"Namespace\"]}")));
|
||||
}
|
||||
|
||||
@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));
|
||||
for (String operation : List.of("ExecuteStatement", "BatchExecuteStatement")) {
|
||||
assertEquals(session, RequestResourceMembers.table().operations().get("redshift-data:" + operation)
|
||||
.getLast(), operation);
|
||||
}
|
||||
assertTrue(RequestResourceMembers.table().operations().get("redshift-data:ListSessions").isEmpty());
|
||||
String formats = "\"arnFormats\":{\"a\":{\"cluster\":\"arn:${Partition}:a:${Region}:${Account}:cluster:${Name}\","
|
||||
+ "\"group\":\"arn:${Partition}:a:${Region}:${Account}:group/${Id}\"}}";
|
||||
assertEquals(new Member("SessionId", false), parseUnchecked(document(formats,
|
||||
"{\"types\":[\"cluster\",\"group\"],\"through\":\"SessionId\",\"endpoint\":\"a\"}"))
|
||||
.operations().get("a:Op").getFirst().through());
|
||||
// No types, a type with no format, no member of one value, or beside members reading it otherwise.
|
||||
for (String bad : List.of("\"types\":[],\"through\":\"SessionId\"",
|
||||
"\"types\":[\"pool\"],\"through\":\"SessionId\"", "\"types\":[\"group\"],\"through\":\"Ids[]\"",
|
||||
"\"types\":[\"group\"],\"through\":\"Session.Id\"",
|
||||
"\"types\":[\"group\"],\"through\":\"SessionId\",\"arn\":\"GroupArn\"",
|
||||
"\"types\":[\"group\"],\"through\":\"SessionId\",\"before\":\"#\"",
|
||||
"\"type\":\"group\",\"fill\":{},\"through\":\"SessionId\"")) {
|
||||
assertThrows(IllegalStateException.class, () -> parse(document(formats, "{" + bad + "}")), bad);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMalformedTableFailsToLoad() {
|
||||
assertThrows(IllegalStateException.class, () -> parse("{\"operations\":{}}"));
|
||||
@@ -231,7 +257,8 @@ class RequestResourceMembersTest {
|
||||
/**
|
||||
* Each resource alone, from a request naming it and nothing else, gives exactly its ARN, in the account its
|
||||
* account member names when it has one, with those of the operation's resources every request names, a create's
|
||||
* new resource no member names (Cloud Map's {@code CreateService}).
|
||||
* new resource no member names (Cloud Map's {@code CreateService}); one named through another resource of its
|
||||
* service's own, the ARN its service gives for that.
|
||||
*/
|
||||
@TestFactory
|
||||
Stream<DynamicTest> everyResourceOfTheTableIsReadFromAJsonBodyAndAForm() {
|
||||
@@ -243,11 +270,12 @@ class RequestResourceMembersTest {
|
||||
ArnFormat format = table.formats().get(namespace).get(resource.types().getFirst());
|
||||
String arn = example(format.format());
|
||||
String account = resource.account() != null ? "111122223333" : "000000000000";
|
||||
String expected = resource.arn() != null ? arn
|
||||
String expected = resource.arn() != null || resource.through() != null ? arn
|
||||
: expected(format.format(), resource, account) + (format.minted() ? "/*" : "");
|
||||
ObjectNode body = MAPPER.createObjectNode();
|
||||
StringBuilder form = new StringBuilder("Action=" + name);
|
||||
Map<Member, String> values = resource.arn() != null ? Map.of(resource.arn(), arn)
|
||||
: resource.through() != null ? Map.of(resource.through(), "x")
|
||||
: Stream.concat(resource.fill().values().stream(), resource.find().stream()).distinct()
|
||||
.collect(Collectors.toMap(m -> m, m -> "x"));
|
||||
Map<Member, String> given = new LinkedHashMap<>(values);
|
||||
@@ -270,12 +298,13 @@ class RequestResourceMembersTest {
|
||||
table.formats().get(namespace).get(other.types().getFirst()).format(), other,
|
||||
"000000000000"))
|
||||
.distinct().toList();
|
||||
StoredResourceArns stored = runningOn(namespace, arn);
|
||||
assertEquals(named, RequestResources.of(operation.getKey(),
|
||||
servedBy(json(body.toString()), resource.endpoint()), "aws", "us-east-1", "000000000000"),
|
||||
body.toString());
|
||||
servedBy(json(body.toString()), resource.endpoint()), "aws", "us-east-1", "000000000000",
|
||||
stored), body.toString());
|
||||
assertEquals(named, RequestResources.of(operation.getKey(),
|
||||
servedBy(form(form.toString()), resource.endpoint()), "aws", "us-east-1", "000000000000"),
|
||||
form.toString());
|
||||
servedBy(form(form.toString()), resource.endpoint()), "aws", "us-east-1", "000000000000",
|
||||
stored), form.toString());
|
||||
})));
|
||||
}
|
||||
|
||||
@@ -308,7 +337,27 @@ class RequestResourceMembersTest {
|
||||
/** Whether every request of its operation names the resource: no member names it and no member's value selects it. */
|
||||
private static boolean named(Resource resource) {
|
||||
return resource.arn() == null && resource.fill().isEmpty() && resource.find().isEmpty()
|
||||
&& resource.when().isEmpty() && resource.unless().isEmpty();
|
||||
&& resource.through() == null && resource.when().isEmpty() && resource.unless().isEmpty();
|
||||
}
|
||||
|
||||
/** A namespace's stored ARNs that find nothing, and give {@code arn} for whatever a request names a resource through. */
|
||||
private static StoredResourceArns runningOn(String namespace, String arn) {
|
||||
return new StoredResourceArns() {
|
||||
@Override
|
||||
public String namespace() {
|
||||
return namespace;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> through(String member, String value, String region) {
|
||||
return Optional.of(arn);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** The value at the member's path in a body: in its list's first element, and in its field's structure. */
|
||||
|
||||
@@ -11,6 +11,7 @@ import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@@ -510,12 +511,18 @@ class RequestResourcesTest {
|
||||
/**
|
||||
* A Data API request runs on the cluster its {@code ClusterIdentifier} names, or on the serverless workgroup
|
||||
* stored under the name or ARN its {@code WorkgroupName} gives, whose ARN ends in the id Redshift Serverless
|
||||
* mints; its {@code SecretArn} names neither, and a request naming its session alone names none.
|
||||
* mints; its {@code SecretArn} names neither. A request naming its session by {@code SessionId} runs on the
|
||||
* cluster or workgroup the caller's session runs on, as the service gives it, and names none when there is no such
|
||||
* session, or the service gives an ARN of neither.
|
||||
*/
|
||||
@Test
|
||||
void aDataApiRequestIsOnTheClusterOrTheStoredWorkgroupItNames() {
|
||||
String workgroups = "arn:aws:redshift-serverless:us-east-1:000000000000:workgroup/";
|
||||
String cluster = "arn:aws:redshift:us-east-1:000000000000:cluster:warehouse";
|
||||
String id = "0f1e2d3c-4b5a-4978-8a9b-0c1d2e3f4a5b";
|
||||
Map<String, String> sessions = Map.of("11111111-2222-4333-8444-555555555555", workgroups + id,
|
||||
"66666666-7777-4888-9999-000000000000", cluster,
|
||||
"77777777-8888-4999-8000-111111111111", "arn:aws:secretsmanager:us-east-1:000000000000:secret:db-AbCdEf");
|
||||
StoredResourceArns stored = new StoredResourceArns() {
|
||||
@Override
|
||||
public String namespace() {
|
||||
@@ -528,6 +535,12 @@ class RequestResourcesTest {
|
||||
&& (List.of("analytics").equals(names) || List.of(workgroups + id).equals(names))
|
||||
? Optional.of(workgroups + id) : Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> through(String member, String value, String region) {
|
||||
return "SessionId".equals(member) && "us-east-1".equals(region)
|
||||
? Optional.ofNullable(sessions.get(value)) : Optional.empty();
|
||||
}
|
||||
};
|
||||
String secret = ",\"SecretArn\":\"arn:aws:secretsmanager:us-east-1:000000000000:secret:db-AbCdEf\"";
|
||||
assertEquals(List.of("arn:aws:redshift:us-east-1:000000000000:cluster:warehouse"), RequestResources.of(
|
||||
@@ -541,9 +554,23 @@ class RequestResourcesTest {
|
||||
assertEquals(List.of(workgroups + "*"), RequestResources.of("redshift-data:ListDatabases",
|
||||
json("{\"Database\":\"dev\",\"WorkgroupName\":\"other\"}"), "aws", "us-east-1", "000000000000",
|
||||
stored));
|
||||
assertEquals(List.of(workgroups + id), RequestResources.of("redshift-data:ExecuteStatement",
|
||||
json("{\"Sql\":\"select 1\",\"SessionId\":\"11111111-2222-4333-8444-555555555555\"}"), "aws",
|
||||
"us-east-1", "000000000000", stored));
|
||||
assertEquals(List.of(workgroups + id), RequestResources.of("redshift-data:ExecuteStatement",
|
||||
json("{\"Sql\":\"select 1\",\"SessionId\":\"11111111-2222-4333-8444-555555555555\","
|
||||
+ "\"WorkgroupName\":\"analytics\"}"), "aws", "us-east-1", "000000000000", stored));
|
||||
assertEquals(List.of(cluster), RequestResources.of("redshift-data:BatchExecuteStatement",
|
||||
json("{\"Sqls\":[\"select 1\"],\"SessionId\":\"66666666-7777-4888-9999-000000000000\"}"), "aws",
|
||||
"us-east-1", "000000000000", stored));
|
||||
for (String session : List.of(id, "77777777-8888-4999-8000-111111111111")) {
|
||||
assertEquals(List.of(), RequestResources.of("redshift-data:ExecuteStatement",
|
||||
json("{\"Sql\":\"select 1\",\"SessionId\":\"" + session + "\"}"), "aws", "us-east-1",
|
||||
"000000000000", stored), session);
|
||||
}
|
||||
assertEquals(List.of(), RequestResources.of("redshift-data:ExecuteStatement",
|
||||
json("{\"Sql\":\"select 1\",\"SessionId\":\"" + id + "\"}"), "aws", "us-east-1", "000000000000",
|
||||
stored));
|
||||
json("{\"Sql\":\"select 1\",\"SessionId\":\"11111111-2222-4333-8444-555555555555\"}"), "aws",
|
||||
"eu-west-1", "000000000000", stored));
|
||||
}
|
||||
|
||||
/** A request value is a name, so a {@code ${...}} in it is kept, not read as a variable of the format. */
|
||||
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures;
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import jakarta.inject.Inject;
|
||||
import org.h2.Driver;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.net.URI;
|
||||
import java.sql.DriverManager;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Under IAM enforcement, a Data API statement naming its session alone, by {@code SessionId}, is checked on the
|
||||
* cluster or serverless workgroup the session runs on, as the statement that opened it was.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class RedshiftDataSessionIamEnforcementIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "111111111111";
|
||||
private static final String CLUSTER = "arn:aws:redshift:us-east-1:" + ACCOUNT + ":cluster:warehouse";
|
||||
private static final String WORKGROUP = "arn:aws:redshift-serverless:us-east-1:" + ACCOUNT
|
||||
+ ":workgroup/12345678-1234-1234-1234-123456789012";
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
@InjectMock
|
||||
RedshiftDataResourceResolver resolver;
|
||||
@InjectMock
|
||||
RedshiftDataConnectionFactory factory;
|
||||
@Inject
|
||||
RedshiftDataService service;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@BeforeAll
|
||||
static void configure() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setup() throws Exception {
|
||||
Driver.load();
|
||||
String url = "jdbc:h2:mem:" + UUID.randomUUID();
|
||||
when(factory.open(any())).thenAnswer(invocation -> DriverManager.getConnection(url));
|
||||
when(resolver.find(eq("workgroup"), eq(List.of("analytics")), eq("us-east-1"))).thenReturn(Optional.of(WORKGROUP));
|
||||
when(resolver.resolve(any(), any())).thenAnswer(invocation -> {
|
||||
JsonNode request = invocation.getArgument(0);
|
||||
return new RedshiftDataResourceResolver.DatabaseTarget(request.has("WorkgroupName") ? WORKGROUP : CLUSTER,
|
||||
"localhost", 5439, "dev", "admin", "password");
|
||||
});
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanup() {
|
||||
service.clear();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void aStatementNamingItsSessionIsCheckedOnTheTargetTheSessionRunsOn(boolean serverless) {
|
||||
String target = serverless ? WORKGROUP : CLUSTER;
|
||||
String user = "rsd-session-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String key = EnforcementFixtures.createUser(cleanup, endpoint.getPort(), auth(ACCOUNT, "iam"), user)
|
||||
.accessKeyId();
|
||||
policy(user, allow("redshift-data:ExecuteStatement", target) + ","
|
||||
+ allow("redshift-data:BatchExecuteStatement", target));
|
||||
String named = serverless ? "\"WorkgroupName\":\"analytics\""
|
||||
: "\"ClusterIdentifier\":\"warehouse\",\"DbUser\":\"admin\"";
|
||||
String session = data(key, "ExecuteStatement", "{" + named + ",\"Database\":\"dev\",\"Sql\":\"SELECT 1\","
|
||||
+ "\"SessionKeepAliveSeconds\":60,\"WaitTimeSeconds\":30}").statusCode(200).extract().path("SessionId");
|
||||
|
||||
Map<String, String> statements = Map.of("ExecuteStatement", "\"Sql\":\"SELECT 2\"",
|
||||
"BatchExecuteStatement", "\"Sqls\":[\"SELECT 3\"]");
|
||||
// Allowed on the target alone, the statements naming the session run there; checked on * before, they were not.
|
||||
statements.forEach((operation, sql) -> data(key, operation, "{\"SessionId\":\"" + session + "\"," + sql
|
||||
+ ",\"WaitTimeSeconds\":30}").statusCode(200).body("SessionId", equalTo(session)));
|
||||
|
||||
// A deny on the target holds for them too, under an allow on everything.
|
||||
policy(user, allow("redshift-data:*", "*") + ",{\"Effect\":\"Deny\",\"Action\":\"redshift-data:*\","
|
||||
+ "\"Resource\":\"" + target + "\"}");
|
||||
statements.forEach((operation, sql) -> data(key, operation, "{\"SessionId\":\"" + session + "\"," + sql + "}")
|
||||
.statusCode(400).body(containsString("AccessDeniedException"))
|
||||
.body(containsString("not authorized to perform: redshift-data:" + operation)));
|
||||
}
|
||||
|
||||
private void policy(String user, String statements) {
|
||||
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth(ACCOUNT, "iam"), user, "data",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
|
||||
}
|
||||
|
||||
private static String allow(String action, String resource) {
|
||||
return "{\"Effect\":\"Allow\",\"Action\":\"" + action + "\",\"Resource\":\"" + resource + "\"}";
|
||||
}
|
||||
|
||||
private static ValidatableResponse data(String accessKeyId, String operation, String body) {
|
||||
return given().contentType("application/x-amz-json-1.1").header("X-Amz-Target", "RedshiftData." + operation)
|
||||
.header("Authorization", auth(accessKeyId, "redshift-data")).body(body).post("/").then();
|
||||
}
|
||||
}
|
||||
+20
@@ -15,6 +15,7 @@ import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
@@ -250,6 +251,25 @@ class RedshiftDataSessionsTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOpenSessionGivesItsOwnerTheTargetItRunsOn() throws Exception {
|
||||
ManualClock clock = new ManualClock(Instant.parse("2026-10-24T00:00:00Z"));
|
||||
try (RedshiftDataSessions sessions = new RedshiftDataSessions(clock)) {
|
||||
RedshiftDataConnectionFactory factory = mock(RedshiftDataConnectionFactory.class);
|
||||
when(factory.open(any())).thenReturn(mock(Connection.class));
|
||||
RedshiftDataSessions.Reservation first = sessions.reserve(OWNER, request().put("SessionKeepAliveSeconds", 10), TARGET);
|
||||
first.admitted();
|
||||
first.connection(factory);
|
||||
first.finish();
|
||||
assertEquals(Optional.of(TARGET.arn()), sessions.targetArn(OWNER, first.id()));
|
||||
assertEquals(Optional.empty(), sessions.targetArn(
|
||||
new RedshiftDataSessions.Scope("000000000000", "us-east-1", "another-caller"), first.id()));
|
||||
assertEquals(Optional.empty(), sessions.targetArn(OWNER, "00000000-0000-0000-0000-000000000000"));
|
||||
clock.advance(Duration.ofSeconds(11));
|
||||
assertEquals(Optional.empty(), sessions.targetArn(OWNER, first.id()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void zeroTimeoutClosesTheSessionAfterItsLastQuery() throws Exception {
|
||||
try (RedshiftDataSessions sessions = new RedshiftDataSessions(Clock.systemUTC())) {
|
||||
|
||||
@@ -91,7 +91,12 @@ members: each operation whose request has them all names the type by them (`find
|
||||
asks the service for the ARN they find, or else checks the ARN with its id open, as for a create; an
|
||||
Application Auto Scaling scalable target, `scalable-target/<id>`, is named by its service namespace,
|
||||
resource id and scalable dimension, and the Redshift Serverless workgroup a Data API request runs on,
|
||||
`workgroup/<id>`, by its name or ARN.
|
||||
`workgroup/<id>`, by its name or ARN. `THROUGH` are the members naming a resource the reference gives no
|
||||
type, through which a request names a resource of one it does, with those types: each operation whose
|
||||
request has the member, and whose action acts on one of them, names its resource through it (`through`),
|
||||
and the reader asks the service for the ARN of the caller's resource at the other end, or else names
|
||||
none; a Data API session, by its `SessionId`, runs on the cluster or the serverless workgroup it was
|
||||
opened on.
|
||||
|
||||
The Service Reference is live rather than a pinned dependency, so a fresh generation is not
|
||||
byte-identical. The two gates split along the sources:
|
||||
@@ -452,6 +457,19 @@ FOUND_BY: dict[str, tuple[list[str], str]] = {
|
||||
"workgroup name or Amazon Resource Name (ARN)'"),
|
||||
}
|
||||
|
||||
# Members naming a resource of their service's own the reference gives no type, through which a request names a
|
||||
# resource of one it does, the types that resource may be of, and why: an operation whose request has the member,
|
||||
# and whose action acts on one of those types, names it through the member, and the reader asks the service for the
|
||||
# ARN of the caller's resource at the other end.
|
||||
THROUGH: dict[str, tuple[list[str], str]] = {
|
||||
"redshift-data:SessionId": (
|
||||
["cluster", "workgroup"],
|
||||
"a Data API session runs on the cluster or the serverless workgroup it was opened on (ListSessions filters "
|
||||
"sessions 'by session status, compute target (cluster or serverless workgroup), or database'), and its "
|
||||
"SessionId 'can then be used in subsequent ExecuteStatement and BatchExecuteStatement operations' "
|
||||
"(Amazon Redshift Management Guide), which then run there"),
|
||||
}
|
||||
|
||||
# The variables of an ARN format the account, partition and Region fill.
|
||||
KNOWN_VARIABLES = {"Partition", "Region", "Account"}
|
||||
VARIABLE_RE = re.compile(r"\$\{(\w+)}")
|
||||
@@ -809,8 +827,9 @@ def entry_for(operation: str, upstream: dict, formats: dict[str, str], models: d
|
||||
raise ValueError(f"CORRECTIONS serves {operation} on {sorted(unknown)}, no endpoint prefix of the clients "
|
||||
f"it reads ({sorted(endpoints)})")
|
||||
else:
|
||||
resources = with_found(resources_for(operation, types, formats, members), namespace_of(operation), types,
|
||||
members)
|
||||
resources = with_through(with_found(resources_for(operation, types, formats, members),
|
||||
namespace_of(operation), types, members),
|
||||
namespace_of(operation), types, members)
|
||||
resources = with_account(resources, formats, account_members(models, operation.split(":", 1)[1]))
|
||||
resources = with_arn_of(resources, formats, name_or_arn_members(models, operation.split(":", 1)[1]))
|
||||
resources = with_made(resources, operation, formats)
|
||||
@@ -832,6 +851,18 @@ def with_found(resources: list[dict], namespace: str, types: list[str], members:
|
||||
return found
|
||||
|
||||
|
||||
def with_through(resources: list[dict], namespace: str, types: list[str], members: dict[str, str]) -> list[dict]:
|
||||
"""The resources, and the one of the `THROUGH` types the action acts on that each member of the request naming
|
||||
a resource of its service's own runs on."""
|
||||
through = []
|
||||
for key, (kinds, _) in sorted(THROUGH.items()):
|
||||
member = key.split(":", 1)[1]
|
||||
on = [kind for kind in types if kind in kinds]
|
||||
if key.startswith(f"{namespace}:") and on and members.get(member) == member:
|
||||
through.append({"types": on, "through": member})
|
||||
return resources + through
|
||||
|
||||
|
||||
def build(documents: list[dict], provenance: str, data: Path, botocore: str) -> dict:
|
||||
upstream = checked_actions(documents)
|
||||
covered = {operation: value for operation, value in upstream.items() if namespace_of(operation) in NAMESPACES}
|
||||
@@ -851,6 +882,9 @@ def build(documents: list[dict], provenance: str, data: Path, botocore: str) ->
|
||||
if kind in formats.get(namespace, {}) and not ONE_VARIABLE_RE.match(_resource(formats[namespace][kind]))]
|
||||
missing += [f"FOUND_BY names {key}, no resource type with an ARN format of a namespace the file reads"
|
||||
for key in sorted(FOUND_BY) if key.split(":", 1)[1] not in formats.get(key.split(":", 1)[0], {})]
|
||||
missing += [f"THROUGH names {key.split(':', 1)[0]}:{kind}, no resource type with an ARN format of a namespace the "
|
||||
f"file reads" for key, (kinds, _) in sorted(THROUGH.items()) for kind in kinds
|
||||
if kind not in formats.get(key.split(":", 1)[0], {})]
|
||||
if missing:
|
||||
raise ValueError("; ".join(missing))
|
||||
operations = {}
|
||||
@@ -1012,6 +1046,7 @@ def validate(document: dict) -> list[str]:
|
||||
def _resource_problems(operation: str, resource: object, types: set[str], formats: dict[str, str]) -> list[str]:
|
||||
if not isinstance(resource, dict) or not ({"types", "arn"} <= set(resource) <= {"types", "arn", "before", "made",
|
||||
"endpoint"}
|
||||
or {"types", "through"} <= set(resource) <= {"types", "through", "endpoint"}
|
||||
or {"type", "fill"} <= set(resource) <= {"type", "fill", "when", "unless", "absent", "arnOf", "account",
|
||||
"fixed", "made", "before", "find", "endpoint"}):
|
||||
return [f"{operation} names {resource!r}, which is neither an ARN member nor a type's variables"]
|
||||
@@ -1029,6 +1064,11 @@ def _resource_problems(operation: str, resource: object, types: set[str], format
|
||||
if not isinstance(resource["arn"], str) or not ARN_PATH_RE.match(resource["arn"]):
|
||||
return [f"{operation} reads an ARN at {resource['arn']!r}, which is no member"]
|
||||
return []
|
||||
if "through" in resource:
|
||||
through = resource["through"]
|
||||
if not isinstance(through, str) or not PATH_RE.match(through) or through.endswith("[]"):
|
||||
return [f"{operation} names {kinds} through {through!r}, which is no member of one value"]
|
||||
return []
|
||||
fill = resource["fill"]
|
||||
find = resource.get("find", [])
|
||||
if not isinstance(find, list) or ("find" in resource and (not find or fill or set(resource) & FOUND_ONLY)) \
|
||||
|
||||
@@ -183,6 +183,7 @@ def corrections(monkeypatch):
|
||||
monkeypatch.setattr(r, "UNQUALIFIED", {})
|
||||
monkeypatch.setattr(r, "MINTED_IDS", {})
|
||||
monkeypatch.setattr(r, "FOUND_BY", {})
|
||||
monkeypatch.setattr(r, "THROUGH", {})
|
||||
monkeypatch.setattr(r, "CLIENTS_NOT_READ", {})
|
||||
return monkeypatch
|
||||
|
||||
@@ -294,6 +295,31 @@ def test_a_type_whose_arn_is_all_an_id_its_service_mints_is_found_by_the_members
|
||||
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):
|
||||
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")})
|
||||
document = r.build(documents, "test", tmp_path, "botocore test")
|
||||
assert r.validate(document) == [] and r.derive(document, tmp_path) == []
|
||||
operations = document["operations"]
|
||||
# Named through the session, as one of the types the action acts on.
|
||||
assert operations["svc:Run"]["resources"] == [{"types": ["cluster", "group"], "through": "SessionId"}]
|
||||
assert operations["svc:RunOnGroup"]["resources"][-1] == {"types": ["group"], "through": "SessionId"}
|
||||
# Not by a request without the member, nor for an action acting on none of the types.
|
||||
assert not any("through" in resource for resource in operations["svc:RunOnCluster"]["resources"])
|
||||
assert operations["svc:ListSessions"]["resources"] == []
|
||||
# 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")})
|
||||
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"})
|
||||
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}}),
|
||||
@@ -387,6 +413,10 @@ def test_a_well_formed_document_validates():
|
||||
document = good_document()
|
||||
document["operations"]["svc:B"]["resources"][0].update(fill={}, find=["Namespace", "Id"])
|
||||
assert r.validate(document) == []
|
||||
# A resource named through a member naming another of its service's own, which it runs on.
|
||||
document = good_document()
|
||||
document["operations"]["svc:A"]["resources"] = [{"types": ["thing"], "through": "SessionId"}]
|
||||
assert r.validate(document) == []
|
||||
|
||||
|
||||
def with_a_create() -> dict:
|
||||
@@ -400,6 +430,14 @@ def with_a_create() -> dict:
|
||||
(lambda d: d["operations"]["svc:A"]["resources"][0].update(types=["pool"]), "not resource types"),
|
||||
(lambda d: d["operations"]["svc:A"]["resources"][0].update(arn="a.b.c"), "no member"),
|
||||
(lambda d: d["operations"]["svc:A"]["resources"][0].update(arn="a[][]"), "no member"),
|
||||
(lambda d: d["operations"]["svc:A"]["resources"].__setitem__(0, {"types": ["thing"], "through": "Ids[]"}),
|
||||
"no member of one value"),
|
||||
(lambda d: d["operations"]["svc:A"]["resources"].__setitem__(0, {"types": ["thing"], "through": "a.b"}),
|
||||
"no member of one value"),
|
||||
(lambda d: d["operations"]["svc:A"]["resources"].__setitem__(0, {"types": ["pool"], "through": "SessionId"}),
|
||||
"not resource types"),
|
||||
(lambda d: d["operations"]["svc:A"]["resources"].__setitem__(0, {"types": ["thing"], "through": "SessionId",
|
||||
"before": "#"}), "neither an ARN member"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0]["fill"].update(GroupName="Group.Names[]"), "no variables"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0]["fill"].update(GroupName="A.B.Name"), "no variables"),
|
||||
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fixed={"Other": "x"}), "fixes"),
|
||||
@@ -581,8 +619,13 @@ def test_the_vendored_file_is_well_formed():
|
||||
# A Data API request runs on the cluster it names, or on the serverless workgroup its name or ARN finds.
|
||||
assert operations["redshift-data:ExecuteStatement"]["resources"][1:] == [
|
||||
{"type": "cluster", "fill": {"ClusterName": "ClusterIdentifier"}},
|
||||
{"type": "workgroup", "fill": {}, "find": ["WorkgroupName"]}]
|
||||
{"type": "workgroup", "fill": {}, "find": ["WorkgroupName"]},
|
||||
{"types": ["cluster", "workgroup"], "through": "SessionId"}]
|
||||
# A request naming its session alone runs on the cluster or workgroup the session was opened on.
|
||||
assert operations["redshift-data:BatchExecuteStatement"]["resources"][-1] == {
|
||||
"types": ["cluster", "workgroup"], "through": "SessionId"}
|
||||
assert operations["redshift-data:ListStatements"]["resources"] == []
|
||||
assert operations["redshift-data:ListSessions"]["resources"] == []
|
||||
# The v2 API's Type picks the load balancer it creates, application when it gives none.
|
||||
assert operations["elasticloadbalancing:CreateLoadBalancer"]["resources"][1] == {
|
||||
"type": "loadbalancer/app/", "fill": {"LoadBalancerName": "Name"}, "when": {"Type": ["application", None]}}
|
||||
Reference in new issue
Block a user