@go-to-k/cdkd 0.296.2 → 0.296.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,12 +2,12 @@ import { r as getAwsClients } from "./aws-clients-CnmtbrxD.js";
2
2
  import { A as displaySafe, F as safeMsg, M as isPasteableIdent, P as plainIdentOr, g as generateResourceNameWithFallback, h as generateResourceName, j as displayStackName, k as displayIdent, n as getLogger, v as getCurrentStackName, w as SECRET_REF_MAX_CODE_POINTS } from "./logger-Dvc7ddKe.js";
3
3
  import { $ as compositeIdFormatMessage, $n as markRedactedCause, A as isTerminalDeleteFailure, B as WITHHELD_AWS_COMMAND, C as refusalTypeShown, D as ProtectionFlipRegistry, Dn as shellQuote, H as pasteableAwsCommand, Ht as AccountIdUnavailableError, J as isInterruptedWaitError, Jn as safeStringify, Kn as describeAwsFailure, L as userPoolProtectionSite, Ln as markNameCollision, Lt as withPasteableAwsProfile, M as observeThenDisableProtection, Mt as injectiveKey, N as protectionFlipKey, Nt as injectiveKeyPrefix, On as withheldTargetClause, P as rdsFamilyProtectionSite, Q as canonicalizeRoute53QueryName, Qn as markNonRetryable, Rn as markReplayMayCollide, Rt as ambientClientDefaults, S as quotedRemedyLogicalId, Sn as pasteableCommand, T as resolveExplicitPhysicalId, U as protectedReplacementAdvice, Un as isRetryableTransientError, V as isAwsCliLiteral, Vn as isAmbiguousOutcomeError, Vt as credentialFingerprint, W as renderDisableCommand, Wn as isTransientServerError, Wt as CdkdError, X as ElapsedBudgetRegistry, Y as startInterruptWatch, Yn as THROTTLING_ERROR_NAMES, Zn as isThrottlingError, _ as VALUE_NOT_SHOWN, a as onlySecretDerived, at as segmentAfterAnchor, b as isQuotableImportValue, bn as hasClauseBreak, bt as markAuxiliaryFailure, c as recordedPrincipalsRepair, ct as createMaskedRetryLogger, dt as maskerOrIdentity, er as wrapMaskedAwsError, et as compositeIdSeparatorRefusal, ft as withDerivedNameMasks, g as assertRegionMatch, h as RESOURCE_NOT_FOUND, ht as clearCreatedBeforeFailure, i as holdsSecretDerivedEntry, in as ProvisioningError, j as logGroupProtectionSite, k as deleteWithProtectionCompensation, lt as isSecretDerivedValue, nt as logicalIdShown, o as readPrincipalLists, on as ResourceUpdateNotSupportedError, ot as stateOrphanRecordRemedy, p as withRemovalDefaults, qn as isAwsAuthoredFailure, r as SECRET_DERIVED_READ_LIVE, rt as packCompositeId, st as createMaskedLogSinks, tt as compositeIdSkipResult, u as clearOnUpdateRemoval, ut as maskDeep, v as isPlainImportJson, w as remedyLogicalId, wn as plainOrDescribed, x as normalizeAwsTagsToCfn, xn as isInertUnquoted, xt as markCreatedBeforeFailure, y as isPlainImportValue, yn as commandHole, z as UNNAMEABLE_ID_CLAUSE, zt as ambientCredentialConfig } from "./iam-policy-targets-DSDSdxXz.js";
4
4
  import { s as ambientRegion } from "./aws-client-defaults-D0q0z4dG.js";
5
- import { $a as recoverMaskedOutput, $i as findSilentDropProperties, $n as observeThenDisableInstanceApiTermination, A as resolveDynamoDbDeleteBudgetClock, Aa as lambdaFunctionNameForMask, An as tagMapAsList, B as getPriorAttempts, Bi as refuseMalformedResourcesForDestroy, Br as passedParameterClassesOf, Ca as requireConfigObject, Cr as s3BucketWebsiteUrl, Ct as getStackRecords, D as beginDeleteWait, Dn as planTagDiff, Dr as getAccountInfo, E as DYNAMODB_DELETE_MIN_RESOURCE_TIMEOUT_MS, En as DBPROXY_TAG_OPTIONS, F as waitForIndexesSettled, Gs as canonicalizeRegion, Gt as REDACTED_DELETE_ADDRESS_SKIP_REASON, Ho as rewriteTemplateAssetReferences, Hs as decodeListingKey, I as ECR_AUTO_DELETE_IMAGES_TAG, Jn as isWaitAbandonedError, Jt as redactedDeleteAddressSkip, Kn as deleteSkipReason, Ks as derivePartitionAndUrlSuffix, Kt as isRedactedRecordedValue, L as S3_AUTO_DELETE_OBJECTS_TAG, Lo as stringifyValue, Lr as parseWebACLArn, M as DELETE_INDEX_WAIT_PROCEED_NOTE, Mn as definedAttributes, N as INDEX_SETTLE_POLL_INTERVAL_MS, Nn as stringifyIfAssigned, O as compensateRemovedDeletionProtection, Oa as withRetry, On as readTagList, P as deleteTableWithIndexBusyRetry, Pt as getCurrentProducerRegions, Qn as isTerminationProtectionPropagationError, R as hasCdkAutoDeleteTag, Sa as requireConfigArray, Sn as reserveStackCreateToken, Sr as s3BucketRegionalDomainName, T as DynamoDBGlobalTableProvider, Tn as DBPROXY_TAGS_WHAT, Un as unchangedBehindSecretReference, V as markRefusedBeforeApplying, Vn as slowCcOperationTimeoutMs, Xa as markSameGenerationBag, Yn as markWaitAbandoned, Za as redactSecretsForState, Zn as ec2InstanceProtectionSite, _a as configBooleanRefusal, _t as getCurrentNestedStackContext, a as findNestedTemplateTreeDefect, ac as resolveAssemblyPath, ao as carriesSecretMask, ba as readConfigString, bi as refuseMalformedNestedChildOutputs, bn as earliestDefined, br as s3BucketDomainName, c as renderNestedTemplateTreeDefect, da as coerceWarmThroughput$1, dt as getNestedRevertRun, er as reDisableInstanceApiTermination, fa as isWarmThroughputDecrease, ga as coerceCfnInteger, ha as coerceCfnBoolean, ic as renderAssemblyPathEscape, j as resolveDynamoDbDeleteBudgetMs, ja as sameLambdaFunctionAddress, jn as tagPlanWarning, k as deleteBudgetKey, ka as canonicalLambdaFunctionName, kn as refuseMalformedDesiredTags, ma as toFiniteNumber, mt as revertNestedChildFromJournal, nc as describeFileReadFailure, o as isAbsoluteAssetPath, pa as toCfnInteger, qn as withIndeterminateGuard, qt as redactedDeleteAddressFields, rc as displayAssemblyPath, s as listNestedTemplateRows, t as DeployEngine, ta as withoutSilentDropProperties, to as dynamicReferenceTokens, tr as reEnableInstanceApiTermination, ua as WARM_THROUGHPUT_MEMBERS, va as configIntegerRefusal, vr as isSettledInstanceState, vt as withNestedStackContext, wa as requireConfigString, wn as acquireIdempotencyToken, xa as replayWarn, xr as s3BucketDualStackDomainName, xt as awaitInFlightSibling, ya as configStringRefusal, yr as s3BucketArn, z as isTruthyCfnBoolean, za as hasMaskableValues, zn as getCurrentResourceSecrets } from "./deploy-engine-C_Eg-RHm.js";
6
- import { n as collectInlinePolicyNamesManagedBySiblings, t as IAMRoleProvider } from "./iam-role-provider-COoTgydF.js";
7
- import { a as canonicalizeIpProtocolValue, i as resolveSecretDerivedPrincipals, n as runDestroyForStack, o as resolvedResourceTimeoutMs, r as isResolvableSecretPrincipalList, t as canonicalizeIpv4Cidr } from "./program-CiMVZi4n.js";
8
- import { RDSProvider } from "./rds-provider-DQwvPJXB.js";
9
- import { NeptuneProvider } from "./neptune-provider-D2SmeISr.js";
10
- import { ASGProvider } from "./asg-provider-DedWRf1j.js";
5
+ import { $a as recoverMaskedOutput, $i as findSilentDropProperties, $n as observeThenDisableInstanceApiTermination, A as resolveDynamoDbDeleteBudgetClock, Aa as lambdaFunctionNameForMask, An as tagMapAsList, B as getPriorAttempts, Bi as refuseMalformedResourcesForDestroy, Br as passedParameterClassesOf, Ca as requireConfigObject, Cr as s3BucketWebsiteUrl, Ct as getStackRecords, D as beginDeleteWait, Dn as planTagDiff, Dr as getAccountInfo, E as DYNAMODB_DELETE_MIN_RESOURCE_TIMEOUT_MS, En as DBPROXY_TAG_OPTIONS, F as waitForIndexesSettled, Gs as canonicalizeRegion, Gt as REDACTED_DELETE_ADDRESS_SKIP_REASON, Ho as rewriteTemplateAssetReferences, Hs as decodeListingKey, I as ECR_AUTO_DELETE_IMAGES_TAG, Jn as isWaitAbandonedError, Jt as redactedDeleteAddressSkip, Kn as deleteSkipReason, Ks as derivePartitionAndUrlSuffix, Kt as isRedactedRecordedValue, L as S3_AUTO_DELETE_OBJECTS_TAG, Lo as stringifyValue, Lr as parseWebACLArn, M as DELETE_INDEX_WAIT_PROCEED_NOTE, Mn as definedAttributes, N as INDEX_SETTLE_POLL_INTERVAL_MS, Nn as stringifyIfAssigned, O as compensateRemovedDeletionProtection, Oa as withRetry, On as readTagList, P as deleteTableWithIndexBusyRetry, Pt as getCurrentProducerRegions, Qn as isTerminationProtectionPropagationError, R as hasCdkAutoDeleteTag, Sa as requireConfigArray, Sn as reserveStackCreateToken, Sr as s3BucketRegionalDomainName, T as DynamoDBGlobalTableProvider, Tn as DBPROXY_TAGS_WHAT, Un as unchangedBehindSecretReference, V as markRefusedBeforeApplying, Vn as slowCcOperationTimeoutMs, Xa as markSameGenerationBag, Yn as markWaitAbandoned, Za as redactSecretsForState, Zn as ec2InstanceProtectionSite, _a as configBooleanRefusal, _t as getCurrentNestedStackContext, a as findNestedTemplateTreeDefect, ac as resolveAssemblyPath, ao as carriesSecretMask, ba as readConfigString, bi as refuseMalformedNestedChildOutputs, bn as earliestDefined, br as s3BucketDomainName, c as renderNestedTemplateTreeDefect, da as coerceWarmThroughput$1, dt as getNestedRevertRun, er as reDisableInstanceApiTermination, fa as isWarmThroughputDecrease, ga as coerceCfnInteger, ha as coerceCfnBoolean, ic as renderAssemblyPathEscape, j as resolveDynamoDbDeleteBudgetMs, ja as sameLambdaFunctionAddress, jn as tagPlanWarning, k as deleteBudgetKey, ka as canonicalLambdaFunctionName, kn as refuseMalformedDesiredTags, ma as toFiniteNumber, mt as revertNestedChildFromJournal, nc as describeFileReadFailure, o as isAbsoluteAssetPath, pa as toCfnInteger, qn as withIndeterminateGuard, qt as redactedDeleteAddressFields, rc as displayAssemblyPath, s as listNestedTemplateRows, t as DeployEngine, ta as withoutSilentDropProperties, to as dynamicReferenceTokens, tr as reEnableInstanceApiTermination, ua as WARM_THROUGHPUT_MEMBERS, va as configIntegerRefusal, vr as isSettledInstanceState, vt as withNestedStackContext, wa as requireConfigString, wn as acquireIdempotencyToken, xa as replayWarn, xr as s3BucketDualStackDomainName, xt as awaitInFlightSibling, ya as configStringRefusal, yr as s3BucketArn, z as isTruthyCfnBoolean, za as hasMaskableValues, zn as getCurrentResourceSecrets } from "./deploy-engine-Dre6eDNJ.js";
6
+ import { n as collectInlinePolicyNamesManagedBySiblings, t as IAMRoleProvider } from "./iam-role-provider-D9wk9Bnh.js";
7
+ import { a as canonicalizeIpProtocolValue, i as resolveSecretDerivedPrincipals, n as runDestroyForStack, o as resolvedResourceTimeoutMs, r as isResolvableSecretPrincipalList, t as canonicalizeIpv4Cidr } from "./program-DFehMfoh.js";
8
+ import { RDSProvider } from "./rds-provider-Dl--9uQU.js";
9
+ import { NeptuneProvider } from "./neptune-provider-B1GRQ6UO.js";
10
+ import { ASGProvider } from "./asg-provider-CksS_6jO.js";
11
11
  import { createHash, randomUUID } from "node:crypto";
12
12
  import { CreateBucketCommand, DeleteBucketAnalyticsConfigurationCommand, DeleteBucketCommand, DeleteBucketCorsCommand, DeleteBucketEncryptionCommand, DeleteBucketIntelligentTieringConfigurationCommand, DeleteBucketInventoryConfigurationCommand, DeleteBucketLifecycleCommand, DeleteBucketMetricsConfigurationCommand, DeleteBucketOwnershipControlsCommand, DeleteBucketPolicyCommand, DeleteBucketReplicationCommand, DeleteBucketTaggingCommand, DeleteBucketWebsiteCommand, DeleteObjectsCommand, GetBucketAccelerateConfigurationCommand, GetBucketCorsCommand, GetBucketEncryptionCommand, GetBucketLifecycleConfigurationCommand, GetBucketLocationCommand, GetBucketLoggingCommand, GetBucketNotificationConfigurationCommand, GetBucketOwnershipControlsCommand, GetBucketPolicyCommand, GetBucketReplicationCommand, GetBucketTaggingCommand, GetBucketVersioningCommand, GetBucketWebsiteCommand, GetObjectCommand, GetObjectLockConfigurationCommand, GetPublicAccessBlockCommand, HeadBucketCommand, ListBucketAnalyticsConfigurationsCommand, ListBucketIntelligentTieringConfigurationsCommand, ListBucketInventoryConfigurationsCommand, ListBucketMetricsConfigurationsCommand, ListObjectVersionsCommand, ListObjectsV2Command, NoSuchBucket, PutBucketAccelerateConfigurationCommand, PutBucketAnalyticsConfigurationCommand, PutBucketCorsCommand, PutBucketEncryptionCommand, PutBucketIntelligentTieringConfigurationCommand, PutBucketInventoryConfigurationCommand, PutBucketLifecycleConfigurationCommand, PutBucketLoggingCommand, PutBucketMetricsConfigurationCommand, PutBucketNotificationConfigurationCommand, PutBucketOwnershipControlsCommand, PutBucketPolicyCommand, PutBucketReplicationCommand, PutBucketTaggingCommand, PutBucketVersioningCommand, PutBucketWebsiteCommand, PutObjectLockConfigurationCommand, PutPublicAccessBlockCommand, S3Client } from "@aws-sdk/client-s3";
13
13
  import { AddRoleToInstanceProfileCommand, AddUserToGroupCommand, AttachGroupPolicyCommand, AttachRolePolicyCommand, AttachUserPolicyCommand, CreateAccessKeyCommand, CreateGroupCommand, CreateInstanceProfileCommand, CreateLoginProfileCommand, CreatePolicyCommand, CreatePolicyVersionCommand, CreateUserCommand, DeleteAccessKeyCommand, DeleteGroupCommand, DeleteGroupPolicyCommand, DeleteInstanceProfileCommand, DeleteLoginProfileCommand, DeletePolicyCommand, DeletePolicyVersionCommand, DeleteRolePolicyCommand, DeleteUserCommand, DeleteUserPermissionsBoundaryCommand, DeleteUserPolicyCommand, DetachGroupPolicyCommand, DetachRolePolicyCommand, DetachUserPolicyCommand, GetAccessKeyLastUsedCommand, GetGroupCommand, GetGroupPolicyCommand, GetInstanceProfileCommand, GetPolicyCommand, GetPolicyVersionCommand, GetRolePolicyCommand, GetUserCommand, GetUserPolicyCommand, IAMClient, ListAccessKeysCommand, ListAttachedGroupPoliciesCommand, ListAttachedUserPoliciesCommand, ListEntitiesForPolicyCommand, ListGroupPoliciesCommand, ListGroupsForUserCommand, ListPoliciesCommand, ListPolicyTagsCommand, ListPolicyVersionsCommand, ListUserPoliciesCommand, NoSuchEntityException, PutGroupPolicyCommand, PutRolePolicyCommand, PutUserPermissionsBoundaryCommand, PutUserPolicyCommand, RemoveRoleFromInstanceProfileCommand, RemoveUserFromGroupCommand, TagPolicyCommand, TagUserCommand, UntagPolicyCommand, UntagUserCommand, UpdateAccessKeyCommand, UpdateLoginProfileCommand } from "@aws-sdk/client-iam";
@@ -5591,8 +5591,8 @@ var SQSQueuePolicyProvider = class {
5591
5591
  async queuesCarryingDocument(candidates, document, logicalId) {
5592
5592
  if (candidates.length === 0) return [];
5593
5593
  let reference;
5594
- if (typeof document === "string" && document.length > 0) reference = canonicalPolicy(document);
5595
- else if (document !== null && typeof document === "object") reference = canonicalJson$1(document);
5594
+ if (typeof document === "string" && document.length > 0) reference = canonicalPolicy$1(document);
5595
+ else if (document !== null && typeof document === "object") reference = canonicalJson$2(document);
5596
5596
  if (reference === void 0) {
5597
5597
  this.logger.warn(safeMsg`The queues ${candidates.join(", ")} listed by ${logicalId} were not checked (no policy document recorded to compare with) and may still carry its policy.`);
5598
5598
  return [];
@@ -5600,7 +5600,7 @@ var SQSQueuePolicyProvider = class {
5600
5600
  const carrying = [];
5601
5601
  for (const queueUrl of candidates) {
5602
5602
  const current = await this.readPolicyForWidening(queueUrl);
5603
- if (current.kind === "policy" && canonicalPolicy(current.policy) === reference) carrying.push(queueUrl);
5603
+ if (current.kind === "policy" && canonicalPolicy$1(current.policy) === reference) carrying.push(queueUrl);
5604
5604
  else if (current.kind === "unreadable") this.logger.warn(safeMsg`Could not read the policy of queue ${queueUrl} (${current.reason}), so it is not cleared: it may still carry the policy of ${logicalId}.`);
5605
5605
  else this.logger.debug(safeMsg`Queue ${queueUrl} does not carry the policy of ${logicalId}; left as is`);
5606
5606
  }
@@ -5696,7 +5696,7 @@ function listedQueues(bag) {
5696
5696
  function isListedQueueUrl(value) {
5697
5697
  return isSqsQueueUrl(value) && !value.includes(",") && !value.includes("*");
5698
5698
  }
5699
- function canonicalJson$1(value) {
5699
+ function canonicalJson$2(value) {
5700
5700
  const sortKeys = (v) => {
5701
5701
  if (Array.isArray(v)) return v.map(sortKeys);
5702
5702
  if (v !== null && typeof v === "object") {
@@ -5709,9 +5709,9 @@ function canonicalJson$1(value) {
5709
5709
  const sorted = sortKeys(value);
5710
5710
  return JSON.stringify(sorted);
5711
5711
  }
5712
- function canonicalPolicy(text) {
5712
+ function canonicalPolicy$1(text) {
5713
5713
  try {
5714
- return canonicalJson$1(JSON.parse(text));
5714
+ return canonicalJson$2(JSON.parse(text));
5715
5715
  } catch {
5716
5716
  return `raw:${text}`;
5717
5717
  }
@@ -6467,15 +6467,27 @@ var SNSTopicPolicyProvider = class {
6467
6467
  throw thrown;
6468
6468
  }
6469
6469
  }
6470
- async update(logicalId, physicalId, resourceType, properties, _previousProperties) {
6470
+ async update(logicalId, physicalId, resourceType, properties, previousProperties, context) {
6471
6471
  this.logger.debug(`Updating SNS topic policy ${logicalId}: ${physicalId}`);
6472
6472
  const topics = properties["Topics"];
6473
6473
  const policyDocument = properties["PolicyDocument"];
6474
6474
  if (!topics || topics.length === 0) throw new ProvisioningError(`Topics is required for SNS topic policy ${logicalId}`, resourceType, logicalId, physicalId);
6475
6475
  if (!policyDocument) throw new ProvisioningError(`PolicyDocument is required for SNS topic policy ${logicalId}`, resourceType, logicalId, physicalId);
6476
6476
  const policyDoc = typeof policyDocument === "string" ? policyDocument : JSON.stringify(policyDocument);
6477
+ const mask = context?.maskSecrets ?? ((t) => t);
6478
+ const written = splitTopicArns(physicalId);
6479
+ const listedOnly = await this.topicsCarryingDocument(listedTopics(previousProperties).filter((arn) => !written.includes(arn) && !topics.includes(arn)), previousProperties["PolicyDocument"], logicalId, mask);
6480
+ const dropped = written.filter((arn) => !topics.includes(arn));
6481
+ const unaddressable = dropped.filter((arn) => !isSnsTopicArn(arn));
6482
+ if (unaddressable.length > 0) {
6483
+ const message = mask(safeMsg`The recorded id segment(s) ${unaddressable.join(", ")} of ${logicalId} are not topic ARNs; ` + (listedTopics(previousProperties).length > 0 ? "the topics its previous Topics listed were checked instead." : "its previous Topics lists no topic ARN either, so a topic it was attached to may still carry its policy."));
6484
+ if (listedTopics(previousProperties).length > 0) this.logger.debug(message);
6485
+ else this.logger.warn(message);
6486
+ }
6487
+ const removed = [...dropped.filter((arn) => isSnsTopicArn(arn)), ...listedOnly];
6477
6488
  try {
6478
6489
  for (const topicArn of topics) await this.setTopicPolicy(topicArn, policyDoc);
6490
+ for (const topicArn of removed) await this.resetTopicPolicy(topicArn, resourceType, logicalId, context?.expectedRegion, "not-found", mask);
6479
6491
  this.logger.debug(`Successfully updated SNS topic policy ${logicalId}`);
6480
6492
  return {
6481
6493
  physicalId: topics.join(","),
@@ -6483,28 +6495,77 @@ var SNSTopicPolicyProvider = class {
6483
6495
  attributes: {}
6484
6496
  };
6485
6497
  } catch (error) {
6498
+ if (error instanceof ProvisioningError) throw error;
6486
6499
  const cause = error instanceof Error ? error : void 0;
6487
6500
  throw new ProvisioningError(`Failed to update SNS topic policy ${logicalId}: ${error instanceof Error ? error.message : String(error)}`, resourceType, logicalId, physicalId, cause);
6488
6501
  }
6489
6502
  }
6490
- async delete(logicalId, physicalId, resourceType, _properties, context) {
6503
+ async delete(logicalId, physicalId, resourceType, properties, context) {
6491
6504
  this.logger.debug(`Deleting SNS topic policy ${logicalId}: ${physicalId}`);
6492
- const topicArns = physicalId.split(",");
6505
+ const named = splitTopicArns(physicalId);
6506
+ if (named.length === 0) throw markNonRetryable(new ProvisioningError(`Failed to delete SNS topic policy ${logicalId}: its physical id is empty, so cdkd changed no topic. Set each topic the policy is attached to back to its default policy by hand, then drop the record with ${stateOrphanRecordRemedy(context, logicalId)}.`, resourceType, logicalId, physicalId));
6507
+ const topicArns = named.every((arn) => isSnsTopicArn(arn)) ? named : [.../* @__PURE__ */ new Set([...named.filter((arn) => isSnsTopicArn(arn)), ...listedTopics(properties ?? {})])];
6508
+ if (topicArns.length === 0) throw markNonRetryable(new ProvisioningError(`Failed to delete SNS topic policy ${logicalId}: its physical id names no SNS topic ARN and its Topics lists none either, so cdkd changed no topic. Set each topic the policy is attached to back to its default policy by hand, then drop the record with ${stateOrphanRecordRemedy(context, logicalId)}.`, resourceType, logicalId, physicalId));
6493
6509
  for (const topicArn of topicArns) try {
6494
- await this.setTopicPolicy(topicArn, "");
6495
- this.logger.debug(`Removed policy from topic ${topicArn}`);
6510
+ await this.resetTopicPolicy(topicArn, resourceType, logicalId, context?.expectedRegion);
6496
6511
  } catch (error) {
6497
- if (error instanceof Error && (error.name === "NotFoundException" || error.name === "NotFound" || error.message.includes("not found") || error.message.includes("does not exist") || error.message.includes("Invalid parameter"))) {
6498
- const clientRegion = await getAwsClients().sns.config.region();
6499
- assertRegionMatch(clientRegion, context?.expectedRegion, resourceType, logicalId, topicArn);
6500
- this.logger.debug(`Topic ${topicArn} not found or policy already removed, skipping`);
6501
- continue;
6502
- }
6512
+ if (error instanceof ProvisioningError) throw error;
6503
6513
  const cause = error instanceof Error ? error : void 0;
6504
6514
  throw new ProvisioningError(`Failed to delete SNS topic policy ${logicalId}: ${error instanceof Error ? error.message : String(error)}`, resourceType, logicalId, physicalId, cause);
6505
6515
  }
6506
6516
  this.logger.debug(`Successfully deleted SNS topic policy ${logicalId}`);
6507
6517
  }
6518
+ async resetTopicPolicy(topicArn, resourceType, logicalId, expectedRegion, phase = "not-found", mask = (t) => t) {
6519
+ const defaultPolicy = defaultTopicPolicy(topicArn);
6520
+ if (defaultPolicy === void 0) throw new ProvisioningError(`Cannot remove SNS topic policy ${logicalId} from ${topicArn}: not an SNS topic ARN`, resourceType, logicalId, topicArn);
6521
+ try {
6522
+ await this.setTopicPolicy(topicArn, defaultPolicy);
6523
+ this.logger.debug(mask(safeMsg`Reset the policy of topic ${topicArn} to the default`));
6524
+ } catch (error) {
6525
+ const name = error?.name;
6526
+ if (name === "NotFoundException" || name === "NotFound") {
6527
+ const clientRegion = await getAwsClients().sns.config.region();
6528
+ assertRegionMatch(clientRegion, expectedRegion, resourceType, logicalId, topicArn, phase);
6529
+ this.logger.debug(mask(safeMsg`Topic ${topicArn} not found, skipping policy removal`));
6530
+ return;
6531
+ }
6532
+ throw error;
6533
+ }
6534
+ }
6535
+ async topicsCarryingDocument(candidates, document, logicalId, mask) {
6536
+ if (candidates.length === 0) return [];
6537
+ let reference;
6538
+ if (typeof document === "string" && document.length > 0) reference = canonicalPolicy(document);
6539
+ else if (document !== null && typeof document === "object") reference = canonicalJson$1(document);
6540
+ if (reference === void 0) {
6541
+ this.logger.warn(mask(safeMsg`The topics ${candidates.join(", ")} listed by ${logicalId} were not checked (no policy document recorded to compare with) and may still carry its policy.`));
6542
+ return [];
6543
+ }
6544
+ const carrying = [];
6545
+ for (const topicArn of candidates) {
6546
+ const current = await this.readPolicyForWidening(topicArn);
6547
+ if (current.kind === "policy" && canonicalPolicy(current.policy) === reference) carrying.push(topicArn);
6548
+ else if (current.kind === "unreadable") this.logger.warn(mask(safeMsg`Could not read the policy of topic ${topicArn} (${current.reason}), so it is not reset: it may still carry the policy of ${logicalId}.`));
6549
+ else this.logger.debug(mask(safeMsg`Topic ${topicArn} does not carry the policy of ${logicalId}; left as is`));
6550
+ }
6551
+ return carrying;
6552
+ }
6553
+ async readPolicyForWidening(topicArn) {
6554
+ try {
6555
+ const policy = (await getAwsClients().sns.send(new GetTopicAttributesCommand({ TopicArn: topicArn }))).Attributes?.["Policy"];
6556
+ return policy ? {
6557
+ kind: "policy",
6558
+ policy
6559
+ } : { kind: "none" };
6560
+ } catch (err) {
6561
+ const name = err.name;
6562
+ if (name === "NotFoundException" || name === "NotFound") return { kind: "none" };
6563
+ return {
6564
+ kind: "unreadable",
6565
+ reason: name ?? "error"
6566
+ };
6567
+ }
6568
+ }
6508
6569
  async readCurrentState(physicalId, _logicalId, _resourceType) {
6509
6570
  const topics = physicalId.split(",").filter((t) => t.length > 0);
6510
6571
  if (topics.length === 0) return void 0;
@@ -6557,6 +6618,60 @@ function isSnsTopicArnList(value) {
6557
6618
  if (segments.length === 0) return false;
6558
6619
  return segments.every((s) => isSnsTopicArn(s));
6559
6620
  }
6621
+ function splitTopicArns(physicalId) {
6622
+ return physicalId.split(",").filter((arn) => arn.length > 0);
6623
+ }
6624
+ function listedTopics(bag) {
6625
+ const listed = bag["Topics"];
6626
+ if (!Array.isArray(listed)) return [];
6627
+ const out = [];
6628
+ for (const entry of listed) if (typeof entry === "string" && isSnsTopicArn(entry) && !out.includes(entry)) out.push(entry);
6629
+ return out;
6630
+ }
6631
+ function defaultTopicPolicy(topicArn) {
6632
+ if (!isSnsTopicArn(topicArn)) return void 0;
6633
+ const account = topicArn.split(":")[4];
6634
+ return JSON.stringify({
6635
+ Version: "2008-10-17",
6636
+ Id: "__default_policy_ID",
6637
+ Statement: [{
6638
+ Sid: "__default_statement_ID",
6639
+ Effect: "Allow",
6640
+ Principal: { AWS: "*" },
6641
+ Action: [
6642
+ "SNS:GetTopicAttributes",
6643
+ "SNS:SetTopicAttributes",
6644
+ "SNS:AddPermission",
6645
+ "SNS:RemovePermission",
6646
+ "SNS:DeleteTopic",
6647
+ "SNS:Subscribe",
6648
+ "SNS:ListSubscriptionsByTopic",
6649
+ "SNS:Publish"
6650
+ ],
6651
+ Resource: topicArn,
6652
+ Condition: { StringEquals: { "AWS:SourceOwner": account } }
6653
+ }]
6654
+ });
6655
+ }
6656
+ function canonicalJson$1(value) {
6657
+ const sortKeys = (v) => {
6658
+ if (Array.isArray(v)) return v.map(sortKeys);
6659
+ if (v !== null && typeof v === "object") {
6660
+ const out = Object.create(null);
6661
+ for (const key of Object.keys(v).sort()) out[key] = sortKeys(v[key]);
6662
+ return out;
6663
+ }
6664
+ return v;
6665
+ };
6666
+ return JSON.stringify(sortKeys(value));
6667
+ }
6668
+ function canonicalPolicy(text) {
6669
+ try {
6670
+ return canonicalJson$1(JSON.parse(text));
6671
+ } catch {
6672
+ return `raw:${text}`;
6673
+ }
6674
+ }
6560
6675
 
6561
6676
  //#endregion
6562
6677
  //#region src/provisioning/providers/lambda-function-provider.ts
@@ -43240,4 +43355,4 @@ var ACMCertificateProvider = class {
43240
43355
 
43241
43356
  //#endregion
43242
43357
  export { ACMCertificateProvider, ASGProvider, AgentCoreBrowserProvider, AgentCoreCodeInterpreterProvider, AgentCoreEvaluatorProvider, AgentCoreRuntimeProvider, ApiGatewayProvider, ApiGatewayV2Provider, AppSyncProvider, BudgetsBudgetProvider, CloudFrontDistributionProvider, CloudFrontOACProvider, CloudFrontOAIProvider, CloudTrailProvider, CloudWatchAlarmProvider, CloudWatchAnomalyDetectorProvider, CodeBuildProvider, CodeCommitRepositoryProvider, CognitoUserPoolProvider, DLMLifecyclePolicyProvider, DocDBProvider, DocDBSubnetGroupProvider, DynamoDBGlobalTableProvider, DynamoDBTableProvider, EC2Provider, ECRProvider, ECSProvider, EFSProvider, ELBv2Provider, EMRClusterProvider, EMRInstanceFleetConfigProvider, EMRInstanceGroupConfigProvider, ElastiCacheProvider, EventBridgeBusProvider, EventBridgeRuleProvider, FSxFileSystemProvider, FirehoseProvider, GlueConnectionProvider, GlueCrawlerProvider, GlueJobProvider, GlueProvider, GlueSecurityConfigurationProvider, GlueTriggerProvider, GlueWorkflowProvider, IAMAccessKeyProvider, IAMInstanceProfileProvider, IAMManagedPolicyProvider, IAMPolicyProvider, IAMRoleProvider, IAMUserGroupProvider, KMSProvider, KinesisStreamConsumerProvider, KinesisStreamProvider, LambdaEventInvokeConfigProvider, LambdaEventSourceMappingProvider, LambdaFunctionProvider, LambdaLayerVersionProvider, LambdaMicrovmImageProvider, LambdaPermissionProvider, LambdaUrlProvider, LogsLogGroupProvider, NeptuneProvider, NestedStackProvider, PipesPipeProvider, RDSDBProxyEndpointProvider, RDSDBProxyProvider, RDSDBProxyTargetGroupProvider, RDSProvider, Route53Provider, S3BucketPolicyProvider, S3BucketProvider, S3DirectoryBucketProvider, S3TablesProvider, S3VectorsProvider, SNSSubscriptionProvider, SNSTopicPolicyProvider, SNSTopicProvider, SQSQueuePolicyProvider, SQSQueueProvider, SSMParameterProvider, SchedulerScheduleProvider, SecretsManagerSecretProvider, ServiceDiscoveryProvider, StepFunctionsProvider, WAFv2WebACLProvider, WaitConditionHandleProvider };
43243
- //# sourceMappingURL=provider-classes-CtsCylnp.js.map
43358
+ //# sourceMappingURL=provider-classes-Ca6o5by0.js.map