mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(redshift): require kms:Decrypt on an encrypted snapshot's key to restore it (#8309)
AWS requires the customer managed key of an encrypted snapshot to be shared with the account restoring it (Redshift Management Guide, "Sharing a snapshot"). Neither botocore nor the Service Reference says so, so the request-resources generator states it in FORWARDED, an evidence entry under MEASURED's rules: the action and the snapshot type, with the rest read from the metadata (the key type and format kms:Decrypt acts on, the snapshot record's KmsKeyId member, the endpoint prefix, kms:ViaService). Under IAM enforcement a Redshift or Redshift Serverless restore is then also checked as kms:Decrypt on the key the snapshot records, found in the snapshot's account, against the key policy and the caller's own policies, with aws:ViaAWSService and kms:ViaService naming the service's endpoint. KMS key policies are now evaluated as resource policies. A key KMS would not use, disabled, pending deletion or not held, refuses the restore, as KMS refuses the request the service makes with it. A snapshot under AWS's own key records none, and one under an AWS managed key (a copy grant made without a key) needs nothing, as AWS writes that key's policy to let the account use it through the service.
This commit is contained in:
1 parent
ddc844b48e
commit
f09468fb19
22 files changed
+1234
-43
No files matched your search
@@ -254,6 +254,10 @@ With `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true`, an operation that names a ke
|
||||
|
||||
`CreateAlias`, `UpdateAlias` and `DeleteAlias` are evaluated against the alias ARN and the key it points at, `UpdateAlias` also against the key it will point at, the two resource types the Service Authorization Reference lists for them. `ReEncrypt` is evaluated against both keys it acts on, under the single `kms:ReEncrypt` action: the source its `SourceKeyId` names, or when it names none the key that encrypted its `CiphertextBlob` (never a `KeyId`, which the operation does not read), and the destination its `DestinationKeyId` names. AWS authorizes the two halves separately as `kms:ReEncryptFrom` and `kms:ReEncryptTo`, which Floci does not split yet. The grant operations name the key the grant they act on belongs to: a `RetireGrant` carrying a `GrantToken` the key that grant belongs to, since the handler finds the grant by the token alone, and a `RetireGrant` or `RevokeGrant` identifying its grant by `KeyId` and `GrantId` the key it names together with the key that grant belongs to. A request nothing resolves keeps the permissive `key/*` pattern, and the operation then fails with its own error. `CreateKey`, `GenerateRandom`, `ListKeys`, `ListAliases` and `ListRetirableGrants` name no key resource and are evaluated against `*`, the resource a policy must name for them on AWS too.
|
||||
|
||||
A key's policy is evaluated as its resource policy. An explicit `Deny` in it refuses the request, and an `Allow` naming the caller grants it. A key in another account needs both its key policy and the caller's own policies to allow the request. An `Allow` naming only the account, as the default key policy's does, leaves the decision to the account's IAM policies. Floci deviates from AWS here: a same-account identity policy grants access even when the key policy does not name the account, while AWS requires the key policy to allow it.
|
||||
|
||||
The same check applies when another service asks KMS, as the caller, to use a key its resource is encrypted with. Restoring a Redshift or Redshift Serverless snapshot encrypted with a customer managed key needs `kms:Decrypt` on that key, read from the key policy in the snapshot owner's account and from the caller's own policies. The request carries `aws:ViaAWSService` as `true` and `kms:ViaService` naming the service's endpoint in the request's Region (`redshift-serverless.us-east-1.amazonaws.com`), as AWS's forward access sessions do. A key KMS would not use, disabled or pending deletion, refuses the restore whatever the policies say, as KMS refuses the request the service makes with it; Floci answers it as an access denial naming `kms:Decrypt`. A key AWS manages (`alias/aws/redshift`, which a snapshot copy grant made without a key records) needs no permission: AWS writes its key policy to let every principal of the account use it through the service. KMS itself still serves only the caller's own keys: a direct request naming another account's key is refused.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Variable | Default | Description |
|
||||
|
||||
@@ -143,7 +143,7 @@ aws redshift-serverless delete-namespace --namespace-name analytics
|
||||
```
|
||||
- **Snapshots dump the database.** While the namespace's workgroup is running, `CreateSnapshot` runs `pg_dump` on its container and stores the dump under `<persistent-path>/redshift-serverless-dumps/<account>/<region>/`. `RestoreFromSnapshot` drops every user schema (the catalog bootstrap schema excepted) and replays the dump with `psql`, stopping at the first failing statement, so rows written after the snapshot are gone. The current contents are dumped first and put back if replay or credential changes fail, and a restore whose recorded dump file has gone missing fails instead of reporting success. A snapshot taken with no running workgroup is metadata only, and restoring it leaves the database untouched. `DeleteSnapshot` removes the dump. Snapshot ARNs use the snapshot name as their id, snapshot names are 3-255 lowercase letters, digits and hyphens, and `retentionPeriod` is `-1` (indefinite, the default) or 1 to 3653 days. Snapshots are taggable by ARN. `snapshotName` and `snapshotArn` cannot be sent together. Floci's own `floci_internal` bootstrap schema, which feeds the `svv_external_*` views from the Glue catalog, is left out of both the dump and the reset, matching AWS where the Glue catalog is outside a namespace snapshot, so a client schema with that exact name is not captured. Snapshots with finite retention expire at their creation time plus the retention period. A dedicated background worker removes expired metadata, dumps and resource policies across all accounts and Regions. It runs every `FLOCI_SERVICES_REDSHIFT_SERVERLESS_SNAPSHOT_EXPIRATION_SWEEP_INTERVAL_SECONDS` (60 by default) and can be disabled with `FLOCI_SERVICES_REDSHIFT_SERVERLESS_SNAPSHOT_EXPIRATION_ENABLED=false`. Indefinite snapshots are preserved. Cleanup serializes with restore and retention updates. A failed cleanup remains `DELETED`, rejects restore and retention updates, and is retried on later sweeps, including after restart. Persistent and WAL storage commit the deletion marker synchronously; hybrid storage retains its periodic-flush durability. Missing dump files are treated as already removed; untrusted paths are preserved and logged. Cross-Region copies are described under snapshot copy configurations below, and an expired copy is removed like any other snapshot.
|
||||
- **`UpdateSnapshot` changes only `retentionPeriod`.** It is validated like `CreateSnapshot` (`-1` or 1 to 3653 days), `-1` makes the snapshot indefinite, and an omitted period leaves the snapshot unchanged. `snapshotRemainingDays` keeps counting from the creation time, because Floci stores no separate retention start.
|
||||
- **Resource policies grant cross-account restore only.** A policy is stored per account and Region, echoed in the shape of the API model, and dropped on read once the snapshot it belongs to is gone. A snapshot recreated under the same name is a different snapshot: the record keeps the snapshot's creation time, so the policy is not inherited. `PutResourcePolicy` accepts a JSON object for a snapshot ARN of this account and Region. Under IAM enforcement the policy is read like the resource policy of an SQS queue: a request naming a snapshot of another account (`snapshotName` with `ownerAccount`, or `snapshotArn`) is checked on that account's snapshot ARN, so the policy must allow the caller (or the caller's account) `redshift-serverless:RestoreFromSnapshot`, an explicit `Deny` wins, a snapshot with no policy is not shared, and the caller's own identity policies must allow the call as well. A statement with no `Resource`, as in AWS's own `PutResourcePolicy` example, applies to the snapshot the policy is on. With enforcement off nothing evaluates the policy. The dump is read from the owner's directory and the workgroup and namespace restored into are the caller's. `GetSnapshot` and `ListSnapshots` with another `ownerAccount` read that account's snapshots. `GetSnapshot` is checked by IAM enforcement like the restore, against `redshift-serverless:GetSnapshot`. `ListSnapshots` names no single snapshot, so it lists only the snapshots whose policy allows the caller `redshift-serverless:GetSnapshot` and leaves the others out, with enforcement on or off. A snapshot is never shared across partitions. A foreign or non-snapshot ARN is a `ValidationException`.
|
||||
- **Resource policies grant cross-account restore only.** A policy is stored per account and Region, echoed in the shape of the API model, and dropped on read once the snapshot it belongs to is gone. A snapshot recreated under the same name is a different snapshot: the record keeps the snapshot's creation time, so the policy is not inherited. `PutResourcePolicy` accepts a JSON object for a snapshot ARN of this account and Region. Under IAM enforcement the policy is read like the resource policy of an SQS queue: a request naming a snapshot of another account (`snapshotName` with `ownerAccount`, or `snapshotArn`) is checked on that account's snapshot ARN, so the policy must allow the caller (or the caller's account) `redshift-serverless:RestoreFromSnapshot`, an explicit `Deny` wins, a snapshot with no policy is not shared, and the caller's own identity policies must allow the call as well. A statement with no `Resource`, as in AWS's own `PutResourcePolicy` example, applies to the snapshot the policy is on. A snapshot whose `kmsKeyId` names a customer managed key also needs `kms:Decrypt` on that key, as AWS requires the key to be shared with the account performing the restore: the key policy in the owner's account must allow the caller or the caller's account, and the caller's own policies must allow it too. The owner restoring its own encrypted snapshot needs `kms:Decrypt` in its own policies. The check carries `kms:ViaService` as `redshift-serverless.<region>.amazonaws.com` and `aws:ViaAWSService` as `true`. A snapshot under `AWS_OWNED_KMS_KEY` needs nothing from KMS. With enforcement off nothing evaluates the policy. The dump is read from the owner's directory and the workgroup and namespace restored into are the caller's. `GetSnapshot` and `ListSnapshots` with another `ownerAccount` read that account's snapshots. `GetSnapshot` is checked by IAM enforcement like the restore, against `redshift-serverless:GetSnapshot`. `ListSnapshots` names no single snapshot, so it lists only the snapshots whose policy allows the caller `redshift-serverless:GetSnapshot` and leaves the others out, with enforcement on or off. A snapshot is never shared across partitions. A foreign or non-snapshot ARN is a `ValidationException`.
|
||||
- **Endpoint access is recorded, not acted on.** An endpoint is stored per account and Region, echoed in the shape of the API model, and dropped on read once its workgroup is gone; a workgroup recreated under the same name is a different workgroup and does not inherit it. `CreateEndpointAccess` creates no VPC endpoint. `address` and `port` are the workgroup's own, so a client can connect; `vpcEndpoint` carries a generated id and one network interface per subnet, without a `vpcId`, and `ListEndpointAccess` with a `vpcId` returns nothing. `vpcSecurityGroupIds` is optional. Endpoint names are 1 to 30 letters, digits or hyphens, start with a letter, and contain no consecutive or trailing hyphens. Security groups are the only member `UpdateEndpointAccess` changes.
|
||||
- **Custom domain associations are recorded, not acted on.** An association is stored per account and Region and dropped on read once its workgroup is gone; a workgroup recreated under the same name does not inherit it. A workgroup has at most one custom domain association. The certificate expiry time comes from ACM when the certificate exists in the emulator.
|
||||
- **Snapshot copy configurations copy snapshots.** A background sweep copies every `AVAILABLE` snapshot of the namespace that was taken at or after the configuration's creation into the destination Region, with its dump and metadata. It runs every `FLOCI_SERVICES_REDSHIFT_SERVERLESS_SNAPSHOT_COPY_SWEEP_INTERVAL_SECONDS` (60 by default) and can be disabled with `FLOCI_SERVICES_REDSHIFT_SERVERLESS_SNAPSHOT_COPY_ENABLED=false`. The copy is a snapshot of its own: it keeps the name, namespace name, owner, tags and admin user of the source, gets an ARN in the destination Region, uses `destinationKmsKeyId` as its key, and counts its `snapshotRetentionPeriod` (indefinite when omitted or `-1`) from the moment it is copied. Describe, restore, delete and expiration treat it like any other snapshot, and restoring it needs an existing namespace and workgroup in the destination Region. A copy is never copied on. The source records where it has been copied, so deleting or expiring the copy does not bring it back, and a retry or restart after a crash makes no second copy. If a snapshot of the same name that is not a copy of this source already exists in the destination Region, Floci keeps it, logs a warning and does not copy. A snapshot deleted and taken again under the same name is copied again and replaces the earlier copy of that name; each copy has its own dump file, and the earlier one is removed only after the replacement is saved, so a failed replacement leaves the earlier copy restorable. A failed copy, such as a missing dump file, leaves the source untouched and is retried by the next sweep. A crash in the middle of a copy can leave an unreferenced dump file in the destination directory, which a reset removes. `UpdateSnapshotCopyConfiguration` changes the retention of copies made afterwards, not of existing ones. Deleting the configuration stops further copies and keeps the copies already made. These are Floci choices where AWS does not say otherwise. A configuration is stored per account and Region and dropped on read once its namespace is gone; a namespace recreated under the same name does not inherit it. The destination must be a known Region in the same partition as the namespace's and must differ from it, and a namespace has only one configuration at a time (`ConflictException`). Delete the existing configuration before choosing another destination Region.
|
||||
|
||||
@@ -669,8 +669,12 @@ For `AWS::Redshift::ClusterParameterGroup`, `Parameters` is applied via `ModifyC
|
||||
`AccountsWithRestoreAccess` and `RevokeSnapshotAccess` removes it, so a snapshot deleted and taken again under
|
||||
the same name starts with no grant. Only a manual, available snapshot can be shared. A shared snapshot can be
|
||||
described and restored by the account it is shared with, and by no other action. The caller's own identity
|
||||
policies are the IAM filter's to check when IAM enforcement is on. KMS key grants are not checked, and a
|
||||
snapshot copied to another Region is shared only through the Region it was taken in.
|
||||
policies are the IAM filter's to check when IAM enforcement is on. A snapshot carrying a `KmsKeyId`, which in
|
||||
Floci is a copy made into another Region under a snapshot copy grant, also needs `kms:Decrypt` on that key under
|
||||
IAM enforcement, from the key policy and the caller's own policies, with `kms:ViaService` as
|
||||
`redshift.<region>.amazonaws.com`, unless the grant was made without a key, whose copies use the AWS managed
|
||||
`alias/aws/redshift` and need nothing from KMS. KMS grants are not evaluated, and a snapshot copied to another
|
||||
Region is shared only through the Region it was taken in.
|
||||
- `AWS::Redshift::ClusterSecurityGroup` is accepted as metadata: Floci does not emulate the legacy EC2-Classic security group model.
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -615,6 +615,10 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
region, accountId, akid)) {
|
||||
return;
|
||||
}
|
||||
if (abortIfForwardedDenied(ctx, caller, principal, callerArns.orElse(null), action,
|
||||
resolvedAuthorization.operation(), credentialScope, resources, region, accountId, akid)) {
|
||||
return;
|
||||
}
|
||||
if (tagOnCreate.isPresent() && abortIfTagOnCreateDenied(ctx, caller, principal, callerArns.orElse(null),
|
||||
action, resolvedAuthorization.operation(), tagOnCreate.get(), credentialScope, resources, region,
|
||||
accountId, akid)) {
|
||||
@@ -1093,6 +1097,47 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* A request whose service then asks another service, as the caller, to act on what a resource it is checked on
|
||||
* holds (see {@link RequestResources#forwarded}) also needs that action on that resource, checked as the caller
|
||||
* against the resource's own policy in its own account (a snapshot's KMS key, against its key policy), with
|
||||
* {@code aws:ViaAWSService} true, as AWS's forward access sessions carry it, the action's {@code ViaService}
|
||||
* key naming the service's endpoint in the request's Region and partition where it takes one, and the keys that
|
||||
* say who is calling. One naming what the action's service does not hold (a key since deleted) is refused, as
|
||||
* that service refuses it. Returns true when the request was aborted.
|
||||
*/
|
||||
private boolean abortIfForwardedDenied(ContainerRequestContext ctx, CallerContext caller, RequestPrincipal principal,
|
||||
CallerArns callerArns, String action, String operation,
|
||||
String credentialScope, List<String> resources, String region,
|
||||
String accountId, String akid) {
|
||||
for (RequestResources.Forwarded forwarded : arnBuilder.forwarded(operation, resources, accountId)) {
|
||||
if (!forwarded.held()) {
|
||||
// The service would ask for what the action's service no longer holds (a deleted key), which that
|
||||
// service refuses, failing the request whatever the policies say.
|
||||
LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}, which its service does not hold",
|
||||
akid, forwarded.action(), forwarded.resource());
|
||||
ctx.abortWith(accessDeniedForRequest(forwarded.action(), credentialScope, ctx, forwarded.resource()));
|
||||
return true;
|
||||
}
|
||||
Map<String, List<String>> context = new HashMap<>();
|
||||
if (callerArns != null) {
|
||||
callerArns.putPrincipalKeys(context);
|
||||
}
|
||||
context.put("aws:ViaAWSService", List.of("true"));
|
||||
if (forwarded.viaService() != null) {
|
||||
// The endpoint in the request's partition, which a custom Region of a China or GovCloud deployment keeps.
|
||||
AwsPartition partition = AwsPartitions.find(requestPartition())
|
||||
.orElseGet(() -> AwsPartitions.forRegionOrCommercial(region));
|
||||
context.put(forwarded.viaService(), List.of(partition.regionalHostname(forwarded.endpoint(), region)));
|
||||
}
|
||||
if (abortIfDenied(ctx, caller, principal, forwarded.action(), action, credentialScope,
|
||||
List.of(forwarded.resource()), List.of(context), region, accountId, akid)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The context once for each set of tags the request carries, with that set's keys where the context has
|
||||
* none of its own, so each resource's tags are checked apart; the context alone when it carries none.
|
||||
|
||||
@@ -202,20 +202,32 @@ final class RequestResourceMembers {
|
||||
record Targets(Member member, String query, Map<String, String> prefixes) {
|
||||
}
|
||||
|
||||
/**
|
||||
* A request an operation's service makes to another service as the caller: {@code action}, on that service's
|
||||
* resource of {@code type} which the record of the operation's resource of type {@code of} holds in
|
||||
* {@code member} (a Redshift Serverless snapshot's {@code kmsKeyId}), sent from the operation's endpoint prefix
|
||||
* {@code endpoint}, which the action's namespace's {@code viaService} key names where the Service Reference lists
|
||||
* one for the action, null otherwise.
|
||||
*/
|
||||
record Forwarded(String action, String type, String of, String member, String endpoint, String viaService) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The file: each operation's resources, the resource types its action acts on, the resources it creates under a
|
||||
* parent and the one a create whose action acts on no type makes ({@code makes}), as
|
||||
* {@code <namespace>:<Operation>}, the members a REST operation's request carries outside its body, each
|
||||
* namespace's ARN formats, and the namespaces it reads, those built by hand, those not read yet, and the others
|
||||
* with resource types. A located member is a label of the request's path, {@code {Label}}, or a parameter of its
|
||||
* query, {@code ?name}, by the member's name.
|
||||
* query, {@code ?name}, by the member's name. Each operation's {@code forwarded} requests are those its service
|
||||
* makes to another as the caller.
|
||||
*/
|
||||
record Table(Map<String, List<Resource>> operations, Map<String, List<String>> types,
|
||||
Map<String, List<Created>> creates, Map<String, List<Resource>> makes,
|
||||
Map<String, Targets> targets,
|
||||
Map<String, Map<String, String>> located, Map<String, Map<String, ArnFormat>> formats,
|
||||
Map<String, Map<String, List<String>>> resourceTagKeys,
|
||||
Set<String> namespaces, Set<String> handBuilt, Set<String> notCovered, Set<String> otherNamespaces) {
|
||||
Set<String> namespaces, Set<String> handBuilt, Set<String> notCovered, Set<String> otherNamespaces,
|
||||
Map<String, List<Forwarded>> forwarded) {
|
||||
}
|
||||
|
||||
private static final class Holder {
|
||||
@@ -300,6 +312,8 @@ final class RequestResourceMembers {
|
||||
Map<String, List<Resource>> makes = new LinkedHashMap<>();
|
||||
Map<String, Targets> targets = new LinkedHashMap<>();
|
||||
Map<String, Map<String, String>> located = new LinkedHashMap<>();
|
||||
Map<String, List<Forwarded>> forwarded = new LinkedHashMap<>();
|
||||
JsonNode forwardedActions = document.path("forwardedActions");
|
||||
operations.properties().forEach(operation -> {
|
||||
String namespace = operation.getKey().substring(0, Math.max(0, operation.getKey().indexOf(':')));
|
||||
if (!namespaces.contains(namespace)) {
|
||||
@@ -371,12 +385,43 @@ final class RequestResourceMembers {
|
||||
if (!where.isEmpty()) {
|
||||
located.put(operation.getKey(), Map.copyOf(where));
|
||||
}
|
||||
List<Forwarded> forwards = new ArrayList<>();
|
||||
for (JsonNode use : operation.getValue().path("forwarded")) {
|
||||
forwards.add(forwarded(operation.getKey(), use, types, formats.getOrDefault(namespace, Map.of()),
|
||||
forwardedActions));
|
||||
}
|
||||
if (!forwards.isEmpty()) {
|
||||
forwarded.put(operation.getKey(), List.copyOf(forwards));
|
||||
}
|
||||
});
|
||||
return new Table(Map.copyOf(entries), Map.copyOf(actsOn), Map.copyOf(creates), Map.copyOf(makes),
|
||||
Map.copyOf(targets), Map.copyOf(located), Map.copyOf(formats), Map.copyOf(resourceTagKeys), namespaces,
|
||||
names(document.path("handBuilt")),
|
||||
Set.copyOf(document.path("notCovered").propertyStream().map(Map.Entry::getKey).toList()),
|
||||
names(document.path("otherNamespaces")));
|
||||
names(document.path("otherNamespaces")), Map.copyOf(forwarded));
|
||||
}
|
||||
|
||||
/**
|
||||
* A request the operation's service makes to another as the caller, joined with what the file records of its
|
||||
* action: the type it acts on and the {@code ViaService} key of its namespace, if any.
|
||||
*/
|
||||
private static Forwarded forwarded(String operation, JsonNode use, List<String> types,
|
||||
Map<String, ArnFormat> formats, JsonNode actions) {
|
||||
String action = use.path("action").asText("");
|
||||
JsonNode facts = actions.path(action);
|
||||
String type = facts.path("type").asText("");
|
||||
String of = use.path("of").asText("");
|
||||
String member = use.path("member").asText("");
|
||||
String endpoint = use.path("endpoint").asText("");
|
||||
String viaService = facts.has("viaService") ? facts.path("viaService").asText("") : null;
|
||||
if (!use.isObject() || use.size() != 4 || !facts.isObject() || type.isEmpty() || !types.contains(of)
|
||||
|| !formats.containsKey(of) || !LOCATED_MEMBER.matcher(member).matches() || endpoint.isEmpty()
|
||||
|| viaService != null
|
||||
&& !viaService.equals(action.substring(0, action.indexOf(':') + 1) + "ViaService")) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " forwards " + use + " for " + operation
|
||||
+ ", no recorded action on a member of the record of a type it acts on");
|
||||
}
|
||||
return new Forwarded(action, type, of, member, endpoint, viaService);
|
||||
}
|
||||
|
||||
private static Set<String> names(JsonNode list) {
|
||||
|
||||
@@ -16,6 +16,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@@ -136,6 +137,64 @@ public final class RequestResources {
|
||||
return named(operation, resources, formats(table, operation), Map.of(), body, partition, region, accountId, stored);
|
||||
}
|
||||
|
||||
/**
|
||||
* A request an operation's service makes to another service as the caller, which the caller needs permission for
|
||||
* too: {@code action} on {@code resource}, sent from {@code endpoint}, the operation's endpoint prefix, which the
|
||||
* condition key {@code viaService} names where the action takes one (null otherwise). Not {@code held} when the
|
||||
* action's service holds no resource of that name (a deleted key), {@code resource} then being the value the
|
||||
* record holds: that service refuses the request, so the operation fails.
|
||||
*/
|
||||
public record Forwarded(String action, String resource, String viaService, String endpoint, boolean held) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The requests the operation's service makes to another as the caller (the table's {@code forwarded}), for the
|
||||
* resources the request is checked on: for each of {@code resources} of the type whose record holds what the
|
||||
* action acts on, the resource that record's member names, as the action's service finds it in the account and
|
||||
* Region of the ARN, the caller's ({@code find}) or another's ({@code findInAccount}), or the value itself, not
|
||||
* held, when it finds none. None for a resource whose service records nothing there (a snapshot under AWS's own
|
||||
* key records no key of the account's), or one whose policy lets every principal of its account have the service
|
||||
* act on it ({@link StoredResourceArns#grantsItsAccountThroughServices}: an AWS managed key). {@code held} is the
|
||||
* operation's service, and {@code services} gives the action's.
|
||||
*/
|
||||
public static List<Forwarded> forwarded(String operation, List<String> resources, String accountId,
|
||||
StoredResourceArns held, Function<String, StoredResourceArns> services) {
|
||||
RequestResourceMembers.Table table = RequestResourceMembers.table();
|
||||
List<RequestResourceMembers.Forwarded> uses = operation == null ? List.of()
|
||||
: table.forwarded().getOrDefault(operation, List.of());
|
||||
if (uses.isEmpty() || held == null) {
|
||||
return List.of();
|
||||
}
|
||||
Map<String, RequestResourceMembers.ArnFormat> formats = formats(table, operation);
|
||||
List<Forwarded> found = new ArrayList<>();
|
||||
for (RequestResourceMembers.Forwarded use : uses) {
|
||||
StoredResourceArns service = services.apply(use.action().substring(0, use.action().indexOf(':')));
|
||||
RequestResourceMembers.ArnFormat of = formats.get(use.of());
|
||||
if (service == null || of == null) {
|
||||
continue;
|
||||
}
|
||||
for (String resource : resources) {
|
||||
if (!of.pattern().matcher(resource).matches()) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(resource);
|
||||
Optional<String> named = held.recorded(resource, use.member());
|
||||
if (named.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
Optional<String> target = arn.accountId().equals(accountId)
|
||||
? service.find(use.type(), List.of(named.get()), arn.region())
|
||||
: service.findInAccount(use.type(), List.of(named.get()), arn.accountId(), arn.region());
|
||||
if (target.isEmpty()) {
|
||||
found.add(new Forwarded(use.action(), named.get(), use.viaService(), use.endpoint(), false));
|
||||
} else if (!service.grantsItsAccountThroughServices(target.get())) {
|
||||
found.add(new Forwarded(use.action(), target.get(), use.viaService(), use.endpoint(), true));
|
||||
}
|
||||
}
|
||||
}
|
||||
return List.copyOf(found);
|
||||
}
|
||||
|
||||
/** Whether the table holds the operation as one with no resource of its own, which is checked on {@code *}. */
|
||||
public static boolean actsOnNoResource(String operation) {
|
||||
return reads(operation) && !hasIndividualTargets(operation)
|
||||
|
||||
@@ -10,7 +10,9 @@ import java.util.Optional;
|
||||
* ({@code scalable-target/<id>}, named by its service namespace, resource id and scalable dimension;
|
||||
* {@code workgroup/<id>}, named by its name). Also the ARNs of the resources a request names through another of its
|
||||
* service's own (the cluster or workgroup a Data API session runs on, the cluster an EMR instance group is in, the
|
||||
* accounts an IAM Identity Center permission set is provisioned to).
|
||||
* accounts an IAM Identity Center permission set is provisioned to). Also what a resource's record holds that a
|
||||
* request the operation's service forwards as the caller acts on (the key a Redshift snapshot is encrypted with), and
|
||||
* the ARN of that resource in the service that owns it (the key, in KMS).
|
||||
*
|
||||
* <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
|
||||
@@ -25,8 +27,8 @@ import java.util.Optional;
|
||||
* 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>
|
||||
* {@code through}, a default, {@code forwarded}): never a fact about what an operation acts on, which the table alone
|
||||
* says, from botocore and the Service Reference, or from what AWS says where neither carries it.</p>
|
||||
*/
|
||||
public interface StoredResourceArns {
|
||||
|
||||
@@ -52,6 +54,26 @@ public interface StoredResourceArns {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
/**
|
||||
* What the resource stored under {@code arn}, in the account and Region the ARN names, records in {@code member},
|
||||
* as botocore names that member of the type's record (a Redshift Serverless snapshot's {@code kmsKeyId}, the key
|
||||
* it is encrypted with); empty when the service holds no such resource, it records nothing there, or the member
|
||||
* is not one it reads. A variable the ARN leaves open ({@code *}) matches whatever the handler would act on in
|
||||
* its place (a provisioned snapshot of any cluster, for a restore naming none).
|
||||
*/
|
||||
default Optional<String> recorded(String arn, String member) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the resource {@code arn} names, one {@link #find} gave, lets every principal of its account have a
|
||||
* service act on it through that service, as the key policy AWS writes for an AWS managed KMS key does: a request
|
||||
* another service forwards as the caller then needs no permission of the caller's on it. False for any other.
|
||||
*/
|
||||
default boolean grantsItsAccountThroughServices(String arn) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* As {@link #findByMembers}, for a resource another account owns that the request names by that account, which its
|
||||
* service lets the caller reach when the resource's policy allows it (a Redshift Serverless snapshot shared by its
|
||||
|
||||
@@ -254,6 +254,19 @@ public class ResourceArnBuilder {
|
||||
return named.isEmpty() ? List.of("*") : named;
|
||||
}
|
||||
|
||||
/**
|
||||
* The requests the service of {@code operation}, the one the request is dispatched as, makes to another service as
|
||||
* the caller on what the resources it is checked on hold (see {@link RequestResources#forwarded}), each resource
|
||||
* looked up in its own service's stored state; none when the table gives the operation none.
|
||||
*/
|
||||
public List<RequestResources.Forwarded> forwarded(String operation, List<String> resources, String accountId) {
|
||||
if (operation == null || operation.indexOf(':') < 0) {
|
||||
return List.of();
|
||||
}
|
||||
return RequestResources.forwarded(operation, resources, accountId,
|
||||
storedResourceArns(operation.substring(0, operation.indexOf(':'))), this::storedResourceArns);
|
||||
}
|
||||
|
||||
/** The registered finder of the namespace's stored ARNs; null when there is none. */
|
||||
private StoredResourceArns storedResourceArns(String namespace) {
|
||||
if (storedResourceArns == null || storedResourceArns.isUnsatisfied()) {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package io.floci.aws.services.kms;
|
||||
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.services.iam.ResourcePolicyProvider;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Supplies a KMS key's key policy to IAM policy evaluation, together with the account that owns the key: the one in
|
||||
* its ARN, also when the key does not exist or has no policy, so a call on another account's key is judged as
|
||||
* cross-account, needing the key policy as well as the caller's own. An alias has no policy of its own, and an ARN
|
||||
* with its id open names no one key.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class KmsResourcePolicyProvider implements ResourcePolicyProvider {
|
||||
|
||||
private static final String KEY_PREFIX = "key/";
|
||||
|
||||
private final KmsService kms;
|
||||
|
||||
@Inject
|
||||
public KmsResourcePolicyProvider(KmsService kms) {
|
||||
this.kms = kms;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ResourcePolicy> getResourcePolicies(String credentialScope, String resourceArn) {
|
||||
Optional<AwsArnUtils.Arn> parsed = ResourcePolicyProvider.regionalArn(resourceArn, "kms");
|
||||
if (parsed.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
String target = parsed.get().resource();
|
||||
if (!target.startsWith(KEY_PREFIX) || target.length() == KEY_PREFIX.length() || target.contains("*")) {
|
||||
return List.of();
|
||||
}
|
||||
return List.of(new ResourcePolicy(kms.findKeyPolicy(resourceArn).orElse(null), parsed.get().accountId()));
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import io.floci.aws.core.common.StripedLocks;
|
||||
import io.floci.aws.core.resource.ExplorerResource;
|
||||
import io.floci.aws.core.resource.ResourceProvider;
|
||||
import io.floci.aws.core.resource.SupportedResourceType;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.kms.keytype.KmsKeyType;
|
||||
@@ -2342,6 +2343,89 @@ public class KmsService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The stored ARN of the key {@code keyIdOrArn} names in {@code accountId}'s {@code region}, whoever is calling: a
|
||||
* key id or an alias name resolved in that account, or a key or alias ARN read in the account and Region it names.
|
||||
* The enforcement filter reads this for a key another service's resource records, which may be another account's
|
||||
* (a shared snapshot's). A reserved {@code alias/aws/<service>} of the caller's account names AWS's managed key
|
||||
* of that service, which every account has whether anything read it before or not. Empty when that account holds
|
||||
* no such key.
|
||||
*/
|
||||
public Optional<String> findKeyArnOfAccount(String keyIdOrArn, String accountId, String region) {
|
||||
if (keyIdOrArn == null || keyIdOrArn.isBlank() || accountId == null || region == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String account = accountId;
|
||||
String inRegion = region;
|
||||
String id = keyIdOrArn;
|
||||
if (AwsArnUtils.isArnFor(keyIdOrArn, "kms")) {
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(keyIdOrArn);
|
||||
account = arn.accountId();
|
||||
inRegion = arn.region();
|
||||
id = arn.resource();
|
||||
}
|
||||
if (id.startsWith("alias/")) {
|
||||
if (AwsManagedKeys.isReservedAlias(id) && account.equals(regionResolver.getAccountId())) {
|
||||
// AWS's own key under alias/aws/<service> is in every account, read or not, as listKeys finds it.
|
||||
ensureAwsManagedKeys(inRegion);
|
||||
}
|
||||
Optional<String> target = ofAccount(aliasStore, account, inRegion + "::" + id).map(KmsAlias::getTargetKeyId);
|
||||
if (target.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
id = target.get();
|
||||
} else if (id.startsWith("key/")) {
|
||||
id = id.substring("key/".length());
|
||||
}
|
||||
return ofAccount(keyStore, account, inRegion + "::" + id).map(KmsKey::getArn).filter(arn -> !arn.isBlank());
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the key {@code keyArn} names, read in the account and Region of the ARN, is one AWS manages, whose key
|
||||
* policy AWS writes to let every principal of the account use it through the service it belongs to.
|
||||
*/
|
||||
public boolean isAwsManagedKey(String keyArn) {
|
||||
return keyAt(keyArn).map(key -> AWS_KEY_MANAGER.equals(key.getKeyManager())).orElse(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the key {@code keyArn} names, read in the account and Region of the ARN, is one KMS uses for a
|
||||
* cryptographic request: enabled, neither disabled nor pending deletion, which KMS refuses one with.
|
||||
*/
|
||||
public boolean isEnabledKey(String keyArn) {
|
||||
return keyAt(keyArn).map(key -> "Enabled".equals(key.getKeyState())).orElse(false);
|
||||
}
|
||||
|
||||
/** The key a key ARN names, read in the account and Region of the ARN, whoever is calling. */
|
||||
private Optional<KmsKey> keyAt(String keyArn) {
|
||||
if (!AwsArnUtils.isArnFor(keyArn, "kms")) {
|
||||
return Optional.empty();
|
||||
}
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(keyArn);
|
||||
return arn.resource().startsWith("key/")
|
||||
? ofAccount(keyStore, arn.accountId(), arn.region() + "::" + arn.resource().substring("key/".length()))
|
||||
: Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* The key policy of the key {@code keyArn} names, read in the account and Region of the ARN, whoever is calling,
|
||||
* which IAM evaluates as the key's resource policy; empty when that account holds no such key, or for an alias.
|
||||
*/
|
||||
public Optional<String> findKeyPolicy(String keyArn) {
|
||||
return keyAt(keyArn).map(KmsKey::getPolicy).filter(policy -> !policy.isBlank());
|
||||
}
|
||||
|
||||
/**
|
||||
* What {@code accountId} stores under {@code key}, an entry written before accounts were kept apart included; a
|
||||
* store that keeps no accounts apart holds the caller's alone.
|
||||
*/
|
||||
private <V> Optional<V> ofAccount(StorageBackend<String, V> store, String accountId, String key) {
|
||||
if (store instanceof AccountAwareStorageBackend<V> accounts) {
|
||||
return accounts.getForAccount(accountId, key).or(() -> accounts.getLegacyForAccount(accountId, key));
|
||||
}
|
||||
return accountId.equals(regionResolver.getAccountId()) ? store.get(key) : Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* The stored ARN of the key the grant a retirement or a revocation acts on belongs to: the
|
||||
* grant its {@code GrantToken} names when the request carries one, and otherwise the grant
|
||||
@@ -2388,7 +2472,7 @@ public class KmsService implements ResourceProvider {
|
||||
if (!region.equals(arn.region())) {
|
||||
throw new AwsException("NotFoundException", "Invalid arn " + arn.region(), 400);
|
||||
}
|
||||
// Floci does not evaluate key policies, so another account's key is never usable here;
|
||||
// KMS serves the caller's own keys only, so another account's key is never usable here;
|
||||
// without this the store would answer with the caller's own key or alias of that name.
|
||||
if (!arn.accountId().equals(regionResolver.getAccountId())) {
|
||||
throw new AwsException("NotFoundException", arn.resource().startsWith("alias/")
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package io.floci.aws.services.kms;
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* Finds the key a KMS key id, alias or ARN names, for a request another service forwards to KMS as the caller on a
|
||||
* key its own resource records (a snapshot's): the key's stored ARN, in the caller's account or in the one that
|
||||
* resource is in, when KMS would use it; none for a key disabled or pending deletion, which KMS refuses such a
|
||||
* request with.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class KmsStoredResourceArns implements StoredResourceArns {
|
||||
|
||||
private final KmsService kms;
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
public KmsStoredResourceArns(KmsService kms, RegionResolver regionResolver) {
|
||||
this.kms = kms;
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String namespace() {
|
||||
return "kms";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
return findInAccount(type, names, regionResolver.getAccountId(), region);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> findInAccount(String type, List<String> names, String account, String region) {
|
||||
return "key".equals(type) && names.size() == 1
|
||||
? kms.findKeyArnOfAccount(names.getFirst(), account, region).filter(kms::isEnabledKey)
|
||||
: Optional.empty();
|
||||
}
|
||||
|
||||
/** Whether the key is one AWS manages, whose policy lets every principal of its account use it through a service. */
|
||||
@Override
|
||||
public boolean grantsItsAccountThroughServices(String arn) {
|
||||
return kms.isAwsManagedKey(arn);
|
||||
}
|
||||
}
|
||||
@@ -74,6 +74,7 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.function.BiPredicate;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@@ -2161,6 +2162,33 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
return named;
|
||||
}
|
||||
|
||||
/**
|
||||
* The snapshot an ARN names in its account, as a restore finds it, a cluster the ARN leaves open ({@code *})
|
||||
* matching any: in the caller's account the copy kept in the ARN's Region before the snapshot itself, and in
|
||||
* another account the snapshot itself alone, taken in the ARN's Region, as a shared one is restored.
|
||||
*/
|
||||
public Optional<Snapshot> findSnapshotAt(String snapshotArn) {
|
||||
if (!AwsArnUtils.isArnFor(snapshotArn, "redshift")) {
|
||||
return Optional.empty();
|
||||
}
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(snapshotArn);
|
||||
String resource = arn.resource();
|
||||
int slash = resource.indexOf('/');
|
||||
if (!resource.startsWith("snapshot:") || slash < 0) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String cluster = resource.substring("snapshot:".length(), slash);
|
||||
String identifier = resource.substring(slash + 1);
|
||||
Predicate<Snapshot> ofCluster = snapshot -> "*".equals(cluster) || cluster.equals(snapshot.getClusterIdentifier());
|
||||
if (!arn.accountId().equals(clusters.accountId())) {
|
||||
return snapshots.getForAccount(arn.accountId(), identifier).filter(ofCluster)
|
||||
.filter(snapshot -> snapshot.getSnapshotArn() == null
|
||||
|| AwsArnUtils.parse(snapshot.getSnapshotArn()).region().equals(arn.region()));
|
||||
}
|
||||
return snapshotCopies.getForAccount(arn.accountId(), copyKey(arn.region(), identifier)).filter(ofCluster)
|
||||
.or(() -> snapshots.getForAccount(arn.accountId(), identifier).filter(ofCluster));
|
||||
}
|
||||
|
||||
private boolean isInRequestRegion(Snapshot snapshot) {
|
||||
if (snapshot.getSnapshotArn() == null) {
|
||||
return true;
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package io.floci.aws.services.redshift;
|
||||
|
||||
import io.floci.aws.core.common.StoredResourceArns;
|
||||
import io.floci.aws.services.redshift.model.Snapshot;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* What IAM asks Redshift of the resources a request names: what a snapshot records as its {@code KmsKeyId}, the key a
|
||||
* restore asks KMS to decrypt with as the caller.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class RedshiftStoredResourceArns implements StoredResourceArns {
|
||||
|
||||
private final RedshiftService redshift;
|
||||
|
||||
@Inject
|
||||
public RedshiftStoredResourceArns(RedshiftService redshift) {
|
||||
this.redshift = redshift;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String namespace() {
|
||||
return "redshift";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/** The key the snapshot an ARN names, in any account, records as its {@code KmsKeyId}. */
|
||||
@Override
|
||||
public Optional<String> recorded(String arn, String member) {
|
||||
if (!"KmsKeyId".equals(member)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return redshift.findSnapshotAt(arn).map(Snapshot::getKmsKeyId).filter(key -> !key.isBlank());
|
||||
}
|
||||
}
|
||||
@@ -1006,6 +1006,23 @@ public class RedshiftServerlessService implements Resettable, StoredResourceArns
|
||||
return findSnapshotOfAccount(account, names.getFirst(), region).map(RedshiftServerlessSnapshot::getSnapshotArn);
|
||||
}
|
||||
|
||||
/**
|
||||
* What the snapshot stored under {@code arn}, in any account, records as its {@code kmsKeyId}: its key, none for
|
||||
* one under AWS's own key ({@value #AWS_OWNED_KMS_KEY}), which is no key of the account's.
|
||||
*/
|
||||
@Override
|
||||
public Optional<String> recorded(String arn, String member) {
|
||||
if (!"kmsKeyId".equals(member) || !AwsArnUtils.isArnFor(arn, "redshift-serverless")) {
|
||||
return Optional.empty();
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
return snapshots.scanForAccount(parsed.accountId(), key -> key.startsWith(parsed.region() + "::")).stream()
|
||||
.filter(snapshot -> arn.equals(snapshot.getSnapshotArn()))
|
||||
.map(RedshiftServerlessSnapshot::getKmsKeyId)
|
||||
.filter(key -> key != null && !key.isBlank() && !AWS_OWNED_KMS_KEY.equals(key))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
/** The snapshot {@code snapshotName} of {@code accountId} in {@code region}, whoever is calling. */
|
||||
public Optional<RedshiftServerlessSnapshot> findSnapshotOfAccount(String accountId, String snapshotName,
|
||||
String region) {
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
"resourceTagKeys": {"ec2": {"instance": ["aws:ResourceTag/", "ec2:ResourceTag/"]}},
|
||||
"unqualified": {"ssm": ["parameter"], "states": ["statemachine"]},
|
||||
"mintedIds": {"events": ["api-destination", "connection"]},
|
||||
"forwardedActions": {"kms:Decrypt": {"type": "key", "format": "arn:${Partition}:kms:${Region}:${Account}:key/${KeyId}", "viaService": "kms:ViaService"}},
|
||||
"operations": {
|
||||
"access-analyzer:ApplyArchiveRule": {"action": "access-analyzer:ApplyArchiveRule", "types": ["Analyzer"], "resources": [{"types": ["Analyzer"], "arn": "analyzerArn"}]},
|
||||
"access-analyzer:CancelPolicyGeneration": {"action": "access-analyzer:CancelPolicyGeneration", "types": [], "resources": []},
|
||||
@@ -3025,7 +3026,7 @@
|
||||
"redshift-serverless:ListWorkgroups": {"action": "redshift-serverless:ListWorkgroups", "types": [], "resources": []},
|
||||
"redshift-serverless:PutResourcePolicy": {"action": "redshift-serverless:PutResourcePolicy", "types": [], "resources": []},
|
||||
"redshift-serverless:RestoreFromRecoveryPoint": {"action": "redshift-serverless:RestoreFromRecoveryPoint", "types": ["recoveryPoint"], "resources": [{"type": "recoveryPoint", "fill": {"RecoveryPointId": "recoveryPointId"}}]},
|
||||
"redshift-serverless:RestoreFromSnapshot": {"action": "redshift-serverless:RestoreFromSnapshot", "types": ["snapshot"], "resources": [{"types": ["snapshot"], "arn": "snapshotArn"}, {"type": "snapshot", "fill": {}, "find": ["snapshotName"], "account": "ownerAccount"}]},
|
||||
"redshift-serverless:RestoreFromSnapshot": {"action": "redshift-serverless:RestoreFromSnapshot", "types": ["snapshot"], "resources": [{"types": ["snapshot"], "arn": "snapshotArn"}, {"type": "snapshot", "fill": {}, "find": ["snapshotName"], "account": "ownerAccount"}], "forwarded": [{"action": "kms:Decrypt", "of": "snapshot", "member": "kmsKeyId", "endpoint": "redshift-serverless"}]},
|
||||
"redshift-serverless:RestoreTableFromRecoveryPoint": {"action": "redshift-serverless:RestoreTableFromRecoveryPoint", "types": ["namespace", "recoveryPoint"], "resources": [{"type": "recoveryPoint", "fill": {"RecoveryPointId": "recoveryPointId"}}, {"type": "namespace", "fill": {}, "find": ["namespaceName"]}]},
|
||||
"redshift-serverless:RestoreTableFromSnapshot": {"action": "redshift-serverless:RestoreTableFromSnapshot", "types": ["namespace", "snapshot"], "resources": [{"type": "namespace", "fill": {}, "find": ["namespaceName"]}, {"type": "snapshot", "fill": {}, "find": ["snapshotName"]}]},
|
||||
"redshift-serverless:TagResource": {"action": "redshift-serverless:TagResource", "types": ["namespace", "recoveryPoint", "snapshot", "workgroup"], "resources": [{"types": ["namespace", "recoveryPoint", "snapshot", "workgroup"], "arn": "resourceArn"}]},
|
||||
@@ -3176,7 +3177,7 @@
|
||||
"redshift:RejectDataShare": {"action": "redshift:RejectDataShare", "types": ["datashare"], "resources": [{"types": ["datashare"], "arn": "DataShareArn"}]},
|
||||
"redshift:ResetClusterParameterGroup": {"action": "redshift:ResetClusterParameterGroup", "types": ["parametergroup"], "resources": [{"type": "parametergroup", "fill": {"ParameterGroupName": "ParameterGroupName"}}]},
|
||||
"redshift:ResizeCluster": {"action": "redshift:ResizeCluster", "types": ["cluster"], "resources": [{"type": "cluster", "fill": {"ClusterName": "ClusterIdentifier"}}]},
|
||||
"redshift:RestoreFromClusterSnapshot": {"action": "redshift:RestoreFromClusterSnapshot", "types": ["cluster", "snapshot"], "resources": [{"types": ["cluster", "snapshot"], "arn": "DefaultIamRoleArn"}, {"types": ["cluster", "snapshot"], "arn": "RedshiftIdcApplicationArn"}, {"types": ["cluster", "snapshot"], "arn": "SnapshotArn"}, {"type": "cluster", "fill": {"ClusterName": "ClusterIdentifier"}}, {"type": "snapshot", "fill": {"ClusterName": "SnapshotClusterIdentifier", "SnapshotName": "SnapshotIdentifier"}, "account": "OwnerAccount"}]},
|
||||
"redshift:RestoreFromClusterSnapshot": {"action": "redshift:RestoreFromClusterSnapshot", "types": ["cluster", "snapshot"], "resources": [{"types": ["cluster", "snapshot"], "arn": "DefaultIamRoleArn"}, {"types": ["cluster", "snapshot"], "arn": "RedshiftIdcApplicationArn"}, {"types": ["cluster", "snapshot"], "arn": "SnapshotArn"}, {"type": "cluster", "fill": {"ClusterName": "ClusterIdentifier"}}, {"type": "snapshot", "fill": {"ClusterName": "SnapshotClusterIdentifier", "SnapshotName": "SnapshotIdentifier"}, "account": "OwnerAccount"}], "forwarded": [{"action": "kms:Decrypt", "of": "snapshot", "member": "KmsKeyId", "endpoint": "redshift"}]},
|
||||
"redshift:RestoreTableFromClusterSnapshot": {"action": "redshift:RestoreTableFromClusterSnapshot", "types": ["cluster", "snapshot"], "resources": [{"type": "cluster", "fill": {"ClusterName": "ClusterIdentifier"}}, {"type": "snapshot", "fill": {"ClusterName": "ClusterIdentifier", "SnapshotName": "SnapshotIdentifier"}}]},
|
||||
"redshift:ResumeCluster": {"action": "redshift:ResumeCluster", "types": ["cluster"], "resources": [{"type": "cluster", "fill": {"ClusterName": "ClusterIdentifier"}}]},
|
||||
"redshift:RevokeClusterSecurityGroupIngress": {"action": "redshift:RevokeClusterSecurityGroupIngress", "types": ["securitygroup", "securitygroupingress-ec2securitygroup"], "resources": []},
|
||||
|
||||
@@ -86,6 +86,39 @@ class RequestResourceMembersTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void forwardedRequestsJoinTheirActionsRecordedTypeAndViaServiceKeyAndRefuseAnythingElse() throws Exception {
|
||||
assertEquals(List.of(new RequestResourceMembers.Forwarded("kms:Decrypt", "key", "snapshot", "kmsKeyId",
|
||||
"redshift-serverless", "kms:ViaService")),
|
||||
RequestResourceMembers.table().forwarded().get("redshift-serverless:RestoreFromSnapshot"));
|
||||
assertEquals(List.of(new RequestResourceMembers.Forwarded("kms:Decrypt", "key", "snapshot", "KmsKeyId",
|
||||
"redshift", "kms:ViaService")),
|
||||
RequestResourceMembers.table().forwarded().get("redshift:RestoreFromClusterSnapshot"));
|
||||
ObjectNode document = (ObjectNode) MAPPER.readTree("""
|
||||
{"namespaces":{"example":["example"]},"arnFormats":{"example":{
|
||||
"thing":"arn:${Partition}:example:${Region}:${Account}:thing/${ThingId}"}},
|
||||
"forwardedActions":{"keys:Decrypt":{"type":"key",
|
||||
"format":"arn:${Partition}:keys:${Region}:${Account}:key/${KeyId}"}},
|
||||
"operations":{"example:Restore":{"types":["thing"],"resources":[],
|
||||
"forwarded":[{"action":"keys:Decrypt","of":"thing","member":"keysKeyId","endpoint":"example"}]}}}
|
||||
""");
|
||||
assertEquals(List.of(new RequestResourceMembers.Forwarded("keys:Decrypt", "key", "thing", "keysKeyId",
|
||||
"example", null)), parse(document.toString()).forwarded().get("example:Restore"));
|
||||
for (String invalid : List.of(
|
||||
"[{\"action\":\"keys:Encrypt\",\"of\":\"thing\",\"member\":\"keysKeyId\",\"endpoint\":\"example\"}]",
|
||||
"[{\"action\":\"keys:Decrypt\",\"of\":\"gadget\",\"member\":\"keysKeyId\",\"endpoint\":\"example\"}]",
|
||||
"[{\"action\":\"keys:Decrypt\",\"of\":\"thing\",\"member\":\"Keys[]\",\"endpoint\":\"example\"}]",
|
||||
"[{\"action\":\"keys:Decrypt\",\"of\":\"thing\",\"member\":\"keysKeyId\",\"endpoint\":\"\"}]",
|
||||
"[{\"action\":\"keys:Decrypt\",\"of\":\"thing\",\"member\":\"keysKeyId\"}]")) {
|
||||
ObjectNode changed = document.deepCopy();
|
||||
((ObjectNode) changed.path("operations").path("example:Restore")).set("forwarded", MAPPER.readTree(invalid));
|
||||
assertThrows(IllegalStateException.class, () -> parse(changed.toString()), invalid);
|
||||
}
|
||||
ObjectNode otherKey = document.deepCopy();
|
||||
((ObjectNode) otherKey.path("forwardedActions").path("keys:Decrypt")).put("viaService", "other:ViaService");
|
||||
assertThrows(IllegalStateException.class, () -> parse(otherKey.toString()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTableReadsItsNamespacesAndGivesEachTypeItNamesAnArnFormat() {
|
||||
RequestResourceMembers.Table table = RequestResourceMembers.table();
|
||||
|
||||
@@ -1110,6 +1110,85 @@ class RequestResourcesTest {
|
||||
assertEquals(List.of(), of("codebuild:StopBuild", json("{\"id\":\"orphan\"}"), codeBuild));
|
||||
}
|
||||
|
||||
/**
|
||||
* A restore whose service asks KMS, as the caller, to decrypt with the key its snapshot records is also checked
|
||||
* as {@code kms:Decrypt} on that key, found in the snapshot's own account and Region, the caller's or another's;
|
||||
* one KMS no longer holds is forwarded as the value the snapshot records, not held, which refuses it; a snapshot
|
||||
* recording no key, or one under a key AWS manages, whose policy lets the account use it through the service,
|
||||
* forwards nothing.
|
||||
*/
|
||||
@Test
|
||||
void aRestoreForwardsDecryptOnTheKeyItsSnapshotRecords() {
|
||||
String caller = "000000000000";
|
||||
String owner = "111122223333";
|
||||
String own = "arn:aws:redshift-serverless:us-east-1:" + caller + ":snapshot/mine";
|
||||
String shared = "arn:aws:redshift-serverless:eu-west-1:" + owner + ":snapshot/theirs";
|
||||
String plain = "arn:aws:redshift-serverless:us-east-1:" + caller + ":snapshot/plain";
|
||||
String lost = "arn:aws:redshift-serverless:us-east-1:" + caller + ":snapshot/lost";
|
||||
String managed = "arn:aws:redshift-serverless:us-east-1:" + caller + ":snapshot/managed";
|
||||
String awsKey = "arn:aws:kms:us-east-1:" + caller + ":key/aws-redshift";
|
||||
Map<String, String> keys = Map.of(own, "k-own", shared, "alias/theirs", lost, "deleted",
|
||||
managed, "alias/aws/redshift");
|
||||
StoredResourceArns serverless = new StoredResourceArns() {
|
||||
@Override
|
||||
public String namespace() {
|
||||
return "redshift-serverless";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> recorded(String arn, String member) {
|
||||
return "kmsKeyId".equals(member) ? Optional.ofNullable(keys.get(arn)) : Optional.empty();
|
||||
}
|
||||
};
|
||||
StoredResourceArns kms = new StoredResourceArns() {
|
||||
@Override
|
||||
public String namespace() {
|
||||
return "kms";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
if (!"key".equals(type)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return names.equals(List.of("k-own")) ? Optional.of("arn:aws:kms:" + region + ":" + caller + ":key/k-own")
|
||||
: names.equals(List.of("alias/aws/redshift")) ? Optional.of(awsKey) : Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> findInAccount(String type, List<String> names, String account, String region) {
|
||||
return "key".equals(type) && names.equals(List.of("alias/theirs"))
|
||||
? Optional.of("arn:aws:kms:" + region + ":" + account + ":key/k-theirs") : Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean grantsItsAccountThroughServices(String arn) {
|
||||
return awsKey.equals(arn);
|
||||
}
|
||||
};
|
||||
String operation = "redshift-serverless:RestoreFromSnapshot";
|
||||
assertEquals(List.of(
|
||||
new RequestResources.Forwarded("kms:Decrypt", "arn:aws:kms:us-east-1:" + caller + ":key/k-own",
|
||||
"kms:ViaService", "redshift-serverless", true),
|
||||
new RequestResources.Forwarded("kms:Decrypt", "arn:aws:kms:eu-west-1:" + owner + ":key/k-theirs",
|
||||
"kms:ViaService", "redshift-serverless", true),
|
||||
new RequestResources.Forwarded("kms:Decrypt", "deleted", "kms:ViaService", "redshift-serverless",
|
||||
false)),
|
||||
RequestResources.forwarded(operation, List.of("*", own, shared, plain, lost, managed), caller,
|
||||
serverless, namespace -> "kms".equals(namespace) ? kms : null));
|
||||
// Without the snapshot's or the key's service, or for an operation forwarding nothing, nothing is forwarded.
|
||||
assertEquals(List.of(), RequestResources.forwarded(operation, List.of(own), caller, null, namespace -> kms));
|
||||
assertEquals(List.of(), RequestResources.forwarded(operation, List.of(own), caller, serverless,
|
||||
namespace -> null));
|
||||
assertEquals(List.of(), RequestResources.forwarded("redshift-serverless:GetSnapshot", List.of(own), caller,
|
||||
serverless, namespace -> kms));
|
||||
}
|
||||
|
||||
/**
|
||||
* A Parameter Store parameter is {@code parameter/<name>} whether its name starts with a slash or not, without the
|
||||
* whitespace around it, a name of two leading slashes keeping the second and one beginning {@code /parameter/}
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
package io.floci.aws.services.kms;
|
||||
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.services.iam.ResourcePolicyProvider.ResourcePolicy;
|
||||
import io.floci.aws.services.kms.model.KmsAlias;
|
||||
import io.floci.aws.services.kms.model.KmsKey;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Another service reads a key its resource records, and the key's policy, in the account that resource is in, whoever
|
||||
* is calling: a shared snapshot's key is the owner's.
|
||||
*/
|
||||
class KmsKeyOfAccountTest {
|
||||
|
||||
private static final String OWNER = "111122223333";
|
||||
private static final String CALLER = "444455556666";
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
private KmsService owners;
|
||||
private KmsService callers;
|
||||
private KmsKey key;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
AccountAwareStorageBackend<KmsKey> keys = new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, OWNER);
|
||||
AccountAwareStorageBackend<KmsAlias> aliases = new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null,
|
||||
OWNER);
|
||||
owners = new KmsService(keys, aliases, new InMemoryStorage<>(), new RegionResolver(REGION, OWNER));
|
||||
callers = new KmsService(keys, aliases, new InMemoryStorage<>(), new RegionResolver(REGION, CALLER));
|
||||
key = owners.createKey("snapshot key", REGION);
|
||||
owners.createAlias("alias/snapshots", key.getKeyId(), REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyIsFoundByItsIdAliasOrArnInTheAccountItIsIn() {
|
||||
String arn = key.getArn();
|
||||
assertEquals(Optional.of(arn), callers.findKeyArnOfAccount(key.getKeyId(), OWNER, REGION));
|
||||
assertEquals(Optional.of(arn), callers.findKeyArnOfAccount("alias/snapshots", OWNER, REGION));
|
||||
assertEquals(Optional.of(arn), callers.findKeyArnOfAccount(arn, CALLER, REGION));
|
||||
assertEquals(Optional.of(arn), callers.findKeyArnOfAccount(
|
||||
"arn:aws:kms:" + REGION + ":" + OWNER + ":alias/snapshots", CALLER, REGION));
|
||||
// Not the caller's key, nor one in another Region, nor AWS's own key, which no account holds.
|
||||
assertEquals(Optional.empty(), callers.findKeyArnOfAccount(key.getKeyId(), CALLER, REGION));
|
||||
assertEquals(Optional.empty(), callers.findKeyArnOfAccount(key.getKeyId(), OWNER, "eu-west-1"));
|
||||
assertEquals(Optional.empty(), callers.findKeyArnOfAccount("AWS_OWNED_KMS_KEY", OWNER, REGION));
|
||||
assertEquals(Optional.empty(), callers.findKeyArnOfAccount("alias/none", OWNER, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeysPolicyIsReadInTheAccountOfItsArn() {
|
||||
assertThat(callers.findKeyPolicy(key.getArn()).orElseThrow(), containsString(OWNER));
|
||||
assertEquals(Optional.empty(), callers.findKeyPolicy(key.getArn().replace(OWNER, CALLER)));
|
||||
assertEquals(Optional.empty(), callers.findKeyPolicy("arn:aws:kms:" + REGION + ":" + OWNER + ":alias/snapshots"));
|
||||
assertEquals(Optional.empty(), callers.findKeyPolicy("arn:aws:sqs:" + REGION + ":" + OWNER + ":queue"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A key's policy is its resource policy, owned by the account in its ARN even when that account holds no such key,
|
||||
* so another account's key is judged as cross-account; an alias or a key left open has none.
|
||||
*/
|
||||
@Test
|
||||
void theProviderGivesAKeysPolicyAndOwnerAndNothingForAnAliasOrAnOpenKey() {
|
||||
KmsResourcePolicyProvider provider = new KmsResourcePolicyProvider(callers);
|
||||
List<ResourcePolicy> policies = provider.getResourcePolicies("redshift-serverless", key.getArn());
|
||||
assertEquals(1, policies.size());
|
||||
assertEquals(OWNER, policies.getFirst().ownerAccountId());
|
||||
assertThat(policies.getFirst().policyDocument(), containsString("kms:*"));
|
||||
String missing = "arn:aws:kms:" + REGION + ":777788889999:key/" + key.getKeyId();
|
||||
assertEquals(List.of(new ResourcePolicy(null, "777788889999")), provider.getResourcePolicies("kms", missing));
|
||||
assertTrue(provider.getResourcePolicies("kms", "arn:aws:kms:" + REGION + ":" + OWNER + ":alias/snapshots")
|
||||
.isEmpty());
|
||||
assertTrue(provider.getResourcePolicies("kms", "arn:aws:kms:" + REGION + ":" + OWNER + ":key/*").isEmpty());
|
||||
assertTrue(provider.getResourcePolicies("kms", "*").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theStoredResourceArnsFindAKeyInTheCallersAccountOrAnother() {
|
||||
KmsStoredResourceArns stored = new KmsStoredResourceArns(owners, new RegionResolver(REGION, OWNER));
|
||||
assertEquals("kms", stored.namespace());
|
||||
assertEquals(Optional.of(key.getArn()), stored.find("key", List.of(key.getKeyId()), REGION));
|
||||
assertEquals(Optional.of(key.getArn()), stored.findInAccount("key", List.of("alias/snapshots"), OWNER, REGION));
|
||||
assertEquals(Optional.empty(), stored.findInAccount("key", List.of(key.getKeyId()), CALLER, REGION));
|
||||
assertEquals(Optional.empty(), stored.find("alias", List.of("alias/snapshots"), REGION));
|
||||
assertFalse(stored.grantsItsAccountThroughServices(key.getArn()));
|
||||
}
|
||||
|
||||
/** A key KMS would refuse a decrypt with, disabled or pending deletion, is none a forwarded request finds. */
|
||||
@Test
|
||||
void theStoredResourceArnsFindNoKeyKmsWouldNotUse() {
|
||||
KmsStoredResourceArns stored = new KmsStoredResourceArns(owners, new RegionResolver(REGION, OWNER));
|
||||
owners.disableKey(key.getKeyId(), REGION);
|
||||
assertEquals(Optional.empty(), stored.find("key", List.of(key.getKeyId()), REGION));
|
||||
owners.enableKey(key.getKeyId(), REGION);
|
||||
assertEquals(Optional.of(key.getArn()), stored.find("key", List.of(key.getKeyId()), REGION));
|
||||
owners.scheduleKeyDeletion(key.getKeyId(), 7, REGION);
|
||||
assertEquals(Optional.empty(), stored.find("key", List.of(key.getKeyId()), REGION));
|
||||
// Its lookup still finds it: only a request KMS would serve with it is refused.
|
||||
assertEquals(Optional.of(key.getArn()), owners.findKeyArnOfAccount(key.getKeyId(), OWNER, REGION));
|
||||
}
|
||||
|
||||
/**
|
||||
* The reserved {@code alias/aws/redshift}, as a default copy grant records it, names AWS's managed key of the
|
||||
* account, which is there before anything read KMS, and whose policy lets the account use it through Redshift.
|
||||
*/
|
||||
@Test
|
||||
void aReservedAliasNamesTheAccountsAwsManagedKeyWhichGrantsItsAccountThroughServices() {
|
||||
AccountAwareStorageBackend<KmsKey> keys = new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, OWNER);
|
||||
AccountAwareStorageBackend<KmsAlias> aliases = new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null,
|
||||
OWNER);
|
||||
KmsService fresh = new KmsService(keys, aliases, new InMemoryStorage<>(), new RegionResolver(REGION, OWNER));
|
||||
KmsStoredResourceArns stored = new KmsStoredResourceArns(fresh, new RegionResolver(REGION, OWNER));
|
||||
String managed = stored.find("key", List.of("arn:aws:kms:" + REGION + ":" + OWNER + ":alias/aws/redshift"),
|
||||
REGION).orElseThrow();
|
||||
assertTrue(fresh.isAwsManagedKey(managed));
|
||||
assertTrue(stored.grantsItsAccountThroughServices(managed));
|
||||
// Another account's reserved alias is not seeded for it, so it names no key here.
|
||||
assertEquals(Optional.empty(), fresh.findKeyArnOfAccount("alias/aws/redshift", CALLER, REGION));
|
||||
}
|
||||
}
|
||||
@@ -4022,6 +4022,52 @@ class RedshiftServiceTest {
|
||||
assertThrows(AwsException.class, () -> service.deleteClusterSubnetGroup("missing"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A snapshot ARN of the caller's names the copy kept in its Region before the snapshot itself, a cluster left open
|
||||
* matching any, and what it records as its {@code KmsKeyId} is the key a restore decrypts with. One of another
|
||||
* account names that account's snapshot itself alone, taken in the ARN's Region, as a shared restore reads it.
|
||||
*/
|
||||
@Test
|
||||
void aSnapshotArnNamesTheCopyInItsRegionFirstAndItsKeyIsWhatItRecords() {
|
||||
Snapshot copy = snapshot("c1", "snap", "arn:aws:redshift:eu-west-1:111111111111:snapshot:c1/snap");
|
||||
copy.setKmsKeyId("key-copy");
|
||||
Snapshot original = snapshot("c1", "snap", "arn:aws:redshift:us-east-1:111111111111:snapshot:c1/snap");
|
||||
when(snapshotCopyBackend.getForAccount("111111111111", "eu-west-1::snap")).thenReturn(Optional.of(copy));
|
||||
when(snapshotBackend.getForAccount("111111111111", "snap")).thenReturn(Optional.of(original));
|
||||
String prefix = "arn:aws:redshift:eu-west-1:111111111111:snapshot:";
|
||||
|
||||
assertEquals(Optional.of(copy), service.findSnapshotAt(prefix + "c1/snap"));
|
||||
assertEquals(Optional.of(copy), service.findSnapshotAt(prefix + "*/snap"));
|
||||
assertEquals(Optional.of(original), service.findSnapshotAt("arn:aws:redshift:us-east-1:111111111111:snapshot:c1/snap"));
|
||||
assertEquals(Optional.empty(), service.findSnapshotAt(prefix + "c2/snap"));
|
||||
assertEquals(Optional.empty(), service.findSnapshotAt("arn:aws:redshift:eu-west-1:111111111111:cluster:c1"));
|
||||
assertEquals(Optional.empty(), service.findSnapshotAt("arn:aws:redshift-serverless:eu-west-1:111111111111:snapshot/x"));
|
||||
|
||||
RedshiftStoredResourceArns stored = new RedshiftStoredResourceArns(service);
|
||||
assertEquals("redshift", stored.namespace());
|
||||
assertEquals(Optional.of("key-copy"), stored.recorded(prefix + "*/snap", "KmsKeyId"));
|
||||
assertEquals(Optional.empty(), stored.recorded("arn:aws:redshift:us-east-1:111111111111:snapshot:c1/snap", "KmsKeyId"));
|
||||
assertEquals(Optional.empty(), stored.recorded(prefix + "c1/snap", "kmsKeyId"));
|
||||
|
||||
// Another account's: its snapshot in the ARN's Region, never the copy it keeps there.
|
||||
Snapshot theirs = snapshot("c1", "snap", "arn:aws:redshift:us-east-1:222222222222:snapshot:c1/snap");
|
||||
Snapshot theirCopy = snapshot("c1", "snap", "arn:aws:redshift:eu-west-1:222222222222:snapshot:c1/snap");
|
||||
theirCopy.setKmsKeyId("key-their-copy");
|
||||
when(snapshotCopyBackend.getForAccount("222222222222", "eu-west-1::snap")).thenReturn(Optional.of(theirCopy));
|
||||
when(snapshotBackend.getForAccount("222222222222", "snap")).thenReturn(Optional.of(theirs));
|
||||
assertEquals(Optional.of(theirs), service.findSnapshotAt("arn:aws:redshift:us-east-1:222222222222:snapshot:c1/snap"));
|
||||
assertEquals(Optional.empty(), service.findSnapshotAt("arn:aws:redshift:eu-west-1:222222222222:snapshot:c1/snap"));
|
||||
assertEquals(Optional.empty(), stored.recorded("arn:aws:redshift:eu-west-1:222222222222:snapshot:*/snap", "KmsKeyId"));
|
||||
}
|
||||
|
||||
private static Snapshot snapshot(String cluster, String identifier, String arn) {
|
||||
Snapshot snapshot = new Snapshot();
|
||||
snapshot.setClusterIdentifier(cluster);
|
||||
snapshot.setSnapshotIdentifier(identifier);
|
||||
snapshot.setSnapshotArn(arn);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
@Test
|
||||
void createsSnapshotCopyGrant() {
|
||||
when(snapshotCopyGrantBackend.get("my-grant")).thenReturn(Optional.empty());
|
||||
|
||||
+147
-7
@@ -18,6 +18,7 @@ import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
@@ -35,7 +36,8 @@ import static org.mockito.Mockito.when;
|
||||
/**
|
||||
* Under IAM enforcement, a snapshot another account owns is restored only when the snapshot's resource policy
|
||||
* names the caller, and the caller's own identity policy allows it as well: the request is checked on the
|
||||
* owner's snapshot ARN, which the policy is attached to.
|
||||
* owner's snapshot ARN, which the policy is attached to. A snapshot encrypted with a customer managed key also needs
|
||||
* {@code kms:Decrypt} on that key, from the key policy and the caller's own policy.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
@@ -48,6 +50,8 @@ class RedshiftServerlessSnapshotSharingIamEnforcementIntegrationTest {
|
||||
private static final String TARGET_PREFIX = "RedshiftServerless.";
|
||||
private static final String ALLOW_RESTORE = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Action\":\"redshift-serverless:RestoreFromSnapshot\",\"Resource\":\"*\"}]}";
|
||||
private static final String ALLOW_RESTORE_AND_DECRYPT = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":"
|
||||
+ "\"Allow\",\"Action\":[\"redshift-serverless:RestoreFromSnapshot\",\"kms:Decrypt\"],\"Resource\":\"*\"}]}";
|
||||
|
||||
@TestHTTPResource
|
||||
URI endpoint;
|
||||
@@ -166,10 +170,7 @@ class RedshiftServerlessSnapshotSharingIamEnforcementIntegrationTest {
|
||||
denied(call(callerKey, "RestoreFromSnapshot", byName));
|
||||
|
||||
// AWS's own PutResourcePolicy example leaves Resource out: the policy is still on this snapshot.
|
||||
String sharedWithCaller = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Principal\":{\"AWS\":\"arn:aws:iam::" + CALLER + ":root\"},"
|
||||
+ "\"Action\":\"redshift-serverless:RestoreFromSnapshot\"}]}";
|
||||
call(OWNER, "PutResourcePolicy", Map.of("resourceArn", snapshotArn, "policy", sharedWithCaller))
|
||||
call(OWNER, "PutResourcePolicy", Map.of("resourceArn", snapshotArn, "policy", sharedWith(CALLER)))
|
||||
.statusCode(200);
|
||||
call(callerKey, "RestoreFromSnapshot", byName).statusCode(200)
|
||||
.body("ownerAccount", equalTo(OWNER))
|
||||
@@ -188,6 +189,136 @@ class RedshiftServerlessSnapshotSharingIamEnforcementIntegrationTest {
|
||||
denied(call(callerKey, "RestoreFromSnapshot", byName));
|
||||
}
|
||||
|
||||
/**
|
||||
* A snapshot encrypted with a customer managed key restores in another account only when the key's policy lets
|
||||
* that account decrypt with it and the caller's own policy allows {@code kms:Decrypt} on it, as AWS requires the
|
||||
* key to be shared with the account performing the restore. Redshift Serverless reaches KMS as the caller, from
|
||||
* its endpoint in the request's Region, which a key policy's {@code kms:ViaService} condition names.
|
||||
*/
|
||||
@Test
|
||||
void anEncryptedSnapshotRestoresInAnotherAccountOnlyWhenItsKeyIsSharedWithIt() {
|
||||
EncryptedSnapshot encrypted = encryptedSnapshot("KeyMetadata.KeyId", CALLER);
|
||||
call(OWNER, "PutResourcePolicy", Map.of("resourceArn", encrypted.snapshotArn(), "policy", sharedWith(CALLER)))
|
||||
.statusCode(200);
|
||||
String decrypting = user(CALLER, ALLOW_RESTORE_AND_DECRYPT);
|
||||
String restoringOnly = user(CALLER, ALLOW_RESTORE);
|
||||
Map<String, String> byName = encrypted.restore(Map.of("snapshotName", encrypted.snapshot(),
|
||||
"ownerAccount", OWNER));
|
||||
|
||||
// Shared, but the key is still the owner's alone.
|
||||
keyDenied(call(decrypting, "RestoreFromSnapshot", byName));
|
||||
|
||||
putKeyPolicy(encrypted.key(), keySharedWith(CALLER, null));
|
||||
call(decrypting, "RestoreFromSnapshot", byName).statusCode(200)
|
||||
.body("snapshotName", equalTo(encrypted.snapshot()));
|
||||
call(decrypting, "RestoreFromSnapshot", encrypted.restore(Map.of("snapshotArn", encrypted.snapshotArn(),
|
||||
"ownerAccount", OWNER))).statusCode(200);
|
||||
// The key policy is the resource side only: the caller's own policy must allow decrypting with the key too.
|
||||
keyDenied(call(restoringOnly, "RestoreFromSnapshot", byName));
|
||||
|
||||
putKeyPolicy(encrypted.key(), keySharedWith(CALLER, "redshift-serverless.us-east-1.amazonaws.com"));
|
||||
call(decrypting, "RestoreFromSnapshot", byName).statusCode(200);
|
||||
putKeyPolicy(encrypted.key(), keySharedWith(CALLER, "ec2.us-east-1.amazonaws.com"));
|
||||
keyDenied(call(decrypting, "RestoreFromSnapshot", byName));
|
||||
}
|
||||
|
||||
/**
|
||||
* The owner restoring its own encrypted snapshot needs {@code kms:Decrypt} on the key in its own policy, which the
|
||||
* default key policy delegates to; a snapshot under AWS's own key needs none (the test above restores one).
|
||||
*/
|
||||
@Test
|
||||
void theOwnerRestoresItsEncryptedSnapshotOnlyWhenItsPolicyAllowsDecryptingWithTheKey() {
|
||||
EncryptedSnapshot encrypted = encryptedSnapshot("KeyMetadata.Arn", OWNER);
|
||||
Map<String, String> restore = encrypted.restore(Map.of("snapshotName", encrypted.snapshot()));
|
||||
|
||||
keyDenied(call(user(OWNER, ALLOW_RESTORE), "RestoreFromSnapshot", restore));
|
||||
call(user(OWNER, ALLOW_RESTORE_AND_DECRYPT), "RestoreFromSnapshot", restore).statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* A snapshot whose key KMS would refuse to decrypt with, disabled or pending deletion, is not restored whatever
|
||||
* the policies allow, as KMS refuses the request Redshift Serverless makes with it.
|
||||
*/
|
||||
@Test
|
||||
void aSnapshotWhoseKeyKmsWouldNotUseIsNotRestored() {
|
||||
EncryptedSnapshot encrypted = encryptedSnapshot("KeyMetadata.KeyId", OWNER);
|
||||
Map<String, String> restore = encrypted.restore(Map.of("snapshotName", encrypted.snapshot()));
|
||||
String decrypting = user(OWNER, ALLOW_RESTORE_AND_DECRYPT);
|
||||
|
||||
kms(OWNER, "DisableKey", Map.of("KeyId", encrypted.key())).statusCode(200);
|
||||
keyDenied(call(decrypting, "RestoreFromSnapshot", restore));
|
||||
kms(OWNER, "EnableKey", Map.of("KeyId", encrypted.key())).statusCode(200);
|
||||
call(decrypting, "RestoreFromSnapshot", restore).statusCode(200);
|
||||
kms(OWNER, "ScheduleKeyDeletion", Map.of("KeyId", encrypted.key(), "PendingWindowInDays", "7"))
|
||||
.statusCode(200);
|
||||
keyDenied(call(decrypting, "RestoreFromSnapshot", restore));
|
||||
}
|
||||
|
||||
/**
|
||||
* An owner's snapshot of a namespace encrypted with a new customer managed key, given to the namespace as the
|
||||
* {@code KeyMetadata} field {@code keyField} names (its id or its ARN), and a namespace and workgroup of
|
||||
* {@code restoringAccount} to restore it into.
|
||||
*/
|
||||
private EncryptedSnapshot encryptedSnapshot(String keyField, String restoringAccount) {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String sourceNamespace = "kms-src-" + suffix;
|
||||
String snapshot = "kms-snap-" + suffix;
|
||||
String namespace = "kms-dst-" + suffix;
|
||||
String workgroup = "kms-wg-" + suffix;
|
||||
String key = kms(OWNER, "CreateKey", Map.of("Description", "snapshot key")).statusCode(200)
|
||||
.extract().path(keyField);
|
||||
call(OWNER, "CreateNamespace", Map.of("namespaceName", sourceNamespace, "adminUsername", "admin",
|
||||
"kmsKeyId", key)).statusCode(200);
|
||||
String snapshotArn = call(OWNER, "CreateSnapshot",
|
||||
Map.of("snapshotName", snapshot, "namespaceName", sourceNamespace))
|
||||
.statusCode(200).extract().path("snapshot.snapshotArn");
|
||||
call(restoringAccount, "CreateNamespace", Map.of("namespaceName", namespace, "adminUsername", "admin"))
|
||||
.statusCode(200);
|
||||
call(restoringAccount, "CreateWorkgroup", Map.of("workgroupName", workgroup, "namespaceName", namespace))
|
||||
.statusCode(200);
|
||||
return new EncryptedSnapshot(key, snapshot, snapshotArn, namespace, workgroup);
|
||||
}
|
||||
|
||||
/** An encrypted snapshot, its key as the namespace was given it, and where it is restored. */
|
||||
private record EncryptedSnapshot(String key, String snapshot, String snapshotArn, String namespace,
|
||||
String workgroup) {
|
||||
|
||||
/** A restore into the namespace and workgroup of the snapshot {@code naming} names. */
|
||||
Map<String, String> restore(Map<String, String> naming) {
|
||||
Map<String, String> request = new HashMap<>(naming);
|
||||
request.put("namespaceName", namespace);
|
||||
request.put("workgroupName", workgroup);
|
||||
return request;
|
||||
}
|
||||
}
|
||||
|
||||
private static String sharedWith(String account) {
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Principal\":{\"AWS\":\"arn:aws:iam::" + account + ":root\"},"
|
||||
+ "\"Action\":\"redshift-serverless:RestoreFromSnapshot\"}]}";
|
||||
}
|
||||
|
||||
/** The default key policy, and {@code kms:Decrypt} for {@code account}, through {@code viaService} if given. */
|
||||
private static String keySharedWith(String account, String viaService) {
|
||||
String condition = viaService == null ? ""
|
||||
: ",\"Condition\":{\"StringEquals\":{\"kms:ViaService\":\"" + viaService + "\"}}";
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::" + OWNER + ":root\"},"
|
||||
+ "\"Action\":\"kms:*\",\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::" + account + ":root\"},"
|
||||
+ "\"Action\":\"kms:Decrypt\",\"Resource\":\"*\"" + condition + "}]}";
|
||||
}
|
||||
|
||||
private void putKeyPolicy(String keyId, String policy) {
|
||||
kms(OWNER, "PutKeyPolicy", Map.of("KeyId", keyId, "PolicyName", "default", "Policy", policy))
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private static void keyDenied(ValidatableResponse response) {
|
||||
response.statusCode(400).body("__type", equalTo("AccessDeniedException"))
|
||||
.body("message", containsString("kms:Decrypt"));
|
||||
}
|
||||
|
||||
private static void denied(ValidatableResponse response) {
|
||||
response.statusCode(400).body("__type", equalTo("AccessDeniedException"))
|
||||
.body("message", containsString("redshift-serverless:RestoreFromSnapshot"));
|
||||
@@ -202,10 +333,19 @@ class RedshiftServerlessSnapshotSharingIamEnforcementIntegrationTest {
|
||||
return accessKeyId;
|
||||
}
|
||||
|
||||
private ValidatableResponse kms(String accessKeyId, String action, Map<String, String> body) {
|
||||
return send("TrentService." + action, "kms", accessKeyId, body);
|
||||
}
|
||||
|
||||
private ValidatableResponse call(String accessKeyId, String action, Map<String, String> body) {
|
||||
return send(TARGET_PREFIX + action, "redshift-serverless", accessKeyId, body);
|
||||
}
|
||||
|
||||
/** A JSON request to {@code target}, signed for {@code service} by {@code accessKeyId}. */
|
||||
private ValidatableResponse send(String target, String service, String accessKeyId, Map<String, String> body) {
|
||||
return given().port(endpoint.getPort())
|
||||
.header("X-Amz-Target", TARGET_PREFIX + action)
|
||||
.header("Authorization", auth(accessKeyId, "redshift-serverless"))
|
||||
.header("X-Amz-Target", target)
|
||||
.header("Authorization", auth(accessKeyId, service))
|
||||
.contentType(CONTENT_TYPE)
|
||||
.body(body)
|
||||
.when().post("/")
|
||||
|
||||
@@ -140,14 +140,25 @@ What a request names, this file alone says. A service only looks up what it hold
|
||||
resource its handler uses for a member left out (Athena's `primary` workgroup, EventBridge's `default` bus). No
|
||||
service says what an operation acts on.
|
||||
|
||||
`MEASURED` holds what AWS was measured to check where neither botocore nor the Service Reference says it, and
|
||||
nothing else. It is the only part of the file stated by hand, and an entry is admitted only with evidence that AWS
|
||||
itself answered (a policy probe against real AWS published in a Floci pull request, or AWS's AccessDenied message
|
||||
recorded verbatim), for resource types the reference does not list for the action, giving what the rules do not
|
||||
already give, and linking to its evidence; the generator refuses an entry that breaks any of the last three, and
|
||||
review the first. Documentation, analogy, the request's shape and what a Floci handler does are not evidence: what
|
||||
they give belongs in a rule. DynamoDB's `ListTables` (`table/*`) and Step Functions' `SendTask*` (the token's
|
||||
activity or state machine) are its entries.
|
||||
`MEASURED` holds what AWS checks where neither botocore nor the Service Reference says it, and nothing else. It
|
||||
and `FORWARDED` are the only parts of the file stated by hand, and an entry is admitted only with evidence from AWS
|
||||
itself (a policy probe against real AWS published in a Floci pull request, AWS's AccessDenied message recorded
|
||||
verbatim, or AWS's documentation saying it in so many words, quoted), for resource types the reference does not
|
||||
list for the action, giving what the rules do not already give, and linking to its evidence; the generator refuses
|
||||
an entry that breaks any of the last three, and review the first. Analogy, the request's shape and what a Floci
|
||||
handler does are not evidence: what they give belongs in a rule. DynamoDB's `ListTables` (`table/*`) and Step
|
||||
Functions' `SendTask*` (the token's activity or state machine) are its entries.
|
||||
An operation whose service asks another service, as the caller, to act on a resource one of the operation's own
|
||||
holds is also checked as that request (`forwarded`): its action, on the resource botocore's record of the
|
||||
operation's type holds in the member named after the action's namespace and the variable of the type the action
|
||||
acts on (a Redshift snapshot's `KmsKeyId`: `kms` and `key/${KeyId}`), which the reader asks the type's service for
|
||||
and then the action's service to find, with `aws:ViaAWSService` and, where the Service Reference lists the
|
||||
namespace's `ViaService` key for the action, that key naming the operation's endpoint. Which operations do this,
|
||||
neither botocore nor the Service Reference says, so `FORWARDED` states it under `MEASURED`'s rules, its evidence
|
||||
cited and the action not one the reference lists for the operation, which a rule would read instead: a Redshift or
|
||||
Redshift Serverless restore asks KMS to decrypt with the snapshot's key. `forwardedActions` records what the
|
||||
reference gives each such action, the type it acts on, that type's ARN format and the `ViaService` key, which
|
||||
`--verify` checks against AWS.
|
||||
A type's ARN given with a qualifier, one more `:<name>` past its format, is checked without one where the
|
||||
metadata says the qualifier names nothing of its own (`unqualified`): the reference gives Step Functions'
|
||||
`statemachinealias` and `statemachineversion` formats as the state machine's and one more `:${...}`, and no action
|
||||
@@ -177,7 +188,9 @@ byte-identical. The two gates split along the sources:
|
||||
operation's resources must be exactly what the rules give from botocore for the resource types and
|
||||
ARN formats the file records, so a hand-edited entry fails.
|
||||
- `--verify` is online and stdlib-only. Every operation must still be checked as the action, on the
|
||||
resource types, the file records, and every type must still have its ARN format. An operation AWS
|
||||
resource types, the file records, and every type must still have its ARN format; every forwarded
|
||||
action must still act on the type, of the format and with the `ViaService` key, the file records,
|
||||
and still be missing from what the reference lists for its operations. An operation AWS
|
||||
has added is reported without failing: until the next sync it is checked on `*`, where it was
|
||||
before this file existed.
|
||||
|
||||
@@ -245,11 +258,12 @@ READ_IN_HAND_BUILT["logs:PutDestination"] = (
|
||||
# This is the only place in the generator that states an operation's resources by hand, and it is closed to
|
||||
# everything but measured AWS behaviour. An entry is admitted only when ALL of these hold:
|
||||
#
|
||||
# 1. Measured. Its evidence is AWS itself answering: a policy probe run against real AWS with real credentials,
|
||||
# published with its cases and results in a Floci pull request, or an AWS response recorded verbatim (an
|
||||
# AccessDenied message naming the resource AWS checked). Documentation prose, an analogy with another
|
||||
# operation, a reading of the request's shape and what a Floci handler does are NOT evidence: a fact one of
|
||||
# those gives belongs in a rule, which reads it from botocore or the Service Reference for every operation.
|
||||
# 1. From AWS. Its evidence is AWS itself: a policy probe run against real AWS with real credentials, published
|
||||
# with its cases and results in a Floci pull request, an AWS response recorded verbatim (an AccessDenied
|
||||
# message naming the resource AWS checked), or AWS's documentation (a user guide, an API reference) saying it
|
||||
# in so many words, the sentence quoted. An analogy with another operation, a reading of the request's shape
|
||||
# and what a Floci handler does are NOT evidence: a fact one of those gives belongs in a rule, which reads it
|
||||
# from botocore or the Service Reference for every operation.
|
||||
# 2. Absent from the metadata. The Service Reference lists none of the entry's resource types for the
|
||||
# operation's action, so no rule can read them; an entry for a type the reference lists is refused.
|
||||
# 3. Needed. The rules do not already give the entry's resources; an entry they give is refused, so one a later
|
||||
@@ -257,9 +271,9 @@ READ_IN_HAND_BUILT["logs:PutDestination"] = (
|
||||
# 4. Cited. Its evidence names where the measurement is, with at least one https:// link to it.
|
||||
#
|
||||
# The generator enforces 2 to 4 (`measured_resources`); review enforces 1. Never add an entry to make a check pass,
|
||||
# to keep Floci's existing behaviour, or because a handler acts on a resource: measure AWS first, or leave the
|
||||
# to keep Floci's existing behaviour, or because a handler acts on a resource: find what AWS does first, or leave the
|
||||
# operation to the rules. Floci services never state what an operation acts on either (`StoredResourceArns` only
|
||||
# looks up what a service holds), so this table is the whole of the hand-stated part of the file.
|
||||
# looks up what a service holds), so this table and `FORWARDED` are the whole of the hand-stated part of the file.
|
||||
# ---------------------------------------------------------------------------------------------------------------------
|
||||
_SEND_TASK_EVIDENCE = (
|
||||
"real AWS probes in https://github.com/floci-io/floci/pull/7277 (boto3 against us-east-1 on 2026-11-02, a fresh "
|
||||
@@ -284,6 +298,40 @@ MEASURED: dict[str, tuple[list[dict], str]] = {
|
||||
for operation in ("SendTaskSuccess", "SendTaskFailure", "SendTaskHeartbeat")},
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------
|
||||
# FORWARDED: what an operation's service asks another service to do as the caller, where neither botocore nor the
|
||||
# Service Reference says it.
|
||||
#
|
||||
# Each entry names the action the service sends and `of`, the operation's resource type whose record holds the
|
||||
# resource that action acts on; everything else is read: the type and ARN format the reference gives the action, the
|
||||
# member of botocore's record of `of` named after the action's namespace and that format's variable, the operation's
|
||||
# endpoint prefix, and the namespace's `ViaService` key where the reference lists it for the action. An entry is
|
||||
# admitted only under `MEASURED`'s rule 1 (evidence from AWS) and when ALL of these hold, which the generator
|
||||
# enforces (`check_forwarded`, `forwarded_actions`, `forwarded_for`):
|
||||
#
|
||||
# - Absent from the metadata. The reference does not list the action among the operation's authorized actions,
|
||||
# which a rule would read instead.
|
||||
# - Read. The action acts on one resource type with an ARN format, `of` is a type the operation's action acts on,
|
||||
# and botocore's record of it has the member.
|
||||
# - Cited. Its evidence names where AWS says it, with at least one https:// link to it.
|
||||
# ---------------------------------------------------------------------------------------------------------------------
|
||||
_SNAPSHOT_KEY_EVIDENCE = (
|
||||
"the Redshift Management Guide, 'Sharing a snapshot' "
|
||||
"(https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-snapshot-share-snapshot.html): 'When you provide "
|
||||
"access to an encrypted snapshot, Redshift requires that the AWS KMS customer managed key used to create the "
|
||||
"snapshot is shared with the account or accounts performing the restore. If the key isn't shared, attempting to "
|
||||
"restore the snapshot results in an access-denied error', the key policy naming the restoring account and "
|
||||
"allowing 'the kms:Decrypt action'; and 'Authorizing use of an AWS KMS customer managed key with Amazon Redshift "
|
||||
"(Provisioned) and Amazon Redshift Serverless' "
|
||||
"(https://docs.aws.amazon.com/redshift/latest/mgmt/authorizing-kms-customer-managed-key.html): 'To create and use "
|
||||
"an Amazon Redshift provisioned cluster or an Amazon Redshift Serverless resource that is encrypted with a "
|
||||
"customer managed key, a user must have permission to call the following operations on the customer managed key', "
|
||||
"kms:Decrypt among them; the Service Reference lists no KMS action for either restore")
|
||||
FORWARDED: dict[str, tuple[list[dict], str]] = {
|
||||
operation: ([{"action": "kms:Decrypt", "of": "snapshot"}], _SNAPSHOT_KEY_EVIDENCE)
|
||||
for operation in ("redshift:RestoreFromClusterSnapshot", "redshift-serverless:RestoreFromSnapshot")
|
||||
}
|
||||
|
||||
_LATER ="not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint"
|
||||
_REST = ("REST: its requests name their resources in the path, which RequestResources reads from the route a request "
|
||||
"matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet")
|
||||
@@ -1654,8 +1702,9 @@ def id_targets(operation: str, types: list[str], formats: dict[str, str], models
|
||||
|
||||
|
||||
def entry_for(operation: str, upstream: dict, formats: dict[str, str], models: dict[str, dict],
|
||||
known: dict[str, str] | None = None) -> dict:
|
||||
"""What the file says for one operation."""
|
||||
known: dict[str, str] | None = None, forwarded: dict[str, dict] | None = None) -> dict:
|
||||
"""What the file says for one operation, `forwarded` being what the file records of each action `FORWARDED`
|
||||
names."""
|
||||
types = upstream["types"] or []
|
||||
members = request_members(models, operation.split(":", 1)[1])
|
||||
patterns = string_patterns(models, operation.split(":", 1)[1])
|
||||
@@ -1687,6 +1736,8 @@ def entry_for(operation: str, upstream: dict, formats: dict[str, str], models: d
|
||||
if member in named}
|
||||
if located:
|
||||
entry["located"] = located
|
||||
if operation in FORWARDED:
|
||||
entry["forwarded"] = forwarded_for(operation, types, models, forwarded or {})
|
||||
return entry
|
||||
|
||||
|
||||
@@ -1710,6 +1761,88 @@ def measured_resources(operation: str, types: list[str], formats: dict[str, str]
|
||||
return resources
|
||||
|
||||
|
||||
def forwarded_actions(documents: list[dict]) -> dict[str, dict]:
|
||||
"""For each action `FORWARDED` names, what the Service Reference gives it: the one resource type it acts on, that
|
||||
type's ARN format, and its namespace's `ViaService` condition key where the reference lists that for the action."""
|
||||
by_name = {document["Name"]: document for document in documents}
|
||||
found: dict[str, dict] = {}
|
||||
for action in sorted({use["action"] for uses, _ in FORWARDED.values() for use in uses}):
|
||||
namespace, name = action.split(":", 1)
|
||||
document = by_name.get(namespace, {})
|
||||
listed = next((entry for entry in document.get("Actions", []) if entry["Name"] == name), None)
|
||||
if listed is None:
|
||||
raise ValueError(f"FORWARDED names {action}, which the Service Reference does not list")
|
||||
kinds = [resource["Name"] for resource in listed.get("Resources") or []]
|
||||
formats = arn_formats([document], {namespace}).get(namespace, {})
|
||||
if len(kinds) != 1 or kinds[0] not in formats \
|
||||
or len(set(VARIABLE_RE.findall(formats[kinds[0]])) - KNOWN_VARIABLES) != 1:
|
||||
raise ValueError(f"FORWARDED names {action}, which acts on {kinds}, not one resource type whose ARN format "
|
||||
f"has one variable of its own")
|
||||
entry = {"type": kinds[0], "format": formats[kinds[0]]}
|
||||
if f"{namespace}:ViaService" in (listed.get("ActionConditionKeys") or []):
|
||||
entry["viaService"] = f"{namespace}:ViaService"
|
||||
found[action] = entry
|
||||
return found
|
||||
|
||||
|
||||
def authorized_by(documents: list[dict]) -> dict[str, set[str]]:
|
||||
"""The actions the Service Reference lists each operation as authorized by, as `<namespace>:<Operation>`."""
|
||||
return {f"{document['Name']}:{operation['Name']}": {f"{action['Service']}:{action['Name']}"
|
||||
for action in operation.get("AuthorizedActions") or []}
|
||||
for document in documents for operation in document.get("Operations", [])}
|
||||
|
||||
|
||||
def check_forwarded(authorized: dict[str, set[str]]) -> None:
|
||||
"""`FORWARDED`'s rules that do not need botocore: each entry links to its evidence, and names no action the
|
||||
Service Reference lists for its operation, which a rule would read instead."""
|
||||
for operation, (uses, evidence) in sorted(FORWARDED.items()):
|
||||
if "https://" not in evidence:
|
||||
raise ValueError(f"FORWARDED gives {operation} with no link to the evidence of AWS it rests on")
|
||||
listed = sorted({use["action"] for use in uses} & authorized.get(operation, set()))
|
||||
if listed:
|
||||
raise ValueError(f"FORWARDED gives {operation} {listed}, which the Service Reference lists for it: "
|
||||
f"a rule reads those, so take it out")
|
||||
|
||||
|
||||
def record_member(models: dict[str, dict], kind: str, word: str) -> str | None:
|
||||
"""The member named `word`, whatever its case, of botocore's record of the type: the structure named after it
|
||||
(Redshift's and Redshift Serverless' `Snapshot`, `KmsKeyId` and `kmsKeyId`)."""
|
||||
record = re.sub(r"[^a-z0-9]", "", kind.lower())
|
||||
for model in models.values():
|
||||
for name, shape in model["shapes"].items():
|
||||
if shape.get("type") == "structure" and name.lower() == record:
|
||||
member = next((member for member in shape.get("members", {}) if member.lower() == word.lower()), None)
|
||||
if member is not None:
|
||||
return member
|
||||
return None
|
||||
|
||||
|
||||
def forwarded_for(operation: str, types: list[str], models: dict[str, dict], actions: dict[str, dict]) -> list[dict]:
|
||||
"""What the operation's service asks another to do as the caller (`FORWARDED`): each action, on the resource
|
||||
botocore's record of `of` holds in the member named after the action's namespace and the variable of the format
|
||||
of the type it acts on (`kms` and `${KeyId}`, a snapshot's `KmsKeyId`), sent from the operation's endpoint prefix."""
|
||||
uses, _ = FORWARDED[operation]
|
||||
prefixes = {model.get("metadata", {}).get("endpointPrefix") for model in models.values()}
|
||||
if len(prefixes) != 1 or None in prefixes:
|
||||
raise ValueError(f"FORWARDED gives {operation}, whose clients have no one endpoint prefix")
|
||||
endpoint = next(iter(prefixes))
|
||||
found = []
|
||||
for use in uses:
|
||||
action = actions.get(use["action"])
|
||||
if action is None:
|
||||
raise ValueError(f"FORWARDED gives {operation} {use['action']}, for which the file records no type")
|
||||
if use["of"] not in types:
|
||||
raise ValueError(f"FORWARDED gives {operation} {use['action']} on what a {use['of']} holds, no type its "
|
||||
f"action acts on")
|
||||
variable = next(iter(set(VARIABLE_RE.findall(action["format"])) - KNOWN_VARIABLES))
|
||||
member = record_member(models, use["of"], namespace_of(use["action"]) + variable)
|
||||
if member is None:
|
||||
raise ValueError(f"FORWARDED gives {operation} {use['action']} on what a {use['of']} holds, which "
|
||||
f"botocore's record of it has no {namespace_of(use['action'])}{variable} member for")
|
||||
found.append({"action": use["action"], "of": use["of"], "member": member, "endpoint": endpoint})
|
||||
return found
|
||||
|
||||
|
||||
def read_resources(operation: str, types: list[str], formats: dict[str, str], models: dict[str, dict]) -> list[dict]:
|
||||
"""The resources the rules read from the request of the clients given."""
|
||||
name = operation.split(":", 1)[1]
|
||||
@@ -2119,13 +2252,15 @@ def build(documents: list[dict], provenance: str, data: Path, botocore: str) ->
|
||||
for namespace in sorted(read_namespaces)}
|
||||
formats = arn_formats(documents, read_namespaces)
|
||||
minted = minted_types(formats, namespaces, data)
|
||||
check_forwarded(authorized_by(documents))
|
||||
forwarded = forwarded_actions(documents)
|
||||
operations = {}
|
||||
prefixes = {namespace: namespace_id_prefixes(namespace, load_models(data, set(namespaces[namespace])))
|
||||
for namespace in ID_TARGETS if namespace in namespaces}
|
||||
for operation, value in sorted(covered.items()):
|
||||
models = load_models(data, set(namespaces[namespace_of(operation)]))
|
||||
operations[operation] = entry_for(operation, value, formats.get(namespace_of(operation), {}), models,
|
||||
prefixes.get(namespace_of(operation)))
|
||||
prefixes.get(namespace_of(operation)), forwarded)
|
||||
unqualified = unqualified_types(formats, operations, namespaces, data)
|
||||
return {
|
||||
"_source": {
|
||||
@@ -2146,6 +2281,7 @@ def build(documents: list[dict], provenance: str, data: Path, botocore: str) ->
|
||||
"resourceTagKeys": resource_tag_keys(documents),
|
||||
"unqualified": unqualified,
|
||||
"mintedIds": minted,
|
||||
"forwardedActions": forwarded,
|
||||
"operations": operations,
|
||||
}
|
||||
|
||||
@@ -2234,6 +2370,8 @@ def _check_overrides(covered: dict[str, dict]) -> None:
|
||||
if operation not in covered]
|
||||
stale += [f"MEASURED gives {operation}, which READ_IN_HAND_BUILT reads by the rules" for operation in MEASURED
|
||||
if operation in READ_IN_HAND_BUILT]
|
||||
stale += [f"FORWARDED gives {operation}, which the file does not read" for operation in FORWARDED
|
||||
if operation not in covered]
|
||||
stale += [f"READ_IN_HAND_BUILT names {operation}, outside HAND_BUILT" for operation in READ_IN_HAND_BUILT
|
||||
if namespace_of(operation) not in HAND_BUILT]
|
||||
for left, right in (("NAMESPACES", "HAND_BUILT"), ("NAMESPACES", "NOT_COVERED"), ("HAND_BUILT", "NOT_COVERED")):
|
||||
@@ -2247,7 +2385,7 @@ def render(document: dict) -> str:
|
||||
"""The document with one operation to a line."""
|
||||
lines = ["{"]
|
||||
for key in ("_source", "namespaces", "handBuilt", "notCovered", "otherNamespaces", "arnFormats", "resourceTagKeys",
|
||||
"unqualified", "mintedIds"):
|
||||
"unqualified", "mintedIds", "forwardedActions"):
|
||||
lines.append(f' "{key}": {json.dumps(document[key])},')
|
||||
lines.append(' "operations": {')
|
||||
operations = list(document["operations"].items())
|
||||
@@ -2317,13 +2455,25 @@ def validate(document: dict) -> list[str]:
|
||||
if not isinstance(document.get("notCovered"), dict) or not all(
|
||||
isinstance(reason, str) and reason for reason in document["notCovered"].values()):
|
||||
problems.append("notCovered does not give each a reason")
|
||||
recorded_actions = document.get("forwardedActions")
|
||||
if not isinstance(recorded_actions, dict) or not all(
|
||||
isinstance(action, str) and OPERATION_RE.match(action) and isinstance(facts, dict)
|
||||
and {"type", "format"} <= set(facts) <= {"type", "format", "viaService"}
|
||||
and isinstance(facts["type"], str) and isinstance(facts["format"], str)
|
||||
and facts["format"].startswith(f"arn:${{Partition}}:{namespace_of(action)}:")
|
||||
and len(set(VARIABLE_RE.findall(facts["format"])) - KNOWN_VARIABLES) == 1
|
||||
and facts.get("viaService", f"{namespace_of(action)}:ViaService") == f"{namespace_of(action)}:ViaService"
|
||||
for action, facts in recorded_actions.items()):
|
||||
problems.append("forwardedActions is not each forwarded action's type, its ARN format of one variable and its "
|
||||
"namespace's ViaService key")
|
||||
recorded_actions = {}
|
||||
for operation, entry in operations.items():
|
||||
namespace = namespace_of(operation)
|
||||
if not OPERATION_RE.match(operation) or namespace not in namespaces:
|
||||
problems.append(f"{operation!r} is not an operation of a namespace the file reads")
|
||||
continue
|
||||
if not isinstance(entry, dict) or not {"action", "types", "resources"} <= set(entry) <= {
|
||||
"action", "types", "resources", "creates", "makes", "located", "targets"}:
|
||||
"action", "types", "resources", "creates", "makes", "located", "targets", "forwarded"}:
|
||||
problems.append(f"{operation} is not an action, its types and its resources")
|
||||
continue
|
||||
if not isinstance(entry["action"], str) or not OPERATION_RE.match(entry["action"]) \
|
||||
@@ -2369,6 +2519,15 @@ def validate(document: dict) -> list[str]:
|
||||
for member, where in located.items()):
|
||||
problems.append(f"{operation} does not give each member it locates a label of its path or a parameter of "
|
||||
f"its query")
|
||||
forwarded = entry.get("forwarded", [])
|
||||
if not isinstance(forwarded, list) or not forwarded and "forwarded" in entry or not all(
|
||||
isinstance(use, dict) and set(use) == {"action", "of", "member", "endpoint"}
|
||||
and use["action"] in recorded_actions and use["of"] in types and use["of"] in formats.get(namespace, {})
|
||||
and isinstance(use["member"], str) and PATH_RE.match(use["member"]) and not use["member"].endswith("[]")
|
||||
and isinstance(use["endpoint"], str) and use["endpoint"]
|
||||
for use in forwarded):
|
||||
problems.append(f"{operation} forwards no recorded action on a member of one of its types' records, from an "
|
||||
f"endpoint prefix")
|
||||
return problems
|
||||
|
||||
|
||||
@@ -2481,18 +2640,42 @@ def derive(document: dict, data: Path) -> list[str]:
|
||||
if document["mintedIds"] != minted:
|
||||
problems.append(f"the file gives {json.dumps(document['mintedIds'])} a minted id, botocore's ARN patterns "
|
||||
f"give {json.dumps(minted)}")
|
||||
named = sorted({use["action"] for uses, _ in FORWARDED.values() for use in uses})
|
||||
if sorted(document["forwardedActions"]) != named:
|
||||
problems.append(f"the file records {sorted(document['forwardedActions'])} as forwarded actions, FORWARDED "
|
||||
f"names {named}")
|
||||
prefixes = {namespace: namespace_id_prefixes(namespace, load_models(data, set(document["namespaces"][namespace])))
|
||||
for namespace in ID_TARGETS if namespace in document["namespaces"]}
|
||||
for operation, entry in document["operations"].items():
|
||||
namespace = namespace_of(operation)
|
||||
models = load_models(data, set(document["namespaces"][namespace]))
|
||||
expected = entry_for(operation, {"action": entry["action"], "types": entry["types"]},
|
||||
document["arnFormats"].get(namespace, {}), models, prefixes.get(namespace))
|
||||
document["arnFormats"].get(namespace, {}), models, prefixes.get(namespace),
|
||||
document["forwardedActions"])
|
||||
if expected != entry:
|
||||
problems.append(f"{operation}: the file has {json.dumps(entry)}, botocore gives {json.dumps(expected)}")
|
||||
return problems
|
||||
|
||||
|
||||
def verify_forwarded(vendored: dict, documents: list[dict]) -> list[str]:
|
||||
"""What the file records of forwarded actions and AWS no longer gives: each action's type, format and `ViaService`
|
||||
key, and its absence from what the reference lists for the operations forwarding it."""
|
||||
untrue: list[str] = []
|
||||
try:
|
||||
actual = forwarded_actions(documents)
|
||||
except ValueError as e:
|
||||
return [str(e)]
|
||||
for action, facts in vendored.get("forwardedActions", {}).items():
|
||||
if actual.get(action) != facts:
|
||||
untrue.append(f"AWS gives {action} {json.dumps(actual.get(action))}, not {json.dumps(facts)}")
|
||||
authorized = authorized_by(documents)
|
||||
for operation, entry in vendored["operations"].items():
|
||||
listed = sorted({use["action"] for use in entry.get("forwarded", [])} & authorized.get(operation, set()))
|
||||
if listed:
|
||||
untrue.append(f"AWS now lists {listed} for {operation}: a rule reads those, so FORWARDED should not give them")
|
||||
return untrue
|
||||
|
||||
|
||||
def verify_against(vendored: dict, upstream: dict[str, dict], formats: dict[str, dict[str, str]]) -> tuple[list[str], list[str]]:
|
||||
"""What the file claims and AWS does not, and the operations AWS has added since."""
|
||||
untrue: list[str] = []
|
||||
@@ -2564,6 +2747,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
untrue, added = verify_against(document, upstream, formats)
|
||||
if document.get("resourceTagKeys", {}) != resource_tag_keys(documents):
|
||||
untrue.append("resourceTagKeys differ from AWS Service Reference")
|
||||
untrue += verify_forwarded(document, documents)
|
||||
for claim in untrue:
|
||||
print(f"error: {claim}", file=sys.stderr)
|
||||
if untrue:
|
||||
|
||||
@@ -372,6 +372,7 @@ def isolated(monkeypatch):
|
||||
monkeypatch.setattr(r, "NOT_COVERED", {"later": "a later batch"})
|
||||
monkeypatch.setattr(r, "READ_IN_HAND_BUILT", {})
|
||||
monkeypatch.setattr(r, "MEASURED", {})
|
||||
monkeypatch.setattr(r, "FORWARDED", {})
|
||||
return monkeypatch
|
||||
|
||||
|
||||
@@ -502,7 +503,8 @@ def test_redshift_serverless_account_inference_preserves_the_generated_resources
|
||||
if not operation.startswith("redshift-serverless:"):
|
||||
continue
|
||||
derived = r.entry_for(operation, {"action": entry["action"], "types": entry["types"]},
|
||||
document["arnFormats"]["redshift-serverless"], models)
|
||||
document["arnFormats"]["redshift-serverless"], models, None,
|
||||
document["forwardedActions"])
|
||||
assert derived == entry, operation
|
||||
if r.account_members(models, operation.split(":", 1)[1]) == ["ownerAccount"]:
|
||||
account_operations.add(operation.split(":", 1)[1])
|
||||
@@ -708,7 +710,7 @@ def good_document() -> dict:
|
||||
return {"namespaces": {"svc": ["svc"]}, "handBuilt": ["hand"],
|
||||
"notCovered": {"later": "a later batch"},
|
||||
"otherNamespaces": ["other"], "arnFormats": {"svc": {"thing": FORMATS["thing"], "group": FORMATS["group"]}},
|
||||
"unqualified": {"svc": ["thing"]}, "mintedIds": {"svc": ["thing"]},
|
||||
"unqualified": {"svc": ["thing"]}, "mintedIds": {"svc": ["thing"]}, "forwardedActions": {},
|
||||
"operations": {
|
||||
"svc:A": {"action": "svc:A", "types": ["thing"], "resources": [{"types": ["thing"], "arn": "ThingArn"}]},
|
||||
"svc:B": {"action": "svc:B", "types": ["group"], "resources": [{"type": "group", "fill": {"GroupName": "Names[]"}}]},
|
||||
@@ -1008,6 +1010,125 @@ def test_a_measured_entry_must_name_an_operation_the_file_reads(isolated, tmp_pa
|
||||
r.build(measured_documents(tmp_path, []), "test", tmp_path, "botocore test")
|
||||
|
||||
|
||||
GUIDE_SAYS = "the guide (https://example.com/guide) says 'restoring a thing needs keys:Decrypt on its key'"
|
||||
KEY_FORMAT = "arn:${Partition}:keys:${Region}:${Account}:key/${KeyId}"
|
||||
|
||||
|
||||
def keys_reference(resources: list[str] | None = None, condition_keys: list[str] | None = None) -> dict:
|
||||
"""A Service Reference document of a key service whose `Decrypt` acts on keys and takes its `ViaService` key."""
|
||||
document = reference("keys", {"Decrypt": ["key"] if resources is None else resources}, {"key": KEY_FORMAT})
|
||||
document["Actions"][0]["ActionConditionKeys"] = ["keys:ViaService"] if condition_keys is None else condition_keys
|
||||
return document
|
||||
|
||||
|
||||
def forwarding_documents(tmp_path, record_member: str = "KeysKeyId", listed: bool = False,
|
||||
keys: dict | None = None) -> list[dict]:
|
||||
"""`svc`, whose `GetThing` restores a thing its record says a key of `keys` encrypts, and that key service."""
|
||||
svc = model({"GetThing": {"ThingName": "String"}, "ListThings": {}})
|
||||
svc["metadata"]["endpointPrefix"] = "svc"
|
||||
svc["shapes"]["Thing"] = {"type": "structure", "members": {"ThingName": {"shape": "String"},
|
||||
record_member: {"shape": "String"}}}
|
||||
write_models(tmp_path, {"svc": svc})
|
||||
documents = [dict(DOCUMENTS[0]), *DOCUMENTS[1:], keys or keys_reference()]
|
||||
if listed:
|
||||
documents[0] = json.loads(json.dumps(DOCUMENTS[0]))
|
||||
documents[0]["Operations"][0]["AuthorizedActions"].append({"Service": "keys", "Name": "Decrypt"})
|
||||
return documents
|
||||
|
||||
|
||||
def test_a_forwarded_operation_is_also_checked_as_the_action_on_what_its_record_holds(isolated, tmp_path):
|
||||
isolated.setattr(r, "FORWARDED", {"svc:GetThing": ([{"action": "keys:Decrypt", "of": "thing"}], GUIDE_SAYS)})
|
||||
document = r.build(forwarding_documents(tmp_path), "test", tmp_path, "botocore test")
|
||||
# The member is the record's, named after the action's namespace and its type's variable, whatever its case.
|
||||
assert document["operations"]["svc:GetThing"]["forwarded"] == [
|
||||
{"action": "keys:Decrypt", "of": "thing", "member": "KeysKeyId", "endpoint": "svc"}]
|
||||
assert document["forwardedActions"] == {
|
||||
"keys:Decrypt": {"type": "key", "format": KEY_FORMAT, "viaService": "keys:ViaService"}}
|
||||
assert "forwarded" not in document["operations"]["svc:ListThings"]
|
||||
assert r.validate(document) == []
|
||||
assert r.derive(document, tmp_path) == []
|
||||
assert json.loads(r.render(document)) == document
|
||||
# An action the reference gives no ViaService key carries none.
|
||||
documents = forwarding_documents(tmp_path / "plain", keys=keys_reference(condition_keys=[]))
|
||||
assert r.build(documents, "test", tmp_path / "plain", "botocore test")["forwardedActions"] == {
|
||||
"keys:Decrypt": {"type": "key", "format": KEY_FORMAT}}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("forwarded, change, problem", [
|
||||
# No link to where AWS says it.
|
||||
((["keys:Decrypt", "thing"], "the guide says so"), {}, "no link to the evidence"),
|
||||
# The reference lists the action for the operation: a rule reads it.
|
||||
((["keys:Decrypt", "thing"], GUIDE_SAYS), {"listed": True}, "which the Service Reference lists for it"),
|
||||
# An action the reference does not list, or one acting on no one type.
|
||||
((["keys:Encrypt", "thing"], GUIDE_SAYS), {}, "which the Service Reference does not list"),
|
||||
((["keys:Decrypt", "thing"], GUIDE_SAYS), {"keys": keys_reference(resources=[])}, "not one resource type"),
|
||||
# What a type the operation's action does not act on holds.
|
||||
((["keys:Decrypt", "group"], GUIDE_SAYS), {}, "no type its action acts on"),
|
||||
# A record holding no member named after the action's namespace and its type's variable.
|
||||
((["keys:Decrypt", "thing"], GUIDE_SAYS), {"record_member": "EncryptionKey"}, "has no keysKeyId member"),
|
||||
])
|
||||
def test_a_forwarded_entry_is_refused_unless_it_cites_aws_for_what_the_metadata_does_not_say_and_is_read(
|
||||
isolated, tmp_path, forwarded, change, problem):
|
||||
(action, of), evidence = forwarded
|
||||
isolated.setattr(r, "FORWARDED", {"svc:GetThing": ([{"action": action, "of": of}], evidence)})
|
||||
with pytest.raises(ValueError, match=problem):
|
||||
r.build(forwarding_documents(tmp_path, **change), "test", tmp_path, "botocore test")
|
||||
|
||||
|
||||
def test_a_forwarded_entry_must_name_an_operation_the_file_reads(isolated, tmp_path):
|
||||
isolated.setattr(r, "FORWARDED", {"svc:Gone": ([{"action": "keys:Decrypt", "of": "thing"}], GUIDE_SAYS)})
|
||||
with pytest.raises(ValueError, match="FORWARDED gives svc:Gone, which the file does not read"):
|
||||
r.build(forwarding_documents(tmp_path), "test", tmp_path, "botocore test")
|
||||
|
||||
|
||||
def forwarding_document() -> dict:
|
||||
document = good_document()
|
||||
document["forwardedActions"] = {"keys:Decrypt": {"type": "key", "format": KEY_FORMAT, "viaService": "keys:ViaService"}}
|
||||
document["operations"]["svc:A"]["forwarded"] = [
|
||||
{"action": "keys:Decrypt", "of": "thing", "member": "KeysKeyId", "endpoint": "svc"}]
|
||||
return document
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change, problem", [
|
||||
(lambda d: d["operations"]["svc:A"]["forwarded"][0].update(action="keys:Encrypt"), "forwards no recorded action"),
|
||||
(lambda d: d["operations"]["svc:A"]["forwarded"][0].update(of="group"), "forwards no recorded action"),
|
||||
(lambda d: d["operations"]["svc:A"]["forwarded"][0].update(member="Keys[]"), "forwards no recorded action"),
|
||||
(lambda d: d["operations"]["svc:A"]["forwarded"][0].pop("endpoint"), "forwards no recorded action"),
|
||||
(lambda d: d["operations"]["svc:A"].update(forwarded=[]), "forwards no recorded action"),
|
||||
(lambda d: d["forwardedActions"]["keys:Decrypt"].update(viaService="other:ViaService"), "forwardedActions is not"),
|
||||
(lambda d: d["forwardedActions"]["keys:Decrypt"].update(format="arn:${Partition}:other:::key/${KeyId}"),
|
||||
"forwardedActions is not"),
|
||||
(lambda d: d.pop("forwardedActions"), "forwardedActions is not"),
|
||||
])
|
||||
def test_a_malformed_forwarded_entry_is_rejected(change, problem):
|
||||
assert r.validate(forwarding_document()) == []
|
||||
document = forwarding_document()
|
||||
change(document)
|
||||
assert any(problem in found for found in r.validate(document))
|
||||
|
||||
|
||||
def test_verify_fails_when_aws_changes_what_it_gives_a_forwarded_action_or_lists_it_for_the_operation(isolated):
|
||||
isolated.setattr(r, "FORWARDED", {"svc:A": ([{"action": "keys:Decrypt", "of": "thing"}], GUIDE_SAYS)})
|
||||
document = forwarding_document()
|
||||
documents = [reference("svc", {"A": ["thing"]}, {"thing": FORMATS["thing"]}), keys_reference()]
|
||||
assert r.verify_forwarded(document, documents) == []
|
||||
assert r.verify_forwarded(document, [documents[0], keys_reference(condition_keys=[])]) == [
|
||||
'AWS gives keys:Decrypt {"type": "key", "format": "' + KEY_FORMAT + '"}, not '
|
||||
'{"type": "key", "format": "' + KEY_FORMAT + '", "viaService": "keys:ViaService"}']
|
||||
documents[0]["Operations"][0]["AuthorizedActions"].append({"Service": "keys", "Name": "Decrypt"})
|
||||
assert r.verify_forwarded(document, documents) == [
|
||||
"AWS now lists ['keys:Decrypt'] for svc:A: a rule reads those, so FORWARDED should not give them"]
|
||||
|
||||
|
||||
def test_check_fails_when_the_file_records_other_forwarded_actions_than_forwarded_names(isolated, tmp_path):
|
||||
isolated.setattr(r, "FORWARDED", {"svc:GetThing": ([{"action": "keys:Decrypt", "of": "thing"}], GUIDE_SAYS)})
|
||||
document = r.build(forwarding_documents(tmp_path), "test", tmp_path, "botocore test")
|
||||
isolated.setattr(r, "FORWARDED", {})
|
||||
document["operations"]["svc:GetThing"].pop("forwarded")
|
||||
assert r.derive(document, tmp_path) == [
|
||||
"the file records ['keys:Decrypt'] as forwarded actions, FORWARDED names []"]
|
||||
|
||||
|
||||
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"}})
|
||||
|
||||
Reference in new issue
Block a user