mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(cloudformation): provision Verified Permissions policy stores, templates and policies (#9162)
A template declaring AWS::VerifiedPermissions::PolicyStore, PolicyTemplate or Policy failed its stack as unsupported, although Floci serves the API behind them. VerifiedPermissionsCfnProvisioner now provisions the three over VerifiedPermissionsService. A policy store answers Ref with its id and sets Arn, PolicyStoreId and EncryptionState; its schema is put once the store stands, and deletion protection is turned on only after that, so a store whose schema the Cedar sidecar refuses is still removed. A template answers Ref with PolicyStoreId|PolicyTemplateId and a policy with its id alone, as the Template Reference documents each; a policy's store is found from its id, and Cloud Control names a policy PolicyId|PolicyStoreId. PolicyStoreId is create-only on both, and a template or a policy is replaced in the new store when the engine says the update replaces it. A schema, Description, DeletionProtection or Name the template drops is cleared, what the stack never declared is left as the service has it, and a create leaves out an optional field the template does not give. An update of a stack from before this provisioner, which holds the dispatcher's stub, creates the entity. An in-place change of a store, a template or a static policy is snapshotted first, so a step that fails is undone and a later resource failing the update puts it back. A store's settings are written before its schema, its tags are reconciled only over the keys the stack owns, and a change of its EncryptionSettings is refused, since Verified Permissions sets encryption at create. Cloud Control's model names a store by PolicyStoreId and a template by PolicyTemplateId. Co-authored-by: Chuck Swanberg <cswanberg@mad-swan.com>
This commit is contained in:
1 parent
ce7f1ab185
commit
543a236747
15 files changed
+1591
-25
No files matched your search
@@ -48,7 +48,8 @@ Cloud Control.
|
||||
- **Identifiers**: a resource is identified by its type's primary identifier, which for
|
||||
most types is the physical id CloudFormation's `Ref` returns. A compound one joins its
|
||||
parts with `|`, as Cloud Control does: an `AWS::ApiGatewayV2::ApiMapping` is
|
||||
`<ApiMappingId>|<DomainName>`.
|
||||
`<ApiMappingId>|<DomainName>` and an `AWS::VerifiedPermissions::Policy`
|
||||
`<PolicyId>|<PolicyStoreId>`.
|
||||
- **Delete needs create-time state**: types whose delete depends on attributes
|
||||
captured at create time (currently `AWS::EKS::Nodegroup` and `AWS::IAM::Policy`, plus
|
||||
any `Custom::*` / `AWS::CloudFormation::CustomResource`) fail `DeleteResource` with a
|
||||
|
||||
@@ -244,6 +244,7 @@ cross-resource references.
|
||||
| CodeDeploy | `Application` |
|
||||
| Batch | `ComputeEnvironment`, `JobQueue`, `JobDefinition` |
|
||||
| Cognito | `UserPool` (`ProviderURL` is the local issuer of the tokens Floci mints, `<base-url>/<pool id>`; `EnabledMfas` is applied with `SetUserPoolMfaConfig`, as on AWS, and once `SMS_MFA` is on only `MfaConfiguration: OFF` turns it off), `UserPoolClient`, `UserPoolDomain`, `UserPoolGroup`, `UserPoolIdentityProvider` (Ref returns the ProviderName; changing only `ProviderType` is refused, as on AWS, because the name is always the template's and the replacement would need the same address), `UserPoolResourceServer`, `UserPoolUser`, `UserPoolUserToGroupAttachment` |
|
||||
| Verified Permissions | `PolicyStore`, `PolicyTemplate`, `Policy` |
|
||||
| ACM | `Certificate` |
|
||||
| EventBridge | `Rule`, `EventBus`, `EventBusPolicy`, `ApiDestination`, `Archive` (`KmsKeyIdentifier` is ignored), `Connection` (Ref returns the connection name; an update changes the supplied properties in place and a dropped `KmsKeyIdentifier` or `InvocationConnectivityParameters` is cleared, a dropped `Description` stays as it is and an empty one clears it, while renaming it or dropping `AuthorizationType` or `AuthParameters` is refused; `KmsKeyIdentifier` and `InvocationConnectivityParameters` are stored and not applied) |
|
||||
| EventBridge V2 | `EventBus`, `Subscriber` (delivers only to Amazon SQS queues; `Transformer` RAW or WITH_METADATA; a target parameter takes a literal or a `$events` path) |
|
||||
|
||||
@@ -452,21 +452,30 @@ public class CloudControlService {
|
||||
}
|
||||
ObjectNode model = desiredState != null && desiredState.isObject()
|
||||
? ((ObjectNode) desiredState).deepCopy() : mapper.createObjectNode();
|
||||
model.put(primaryIdentifierField(typeName), physicalId);
|
||||
// A policy template's physical id is <PolicyStoreId>|<PolicyTemplateId>; its model names the template alone.
|
||||
int separator = physicalId.indexOf('|');
|
||||
model.put(primaryIdentifierField(typeName),
|
||||
"AWS::VerifiedPermissions::PolicyTemplate".equals(typeName) && separator >= 0
|
||||
? physicalId.substring(separator + 1) : physicalId);
|
||||
return propertiesString(model);
|
||||
}
|
||||
|
||||
/**
|
||||
* The identifier Cloud Control hands out for a created resource: the type's primary identifier,
|
||||
* which for most types is the physical id. A compound one joins its parts with {@code |}, as
|
||||
* Cloud Control does; an {@code AWS::ApiGatewayV2::ApiMapping} is {@code <ApiMappingId>|<DomainName>},
|
||||
* where CloudFormation's {@code Ref} is the bare id.
|
||||
* Cloud Control does; an {@code AWS::ApiGatewayV2::ApiMapping} is {@code <ApiMappingId>|<DomainName>}
|
||||
* and an {@code AWS::VerifiedPermissions::Policy} {@code <PolicyId>|<PolicyStoreId>}, where
|
||||
* CloudFormation's {@code Ref} is the bare id.
|
||||
*/
|
||||
private static String identifierOf(String typeName, String physicalId, JsonNode desiredState) {
|
||||
if ("AWS::ApiGatewayV2::ApiMapping".equals(typeName) && desiredState != null
|
||||
&& desiredState.path("DomainName").isTextual()) {
|
||||
return physicalId + "|" + desiredState.path("DomainName").asText();
|
||||
}
|
||||
if ("AWS::VerifiedPermissions::Policy".equals(typeName) && desiredState != null
|
||||
&& desiredState.path("PolicyStoreId").isTextual()) {
|
||||
return physicalId + "|" + desiredState.path("PolicyStoreId").asText();
|
||||
}
|
||||
return physicalId;
|
||||
}
|
||||
|
||||
@@ -481,6 +490,9 @@ public class CloudControlService {
|
||||
case "AWS::EC2::RouteTable" -> "RouteTableId";
|
||||
case "AWS::EC2::LaunchTemplate" -> "LaunchTemplateId";
|
||||
case "AWS::ApiGatewayV2::ApiMapping" -> "ApiMappingId";
|
||||
case "AWS::VerifiedPermissions::PolicyStore" -> "PolicyStoreId";
|
||||
case "AWS::VerifiedPermissions::PolicyTemplate" -> "PolicyTemplateId";
|
||||
case "AWS::VerifiedPermissions::Policy" -> "PolicyId";
|
||||
default -> "Id";
|
||||
};
|
||||
}
|
||||
|
||||
@@ -324,6 +324,16 @@ public final class CfnRollback {
|
||||
*/
|
||||
public static final String APPCONFIG_UPDATE_SNAPSHOT_ATTR = "__FlociAppConfigUpdateSnapshot";
|
||||
|
||||
/**
|
||||
* Holds what a Verified Permissions policy store, policy template or static policy was before an
|
||||
* in-place update changed it: the store's validation mode, description, deletion protection,
|
||||
* schema and the tags the stack owns, a template's or policy's statement, description and name. A
|
||||
* later resource failing the update puts it back through {@code rollbackUpdate}, and the
|
||||
* provisioner carries it onto the restored resource through
|
||||
* {@code mergeFailedUpdateResourceTracking}.
|
||||
*/
|
||||
public static final String VERIFIED_PERMISSIONS_UPDATE_SNAPSHOT_ATTR = "__FlociVerifiedPermissionsUpdateSnapshot";
|
||||
|
||||
/**
|
||||
* Holds the members an AppSync GraphQL API, data source, function, resolver or API key carried
|
||||
* before an in-place update changed or cleared them, in the request shape its update call takes,
|
||||
|
||||
+586
@@ -0,0 +1,586 @@
|
||||
package io.floci.aws.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.cloudformation.model.StackResource;
|
||||
import io.floci.aws.services.verifiedpermissions.VerifiedPermissionsService;
|
||||
import io.floci.aws.services.verifiedpermissions.model.EntityIdentifier;
|
||||
import io.floci.aws.services.verifiedpermissions.model.Policy;
|
||||
import io.floci.aws.services.verifiedpermissions.model.PolicyStore;
|
||||
import io.floci.aws.services.verifiedpermissions.model.PolicyTemplate;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Provisions {@code AWS::VerifiedPermissions::PolicyStore}, {@code AWS::VerifiedPermissions::PolicyTemplate}
|
||||
* and {@code AWS::VerifiedPermissions::Policy} over {@link VerifiedPermissionsService}.
|
||||
*
|
||||
* <p>A policy store answers {@code Ref} with its id and sets {@code Arn}, {@code PolicyStoreId} and
|
||||
* {@code EncryptionState}. Its {@code Schema} is put after the store exists, which is how the API
|
||||
* takes it, and a template that drops the schema clears it, since the whole template is the desired
|
||||
* state. Every property of a store updates in place; a template or a policy is replaced when the
|
||||
* engine says the update replaces it.
|
||||
*
|
||||
* <p>A template answers {@code Ref} with {@code PolicyStoreId|PolicyTemplateId} and a policy with its
|
||||
* id alone, as the CloudFormation Template Reference spells each out. A policy's store is found from
|
||||
* the policy id, which Floci generates unique, and the id-only delete also takes Cloud Control's
|
||||
* {@code PolicyId|PolicyStoreId}. {@code PolicyStoreId} is createOnly on both, so a change to it
|
||||
* creates the replacement in the new store and the displaced entity is deleted once the update
|
||||
* commits. Everything else updates in place; the service refuses what Verified Permissions refuses,
|
||||
* a changed effect or scope, a template-linked policy's definition, and the stack reports that as the
|
||||
* resource's failure.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class VerifiedPermissionsCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
private static final String POLICY_STORE = "AWS::VerifiedPermissions::PolicyStore";
|
||||
private static final String POLICY_TEMPLATE = "AWS::VerifiedPermissions::PolicyTemplate";
|
||||
private static final String POLICY = "AWS::VerifiedPermissions::Policy";
|
||||
private static final String NOT_FOUND = "ResourceNotFoundException";
|
||||
private static final String EMPTY_SCHEMA = "{}";
|
||||
private static final String SNAPSHOT_ATTR = CfnRollback.VERIFIED_PERMISSIONS_UPDATE_SNAPSHOT_ATTR;
|
||||
/** The tag keys the last deployment of a store wrote: the keys the stack owns. */
|
||||
static final String TAG_KEYS_ATTR = "__FlociVerifiedPermissionsTagKeys";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private final VerifiedPermissionsService verifiedPermissions;
|
||||
|
||||
public VerifiedPermissionsCfnProvisioner(VerifiedPermissionsService verifiedPermissions) {
|
||||
this.verifiedPermissions = verifiedPermissions;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of(POLICY_STORE, POLICY_TEMPLATE, POLICY);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Set<String>> jsonAttributes() {
|
||||
return Map.of(POLICY_STORE, Set.of("EncryptionState"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
switch (r.getResourceType()) {
|
||||
case POLICY_STORE -> provisionPolicyStore(r, props, ctx);
|
||||
case POLICY_TEMPLATE -> provisionPolicyTemplate(r, props, ctx);
|
||||
case POLICY -> provisionPolicy(r, props, ctx);
|
||||
default -> throw new IllegalStateException(
|
||||
"VerifiedPermissionsCfnProvisioner cannot provision " + r.getResourceType());
|
||||
}
|
||||
}
|
||||
|
||||
private void provisionPolicyStore(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
JsonNode validation = requiredObject(props, "ValidationSettings", r, ctx);
|
||||
String mode = required(ctx.engine().resolve(validation.path("Mode")), "ValidationSettings.Mode", r);
|
||||
String description = ctx.resolveOptional(props, "Description");
|
||||
JsonNode deletionProtection = optionalObject(props, "DeletionProtection", ctx);
|
||||
String deletionMode = deletionProtection == null
|
||||
? null : blankToNull(ctx.engine().resolve(deletionProtection.path("Mode")));
|
||||
Map<String, String> tags = ctx.resolveTags(props, "Tags");
|
||||
String schema = schema(props, ctx);
|
||||
|
||||
ObjectNode request = MAPPER.createObjectNode();
|
||||
request.putObject("validationSettings").put("mode", mode);
|
||||
PropertyChanges changes = ctx.changes(POLICY_STORE, props);
|
||||
PolicyStore store;
|
||||
if (updatesInPlace(ctx, changes, r.getAttributes())) {
|
||||
putOrClear(request, "description", description, changes.kindOf("Description"), "");
|
||||
putOrClear(request, "deletionProtection", deletionMode, changes.kindOf("DeletionProtection"), "DISABLED");
|
||||
store = updatePolicyStore(r, props, ctx, changes, request, schema, tags);
|
||||
} else {
|
||||
if (description != null) {
|
||||
request.put("description", description);
|
||||
}
|
||||
store = createPolicyStore(r, props, ctx, request, schema, deletionMode, tags);
|
||||
}
|
||||
|
||||
r.setPhysicalId(store.policyStoreId());
|
||||
r.getAttributes().put("Arn", store.arn());
|
||||
r.getAttributes().put("PolicyStoreId", store.policyStoreId());
|
||||
r.getAttributes().put("EncryptionState", encryptionState(store).toString());
|
||||
Ec2Tags.recordKeys(r, TAG_KEYS_ATTR, tags);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the store, then puts its schema and only after that turns deletion protection on, so a
|
||||
* schema the Cedar sidecar refuses, or a protection the service refuses, leaves no store behind.
|
||||
*/
|
||||
private PolicyStore createPolicyStore(StackResource r, JsonNode props, ProvisionContext ctx, ObjectNode request,
|
||||
String schema, String deletionMode, Map<String, String> tags) {
|
||||
String region = ctx.region();
|
||||
JsonNode encryption = optionalObject(props, "EncryptionSettings", ctx);
|
||||
if (encryption != null) {
|
||||
request.set("encryptionSettings", encryptionSettings(encryption, ctx));
|
||||
}
|
||||
if (!tags.isEmpty()) {
|
||||
ObjectNode tagNode = request.putObject("tags");
|
||||
tags.forEach(tagNode::put);
|
||||
}
|
||||
boolean protectAfterSchema = schema != null && deletionMode != null && !"DISABLED".equals(deletionMode);
|
||||
if (deletionMode != null && !protectAfterSchema) {
|
||||
request.put("deletionProtection", deletionMode);
|
||||
}
|
||||
r.getAttributes().remove(SNAPSHOT_ATTR);
|
||||
PolicyStore created = verifiedPermissions.createPolicyStore(request, region);
|
||||
String policyStoreId = created.policyStoreId();
|
||||
r.setPhysicalId(policyStoreId);
|
||||
PolicyStore[] finished = {created};
|
||||
CfnRollback.guarded(r, ctx, true, () -> verifiedPermissions.deletePolicyStore(policyStoreId, region), () -> { },
|
||||
() -> {
|
||||
if (schema == null) {
|
||||
return;
|
||||
}
|
||||
finished[0] = verifiedPermissions.putSchema(schemaRequest(policyStoreId, schema), region);
|
||||
if (protectAfterSchema) {
|
||||
ObjectNode protect = request.deepCopy();
|
||||
protect.remove("encryptionSettings");
|
||||
protect.remove("tags");
|
||||
protect.put("policyStoreId", policyStoreId);
|
||||
protect.put("deletionProtection", deletionMode);
|
||||
finished[0] = verifiedPermissions.updatePolicyStore(protect, region);
|
||||
}
|
||||
});
|
||||
return finished[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the store in place: its settings first, which the service validates before it writes,
|
||||
* then its schema, then the tags the stack owns. What it was is snapshotted before, so a step that
|
||||
* fails, or a later resource failing the update, puts it back.
|
||||
*/
|
||||
private PolicyStore updatePolicyStore(StackResource r, JsonNode props, ProvisionContext ctx, PropertyChanges changes,
|
||||
ObjectNode request, String schema, Map<String, String> tags) {
|
||||
String region = ctx.region();
|
||||
String policyStoreId = ctx.priorPhysicalId();
|
||||
PropertyChanges.Kind encryption = changes.kindOf("EncryptionSettings");
|
||||
if (encryption != null && encryption != PropertyChanges.Kind.UNCHANGED) {
|
||||
throw new AwsException("ValidationError", "EncryptionSettings of " + r.getLogicalId()
|
||||
+ " can't change: Verified Permissions sets a policy store's encryption when it creates the store.", 400);
|
||||
}
|
||||
// A template that drops Schema, or declares one without CedarJson, wants no schema; one that never
|
||||
// declared it leaves a schema set outside the stack alone.
|
||||
boolean clearSchema = schema == null
|
||||
&& (changes.kindOf("Schema") == PropertyChanges.Kind.DROPPED || declares(props, "Schema"));
|
||||
PolicyStore current = verifiedPermissions.getPolicyStore(policyStoreId, region);
|
||||
Set<String> owned = Ec2Tags.ownedKeys(r, TAG_KEYS_ATTR, ctx);
|
||||
Set<String> touched = Ec2Tags.touched(owned, tags);
|
||||
ObjectNode snapshot = MAPPER.createObjectNode();
|
||||
snapshot.put("region", region);
|
||||
snapshot.put("policyStoreId", policyStoreId);
|
||||
snapshot.put("mode", current.validationMode());
|
||||
snapshot.put("description", current.description());
|
||||
snapshot.put("deletionProtection", current.deletionProtection());
|
||||
snapshot.put("schema", current.schema());
|
||||
Ec2Tags.snapshotOwned(snapshot, owned, tags, verifiedPermissions.listTags(current.arn(), region),
|
||||
r.getAttributes().get(TAG_KEYS_ATTR));
|
||||
r.getAttributes().put(SNAPSHOT_ATTR, snapshot.toString());
|
||||
|
||||
request.put("policyStoreId", policyStoreId);
|
||||
PolicyStore[] updated = {current};
|
||||
CfnRollback.guarded(r, ctx, false, () -> { }, () -> restoreSnapshot(r), () -> {
|
||||
updated[0] = verifiedPermissions.updatePolicyStore(request, region);
|
||||
if (schema != null) {
|
||||
verifiedPermissions.putSchema(schemaRequest(policyStoreId, schema), region);
|
||||
} else if (clearSchema && current.schema() != null) {
|
||||
verifiedPermissions.putSchema(schemaRequest(policyStoreId, EMPTY_SCHEMA), region);
|
||||
}
|
||||
reconcileTags(current.arn(), touched, tags, region);
|
||||
});
|
||||
return updated[0];
|
||||
}
|
||||
|
||||
private void provisionPolicyTemplate(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());
|
||||
String policyStoreId = required(ctx.resolveOptional(props, "PolicyStoreId"), "PolicyStoreId", r);
|
||||
String statement = required(ctx.resolveOptional(props, "Statement"), "Statement", r);
|
||||
String description = ctx.resolveOptional(props, "Description");
|
||||
String name = ctx.resolveOptional(props, "Name");
|
||||
String region = ctx.region();
|
||||
|
||||
PropertyChanges changes = ctx.changes(POLICY_TEMPLATE, props);
|
||||
ObjectNode request = MAPPER.createObjectNode();
|
||||
request.put("policyStoreId", policyStoreId);
|
||||
request.put("statement", statement);
|
||||
putOrClear(request, "description", description, changes.kindOf("Description"), "");
|
||||
putOrClear(request, "name", name, changes.kindOf("Name"), "");
|
||||
PolicyTemplate template;
|
||||
if (updatesInPlace(ctx, changes, attributesBefore)) {
|
||||
String priorStoreId = storeOf(ctx.priorPhysicalId());
|
||||
String templateId = entityOf(ctx.priorPhysicalId());
|
||||
PolicyTemplate current = verifiedPermissions.getPolicyTemplate(priorStoreId, templateId, region);
|
||||
ObjectNode snapshot = entitySnapshot(region, priorStoreId, current.statement(), current.description(),
|
||||
current.name());
|
||||
snapshot.put("policyTemplateId", templateId);
|
||||
r.getAttributes().put(SNAPSHOT_ATTR, snapshot.toString());
|
||||
request.put("policyTemplateId", templateId);
|
||||
PolicyTemplate[] updated = {current};
|
||||
CfnRollback.guarded(r, ctx, false, () -> { }, () -> restoreSnapshot(r),
|
||||
() -> updated[0] = verifiedPermissions.updatePolicyTemplate(request, region));
|
||||
template = updated[0];
|
||||
} else {
|
||||
r.getAttributes().remove(SNAPSHOT_ATTR);
|
||||
template = verifiedPermissions.createPolicyTemplate(request, region);
|
||||
}
|
||||
|
||||
r.setPhysicalId(template.policyStoreId() + "|" + template.policyTemplateId());
|
||||
r.getAttributes().put("PolicyTemplateId", template.policyTemplateId());
|
||||
ReplacementCleanup.record(r, ctx, attributesBefore);
|
||||
}
|
||||
|
||||
private void provisionPolicy(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());
|
||||
String policyStoreId = required(ctx.resolveOptional(props, "PolicyStoreId"), "PolicyStoreId", r);
|
||||
JsonNode definition = requiredObject(props, "Definition", r, ctx);
|
||||
String name = ctx.resolveOptional(props, "Name");
|
||||
String region = ctx.region();
|
||||
|
||||
PropertyChanges changes = ctx.changes(POLICY, props);
|
||||
ObjectNode request = MAPPER.createObjectNode();
|
||||
request.put("policyStoreId", policyStoreId);
|
||||
request.set("definition", CfnApiShapeConverter.convert(definition, CfnApiShapeConverter.OMIT_NULL_PROPERTIES));
|
||||
putOrClear(request, "name", name, changes.kindOf("Name"), "");
|
||||
Policy policy;
|
||||
if (updatesInPlace(ctx, changes, attributesBefore)) {
|
||||
String policyId = policyIdOf(ctx.priorPhysicalId());
|
||||
Policy current = verifiedPermissions.getPolicy(policyStoreId, policyId, region);
|
||||
if ("TEMPLATE_LINKED".equals(current.policyType())) {
|
||||
// Verified Permissions takes no update of a template-linked policy, and the Template
|
||||
// Reference says the same of its definition: one that stands unchanged is left alone.
|
||||
if (!sameLinkedPolicy(current, request, name)) {
|
||||
throw new AwsException("ValidationError", "Updating template-linked policy " + policyId
|
||||
+ " is not supported.", 400);
|
||||
}
|
||||
r.getAttributes().remove(SNAPSHOT_ATTR);
|
||||
policy = current;
|
||||
} else {
|
||||
request.put("policyId", policyId);
|
||||
JsonNode staticDefinition = request.path("definition").path("static");
|
||||
if (staticDefinition instanceof ObjectNode body && !body.has("description")
|
||||
&& current.description() != null) {
|
||||
// The definition is declared whole, so a description it no longer carries is cleared,
|
||||
// where the API on its own keeps the one the policy has.
|
||||
body.put("description", "");
|
||||
}
|
||||
ObjectNode snapshot = entitySnapshot(region, policyStoreId, current.statement(), current.description(),
|
||||
current.name());
|
||||
snapshot.put("policyId", policyId);
|
||||
r.getAttributes().put(SNAPSHOT_ATTR, snapshot.toString());
|
||||
Policy[] updated = {current};
|
||||
CfnRollback.guarded(r, ctx, false, () -> { }, () -> restoreSnapshot(r),
|
||||
() -> updated[0] = verifiedPermissions.updatePolicy(request, region));
|
||||
policy = updated[0];
|
||||
}
|
||||
} else {
|
||||
r.getAttributes().remove(SNAPSHOT_ATTR);
|
||||
policy = verifiedPermissions.createPolicy(request, region);
|
||||
}
|
||||
|
||||
r.setPhysicalId(policy.policyId());
|
||||
r.getAttributes().put("PolicyId", policy.policyId());
|
||||
r.getAttributes().put("PolicyType", policy.policyType());
|
||||
ReplacementCleanup.record(r, ctx, attributesBefore);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the store, template or policy the physical id names. A store that is already gone
|
||||
* deletes silently in the service; one whose deletion protection is on fails, as on AWS. A
|
||||
* template or policy whose store is gone went with it, and so did a policy no store holds.
|
||||
*/
|
||||
@Override
|
||||
public void delete(String resourceType, String physicalId, String region) {
|
||||
switch (resourceType) {
|
||||
case POLICY_STORE -> verifiedPermissions.deletePolicyStore(physicalId, region);
|
||||
case POLICY_TEMPLATE -> CfnDeletes.safeDelete("Verified Permissions policy template", physicalId,
|
||||
() -> verifiedPermissions.deletePolicyTemplate(storeOf(physicalId), entityOf(physicalId), region),
|
||||
NOT_FOUND);
|
||||
case POLICY -> {
|
||||
String policyStoreId = storeOfPolicy(physicalId, region);
|
||||
if (policyStoreId != null) {
|
||||
CfnDeletes.safeDelete("Verified Permissions policy", physicalId,
|
||||
() -> verifiedPermissions.deletePolicy(policyStoreId, policyIdOf(physicalId), region),
|
||||
NOT_FOUND);
|
||||
}
|
||||
}
|
||||
default -> throw new IllegalStateException(
|
||||
"VerifiedPermissionsCfnProvisioner cannot delete " + resourceType);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasReplacementUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.hasReplacement(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String updateCleanupPhysicalId(StackResource resource) {
|
||||
return ReplacementCleanup.cleanupPhysicalId(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateCleanupResult completeUpdate(StackResource resource) {
|
||||
// The update committed, so what an in-place change snapshotted for a rollback is spent.
|
||||
resource.getAttributes().remove(SNAPSHOT_ATTR);
|
||||
return ReplacementCleanup.complete(resource, this::delete);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearUpdate(StackResource resource) {
|
||||
resource.getAttributes().remove(SNAPSHOT_ATTR);
|
||||
ReplacementCleanup.clear(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) {
|
||||
CfnRollback.carryFailedUndoSnapshot(previous, attempted, SNAPSHOT_ATTR);
|
||||
}
|
||||
|
||||
/**
|
||||
* Undoes this update when a later resource failed it: a replacement is deleted and the prior
|
||||
* entity named again, an in-place change is written back from its snapshot. An update that changed
|
||||
* nothing in place, a template-linked policy left as it was, has nothing to undo.
|
||||
*/
|
||||
@Override
|
||||
public boolean rollbackUpdate(StackResource resource) {
|
||||
if (ReplacementCleanup.rollback(resource, this::delete)) {
|
||||
return true;
|
||||
}
|
||||
restoreSnapshot(resource);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes back what the snapshot holds, if the resource carries one. It is spent only once the
|
||||
* restore succeeded: a restore that throws leaves it in place for the next attempt.
|
||||
*/
|
||||
private void restoreSnapshot(StackResource resource) {
|
||||
JsonNode snapshot = CfnRollback.updateSnapshot(resource, SNAPSHOT_ATTR);
|
||||
if (snapshot == null) {
|
||||
return;
|
||||
}
|
||||
String region = snapshot.path("region").asText();
|
||||
String policyStoreId = snapshot.path("policyStoreId").asText();
|
||||
switch (resource.getResourceType()) {
|
||||
case POLICY_STORE -> {
|
||||
ObjectNode settings = MAPPER.createObjectNode();
|
||||
settings.put("policyStoreId", policyStoreId);
|
||||
settings.putObject("validationSettings").put("mode", snapshot.path("mode").asText());
|
||||
settings.put("description", Objects.requireNonNullElse(CfnRollback.snapshotText(snapshot, "description"), ""));
|
||||
settings.put("deletionProtection", snapshot.path("deletionProtection").asText());
|
||||
PolicyStore restored = verifiedPermissions.updatePolicyStore(settings, region);
|
||||
String schema = CfnRollback.snapshotText(snapshot, "schema");
|
||||
if (!Objects.equals(schema, restored.schema())) {
|
||||
// Verified Permissions has no call that removes a schema; an empty one is the nearest.
|
||||
verifiedPermissions.putSchema(schemaRequest(policyStoreId, schema == null ? EMPTY_SCHEMA : schema),
|
||||
region);
|
||||
}
|
||||
Set<String> touched = new LinkedHashSet<>();
|
||||
snapshot.path("touched").forEach(key -> touched.add(key.asText()));
|
||||
Map<String, String> priorTags = new LinkedHashMap<>();
|
||||
snapshot.path("tags").properties().forEach(tag -> priorTags.put(tag.getKey(), tag.getValue().asText()));
|
||||
reconcileTags(restored.arn(), touched, priorTags, region);
|
||||
Ec2Tags.restoreRecord(resource, TAG_KEYS_ATTR, snapshot);
|
||||
}
|
||||
case POLICY_TEMPLATE -> {
|
||||
ObjectNode prior = entityRequest(snapshot, policyStoreId);
|
||||
prior.put("policyTemplateId", snapshot.path("policyTemplateId").asText());
|
||||
verifiedPermissions.updatePolicyTemplate(prior, region);
|
||||
}
|
||||
case POLICY -> {
|
||||
ObjectNode prior = MAPPER.createObjectNode();
|
||||
prior.put("policyStoreId", policyStoreId);
|
||||
prior.put("policyId", snapshot.path("policyId").asText());
|
||||
prior.put("name", Objects.requireNonNullElse(CfnRollback.snapshotText(snapshot, "name"), ""));
|
||||
ObjectNode body = prior.putObject("definition").putObject("static");
|
||||
body.put("statement", snapshot.path("statement").asText());
|
||||
body.put("description", Objects.requireNonNullElse(CfnRollback.snapshotText(snapshot, "description"), ""));
|
||||
verifiedPermissions.updatePolicy(prior, region);
|
||||
}
|
||||
default -> throw new IllegalStateException(
|
||||
"VerifiedPermissionsCfnProvisioner cannot restore " + resource.getResourceType());
|
||||
}
|
||||
resource.getAttributes().remove(SNAPSHOT_ATTR);
|
||||
}
|
||||
|
||||
private static ObjectNode entitySnapshot(String region, String policyStoreId, String statement, String description,
|
||||
String name) {
|
||||
ObjectNode snapshot = MAPPER.createObjectNode();
|
||||
snapshot.put("region", region);
|
||||
snapshot.put("policyStoreId", policyStoreId);
|
||||
snapshot.put("statement", statement);
|
||||
snapshot.put("description", description);
|
||||
snapshot.put("name", name);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
private static ObjectNode entityRequest(JsonNode snapshot, String policyStoreId) {
|
||||
ObjectNode request = MAPPER.createObjectNode();
|
||||
request.put("policyStoreId", policyStoreId);
|
||||
request.put("statement", snapshot.path("statement").asText());
|
||||
request.put("description", Objects.requireNonNullElse(CfnRollback.snapshotText(snapshot, "description"), ""));
|
||||
request.put("name", Objects.requireNonNullElse(CfnRollback.snapshotText(snapshot, "name"), ""));
|
||||
return request;
|
||||
}
|
||||
|
||||
/** Drives the tags among {@code managedKeys} to {@code desired}; keys the stack does not own stay. */
|
||||
private void reconcileTags(String arn, Set<String> managedKeys, Map<String, String> desired, String region) {
|
||||
CfnRollback.reconcileTags(managedKeys, desired,
|
||||
dropped -> verifiedPermissions.untagResource(arn, dropped, region),
|
||||
added -> verifiedPermissions.tagResource(arn, added, region));
|
||||
}
|
||||
|
||||
private static boolean declares(JsonNode props, String property) {
|
||||
return props != null && props.has(property) && !props.get(property).isNull();
|
||||
}
|
||||
|
||||
/** {@code Schema.CedarJson} as the API takes it, or null when the template declares no schema. */
|
||||
private static String schema(JsonNode props, ProvisionContext ctx) {
|
||||
JsonNode schema = optionalObject(props, "Schema", ctx);
|
||||
if (schema == null || !schema.has("CedarJson") || schema.get("CedarJson").isNull()) {
|
||||
return null;
|
||||
}
|
||||
JsonNode cedarJson = schema.get("CedarJson");
|
||||
// The schema is a JSON document given as a string; a template that writes it as an object
|
||||
// is taken as the document itself.
|
||||
String value = cedarJson.isObject() ? cedarJson.toString() : ctx.engine().resolve(cedarJson);
|
||||
return value == null || value.isBlank() ? null : value;
|
||||
}
|
||||
|
||||
private static ObjectNode schemaRequest(String policyStoreId, String cedarJson) {
|
||||
ObjectNode request = MAPPER.createObjectNode();
|
||||
request.put("policyStoreId", policyStoreId);
|
||||
request.putObject("definition").put("cedarJson", cedarJson);
|
||||
return request;
|
||||
}
|
||||
|
||||
/** {@code EncryptionSettings}, a union of {@code Default} and {@code KmsEncryptionSettings}, as the API takes it. */
|
||||
private static ObjectNode encryptionSettings(JsonNode settings, ProvisionContext ctx) {
|
||||
ObjectNode request = MAPPER.createObjectNode();
|
||||
JsonNode kms = settings.get("KmsEncryptionSettings");
|
||||
if (kms == null || kms.isNull()) {
|
||||
request.putObject("default");
|
||||
return request;
|
||||
}
|
||||
ObjectNode kmsRequest = request.putObject("kmsEncryptionSettings");
|
||||
kmsRequest.put("key", ctx.engine().resolve(kms.path("Key")));
|
||||
JsonNode context = kms.get("EncryptionContext");
|
||||
if (context != null && context.isObject()) {
|
||||
ObjectNode contextRequest = kmsRequest.putObject("encryptionContext");
|
||||
context.fields().forEachRemaining(entry -> contextRequest.put(entry.getKey(), ctx.engine().resolve(entry.getValue())));
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
/** The store's {@code EncryptionState}, in the shape the registry schema gives the attribute. */
|
||||
private static ObjectNode encryptionState(PolicyStore store) {
|
||||
ObjectNode state = MAPPER.createObjectNode();
|
||||
if (store.encryptionKeyArn() == null) {
|
||||
state.putObject("Default");
|
||||
return state;
|
||||
}
|
||||
ObjectNode kms = state.putObject("KmsEncryptionState");
|
||||
kms.put("Key", store.encryptionKeyArn());
|
||||
ObjectNode context = kms.putObject("EncryptionContext");
|
||||
store.encryptionContext().forEach(context::put);
|
||||
return state;
|
||||
}
|
||||
|
||||
private static boolean sameLinkedPolicy(Policy current, ObjectNode request, String name) {
|
||||
JsonNode linked = request.path("definition").path("templateLinked");
|
||||
return linked.isObject()
|
||||
&& linked.path("policyTemplateId").asText().equals(current.policyTemplateId())
|
||||
&& Objects.equals(current.principal(), entity(linked.get("principal")))
|
||||
&& Objects.equals(current.resource(), entity(linked.get("resource")))
|
||||
&& Objects.equals(current.name(), blankToNull(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the update changes the prior entity in place: the engine does not replace it, and the
|
||||
* prior is a real entity, not the dispatcher's stub a stack from before this provisioner holds,
|
||||
* whose update creates the entity instead.
|
||||
*/
|
||||
private static boolean updatesInPlace(ProvisionContext ctx, PropertyChanges changes,
|
||||
Map<String, String> attributesBefore) {
|
||||
return ctx.isUpdate() && !changes.requiresReplacement()
|
||||
&& !CfnResourceDispatcher.isStub(ctx.priorPhysicalId(), attributesBefore);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets {@code field} to the template's value, to {@code cleared} when the template dropped the
|
||||
* property, and leaves it out when the stack never declared it, so the service keeps what it has.
|
||||
*/
|
||||
private static void putOrClear(ObjectNode request, String field, String value, PropertyChanges.Kind kind,
|
||||
String cleared) {
|
||||
if (value != null) {
|
||||
request.put(field, value);
|
||||
} else if (kind == PropertyChanges.Kind.DROPPED) {
|
||||
request.put(field, cleared);
|
||||
}
|
||||
}
|
||||
|
||||
private static EntityIdentifier entity(JsonNode node) {
|
||||
if (node == null || !node.isObject()) {
|
||||
return null;
|
||||
}
|
||||
return new EntityIdentifier(node.path("entityType").asText(), node.path("entityId").asText());
|
||||
}
|
||||
|
||||
private static String blankToNull(String value) {
|
||||
return value == null || value.isBlank() ? null : value;
|
||||
}
|
||||
|
||||
private static String storeOf(String templatePhysicalId) {
|
||||
return templatePhysicalId.substring(0, templatePhysicalId.indexOf('|'));
|
||||
}
|
||||
|
||||
private static String entityOf(String templatePhysicalId) {
|
||||
return templatePhysicalId.substring(templatePhysicalId.indexOf('|') + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* The store holding the policy a physical id names, or null when none does: CloudFormation's id is
|
||||
* the policy id alone, Cloud Control's {@code PolicyId|PolicyStoreId}.
|
||||
*/
|
||||
private String storeOfPolicy(String physicalId, String region) {
|
||||
int separator = physicalId.indexOf('|');
|
||||
return separator < 0 ? verifiedPermissions.policyStoreIdOf(physicalId, region) : physicalId.substring(separator + 1);
|
||||
}
|
||||
|
||||
private static String policyIdOf(String physicalId) {
|
||||
int separator = physicalId.indexOf('|');
|
||||
return separator < 0 ? physicalId : physicalId.substring(0, separator);
|
||||
}
|
||||
|
||||
private static JsonNode requiredObject(JsonNode props, String property, StackResource r, ProvisionContext ctx) {
|
||||
JsonNode node = optionalObject(props, property, ctx);
|
||||
if (node == null) {
|
||||
throw new AwsException("ValidationError", "Property " + property + " of " + r.getLogicalId()
|
||||
+ " (" + r.getResourceType() + ") is required.", 400);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private static JsonNode optionalObject(JsonNode props, String property, ProvisionContext ctx) {
|
||||
if (props == null || !props.has(property) || props.get(property).isNull()) {
|
||||
return null;
|
||||
}
|
||||
JsonNode resolved = ctx.engine().resolveNode(props.get(property));
|
||||
return resolved == null || resolved.isNull() || resolved.isMissingNode() ? null : resolved;
|
||||
}
|
||||
|
||||
private static String required(String value, String property, StackResource r) {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new AwsException("ValidationError", "Property " + property + " of " + r.getLogicalId()
|
||||
+ " (" + r.getResourceType() + ") is required.", 400);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
+15
@@ -383,6 +383,21 @@ public class VerifiedPermissionsService implements Resettable {
|
||||
.orElseThrow(() -> notFound("Policy not found: " + policyIdentifier));
|
||||
}
|
||||
|
||||
/**
|
||||
* The id of the store in {@code region} holding the policy whose id is {@code policyId}, or null when
|
||||
* none does. Floci generates policy ids unique, so one names its store; CloudFormation's {@code Ref}
|
||||
* for a policy is the policy id alone.
|
||||
*/
|
||||
public String policyStoreIdOf(String policyId, String region) {
|
||||
String prefix = region + ":";
|
||||
String suffix = ":" + policyId;
|
||||
return policies.keys().stream()
|
||||
.filter(key -> key.startsWith(prefix) && key.endsWith(suffix))
|
||||
.map(key -> key.substring(prefix.length(), key.length() - suffix.length()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
public synchronized Policy updatePolicy(JsonNode request, String region) {
|
||||
Policy current = getPolicy(requiredText(request, "policyStoreId"), requiredText(request, "policyId"), region);
|
||||
if (!"STATIC".equals(current.policyType())) {
|
||||
|
||||
@@ -1076,6 +1076,13 @@
|
||||
"ServerId",
|
||||
"UserName"
|
||||
],
|
||||
"AWS::VerifiedPermissions::Policy": [
|
||||
"PolicyStoreId"
|
||||
],
|
||||
"AWS::VerifiedPermissions::PolicyStore": [],
|
||||
"AWS::VerifiedPermissions::PolicyTemplate": [
|
||||
"PolicyStoreId"
|
||||
],
|
||||
"AWS::WAFv2::IPSet": [
|
||||
"Name",
|
||||
"Scope"
|
||||
|
||||
@@ -13,6 +13,8 @@ import io.floci.aws.services.iam.IamService;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -87,37 +89,41 @@ class CloudControlServiceTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* Cloud Control names an AWS::ApiGatewayV2::ApiMapping by the type's primary identifier,
|
||||
* {@code <ApiMappingId>|<DomainName>}, where CloudFormation's Ref is the bare ApiMappingId.
|
||||
* Cloud Control names a resource by its type's primary identifier and reports the identifying
|
||||
* property in its model. One that joins two properties is named by both: an
|
||||
* AWS::ApiGatewayV2::ApiMapping by {@code <ApiMappingId>|<DomainName>} and an
|
||||
* AWS::VerifiedPermissions::Policy by {@code <PolicyId>|<PolicyStoreId>}, where CloudFormation's
|
||||
* Ref is the bare id, and an AWS::VerifiedPermissions::PolicyTemplate by its physical id,
|
||||
* {@code <PolicyStoreId>|<PolicyTemplateId>}, whose model names the template alone.
|
||||
*/
|
||||
@Test
|
||||
void anApiMappingIsIdentifiedByItsIdAndItsDomain() throws Exception {
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = ';', value = {
|
||||
"AWS::ApiGatewayV2::ApiMapping;ApiMappingId;abc123;{\"DomainName\":\"api.example.com\",\"ApiId\":\"a1b2c3\",\"Stage\":\"$default\"};abc123|api.example.com;abc123",
|
||||
"AWS::VerifiedPermissions::Policy;PolicyId;SP1;{\"PolicyStoreId\":\"PS1\"};SP1|PS1;SP1",
|
||||
"AWS::VerifiedPermissions::PolicyTemplate;PolicyTemplateId;PS1|PT1;{\"PolicyStoreId\":\"PS1\"};PS1|PT1;PT1",
|
||||
"AWS::VerifiedPermissions::PolicyStore;PolicyStoreId;PS1;{\"ValidationSettings\":{\"Mode\":\"OFF\"}};PS1;PS1"
|
||||
})
|
||||
void aResourceIsNamedByItsPrimaryIdentifierAndReportsItInItsModel(String type, String idField, String physicalId,
|
||||
String desiredState, String identifier,
|
||||
String modelId) throws Exception {
|
||||
CfnResourceDispatcher provisioner = mock(CfnResourceDispatcher.class);
|
||||
StackResource resource = new StackResource();
|
||||
resource.setPhysicalId("abc123");
|
||||
resource.setAttributes(Map.of("ApiMappingId", "abc123"));
|
||||
when(provisioner.provisionStandalone(eq("AWS::ApiGatewayV2::ApiMapping"),
|
||||
any(), eq("us-east-1"), eq("111111111111"))).thenReturn(resource);
|
||||
resource.setPhysicalId(physicalId);
|
||||
resource.setAttributes(Map.of(idField, physicalId));
|
||||
when(provisioner.provisionStandalone(eq(type), any(), eq("us-east-1"), eq("111111111111"))).thenReturn(resource);
|
||||
CloudControlService service = new CloudControlService(
|
||||
mock(S3Service.class), mock(Ec2Service.class), mock(IamService.class), provisioner,
|
||||
new ObjectMapper());
|
||||
String identifier = "abc123|api.example.com";
|
||||
|
||||
CloudControlService.ProgressEvent pending = service.createResource("us-east-1", "111111111111",
|
||||
"AWS::ApiGatewayV2::ApiMapping",
|
||||
"{\"DomainName\":\"api.example.com\",\"ApiId\":\"a1b2c3\",\"Stage\":\"$default\"}");
|
||||
CloudControlService.ProgressEvent pending = service.createResource("us-east-1", "111111111111", type, desiredState);
|
||||
awaitSuccess(service, "111111111111", pending.requestToken());
|
||||
assertEquals(identifier, service.requestStatus("111111111111", pending.requestToken()).identifier());
|
||||
String model = service.getResource("us-east-1", "111111111111",
|
||||
"AWS::ApiGatewayV2::ApiMapping", identifier).properties();
|
||||
assertEquals("abc123", new ObjectMapper().readTree(model).path("ApiMappingId").asText());
|
||||
String model = service.getResource("us-east-1", "111111111111", type, identifier).properties();
|
||||
assertEquals(modelId, new ObjectMapper().readTree(model).path(idField).asText());
|
||||
|
||||
assertEquals("SUCCESS", service.deleteResource("us-east-1", "111111111111",
|
||||
"AWS::ApiGatewayV2::ApiMapping", identifier).operationStatus());
|
||||
verify(provisioner).deleteStandalone("AWS::ApiGatewayV2::ApiMapping", identifier, "us-east-1",
|
||||
Map.of("ApiMappingId", "abc123"));
|
||||
assertThrows(AwsException.class, () -> service.getResource("us-east-1", "111111111111",
|
||||
"AWS::ApiGatewayV2::ApiMapping", identifier));
|
||||
assertEquals("SUCCESS", service.deleteResource("us-east-1", "111111111111", type, identifier).operationStatus());
|
||||
verify(provisioner).deleteStandalone(type, identifier, "us-east-1", Map.of(idField, physicalId));
|
||||
assertThrows(AwsException.class, () -> service.getResource("us-east-1", "111111111111", type, identifier));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -129,6 +129,7 @@ import io.floci.aws.services.cloudformation.provisioners.SqsCfnProvisioner;
|
||||
import io.floci.aws.services.cloudformation.provisioners.SsmCfnProvisioner;
|
||||
import io.floci.aws.services.cloudformation.provisioners.StepFunctionsCfnProvisioner;
|
||||
import io.floci.aws.services.cloudformation.provisioners.TransferCfnProvisioner;
|
||||
import io.floci.aws.services.cloudformation.provisioners.VerifiedPermissionsCfnProvisioner;
|
||||
import io.floci.aws.services.cloudformation.provisioners.WafV2CfnProvisioner;
|
||||
import io.floci.aws.services.cloudfront.CloudFrontService;
|
||||
import io.floci.aws.services.cloudmap.CloudMapService;
|
||||
@@ -198,6 +199,7 @@ import io.floci.aws.services.sqs.SqsService;
|
||||
import io.floci.aws.services.ssm.SsmService;
|
||||
import io.floci.aws.services.stepfunctions.StepFunctionsService;
|
||||
import io.floci.aws.services.transfer.TransferService;
|
||||
import io.floci.aws.services.verifiedpermissions.VerifiedPermissionsService;
|
||||
import io.floci.aws.services.wafv2.WafV2Service;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
@@ -255,6 +257,7 @@ final class CfnProvisionerFixture {
|
||||
private IamService iamService;
|
||||
private SsmService ssmService;
|
||||
private KmsService kmsService;
|
||||
private VerifiedPermissionsService verifiedPermissionsService;
|
||||
private SecretsManagerService secretsManagerService;
|
||||
private EventBridgeService eventBridgeService;
|
||||
private ApiGatewayService apiGatewayService;
|
||||
@@ -403,6 +406,9 @@ final class CfnProvisionerFixture {
|
||||
if (kmsService != null) {
|
||||
discovered.add(new KmsCfnProvisioner(kmsService));
|
||||
}
|
||||
if (verifiedPermissionsService != null) {
|
||||
discovered.add(new VerifiedPermissionsCfnProvisioner(verifiedPermissionsService));
|
||||
}
|
||||
if (ecrService != null) {
|
||||
discovered.add(new EcrCfnProvisioner(ecrService));
|
||||
}
|
||||
@@ -706,6 +712,11 @@ final class CfnProvisionerFixture {
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder verifiedPermissions(VerifiedPermissionsService v) {
|
||||
this.verifiedPermissionsService = v;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder secretsManager(SecretsManagerService v) {
|
||||
this.secretsManagerService = v;
|
||||
return this;
|
||||
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
package io.floci.aws.services.cloudformation;
|
||||
|
||||
import io.floci.aws.core.common.XmlParser;
|
||||
import io.floci.aws.testing.CfnRequests;
|
||||
import io.floci.aws.testing.CfnStackWaits;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.floci.aws.testing.SidecarContainersProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasEntry;
|
||||
import static org.hamcrest.Matchers.matchesPattern;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Stands a STRICT policy store with its schema, a policy template, a static policy and a policy
|
||||
* linked to the template through {@code Fn::GetAtt PolicyTemplateId}, reads each back through
|
||||
* Verified Permissions' own API, updates the descriptions and tags in place, and deletes the stack.
|
||||
*
|
||||
* <p>Runs against the real Cedar sidecar image, started by {@code CedarSidecarManager} as in
|
||||
* production, since the service parses every policy and validates every schema through it. Needs
|
||||
* Docker; skipped without it, and locally when the pinned image is not present.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(SidecarContainersProfile.class)
|
||||
class VerifiedPermissionsCfnIntegrationTest {
|
||||
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261113/us-east-1/cloudformation/aws4_request";
|
||||
private static final String AVP_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261113/us-east-1/verifiedpermissions/aws4_request";
|
||||
private static final String STACK = "verifiedpermissions-cfn-it";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String SCHEMA = "{\\\"Demo\\\":{\\\"entityTypes\\\":{"
|
||||
+ "\\\"User\\\":{\\\"shape\\\":{\\\"type\\\":\\\"Record\\\",\\\"attributes\\\":{}}},"
|
||||
+ "\\\"Doc\\\":{\\\"shape\\\":{\\\"type\\\":\\\"Record\\\",\\\"attributes\\\":{}}}},"
|
||||
+ "\\\"actions\\\":{\\\"read\\\":{\\\"appliesTo\\\":{\\\"principalTypes\\\":[\\\"User\\\"],"
|
||||
+ "\\\"resourceTypes\\\":[\\\"Doc\\\"]}}}}}";
|
||||
private static final String TEMPLATE_STATEMENT =
|
||||
"permit(principal == ?principal, action == Demo::Action::\\\"read\\\", resource == ?resource);";
|
||||
private static final String STATIC_STATEMENT = "permit(principal, action == Demo::Action::\\\"read\\\", resource);";
|
||||
|
||||
private static final String TEMPLATE = """
|
||||
{
|
||||
"Parameters": {
|
||||
"Phase": {"Type": "String"},
|
||||
"Team": {"Type": "String"}
|
||||
},
|
||||
"Resources": {
|
||||
"Store": {
|
||||
"Type": "AWS::VerifiedPermissions::PolicyStore",
|
||||
"Properties": {
|
||||
"ValidationSettings": {"Mode": "STRICT"},
|
||||
"Description": {"Fn::Join": ["", ["authz ", {"Ref": "Phase"}]]},
|
||||
"DeletionProtection": {"Mode": "DISABLED"},
|
||||
"Schema": {"CedarJson": "%1$s"},
|
||||
"Tags": [{"Key": "team", "Value": {"Ref": "Team"}}]
|
||||
}
|
||||
},
|
||||
"ReadTemplate": {
|
||||
"Type": "AWS::VerifiedPermissions::PolicyTemplate",
|
||||
"Properties": {
|
||||
"PolicyStoreId": {"Ref": "Store"},
|
||||
"Statement": "%2$s",
|
||||
"Description": {"Fn::Join": ["", ["per-document read ", {"Ref": "Phase"}]]}
|
||||
}
|
||||
},
|
||||
"ReadAll": {
|
||||
"Type": "AWS::VerifiedPermissions::Policy",
|
||||
"Properties": {
|
||||
"PolicyStoreId": {"Fn::GetAtt": ["Store", "PolicyStoreId"]},
|
||||
"Definition": {"Static": {
|
||||
"Statement": "%3$s",
|
||||
"Description": {"Fn::Join": ["", ["everyone reads ", {"Ref": "Phase"}]]}
|
||||
}}
|
||||
}
|
||||
},
|
||||
"AliceReadsReadme": {
|
||||
"Type": "AWS::VerifiedPermissions::Policy",
|
||||
"Properties": {
|
||||
"PolicyStoreId": {"Ref": "Store"},
|
||||
"Definition": {"TemplateLinked": {
|
||||
"PolicyTemplateId": {"Fn::GetAtt": ["ReadTemplate", "PolicyTemplateId"]},
|
||||
"Principal": {"EntityType": "Demo::User", "EntityId": "alice"},
|
||||
"Resource": {"EntityType": "Demo::Doc", "EntityId": "readme"}
|
||||
}}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"StoreRef": {"Value": {"Ref": "Store"}},
|
||||
"StoreArn": {"Value": {"Fn::GetAtt": ["Store", "Arn"]}},
|
||||
"StoreId": {"Value": {"Fn::GetAtt": ["Store", "PolicyStoreId"]}},
|
||||
"TemplateRef": {"Value": {"Ref": "ReadTemplate"}},
|
||||
"TemplateId": {"Value": {"Fn::GetAtt": ["ReadTemplate", "PolicyTemplateId"]}},
|
||||
"ReadAllRef": {"Value": {"Ref": "ReadAll"}},
|
||||
"ReadAllId": {"Value": {"Fn::GetAtt": ["ReadAll", "PolicyId"]}},
|
||||
"ReadAllType": {"Value": {"Fn::GetAtt": ["ReadAll", "PolicyType"]}},
|
||||
"LinkedRef": {"Value": {"Ref": "AliceReadsReadme"}},
|
||||
"LinkedId": {"Value": {"Fn::GetAtt": ["AliceReadsReadme", "PolicyId"]}},
|
||||
"LinkedType": {"Value": {"Fn::GetAtt": ["AliceReadsReadme", "PolicyType"]}}
|
||||
}
|
||||
}
|
||||
""".formatted(SCHEMA, TEMPLATE_STATEMENT, STATIC_STATEMENT);
|
||||
|
||||
@BeforeAll
|
||||
static void requireDockerAndTheSidecarImage() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
SidecarContainersProfile.requireDockerAndImage("floci.services.verifiedpermissions.cedar-image");
|
||||
}
|
||||
|
||||
@Test
|
||||
void standsUpdatesAndDeletesAStoreWithItsSchemaTemplateAndPolicies() {
|
||||
cloudFormation("CreateStack", "create", "platform");
|
||||
CfnStackWaits.awaitStatus(STACK, "CREATE_COMPLETE");
|
||||
Map<String, String> created = outputs();
|
||||
|
||||
String storeId = created.get("StoreId");
|
||||
String storeArn = "arn:aws:verifiedpermissions::" + ACCOUNT + ":policy-store/" + storeId;
|
||||
String templateId = created.get("TemplateId");
|
||||
String readAllId = created.get("ReadAllId");
|
||||
String linkedId = created.get("LinkedId");
|
||||
assertEquals(storeId, created.get("StoreRef"));
|
||||
assertEquals(storeArn, created.get("StoreArn"));
|
||||
assertEquals(storeId + "|" + templateId, created.get("TemplateRef"));
|
||||
assertEquals(readAllId, created.get("ReadAllRef"));
|
||||
assertEquals("STATIC", created.get("ReadAllType"));
|
||||
assertEquals(linkedId, created.get("LinkedRef"));
|
||||
assertEquals("TEMPLATE_LINKED", created.get("LinkedType"));
|
||||
|
||||
avp("GetPolicyStore", "{\"policyStoreId\":\"" + storeId + "\",\"tags\":true}")
|
||||
.statusCode(200)
|
||||
.body("arn", equalTo(storeArn))
|
||||
.body("validationSettings.mode", equalTo("STRICT"))
|
||||
.body("deletionProtection", equalTo("DISABLED"))
|
||||
.body("description", equalTo("authz create"))
|
||||
.body("tags", hasEntry("team", "platform"));
|
||||
avp("GetSchema", "{\"policyStoreId\":\"" + storeId + "\"}")
|
||||
.statusCode(200)
|
||||
.body("namespaces[0]", equalTo("Demo"));
|
||||
avp("GetPolicyTemplate", "{\"policyStoreId\":\"" + storeId + "\",\"policyTemplateId\":\"" + templateId + "\"}")
|
||||
.statusCode(200)
|
||||
.body("policyTemplateId", matchesPattern("PT[A-Za-z0-9]+"))
|
||||
.body("statement", containsString("?principal"))
|
||||
.body("description", equalTo("per-document read create"));
|
||||
avp("GetPolicy", "{\"policyStoreId\":\"" + storeId + "\",\"policyId\":\"" + readAllId + "\"}")
|
||||
.statusCode(200)
|
||||
.body("policyType", equalTo("STATIC"))
|
||||
.body("definition.static.statement", containsString("Demo::Action::\"read\""))
|
||||
.body("definition.static.description", equalTo("everyone reads create"));
|
||||
avp("GetPolicy", "{\"policyStoreId\":\"" + storeId + "\",\"policyId\":\"" + linkedId + "\"}")
|
||||
.statusCode(200)
|
||||
.body("policyType", equalTo("TEMPLATE_LINKED"))
|
||||
.body("definition.templateLinked.policyTemplateId", equalTo(templateId))
|
||||
.body("definition.templateLinked.principal.entityId", equalTo("alice"))
|
||||
.body("definition.templateLinked.resource.entityType", equalTo("Demo::Doc"));
|
||||
|
||||
cloudFormation("UpdateStack", "update", "data");
|
||||
CfnStackWaits.awaitStatus(STACK, "UPDATE_COMPLETE");
|
||||
Map<String, String> updated = outputs();
|
||||
|
||||
assertEquals(storeId, updated.get("StoreRef"));
|
||||
assertEquals(storeId + "|" + templateId, updated.get("TemplateRef"));
|
||||
assertEquals(readAllId, updated.get("ReadAllRef"));
|
||||
assertEquals(linkedId, updated.get("LinkedRef"));
|
||||
avp("GetPolicyStore", "{\"policyStoreId\":\"" + storeId + "\",\"tags\":true}")
|
||||
.statusCode(200)
|
||||
.body("description", equalTo("authz update"))
|
||||
.body("tags", hasEntry("team", "data"))
|
||||
.body("tags", not(hasEntry("team", "platform")));
|
||||
avp("GetSchema", "{\"policyStoreId\":\"" + storeId + "\"}").statusCode(200);
|
||||
avp("GetPolicyTemplate", "{\"policyStoreId\":\"" + storeId + "\",\"policyTemplateId\":\"" + templateId + "\"}")
|
||||
.statusCode(200)
|
||||
.body("description", equalTo("per-document read update"));
|
||||
avp("GetPolicy", "{\"policyStoreId\":\"" + storeId + "\",\"policyId\":\"" + readAllId + "\"}")
|
||||
.statusCode(200)
|
||||
.body("definition.static.description", equalTo("everyone reads update"));
|
||||
|
||||
cloudFormation("DeleteStack", null, null);
|
||||
CfnStackWaits.awaitStackDeleted(STACK);
|
||||
|
||||
avp("GetPolicyStore", "{\"policyStoreId\":\"" + storeId + "\"}")
|
||||
.statusCode(400)
|
||||
.body("__type", containsString("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
private static void cloudFormation(String action, String phase, String team) {
|
||||
RequestSpecification request = CfnRequests.cfn(action, STACK).header("Authorization", CFN_AUTH);
|
||||
if (phase != null) {
|
||||
request.formParam("TemplateBody", TEMPLATE)
|
||||
.formParam("Parameters.member.1.ParameterKey", "Phase")
|
||||
.formParam("Parameters.member.1.ParameterValue", phase)
|
||||
.formParam("Parameters.member.2.ParameterKey", "Team")
|
||||
.formParam("Parameters.member.2.ParameterValue", team);
|
||||
}
|
||||
request.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static Map<String, String> outputs() {
|
||||
String xml = CfnRequests.cfn("DescribeStacks", STACK).header("Authorization", CFN_AUTH)
|
||||
.when().post("/").then().statusCode(200).extract().asString();
|
||||
return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue");
|
||||
}
|
||||
|
||||
private static ValidatableResponse avp(String action, String body) {
|
||||
return given().contentType("application/x-amz-json-1.0").header("Authorization", AVP_AUTH)
|
||||
.header("X-Amz-Target", "VerifiedPermissions." + action).body(body)
|
||||
.when().post("/").then();
|
||||
}
|
||||
}
|
||||
+664
@@ -0,0 +1,664 @@
|
||||
package io.floci.aws.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.floci.aws.services.cloudformation.model.StackResource;
|
||||
import io.floci.aws.services.verifiedpermissions.VerifiedPermissionsService;
|
||||
import io.floci.aws.services.verifiedpermissions.model.EntityIdentifier;
|
||||
import io.floci.aws.services.verifiedpermissions.model.Policy;
|
||||
import io.floci.aws.services.verifiedpermissions.model.PolicyStore;
|
||||
import io.floci.aws.services.verifiedpermissions.model.PolicyTemplate;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyMap;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** The Verified Permissions CFN provisioner in isolation, against a mocked {@link VerifiedPermissionsService}. */
|
||||
class VerifiedPermissionsCfnProvisionerTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String STORE_ID = "PS1a2b3c4d5e6f7g8h9i0j";
|
||||
private static final String STORE_ARN = "arn:aws:verifiedpermissions::000000000000:policy-store/" + STORE_ID;
|
||||
private static final String KEY_ARN = "arn:aws:kms:us-east-1:000000000000:key/11111111-2222-3333-4444-555555555555";
|
||||
private static final String SCHEMA = "{\"Demo\":{\"entityTypes\":{},\"actions\":{}}}";
|
||||
private static final String TEMPLATE_STATEMENT = "permit(principal == ?principal, action, resource == ?resource);";
|
||||
private static final Instant NOW = Instant.parse("2026-11-13T12:00:00Z");
|
||||
|
||||
private final VerifiedPermissionsService service = mock(VerifiedPermissionsService.class);
|
||||
private final VerifiedPermissionsCfnProvisioner provisioner = new VerifiedPermissionsCfnProvisioner(service);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private ProvisionContext ctx(String priorPhysicalId) {
|
||||
return ctx(priorPhysicalId, null);
|
||||
}
|
||||
|
||||
/** An update whose previous template declared {@code priorProperties}, which the engine's changes compare against. */
|
||||
private ProvisionContext ctx(String priorPhysicalId, JsonNode priorProperties) {
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(inv -> {
|
||||
JsonNode node = inv.getArgument(0);
|
||||
return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
|
||||
});
|
||||
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
return new ProvisionContext(engine, REGION, ACCOUNT, "authz-stack", priorPhysicalId, event -> { },
|
||||
priorProperties);
|
||||
}
|
||||
|
||||
private static StackResource resource(String type, String priorPhysicalId, Map<String, String> attributes) {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId("Thing");
|
||||
r.setResourceType(type);
|
||||
r.setPhysicalId(priorPhysicalId);
|
||||
r.setAttributes(new HashMap<>(attributes));
|
||||
return r;
|
||||
}
|
||||
|
||||
private static PolicyStore store(String mode, String schema, String keyArn) {
|
||||
return new PolicyStore(STORE_ID, STORE_ARN, mode, "DISABLED", "authz", keyArn,
|
||||
keyArn == null ? Map.of() : Map.of("tenant", "acme"), Map.of(), schema, null, null, NOW, NOW);
|
||||
}
|
||||
|
||||
private static PolicyTemplate template(String storeId, String templateId) {
|
||||
return new PolicyTemplate(storeId, templateId, null, TEMPLATE_STATEMENT, null, NOW, NOW);
|
||||
}
|
||||
|
||||
private static Policy staticPolicy(String storeId, String policyId) {
|
||||
return staticPolicy(storeId, policyId, null);
|
||||
}
|
||||
|
||||
private static Policy staticPolicy(String storeId, String policyId, String description) {
|
||||
return new Policy(storeId, policyId, null, "STATIC", "permit(principal, action, resource);", description,
|
||||
null, null, null, "permit", NOW, NOW);
|
||||
}
|
||||
|
||||
/** What the dispatcher left for this type in a stack from before it had a provisioner. */
|
||||
private static Map<String, String> stubAttributes() {
|
||||
return Map.of("Arn", CfnResourceDispatcher.STUB_ARN_PREFIX + "Thing");
|
||||
}
|
||||
|
||||
private static Policy linkedPolicy(String storeId, String policyId, String principalId) {
|
||||
return new Policy(storeId, policyId, null, "TEMPLATE_LINKED", null, null, "PT1",
|
||||
new EntityIdentifier("Demo::User", principalId), new EntityIdentifier("Demo::Doc", "readme"),
|
||||
"permit", NOW, NOW);
|
||||
}
|
||||
|
||||
private ObjectNode storeProps(String mode) {
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.putObject("ValidationSettings").put("Mode", mode);
|
||||
props.put("Description", "authz");
|
||||
return props;
|
||||
}
|
||||
|
||||
/** The store's previous template: STRICT, with a schema and the team and stale tags. */
|
||||
private ObjectNode priorStore() {
|
||||
ObjectNode prior = storeProps("STRICT");
|
||||
prior.putObject("Schema").put("CedarJson", SCHEMA);
|
||||
ArrayNode tags = prior.putArray("Tags");
|
||||
tags.addObject().put("Key", "team").put("Value", "platform");
|
||||
tags.addObject().put("Key", "stale").put("Value", "yes");
|
||||
return prior;
|
||||
}
|
||||
|
||||
private ObjectNode linkedDefinition(String principalId) {
|
||||
ObjectNode definition = mapper.createObjectNode();
|
||||
ObjectNode linked = definition.putObject("TemplateLinked");
|
||||
linked.put("PolicyTemplateId", "PT1");
|
||||
linked.putObject("Principal").put("EntityType", "Demo::User").put("EntityId", principalId);
|
||||
linked.putObject("Resource").put("EntityType", "Demo::Doc").put("EntityId", "readme");
|
||||
return definition;
|
||||
}
|
||||
|
||||
@Test
|
||||
void policyStoreAnswersRefWithItsIdSetsEveryAttributeAndPutsTheSchemaAfterTheCreate() {
|
||||
when(service.createPolicyStore(any(), eq(REGION))).thenReturn(store("STRICT", null, null));
|
||||
when(service.putSchema(any(), eq(REGION))).thenReturn(store("STRICT", SCHEMA, null));
|
||||
when(service.updatePolicyStore(any(), eq(REGION))).thenReturn(store("STRICT", SCHEMA, null));
|
||||
ObjectNode props = storeProps("STRICT");
|
||||
props.putObject("DeletionProtection").put("Mode", "ENABLED");
|
||||
props.putArray("Tags").addObject().put("Key", "team").put("Value", "platform");
|
||||
props.putObject("Schema").put("CedarJson", SCHEMA);
|
||||
StackResource r = resource("AWS::VerifiedPermissions::PolicyStore", null, Map.of());
|
||||
|
||||
provisioner.provision(r, props, ctx(null));
|
||||
|
||||
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).createPolicyStore(request.capture(), eq(REGION));
|
||||
assertEquals("STRICT", request.getValue().path("validationSettings").path("mode").asText());
|
||||
assertEquals("authz", request.getValue().path("description").asText());
|
||||
// Created unprotected, so a refused schema can still take it away; protection follows the schema.
|
||||
assertFalse(request.getValue().has("deletionProtection"));
|
||||
assertEquals("platform", request.getValue().path("tags").path("team").asText());
|
||||
assertFalse(request.getValue().has("encryptionSettings"));
|
||||
ArgumentCaptor<JsonNode> schema = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).putSchema(schema.capture(), eq(REGION));
|
||||
assertEquals(STORE_ID, schema.getValue().path("policyStoreId").asText());
|
||||
assertEquals(SCHEMA, schema.getValue().path("definition").path("cedarJson").asText());
|
||||
ArgumentCaptor<JsonNode> protect = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).updatePolicyStore(protect.capture(), eq(REGION));
|
||||
assertEquals(STORE_ID, protect.getValue().path("policyStoreId").asText());
|
||||
assertEquals("ENABLED", protect.getValue().path("deletionProtection").asText());
|
||||
assertEquals("STRICT", protect.getValue().path("validationSettings").path("mode").asText());
|
||||
assertFalse(protect.getValue().has("tags"));
|
||||
assertEquals(STORE_ID, r.getPhysicalId());
|
||||
assertEquals(STORE_ARN, r.getAttributes().get("Arn"));
|
||||
assertEquals(STORE_ID, r.getAttributes().get("PolicyStoreId"));
|
||||
assertEquals("{\"Default\":{}}", r.getAttributes().get("EncryptionState"));
|
||||
assertEquals("[\"team\"]", r.getAttributes().get(VerifiedPermissionsCfnProvisioner.TAG_KEYS_ATTR));
|
||||
}
|
||||
|
||||
// Catches: a store left standing when the deletion protection asked for after its schema is refused.
|
||||
@Test
|
||||
void policyStoreWhoseProtectionIsRefusedIsRemovedAgain() {
|
||||
when(service.createPolicyStore(any(), eq(REGION))).thenReturn(store("STRICT", null, null));
|
||||
when(service.putSchema(any(), eq(REGION))).thenReturn(store("STRICT", SCHEMA, null));
|
||||
AwsException refused = new AwsException("ValidationException", "deletionProtection is invalid", 400);
|
||||
when(service.updatePolicyStore(any(), eq(REGION))).thenThrow(refused);
|
||||
ObjectNode props = storeProps("STRICT");
|
||||
props.putObject("DeletionProtection").put("Mode", "SOMETIMES");
|
||||
props.putObject("Schema").put("CedarJson", SCHEMA);
|
||||
StackResource r = resource("AWS::VerifiedPermissions::PolicyStore", null, Map.of());
|
||||
|
||||
assertSame(refused, assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx(null))));
|
||||
|
||||
verify(service).deletePolicyStore(STORE_ID, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void policyStoreSendsItsKmsEncryptionAndReportsItsEncryptionState() {
|
||||
when(service.createPolicyStore(any(), eq(REGION))).thenReturn(store("OFF", null, KEY_ARN));
|
||||
ObjectNode props = storeProps("OFF");
|
||||
ObjectNode kms = props.putObject("EncryptionSettings").putObject("KmsEncryptionSettings");
|
||||
kms.put("Key", KEY_ARN);
|
||||
kms.putObject("EncryptionContext").put("tenant", "acme");
|
||||
StackResource r = resource("AWS::VerifiedPermissions::PolicyStore", null, Map.of());
|
||||
|
||||
provisioner.provision(r, props, ctx(null));
|
||||
|
||||
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).createPolicyStore(request.capture(), eq(REGION));
|
||||
JsonNode encryption = request.getValue().path("encryptionSettings").path("kmsEncryptionSettings");
|
||||
assertEquals(KEY_ARN, encryption.path("key").asText());
|
||||
assertEquals("acme", encryption.path("encryptionContext").path("tenant").asText());
|
||||
verify(service, never()).putSchema(any(), any());
|
||||
assertEquals("{\"KmsEncryptionState\":{\"Key\":\"" + KEY_ARN + "\",\"EncryptionContext\":{\"tenant\":\"acme\"}}}",
|
||||
r.getAttributes().get("EncryptionState"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void policyStoreWithoutValidationSettingsIsRefused() {
|
||||
ObjectNode props = mapper.createObjectNode().put("Description", "authz");
|
||||
StackResource r = resource("AWS::VerifiedPermissions::PolicyStore", null, Map.of());
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx(null)));
|
||||
|
||||
assertEquals("ValidationError", e.getErrorCode());
|
||||
verify(service, never()).createPolicyStore(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void policyStoreThatCannotTakeItsSchemaIsRemovedAgain() {
|
||||
when(service.createPolicyStore(any(), eq(REGION))).thenReturn(store("STRICT", null, null));
|
||||
AwsException rejected = new AwsException("ValidationException", "The Cedar schema is invalid", 400);
|
||||
when(service.putSchema(any(), eq(REGION))).thenThrow(rejected);
|
||||
ObjectNode props = storeProps("STRICT");
|
||||
props.putObject("DeletionProtection").put("Mode", "ENABLED");
|
||||
props.putObject("Schema").put("CedarJson", "{\"Demo\":{}}");
|
||||
StackResource r = resource("AWS::VerifiedPermissions::PolicyStore", null, Map.of());
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx(null)));
|
||||
|
||||
assertSame(rejected, e);
|
||||
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).createPolicyStore(request.capture(), eq(REGION));
|
||||
assertFalse(request.getValue().has("deletionProtection"));
|
||||
verify(service).deletePolicyStore(STORE_ID, REGION);
|
||||
verify(service, never()).updatePolicyStore(any(), any());
|
||||
}
|
||||
|
||||
// Catches: an update untagging keys added outside the stack, writing the schema before settings the
|
||||
// service then refuses, or leaving nothing for a rollback to put back.
|
||||
@Test
|
||||
void policyStoreUpdateKeepsItsIdChangesItsSettingsThenItsSchemaAndOnlyTheTagsTheStackOwns() {
|
||||
when(service.getPolicyStore(STORE_ID, REGION)).thenReturn(store("STRICT", SCHEMA, null));
|
||||
when(service.updatePolicyStore(any(), eq(REGION))).thenReturn(store("OFF", SCHEMA, null));
|
||||
when(service.listTags(STORE_ARN, REGION))
|
||||
.thenReturn(Map.of("team", "platform", "stale", "yes", "external", "kept"));
|
||||
ObjectNode props = storeProps("OFF");
|
||||
props.putArray("Tags").addObject().put("Key", "team").put("Value", "data");
|
||||
StackResource r = resource("AWS::VerifiedPermissions::PolicyStore", STORE_ID,
|
||||
Map.of("Arn", STORE_ARN, "PolicyStoreId", STORE_ID));
|
||||
|
||||
provisioner.provision(r, props, ctx(STORE_ID, priorStore()));
|
||||
|
||||
InOrder order = inOrder(service);
|
||||
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
|
||||
order.verify(service).updatePolicyStore(request.capture(), eq(REGION));
|
||||
ArgumentCaptor<JsonNode> schema = ArgumentCaptor.forClass(JsonNode.class);
|
||||
order.verify(service).putSchema(schema.capture(), eq(REGION));
|
||||
assertEquals(STORE_ID, request.getValue().path("policyStoreId").asText());
|
||||
assertEquals("OFF", request.getValue().path("validationSettings").path("mode").asText());
|
||||
assertFalse(request.getValue().has("deletionProtection"));
|
||||
assertEquals("authz", request.getValue().path("description").asText());
|
||||
assertEquals("{}", schema.getValue().path("definition").path("cedarJson").asText());
|
||||
verify(service).untagResource(STORE_ARN, List.of("stale"), REGION);
|
||||
verify(service).tagResource(STORE_ARN, Map.of("team", "data"), REGION);
|
||||
verify(service, never()).createPolicyStore(any(), any());
|
||||
assertEquals(STORE_ID, r.getPhysicalId());
|
||||
assertEquals("[\"team\"]", r.getAttributes().get(VerifiedPermissionsCfnProvisioner.TAG_KEYS_ATTR));
|
||||
assertFalse(provisioner.hasReplacementUpdate(r));
|
||||
}
|
||||
|
||||
// Catches: a later resource failing the update leaving the store with this update's settings,
|
||||
// schema and tags, since an in-place change has no replacement to roll back.
|
||||
@Test
|
||||
void policyStoreRollbackPutsBackItsSettingsSchemaAndTags() {
|
||||
when(service.getPolicyStore(STORE_ID, REGION)).thenReturn(store("STRICT", SCHEMA, null));
|
||||
when(service.updatePolicyStore(any(), eq(REGION))).thenReturn(store("OFF", "{}", null));
|
||||
when(service.listTags(STORE_ARN, REGION)).thenReturn(Map.of("team", "platform", "stale", "yes"));
|
||||
ObjectNode props = storeProps("OFF");
|
||||
props.putArray("Tags").addObject().put("Key", "team").put("Value", "data");
|
||||
StackResource r = resource("AWS::VerifiedPermissions::PolicyStore", STORE_ID,
|
||||
Map.of("Arn", STORE_ARN, "PolicyStoreId", STORE_ID));
|
||||
provisioner.provision(r, props, ctx(STORE_ID, priorStore()));
|
||||
clearInvocations(service);
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
ArgumentCaptor<JsonNode> settings = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).updatePolicyStore(settings.capture(), eq(REGION));
|
||||
assertEquals("STRICT", settings.getValue().path("validationSettings").path("mode").asText());
|
||||
assertEquals("authz", settings.getValue().path("description").asText());
|
||||
ArgumentCaptor<JsonNode> schema = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).putSchema(schema.capture(), eq(REGION));
|
||||
assertEquals(SCHEMA, schema.getValue().path("definition").path("cedarJson").asText());
|
||||
verify(service).tagResource(STORE_ARN, Map.of("team", "platform", "stale", "yes"), REGION);
|
||||
verify(service, never()).untagResource(any(), anyList(), any());
|
||||
assertNull(r.getAttributes().get(CfnRollback.VERIFIED_PERMISSIONS_UPDATE_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
// Catches: a schema written although the settings update in the same change was refused.
|
||||
@Test
|
||||
void policyStoreSettingsTheServiceRefusesLeaveItsSchemaAlone() {
|
||||
when(service.getPolicyStore(STORE_ID, REGION)).thenReturn(store("STRICT", SCHEMA, null));
|
||||
AwsException refused = new AwsException("ValidationException", "validationSettings.mode is invalid", 400);
|
||||
when(service.updatePolicyStore(any(), eq(REGION))).thenThrow(refused).thenReturn(store("STRICT", SCHEMA, null));
|
||||
when(service.listTags(STORE_ARN, REGION)).thenReturn(Map.of());
|
||||
ObjectNode props = storeProps("SOMETIMES");
|
||||
props.putObject("Schema").put("CedarJson", "{\"Other\":{\"entityTypes\":{},\"actions\":{}}}");
|
||||
StackResource r = resource("AWS::VerifiedPermissions::PolicyStore", STORE_ID,
|
||||
Map.of("Arn", STORE_ARN, "PolicyStoreId", STORE_ID));
|
||||
|
||||
assertSame(refused, assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(r, props, ctx(STORE_ID, priorStore()))));
|
||||
|
||||
verify(service, never()).putSchema(any(), any());
|
||||
}
|
||||
|
||||
// Catches: an encryption change reported as applied while the store keeps its create-time key.
|
||||
@Test
|
||||
void policyStoreRefusesAChangeOfItsEncryption() {
|
||||
ObjectNode props = storeProps("STRICT");
|
||||
props.putObject("EncryptionSettings").putObject("KmsEncryptionSettings").put("Key", KEY_ARN);
|
||||
StackResource r = resource("AWS::VerifiedPermissions::PolicyStore", STORE_ID,
|
||||
Map.of("Arn", STORE_ARN, "PolicyStoreId", STORE_ID));
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(r, props, ctx(STORE_ID, storeProps("STRICT"))));
|
||||
|
||||
assertEquals("ValidationError", e.getErrorCode());
|
||||
verify(service, never()).updatePolicyStore(any(), any());
|
||||
}
|
||||
|
||||
// Catches: a Schema declared without CedarJson keeping the store's old schema.
|
||||
@Test
|
||||
void policyStoreSchemaDeclaredWithoutCedarJsonClearsTheOldOne() {
|
||||
when(service.getPolicyStore(STORE_ID, REGION)).thenReturn(store("OFF", SCHEMA, null));
|
||||
when(service.updatePolicyStore(any(), eq(REGION))).thenReturn(store("OFF", SCHEMA, null));
|
||||
when(service.listTags(STORE_ARN, REGION)).thenReturn(Map.of());
|
||||
ObjectNode props = storeProps("OFF");
|
||||
props.putObject("Schema");
|
||||
StackResource r = resource("AWS::VerifiedPermissions::PolicyStore", STORE_ID,
|
||||
Map.of("Arn", STORE_ARN, "PolicyStoreId", STORE_ID));
|
||||
|
||||
provisioner.provision(r, props, ctx(STORE_ID, priorStore()));
|
||||
|
||||
ArgumentCaptor<JsonNode> schema = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).putSchema(schema.capture(), eq(REGION));
|
||||
assertEquals("{}", schema.getValue().path("definition").path("cedarJson").asText());
|
||||
}
|
||||
|
||||
// Catches: a description or deletion protection the template dropped staying on the store.
|
||||
@Test
|
||||
void policyStoreUpdateClearsTheDescriptionAndProtectionTheTemplateDropped() {
|
||||
when(service.getPolicyStore(STORE_ID, REGION)).thenReturn(store("STRICT", null, null));
|
||||
when(service.updatePolicyStore(any(), eq(REGION))).thenReturn(store("OFF", null, null));
|
||||
when(service.listTags(STORE_ARN, REGION)).thenReturn(Map.of());
|
||||
ObjectNode prior = storeProps("STRICT");
|
||||
prior.putObject("DeletionProtection").put("Mode", "ENABLED");
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.putObject("ValidationSettings").put("Mode", "OFF");
|
||||
StackResource r = resource("AWS::VerifiedPermissions::PolicyStore", STORE_ID,
|
||||
Map.of("Arn", STORE_ARN, "PolicyStoreId", STORE_ID));
|
||||
|
||||
provisioner.provision(r, props, ctx(STORE_ID, prior));
|
||||
|
||||
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).updatePolicyStore(request.capture(), eq(REGION));
|
||||
assertEquals("", request.getValue().path("description").asText(null));
|
||||
assertEquals("DISABLED", request.getValue().path("deletionProtection").asText());
|
||||
}
|
||||
|
||||
// Catches: an update writing a description or deletion protection the stack never declared over
|
||||
// what the store has.
|
||||
@Test
|
||||
void policyStoreUpdateLeavesWhatTheStackNeverDeclared() {
|
||||
when(service.getPolicyStore(STORE_ID, REGION)).thenReturn(store("STRICT", SCHEMA, null));
|
||||
when(service.updatePolicyStore(any(), eq(REGION))).thenReturn(store("STRICT", SCHEMA, null));
|
||||
when(service.listTags(STORE_ARN, REGION)).thenReturn(Map.of());
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.putObject("ValidationSettings").put("Mode", "STRICT");
|
||||
StackResource r = resource("AWS::VerifiedPermissions::PolicyStore", STORE_ID,
|
||||
Map.of("Arn", STORE_ARN, "PolicyStoreId", STORE_ID));
|
||||
|
||||
provisioner.provision(r, props, ctx(STORE_ID, props.deepCopy()));
|
||||
|
||||
verify(service, never()).putSchema(any(), any());
|
||||
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).updatePolicyStore(request.capture(), eq(REGION));
|
||||
assertFalse(request.getValue().has("description"));
|
||||
assertFalse(request.getValue().has("deletionProtection"));
|
||||
}
|
||||
|
||||
// Catches: a stack from before this provisioner, which holds the dispatcher's stub, failing its
|
||||
// update because the stub's id names no store.
|
||||
@Test
|
||||
void policyStoreUpdateOverTheDispatchersStubCreatesTheStore() {
|
||||
when(service.createPolicyStore(any(), eq(REGION))).thenReturn(store("STRICT", null, null));
|
||||
StackResource r = resource("AWS::VerifiedPermissions::PolicyStore", "Thing-0a1b2c3d", stubAttributes());
|
||||
|
||||
provisioner.provision(r, storeProps("STRICT"), ctx("Thing-0a1b2c3d", storeProps("STRICT")));
|
||||
|
||||
verify(service).createPolicyStore(any(), eq(REGION));
|
||||
verify(service, never()).updatePolicyStore(any(), any());
|
||||
assertEquals(STORE_ID, r.getPhysicalId());
|
||||
}
|
||||
|
||||
// Catches: an update wiping a schema the stack never managed, set on the store outside the stack.
|
||||
@Test
|
||||
void policyStoreUpdateLeavesAloneASchemaItsTemplatesNeverDeclared() {
|
||||
when(service.getPolicyStore(STORE_ID, REGION)).thenReturn(store("STRICT", SCHEMA, null));
|
||||
when(service.updatePolicyStore(any(), eq(REGION))).thenReturn(store("OFF", SCHEMA, null));
|
||||
when(service.listTags(STORE_ARN, REGION)).thenReturn(Map.of());
|
||||
StackResource r = resource("AWS::VerifiedPermissions::PolicyStore", STORE_ID,
|
||||
Map.of("Arn", STORE_ARN, "PolicyStoreId", STORE_ID));
|
||||
|
||||
provisioner.provision(r, storeProps("OFF"), ctx(STORE_ID, storeProps("STRICT")));
|
||||
|
||||
verify(service, never()).putSchema(any(), any());
|
||||
verify(service).updatePolicyStore(any(), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void policyTemplateAnswersRefWithStoreAndTemplateIdsJoinedByAPipe() {
|
||||
when(service.createPolicyTemplate(any(), eq(REGION))).thenReturn(template(STORE_ID, "PT1"));
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("PolicyStoreId", STORE_ID);
|
||||
props.put("Statement", TEMPLATE_STATEMENT);
|
||||
props.put("Description", "per-document grants");
|
||||
StackResource r = resource("AWS::VerifiedPermissions::PolicyTemplate", null, Map.of());
|
||||
|
||||
provisioner.provision(r, props, ctx(null));
|
||||
|
||||
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).createPolicyTemplate(request.capture(), eq(REGION));
|
||||
assertEquals(STORE_ID, request.getValue().path("policyStoreId").asText());
|
||||
assertEquals(TEMPLATE_STATEMENT, request.getValue().path("statement").asText());
|
||||
assertEquals("per-document grants", request.getValue().path("description").asText());
|
||||
assertEquals(STORE_ID + "|PT1", r.getPhysicalId());
|
||||
assertEquals("PT1", r.getAttributes().get("PolicyTemplateId"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void policyTemplateUpdatesInPlaceInItsStoreAndIsReplacedWhenTheStoreChanges() {
|
||||
when(service.getPolicyTemplate(STORE_ID, "PT1", REGION)).thenReturn(template(STORE_ID, "PT1"));
|
||||
when(service.updatePolicyTemplate(any(), eq(REGION))).thenReturn(template(STORE_ID, "PT1"));
|
||||
when(service.createPolicyTemplate(any(), eq(REGION))).thenReturn(template("PS2", "PT2"));
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("PolicyStoreId", STORE_ID);
|
||||
props.put("Statement", TEMPLATE_STATEMENT);
|
||||
StackResource same = resource("AWS::VerifiedPermissions::PolicyTemplate", STORE_ID + "|PT1",
|
||||
Map.of("PolicyTemplateId", "PT1"));
|
||||
ObjectNode prior = props.deepCopy().put("Description", "per-document grants");
|
||||
|
||||
provisioner.provision(same, props, ctx(STORE_ID + "|PT1", prior));
|
||||
|
||||
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).updatePolicyTemplate(request.capture(), eq(REGION));
|
||||
assertEquals("PT1", request.getValue().path("policyTemplateId").asText());
|
||||
assertEquals("", request.getValue().path("description").asText(null));
|
||||
assertFalse(request.getValue().has("name"));
|
||||
assertEquals(STORE_ID + "|PT1", same.getPhysicalId());
|
||||
assertFalse(provisioner.hasReplacementUpdate(same));
|
||||
clearInvocations(service);
|
||||
assertTrue(provisioner.rollbackUpdate(same));
|
||||
ArgumentCaptor<JsonNode> restored = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).updatePolicyTemplate(restored.capture(), eq(REGION));
|
||||
assertEquals("PT1", restored.getValue().path("policyTemplateId").asText());
|
||||
assertEquals(TEMPLATE_STATEMENT, restored.getValue().path("statement").asText());
|
||||
|
||||
props.put("PolicyStoreId", "PS2");
|
||||
StackResource moved = resource("AWS::VerifiedPermissions::PolicyTemplate", STORE_ID + "|PT1",
|
||||
Map.of("PolicyTemplateId", "PT1"));
|
||||
|
||||
provisioner.provision(moved, props, ctx(STORE_ID + "|PT1", prior));
|
||||
|
||||
assertEquals("PS2|PT2", moved.getPhysicalId());
|
||||
assertEquals("PT2", moved.getAttributes().get("PolicyTemplateId"));
|
||||
assertTrue(provisioner.hasReplacementUpdate(moved));
|
||||
assertEquals(STORE_ID + "|PT1", provisioner.updateCleanupPhysicalId(moved));
|
||||
}
|
||||
|
||||
// Catches: a template stub left by the dispatcher in an older stack failing its update.
|
||||
@Test
|
||||
void policyTemplateUpdateOverTheDispatchersStubCreatesTheTemplate() {
|
||||
when(service.createPolicyTemplate(any(), eq(REGION))).thenReturn(template(STORE_ID, "PT1"));
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("PolicyStoreId", STORE_ID);
|
||||
props.put("Statement", TEMPLATE_STATEMENT);
|
||||
StackResource r = resource("AWS::VerifiedPermissions::PolicyTemplate", "Thing-0a1b2c3d", stubAttributes());
|
||||
|
||||
provisioner.provision(r, props, ctx("Thing-0a1b2c3d", props.deepCopy()));
|
||||
|
||||
verify(service).createPolicyTemplate(any(), eq(REGION));
|
||||
verify(service, never()).updatePolicyTemplate(any(), any());
|
||||
assertEquals(STORE_ID + "|PT1", r.getPhysicalId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void staticPolicyAnswersRefWithItsIdAndSendsTheDefinitionInTheApiSpelling() {
|
||||
when(service.createPolicy(any(), eq(REGION))).thenReturn(staticPolicy(STORE_ID, "SP1"));
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("PolicyStoreId", STORE_ID);
|
||||
props.putObject("Definition").putObject("Static")
|
||||
.put("Statement", "permit(principal, action, resource);")
|
||||
.put("Description", "everyone");
|
||||
StackResource r = resource("AWS::VerifiedPermissions::Policy", null, Map.of());
|
||||
|
||||
provisioner.provision(r, props, ctx(null));
|
||||
|
||||
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).createPolicy(request.capture(), eq(REGION));
|
||||
JsonNode definition = request.getValue().path("definition");
|
||||
assertEquals("permit(principal, action, resource);", definition.path("static").path("statement").asText());
|
||||
assertEquals("everyone", definition.path("static").path("description").asText());
|
||||
assertEquals("SP1", r.getPhysicalId());
|
||||
assertEquals("SP1", r.getAttributes().get("PolicyId"));
|
||||
assertEquals("STATIC", r.getAttributes().get("PolicyType"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void staticPolicyUpdatesInPlaceInItsStoreAndClearsADroppedDescription() {
|
||||
when(service.getPolicy(STORE_ID, "SP1", REGION)).thenReturn(staticPolicy(STORE_ID, "SP1", "everyone"));
|
||||
when(service.updatePolicy(any(), eq(REGION))).thenReturn(staticPolicy(STORE_ID, "SP1"));
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("PolicyStoreId", STORE_ID);
|
||||
props.putObject("Definition").putObject("Static").put("Statement", "permit(principal, action, resource);");
|
||||
StackResource r = resource("AWS::VerifiedPermissions::Policy", "SP1",
|
||||
Map.of("PolicyId", "SP1", "PolicyType", "STATIC"));
|
||||
ObjectNode prior = props.deepCopy();
|
||||
((ObjectNode) prior.path("Definition").path("Static")).put("Description", "everyone");
|
||||
|
||||
provisioner.provision(r, props, ctx("SP1", prior));
|
||||
|
||||
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).updatePolicy(request.capture(), eq(REGION));
|
||||
assertEquals("SP1", request.getValue().path("policyId").asText());
|
||||
assertEquals(STORE_ID, request.getValue().path("policyStoreId").asText());
|
||||
assertEquals("", request.getValue().path("definition").path("static").path("description").asText(null));
|
||||
verify(service, never()).createPolicy(any(), any());
|
||||
assertEquals("SP1", r.getPhysicalId());
|
||||
assertFalse(provisioner.hasReplacementUpdate(r));
|
||||
|
||||
clearInvocations(service);
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
ArgumentCaptor<JsonNode> restored = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).updatePolicy(restored.capture(), eq(REGION));
|
||||
assertEquals("SP1", restored.getValue().path("policyId").asText());
|
||||
assertEquals("permit(principal, action, resource);",
|
||||
restored.getValue().path("definition").path("static").path("statement").asText());
|
||||
assertNull(r.getAttributes().get(CfnRollback.VERIFIED_PERMISSIONS_UPDATE_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
// Catches: a policy moved to another store keeping the old one, or the displaced policy left behind
|
||||
// because its bare id no longer names the store it has to be deleted from.
|
||||
@Test
|
||||
void staticPolicyMovedToAnotherStoreIsReplacedAndTheOldOneDeletedFromItsStore() {
|
||||
when(service.policyStoreIdOf("SP1", REGION)).thenReturn(STORE_ID);
|
||||
when(service.createPolicy(any(), eq(REGION))).thenReturn(staticPolicy("PS2", "SP2"));
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("PolicyStoreId", "PS2");
|
||||
props.putObject("Definition").putObject("Static").put("Statement", "permit(principal, action, resource);");
|
||||
StackResource r = resource("AWS::VerifiedPermissions::Policy", "SP1",
|
||||
Map.of("PolicyId", "SP1", "PolicyType", "STATIC"));
|
||||
ObjectNode prior = props.deepCopy().put("PolicyStoreId", STORE_ID);
|
||||
|
||||
provisioner.provision(r, props, ctx("SP1", prior));
|
||||
|
||||
verify(service, never()).updatePolicy(any(), any());
|
||||
assertEquals("SP2", r.getPhysicalId());
|
||||
assertTrue(provisioner.hasReplacementUpdate(r));
|
||||
assertEquals("SP1", provisioner.updateCleanupPhysicalId(r));
|
||||
|
||||
provisioner.completeUpdate(r);
|
||||
|
||||
verify(service).deletePolicy(STORE_ID, "SP1", REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void templateLinkedPolicyIsCreatedWithItsSlotsAndLeftAloneByAnUpdateThatKeepsThem() {
|
||||
when(service.createPolicy(any(), eq(REGION))).thenReturn(linkedPolicy(STORE_ID, "LP1", "alice"));
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("PolicyStoreId", STORE_ID);
|
||||
props.set("Definition", linkedDefinition("alice"));
|
||||
StackResource r = resource("AWS::VerifiedPermissions::Policy", null, Map.of());
|
||||
|
||||
provisioner.provision(r, props, ctx(null));
|
||||
|
||||
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).createPolicy(request.capture(), eq(REGION));
|
||||
JsonNode linked = request.getValue().path("definition").path("templateLinked");
|
||||
assertEquals("PT1", linked.path("policyTemplateId").asText());
|
||||
assertEquals("alice", linked.path("principal").path("entityId").asText());
|
||||
assertEquals("Demo::Doc", linked.path("resource").path("entityType").asText());
|
||||
assertEquals("LP1", r.getPhysicalId());
|
||||
assertEquals("TEMPLATE_LINKED", r.getAttributes().get("PolicyType"));
|
||||
|
||||
when(service.getPolicy(STORE_ID, "LP1", REGION)).thenReturn(linkedPolicy(STORE_ID, "LP1", "alice"));
|
||||
StackResource again = resource("AWS::VerifiedPermissions::Policy", "LP1",
|
||||
Map.of("PolicyId", "LP1", "PolicyType", "TEMPLATE_LINKED"));
|
||||
|
||||
provisioner.provision(again, props, ctx("LP1", props.deepCopy()));
|
||||
|
||||
verify(service, never()).updatePolicy(any(), any());
|
||||
assertEquals("LP1", again.getPhysicalId());
|
||||
assertEquals("LP1", again.getAttributes().get("PolicyId"));
|
||||
assertTrue(provisioner.rollbackUpdate(again));
|
||||
verify(service, never()).updatePolicy(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void templateLinkedPolicyRefusesAnUpdateOfItsDefinition() {
|
||||
when(service.getPolicy(STORE_ID, "LP1", REGION)).thenReturn(linkedPolicy(STORE_ID, "LP1", "alice"));
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
props.put("PolicyStoreId", STORE_ID);
|
||||
props.set("Definition", linkedDefinition("bob"));
|
||||
StackResource r = resource("AWS::VerifiedPermissions::Policy", "LP1",
|
||||
Map.of("PolicyId", "LP1", "PolicyType", "TEMPLATE_LINKED"));
|
||||
ObjectNode prior = props.deepCopy();
|
||||
prior.set("Definition", linkedDefinition("alice"));
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx("LP1", prior)));
|
||||
|
||||
assertEquals("ValidationError", e.getErrorCode());
|
||||
verify(service, never()).updatePolicy(any(), any());
|
||||
verify(service, never()).createPolicy(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteNamesTheStoreAndEntityEachIdCarriesAndToleratesOneAlreadyGone() {
|
||||
when(service.policyStoreIdOf("SP1", REGION)).thenReturn(STORE_ID);
|
||||
provisioner.delete("AWS::VerifiedPermissions::PolicyStore", STORE_ID, REGION);
|
||||
provisioner.delete("AWS::VerifiedPermissions::PolicyTemplate", STORE_ID + "|PT1", REGION);
|
||||
provisioner.delete("AWS::VerifiedPermissions::Policy", "SP1", REGION);
|
||||
// Cloud Control's identifier for a policy names its store.
|
||||
provisioner.delete("AWS::VerifiedPermissions::Policy", "SP2|PS2", REGION);
|
||||
// A policy no store holds any more went with its store.
|
||||
provisioner.delete("AWS::VerifiedPermissions::Policy", "SP3", REGION);
|
||||
|
||||
verify(service).deletePolicyStore(STORE_ID, REGION);
|
||||
verify(service).deletePolicyTemplate(STORE_ID, "PT1", REGION);
|
||||
verify(service).deletePolicy(STORE_ID, "SP1", REGION);
|
||||
verify(service).deletePolicy("PS2", "SP2", REGION);
|
||||
verify(service, never()).deletePolicy(any(), eq("SP3"), any());
|
||||
|
||||
doThrow(new AwsException("ResourceNotFoundException", "Policy store not found", 400))
|
||||
.when(service).deletePolicyTemplate("PS9", "PT9", REGION);
|
||||
provisioner.delete("AWS::VerifiedPermissions::PolicyTemplate", "PS9|PT9", REGION);
|
||||
|
||||
AwsException protectedStore = new AwsException("InvalidStateException",
|
||||
"The policy store can't be deleted because deletion protection is enabled.", 400);
|
||||
doThrow(protectedStore).when(service).deletePolicyStore("PS9", REGION);
|
||||
assertSame(protectedStore, assertThrows(AwsException.class,
|
||||
() -> provisioner.delete("AWS::VerifiedPermissions::PolicyStore", "PS9", REGION)));
|
||||
verify(service, never()).tagResource(any(), anyMap(), any());
|
||||
verify(service, never()).untagResource(any(), anyList(), any());
|
||||
assertNull(provisioner.updateCleanupPhysicalId(resource("AWS::VerifiedPermissions::Policy", null, Map.of())));
|
||||
}
|
||||
}
|
||||
+24
@@ -53,6 +53,14 @@ class VerifiedPermissionsServiceTest {
|
||||
out.write(bytes);
|
||||
}
|
||||
});
|
||||
fakeCedar.createContext("/v1/policy/parse", exchange -> {
|
||||
byte[] bytes = "{\"effect\":\"permit\",\"ast\":{}}".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json");
|
||||
exchange.sendResponseHeaders(200, bytes.length);
|
||||
try (OutputStream out = exchange.getResponseBody()) {
|
||||
out.write(bytes);
|
||||
}
|
||||
});
|
||||
fakeCedar.start();
|
||||
}
|
||||
|
||||
@@ -109,6 +117,22 @@ class VerifiedPermissionsServiceTest {
|
||||
assertEquals("ResourceNotFoundException", missing.getErrorCode());
|
||||
}
|
||||
|
||||
// Catches: CloudFormation's bare policy id, which is all its Ref carries, finding no store, or the
|
||||
// store of a policy in another Region, so the policy's update or delete goes to the wrong place.
|
||||
@Test
|
||||
void policyStoreIdOfNamesTheStoreHoldingThePolicyInTheRegion() throws Exception {
|
||||
PolicyStore store = service.createPolicyStore(json("""
|
||||
{"validationSettings":{"mode":"OFF"}}
|
||||
"""), REGION);
|
||||
Policy policy = service.createPolicy(json("""
|
||||
{"policyStoreId":"%s","definition":{"static":{"statement":"permit(principal, action, resource);"}}}
|
||||
""".formatted(store.policyStoreId())), REGION);
|
||||
|
||||
assertEquals(store.policyStoreId(), service.policyStoreIdOf(policy.policyId(), REGION));
|
||||
assertNull(service.policyStoreIdOf(policy.policyId(), "eu-west-1"));
|
||||
assertNull(service.policyStoreIdOf("SPnosuchpolicy", REGION));
|
||||
}
|
||||
|
||||
private JsonNode json(String value) throws Exception {
|
||||
return objectMapper.readTree(value);
|
||||
}
|
||||
|
||||
@@ -219,6 +219,9 @@ AWS::Signer::SigningProfile Arn,ProfileName,ProfileVersion,ProfileVersionArn Pla
|
||||
AWS::StepFunctions::StateMachine Arn,Name,StateMachineRevisionId Definition,DefinitionS3Location,DefinitionString,DefinitionSubstitutions,EncryptionConfiguration,LoggingConfiguration,RoleArn,StateMachineName,StateMachineType,Tags,TracingConfiguration
|
||||
AWS::Transfer::Server Arn,As2ServiceManagedEgressIpAddresses,ServerId,State Certificate,CreateWithHostKey,Domain,EndpointDetails,EndpointType,IdentityProviderDetails,IdentityProviderType,IpAddressType,LoggingRole,PostAuthenticationLoginBanner,PreAuthenticationLoginBanner,ProtocolDetails,Protocols,S3StorageOptions,SecurityPolicyName,StructuredLogDestinations,Tags,WorkflowDetails
|
||||
AWS::Transfer::User Arn HomeDirectory,HomeDirectoryMappings,HomeDirectoryType,Policy,PosixProfile,Role,ServerId,SshPublicKeys,Tags,UserName
|
||||
AWS::VerifiedPermissions::Policy PolicyId,PolicyType Definition,Name,PolicyStoreId
|
||||
AWS::VerifiedPermissions::PolicyStore Arn,EncryptionState,PolicyStoreId DeletionProtection,Description,EncryptionSettings,Schema,Tags,ValidationSettings
|
||||
AWS::VerifiedPermissions::PolicyTemplate PolicyTemplateId Description,Name,PolicyStoreId,Statement
|
||||
AWS::WAFv2::IPSet Arn,Id Addresses,Description,IPAddressVersion,Name,Scope,Tags
|
||||
AWS::WAFv2::LoggingConfiguration ManagedByFirewallManager LogDestinationConfigs,LoggingFilter,RedactedFields,ResourceArn
|
||||
AWS::WAFv2::WebACL Arn,Capacity,Id,LabelNamespace ApplicationConfig,AssociationConfig,CaptchaConfig,ChallengeConfig,CustomResponseBodies,DataProtectionConfig,DefaultAction,Description,MonetizationConfig,Name,OnSourceDDoSProtectionConfig,Rules,Scope,Tags,TokenDomains,VisibilityConfig
|
||||
|
||||
|
@@ -220,6 +220,9 @@ AWS::Signer::SigningProfile SignerCfnProvisioner
|
||||
AWS::StepFunctions::StateMachine StepFunctionsCfnProvisioner
|
||||
AWS::Transfer::Server TransferCfnProvisioner
|
||||
AWS::Transfer::User TransferCfnProvisioner
|
||||
AWS::VerifiedPermissions::Policy VerifiedPermissionsCfnProvisioner
|
||||
AWS::VerifiedPermissions::PolicyStore VerifiedPermissionsCfnProvisioner
|
||||
AWS::VerifiedPermissions::PolicyTemplate VerifiedPermissionsCfnProvisioner
|
||||
AWS::WAFv2::IPSet WafV2CfnProvisioner
|
||||
AWS::WAFv2::LoggingConfiguration WafV2CfnProvisioner
|
||||
AWS::WAFv2::WebACL WafV2CfnProvisioner
|
||||
|
||||
|
@@ -51,6 +51,7 @@ order:
|
||||
- AWS::CodeDeploy
|
||||
- AWS::Batch
|
||||
- AWS::Cognito
|
||||
- AWS::VerifiedPermissions
|
||||
- AWS::CertificateManager
|
||||
- AWS::Events
|
||||
- AWS::EventsV2
|
||||
@@ -96,6 +97,7 @@ type_order:
|
||||
AWS::IAM: [Role, User, AccessKey, Policy, ManagedPolicy, InstanceProfile]
|
||||
AWS::Organizations: [Organization, OrganizationalUnit, Account, Policy, ResourcePolicy]
|
||||
AWS::KMS: [Key, Alias]
|
||||
AWS::VerifiedPermissions: [PolicyStore, PolicyTemplate, Policy]
|
||||
AWS::SecretsManager: [Secret, SecretTargetAttachment]
|
||||
AWS::ECS: [Cluster, TaskDefinition, Service]
|
||||
AWS::EFS: [FileSystem, MountTarget, AccessPoint]
|
||||
@@ -193,6 +195,7 @@ service_labels:
|
||||
AWS::Signer: Signer
|
||||
AWS::StepFunctions: Step Functions
|
||||
AWS::Transfer: Transfer Family
|
||||
AWS::VerifiedPermissions: Verified Permissions
|
||||
AWS::WAFv2: WAFv2
|
||||
Custom: CloudFormation
|
||||
|
||||
|
||||
Reference in new issue
Block a user