cdk-real-drift 0.5.2 → 0.5.4
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.
- package/dist/cli.js +193 -34
- package/dist/cli.js.map +1 -1
- package/package.json +2 -1
package/dist/cli.js
CHANGED
|
@@ -9,6 +9,7 @@ import { homedir } from "node:os";
|
|
|
9
9
|
import { BaseCredentials, CdkAppMultiContext, NonInteractiveIoHost, StackSelectionStrategy, Toolkit } from "@aws-cdk/toolkit-lib";
|
|
10
10
|
import { CloudFormationClient, DescribeStackResourcesCommand, DescribeStacksCommand, DescribeTypeCommand, GetTemplateCommand, ListExportsCommand, ListStackResourcesCommand } from "@aws-sdk/client-cloudformation";
|
|
11
11
|
import jsonata from "jsonata";
|
|
12
|
+
import { createCredentialChain, fromEnv, fromNodeProviderChain } from "@aws-sdk/credential-providers";
|
|
12
13
|
import { KMSClient, ListAliasesCommand } from "@aws-sdk/client-kms";
|
|
13
14
|
import { APIGatewayClient, GetAuthorizersCommand, GetGatewayResponsesCommand, GetModelsCommand, GetRequestValidatorsCommand, GetResourcesCommand, GetStagesCommand, UpdateIntegrationCommand, UpdateIntegrationResponseCommand, UpdateMethodResponseCommand, UpdateRestApiCommand } from "@aws-sdk/client-api-gateway";
|
|
14
15
|
import { AppConfigClient, ListConfigurationProfilesCommand, ListEnvironmentsCommand } from "@aws-sdk/client-appconfig";
|
|
@@ -409,6 +410,7 @@ function parseCommonArgs(args, verb) {
|
|
|
409
410
|
"--undeclared-only"
|
|
410
411
|
].filter(has);
|
|
411
412
|
if (scopes.length > 1) throw new Error(`${scopes.join(" and ")} are mutually exclusive — see cdkrd --help`);
|
|
413
|
+
if (values["--profile"] !== void 0) process.env.CDKRD_EXPLICIT_PROFILE = "1";
|
|
412
414
|
return {
|
|
413
415
|
stackNames,
|
|
414
416
|
all: has("--all"),
|
|
@@ -3281,7 +3283,13 @@ function normalizeWafByteMatchDeep(value) {
|
|
|
3281
3283
|
if (Array.isArray(value)) return value.map(normalizeWafByteMatchDeep);
|
|
3282
3284
|
if (value === null || typeof value !== "object") return value;
|
|
3283
3285
|
const out = {};
|
|
3284
|
-
for (const [k, v] of Object.entries(value))
|
|
3286
|
+
for (const [k, v] of Object.entries(value)) {
|
|
3287
|
+
if ((k === "SingleHeader" || k === "SingleQueryArgument") && v !== null && typeof v === "object" && !Array.isArray(v)) {
|
|
3288
|
+
out[k] = canonicalizeWafFieldNameSelector(v);
|
|
3289
|
+
continue;
|
|
3290
|
+
}
|
|
3291
|
+
out[k] = normalizeWafByteMatchDeep(v);
|
|
3292
|
+
}
|
|
3285
3293
|
const b64 = out.SearchStringBase64;
|
|
3286
3294
|
if (typeof b64 === "string") {
|
|
3287
3295
|
const plain = out.SearchString;
|
|
@@ -3297,6 +3305,12 @@ function normalizeWafByteMatchDeep(value) {
|
|
|
3297
3305
|
}
|
|
3298
3306
|
return out;
|
|
3299
3307
|
}
|
|
3308
|
+
function canonicalizeWafFieldNameSelector(obj) {
|
|
3309
|
+
const out = {};
|
|
3310
|
+
for (const [k, v] of Object.entries(obj)) if (k === "name" || k === "Name") out.Name = typeof v === "string" ? v.toLowerCase() : v;
|
|
3311
|
+
else out[k] = normalizeWafByteMatchDeep(v);
|
|
3312
|
+
return out;
|
|
3313
|
+
}
|
|
3300
3314
|
const SSH_PUBLIC_KEY_PATHS = { "AWS::EC2::KeyPair": new Set(["PublicKeyMaterial"]) };
|
|
3301
3315
|
function isSshPublicKeyEqual(a, b) {
|
|
3302
3316
|
if (typeof a !== "string" || typeof b !== "string") return false;
|
|
@@ -3944,6 +3958,19 @@ function deletedResourceInfo(physIds, template, stackName) {
|
|
|
3944
3958
|
const more = deleted.length > shown.length ? `, …(+${deleted.length - shown.length} more)` : "";
|
|
3945
3959
|
return `info: ${stackName}: ${deleted.length} deployed resource(s) absent from the local template — the next deploy will DELETE them: ${shown.join(", ")}${more}`;
|
|
3946
3960
|
}
|
|
3961
|
+
function typeChangedResources(templateResources, deployedTypeOf) {
|
|
3962
|
+
return Object.entries(templateResources).filter(([lid, res]) => {
|
|
3963
|
+
const declaredType = res?.Type;
|
|
3964
|
+
const deployedType = deployedTypeOf[lid];
|
|
3965
|
+
return typeof declaredType === "string" && typeof deployedType === "string" && declaredType !== deployedType;
|
|
3966
|
+
}).map(([lid]) => lid).sort();
|
|
3967
|
+
}
|
|
3968
|
+
function typeChangeReplaceInfo(changed, templateResources, deployedTypeOf, stackName) {
|
|
3969
|
+
if (changed.length === 0) return null;
|
|
3970
|
+
const shown = changed.slice(0, 10).map((lid) => `${lid} (${deployedTypeOf[lid]} -> ${templateResources[lid]?.Type})`);
|
|
3971
|
+
const more = changed.length > shown.length ? `, …(+${changed.length - shown.length} more)` : "";
|
|
3972
|
+
return `info: ${stackName}: ${changed.length} resource(s) changed Type at the same logical id — the next deploy will REPLACE them (old resource deleted, new created): ${shown.join(", ")}${more}`;
|
|
3973
|
+
}
|
|
3947
3974
|
function partitionForRegion(region) {
|
|
3948
3975
|
if (region.startsWith("us-gov-")) return {
|
|
3949
3976
|
partition: "aws-us-gov",
|
|
@@ -3984,6 +4011,7 @@ function buildResolverContext(template, stackParams, physIds, region, accountId,
|
|
|
3984
4011
|
const params = {};
|
|
3985
4012
|
for (const [k, def] of Object.entries(paramDefs)) {
|
|
3986
4013
|
if (def?.NoEcho === true || def?.NoEcho === "true") continue;
|
|
4014
|
+
if ((def?.Type ?? "").includes("::Parameter::Value<")) continue;
|
|
3987
4015
|
if (def && "Default" in def) params[k] = toParam(k, String(def.Default));
|
|
3988
4016
|
}
|
|
3989
4017
|
for (const [k, v] of Object.entries(stackParams)) params[k] = toParam(k, v);
|
|
@@ -4051,16 +4079,13 @@ async function listStackResources(client, stackName) {
|
|
|
4051
4079
|
};
|
|
4052
4080
|
}
|
|
4053
4081
|
async function loadDesired(client, stackName, region, templateOverride, recoveryTemplate) {
|
|
4054
|
-
const [tmplRes, stkRes, { physIds }] = await Promise.all([
|
|
4082
|
+
const [tmplRes, stkRes, { physIds, typeOf: deployedTypeOf }] = await Promise.all([
|
|
4055
4083
|
templateOverride ? Promise.resolve({ TemplateBody: void 0 }) : client.send(new GetTemplateCommand({ StackName: stackName })),
|
|
4056
4084
|
client.send(new DescribeStacksCommand({ StackName: stackName })),
|
|
4057
4085
|
listStackResources(client, stackName)
|
|
4058
4086
|
]);
|
|
4059
4087
|
const stack = stkRes.Stacks?.[0];
|
|
4060
|
-
const stateClass =
|
|
4061
|
-
kind: "ok",
|
|
4062
|
-
message: ""
|
|
4063
|
-
} : classifyStackStatus(stack?.StackStatus);
|
|
4088
|
+
const stateClass = classifyStackStatus(stack?.StackStatus);
|
|
4064
4089
|
if (stateClass.kind === "skip") throw new StackNotCheckableError(stateClass.message);
|
|
4065
4090
|
const stackStatusWarning = stateClass.kind === "warn" ? stateClass.message : void 0;
|
|
4066
4091
|
const template = templateOverride ?? parseTemplateBody(tmplRes.TemplateBody ?? "{}");
|
|
@@ -4079,6 +4104,12 @@ async function loadDesired(client, stackName, region, templateOverride, recovery
|
|
|
4079
4104
|
const deletedInfo = deletedResourceInfo(physIds, template, stackName);
|
|
4080
4105
|
if (deletedInfo) console.error(deletedInfo);
|
|
4081
4106
|
}
|
|
4107
|
+
const templateResourcesForTypeCheck = template.Resources ?? {};
|
|
4108
|
+
const typeChanged = new Set(typeChangedResources(templateResourcesForTypeCheck, deployedTypeOf));
|
|
4109
|
+
if (templateOverride && typeChanged.size > 0) {
|
|
4110
|
+
const replaceInfo = typeChangeReplaceInfo([...typeChanged].sort(), templateResourcesForTypeCheck, deployedTypeOf, stackName);
|
|
4111
|
+
if (replaceInfo) console.error(replaceInfo);
|
|
4112
|
+
}
|
|
4082
4113
|
const ctx = buildResolverContext(template, stackParams, physIds, region, accountId, stackName, stackId);
|
|
4083
4114
|
const notificationArns = stack?.NotificationARNs ?? [];
|
|
4084
4115
|
if (notificationArns.length > 0) ctx.params["AWS::NotificationARNs"] = notificationArns;
|
|
@@ -4098,10 +4129,11 @@ async function loadDesired(client, stackName, region, templateOverride, recovery
|
|
|
4098
4129
|
}
|
|
4099
4130
|
const cdkPath = res.Metadata?.["aws:cdk:path"];
|
|
4100
4131
|
const declaredRaw = res.Properties ?? {};
|
|
4132
|
+
const physicalId = typeChanged.has(logicalId) ? void 0 : physIds[logicalId];
|
|
4101
4133
|
resources.push({
|
|
4102
4134
|
logicalId,
|
|
4103
4135
|
resourceType: res.Type,
|
|
4104
|
-
physicalId
|
|
4136
|
+
physicalId,
|
|
4105
4137
|
constructPath: typeof cdkPath === "string" ? prettyConstructPath(cdkPath) : void 0,
|
|
4106
4138
|
declared: resolveProperties(declaredRaw, ctx),
|
|
4107
4139
|
declaredRaw,
|
|
@@ -4495,7 +4527,7 @@ function normWalk(v, freeForm) {
|
|
|
4495
4527
|
function canonicalizeForCompare(v, resourceType) {
|
|
4496
4528
|
const orderSig = resourceType ? ORDER_SIGNIFICANT_ARRAY_KEYS[resourceType] : void 0;
|
|
4497
4529
|
const base = canonicalizeIdArraysDeep(canonicalizeTagListsDeep(normalizePoliciesDeep(v), orderSig));
|
|
4498
|
-
return resourceType === "AWS::WAFv2::WebACL" ? normalizeWafByteMatchDeep(base) : base;
|
|
4530
|
+
return resourceType === "AWS::WAFv2::WebACL" || resourceType === "AWS::WAFv2::RuleGroup" ? normalizeWafByteMatchDeep(base) : base;
|
|
4499
4531
|
}
|
|
4500
4532
|
|
|
4501
4533
|
//#endregion
|
|
@@ -5163,7 +5195,7 @@ function classifyResource(resource, liveRaw, schema, opts = {}) {
|
|
|
5163
5195
|
"EndpointConfiguration.IpAddressType": "dualstack"
|
|
5164
5196
|
};
|
|
5165
5197
|
}
|
|
5166
|
-
if (physicalId && opts.accountId !== void 0 && declared["Policy"]) {
|
|
5198
|
+
if (physicalId && opts.accountId !== void 0 && declared["Policy"] && declared["Policy"] !== UNRESOLVED && !hasUnresolved(declared["Policy"])) {
|
|
5167
5199
|
const arnPrefix = `arn:${opts.region !== void 0 ? partitionForRegion(opts.region).partition : "aws"}:execute-api:${opts.region ?? ""}:${opts.accountId}:${physicalId}`;
|
|
5168
5200
|
declared["Policy"] = canonicalizePolicy(expandExecuteApiResources(declared["Policy"], arnPrefix));
|
|
5169
5201
|
}
|
|
@@ -5795,11 +5827,22 @@ function classifyResource(resource, liveRaw, schema, opts = {}) {
|
|
|
5795
5827
|
|
|
5796
5828
|
//#endregion
|
|
5797
5829
|
//#region src/read/client-config.ts
|
|
5798
|
-
|
|
5799
|
-
|
|
5800
|
-
|
|
5801
|
-
|
|
5802
|
-
|
|
5830
|
+
/** Port of toolkit-lib awscli-compatible `shouldPrioritizeEnv()` (env creds win over profile). */
|
|
5831
|
+
function shouldPrioritizeEnv() {
|
|
5832
|
+
if (process.env.CDKRD_EXPLICIT_PROFILE) return false;
|
|
5833
|
+
const id = process.env.AWS_ACCESS_KEY_ID || process.env.AMAZON_ACCESS_KEY_ID;
|
|
5834
|
+
const key = process.env.AWS_SECRET_ACCESS_KEY || process.env.AMAZON_SECRET_ACCESS_KEY;
|
|
5835
|
+
return !!id && !!key;
|
|
5836
|
+
}
|
|
5837
|
+
const CLIENT_CREDENTIALS = (awsIdentityProperties) => (shouldPrioritizeEnv() ? createCredentialChain(fromEnv(), fromNodeProviderChain()) : fromNodeProviderChain())(awsIdentityProperties);
|
|
5838
|
+
const CLIENT_TIMEOUTS = {
|
|
5839
|
+
credentials: CLIENT_CREDENTIALS,
|
|
5840
|
+
requestHandler: {
|
|
5841
|
+
connectionTimeout: 6e3,
|
|
5842
|
+
requestTimeout: 6e4,
|
|
5843
|
+
throwOnRequestTimeout: true
|
|
5844
|
+
}
|
|
5845
|
+
};
|
|
5803
5846
|
const READ_RETRY = {
|
|
5804
5847
|
maxAttempts: 10,
|
|
5805
5848
|
retryMode: "adaptive",
|
|
@@ -9906,11 +9949,12 @@ function restoreSupplementReadGaps(resourceType, declared, live, error) {
|
|
|
9906
9949
|
const exempt = OVERRIDE_READABLE_WRITEONLY[resourceType];
|
|
9907
9950
|
const restored = [];
|
|
9908
9951
|
for (const path of exempt ?? []) if (path in declared && !(path in live)) {
|
|
9909
|
-
|
|
9952
|
+
const value = declared[path];
|
|
9953
|
+
if (Array.isArray(value) && value.length > 0 || value !== null && typeof value === "object" && Object.keys(value).length > 0) live[path] = value;
|
|
9910
9954
|
restored.push(path);
|
|
9911
9955
|
}
|
|
9912
9956
|
const call = error?.name || "unknown error";
|
|
9913
|
-
const gap = restored.length ? ` — treating ${restored.join(", ")} as an unverifiable read-gap (
|
|
9957
|
+
const gap = restored.length ? ` — treating ${restored.join(", ")} as an unverifiable read-gap (grant the missing read permission to detect out-of-band drift on it)` : "";
|
|
9914
9958
|
process.stderr.write(`[cdkrd] warning: supplement read for ${resourceType} failed (${call})${gap}\n`);
|
|
9915
9959
|
}
|
|
9916
9960
|
async function readLive(cc, resource, region, accountId) {
|
|
@@ -10657,7 +10701,12 @@ function carryForwardUnreadable(recorded, existing, findings) {
|
|
|
10657
10701
|
const unreadable = new Set(findings.filter((f) => f.tier === "skipped" || f.modelReadFailed).map((f) => f.logicalId));
|
|
10658
10702
|
if (unreadable.size === 0) return recorded;
|
|
10659
10703
|
const present = new Set(recorded.map(recordedKey));
|
|
10660
|
-
const
|
|
10704
|
+
const isUnread = (e) => {
|
|
10705
|
+
if (unreadable.has(e.logicalId)) return true;
|
|
10706
|
+
const parent = addedChildParentLogicalId(e.logicalId);
|
|
10707
|
+
return parent !== void 0 && unreadable.has(parent);
|
|
10708
|
+
};
|
|
10709
|
+
const preserved = prior.filter((e) => isUnread(e) && !present.has(recordedKey(e)));
|
|
10661
10710
|
return preserved.length === 0 ? recorded : [...recorded, ...preserved];
|
|
10662
10711
|
}
|
|
10663
10712
|
/**
|
|
@@ -10861,6 +10910,10 @@ function selectRecorded(findings, selectedKeys) {
|
|
|
10861
10910
|
function pathSegments$1(path) {
|
|
10862
10911
|
return path.replace(/\[([^\]]*)\]/g, ".$1").split(".").filter((s) => s.length > 0);
|
|
10863
10912
|
}
|
|
10913
|
+
function addedChildParentLogicalId(logicalId) {
|
|
10914
|
+
const slash = logicalId.indexOf("/");
|
|
10915
|
+
return slash < 0 ? void 0 : logicalId.slice(0, slash);
|
|
10916
|
+
}
|
|
10864
10917
|
function descendDeclared(node, seg) {
|
|
10865
10918
|
if (node === null || typeof node !== "object") return void 0;
|
|
10866
10919
|
if (Array.isArray(node)) {
|
|
@@ -10979,6 +11032,8 @@ function applyBaseline(findings, baseline, opts = {}) {
|
|
|
10979
11032
|
const currentPaths = new Set(findings.filter((f) => f.tier === "undeclared" || f.tier === "atDefault" || f.tier === "generated").map((f) => `${f.logicalId}.${f.path}`));
|
|
10980
11033
|
const skippedLogical = new Set(findings.filter((f) => f.tier === "skipped").map((f) => f.logicalId));
|
|
10981
11034
|
const deletedLogical = new Set(findings.filter((f) => f.tier === "deleted").map((f) => f.logicalId));
|
|
11035
|
+
const presentAddedLogical = new Set(findings.filter((f) => f.tier === "added").map((f) => f.logicalId));
|
|
11036
|
+
const readParentLogical = new Set(findings.filter((f) => f.tier !== "skipped" && f.tier !== "deleted").map((f) => f.logicalId));
|
|
10982
11037
|
const declaredDriftByLogical = /* @__PURE__ */ new Map();
|
|
10983
11038
|
for (const f of findings) {
|
|
10984
11039
|
if (f.tier !== "declared") continue;
|
|
@@ -10992,7 +11047,20 @@ function applyBaseline(findings, baseline, opts = {}) {
|
|
|
10992
11047
|
const replacedStale = [];
|
|
10993
11048
|
const typeMismatchStale = [];
|
|
10994
11049
|
for (const a of recorded) {
|
|
10995
|
-
if (a.path === "")
|
|
11050
|
+
if (a.path === "") {
|
|
11051
|
+
if (presentAddedLogical.has(a.logicalId)) continue;
|
|
11052
|
+
const parent = addedChildParentLogicalId(a.logicalId);
|
|
11053
|
+
if (!(parent !== void 0 && readParentLogical.has(parent))) continue;
|
|
11054
|
+
kept.push({
|
|
11055
|
+
tier: "deleted",
|
|
11056
|
+
logicalId: a.logicalId,
|
|
11057
|
+
resourceType: a.resourceType,
|
|
11058
|
+
...opts.constructPathByLogical?.get(a.logicalId) !== void 0 && { constructPath: opts.constructPathByLogical.get(a.logicalId) },
|
|
11059
|
+
path: "",
|
|
11060
|
+
note: "recorded added resource removed since record"
|
|
11061
|
+
});
|
|
11062
|
+
continue;
|
|
11063
|
+
}
|
|
10996
11064
|
if (isTypeVoid(a)) {
|
|
10997
11065
|
typeMismatchStale.push(`${a.logicalId}.${a.path}`);
|
|
10998
11066
|
continue;
|
|
@@ -12897,6 +12965,38 @@ function reindexNestedPointer(pointer, live, resourceType) {
|
|
|
12897
12965
|
}
|
|
12898
12966
|
return `/${out.join("/")}`;
|
|
12899
12967
|
}
|
|
12968
|
+
const NESTED_POLL_INTERVAL_MS = 2e3;
|
|
12969
|
+
const NESTED_POLL_TIMEOUT_MS = 900 * 1e3;
|
|
12970
|
+
const NESTED_MAX_POLL_READ_FAILURES = 10;
|
|
12971
|
+
const nestedSleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
12972
|
+
async function pollNestedToCompletion(cc, first, poll = {}) {
|
|
12973
|
+
const doSleep = poll.sleep ?? nestedSleep;
|
|
12974
|
+
const clock = poll.now ?? Date.now;
|
|
12975
|
+
let event = first;
|
|
12976
|
+
const token = event?.RequestToken;
|
|
12977
|
+
if (!token) throw new Error("Cloud Control UpdateResource returned no request token");
|
|
12978
|
+
const deadline = clock() + NESTED_POLL_TIMEOUT_MS;
|
|
12979
|
+
let pollFailures = 0;
|
|
12980
|
+
while (clock() < deadline) {
|
|
12981
|
+
const status = event?.OperationStatus;
|
|
12982
|
+
if (status === "SUCCESS") return;
|
|
12983
|
+
if (status === "FAILED" || status === "CANCEL_COMPLETE") {
|
|
12984
|
+
const msg = event?.StatusMessage ?? status;
|
|
12985
|
+
const code = event?.ErrorCode;
|
|
12986
|
+
throw new Error(code && !msg.includes(code) ? `${code}: ${msg}` : msg);
|
|
12987
|
+
}
|
|
12988
|
+
await doSleep(NESTED_POLL_INTERVAL_MS);
|
|
12989
|
+
try {
|
|
12990
|
+
event = (await cc.send(new GetResourceRequestStatusCommand({ RequestToken: token }))).ProgressEvent;
|
|
12991
|
+
pollFailures = 0;
|
|
12992
|
+
} catch (e) {
|
|
12993
|
+
const text = errorText(e);
|
|
12994
|
+
if (!classifyTransient(text).transient) throw new Error(text);
|
|
12995
|
+
if (++pollFailures >= NESTED_MAX_POLL_READ_FAILURES) throw new Error(`unable to confirm Cloud Control request status after ${NESTED_MAX_POLL_READ_FAILURES} poll attempts`);
|
|
12996
|
+
}
|
|
12997
|
+
}
|
|
12998
|
+
throw new Error("timed out waiting for Cloud Control request");
|
|
12999
|
+
}
|
|
12900
13000
|
const writeCloudControlIndexNested = async (ctx, ops) => {
|
|
12901
13001
|
const type = ctx.resourceType;
|
|
12902
13002
|
if (!type) throw new Error("writeCloudControlIndexNested: resourceType missing on ctx");
|
|
@@ -12921,11 +13021,11 @@ const writeCloudControlIndexNested = async (ctx, ops) => {
|
|
|
12921
13021
|
value: op.value
|
|
12922
13022
|
};
|
|
12923
13023
|
});
|
|
12924
|
-
await cc.send(new UpdateResourceCommand({
|
|
13024
|
+
await pollNestedToCompletion(cc, (await cc.send(new UpdateResourceCommand({
|
|
12925
13025
|
TypeName: type,
|
|
12926
13026
|
Identifier: identifier,
|
|
12927
13027
|
PatchDocument: JSON.stringify(patch)
|
|
12928
|
-
}));
|
|
13028
|
+
}))).ProgressEvent);
|
|
12929
13029
|
};
|
|
12930
13030
|
const SDK_NESTED_WRITERS = {
|
|
12931
13031
|
"AWS::ApiGateway::Method": {
|
|
@@ -13328,6 +13428,7 @@ function buildRevertPlan(findings, baseline, opts = {}) {
|
|
|
13328
13428
|
if (item.kind !== "cc") continue;
|
|
13329
13429
|
const live = opts.liveByLogical.get(item.logicalId);
|
|
13330
13430
|
if (!live) continue;
|
|
13431
|
+
item.liveRaw = live;
|
|
13331
13432
|
const huskOps = nullHuskRemovalOps(live);
|
|
13332
13433
|
if (huskOps.length > 0) item.ops.unshift(...huskOps);
|
|
13333
13434
|
}
|
|
@@ -13504,27 +13605,62 @@ function rejectedEmptyStripOps(resourceType, ops, liveRaw) {
|
|
|
13504
13605
|
function hasArrayIndexSegment(pointer) {
|
|
13505
13606
|
return pointer.split("/").some((seg) => /^\d+$/.test(seg));
|
|
13506
13607
|
}
|
|
13608
|
+
const POINTER_ABSENT = Symbol("pointer-absent");
|
|
13609
|
+
function rawValueAtPointer(model, pointer) {
|
|
13610
|
+
let node = model;
|
|
13611
|
+
for (const rawSeg of pointer.split("/").slice(1)) {
|
|
13612
|
+
const seg = rawSeg.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
13613
|
+
if (Array.isArray(node)) {
|
|
13614
|
+
if (!/^\d+$/.test(seg)) return POINTER_ABSENT;
|
|
13615
|
+
const idx = Number(seg);
|
|
13616
|
+
if (idx >= node.length) return POINTER_ABSENT;
|
|
13617
|
+
node = node[idx];
|
|
13618
|
+
} else if (node !== null && typeof node === "object") {
|
|
13619
|
+
if (!Object.hasOwn(node, seg)) return POINTER_ABSENT;
|
|
13620
|
+
node = node[seg];
|
|
13621
|
+
} else return POINTER_ABSENT;
|
|
13622
|
+
}
|
|
13623
|
+
return node;
|
|
13624
|
+
}
|
|
13507
13625
|
/**
|
|
13508
13626
|
* Serialize a RevertItem's ops to an RFC6902 PatchDocument string for Cloud Control.
|
|
13509
13627
|
*
|
|
13510
13628
|
* #762: the Cloud Control path had no analogue of the SDK-writer guard (writers.ts
|
|
13511
13629
|
* `desiredModel` re-reads + re-canonicalizes the live model so an indexed op lands on the
|
|
13512
13630
|
* SAME element classify diffed). For an INDEX-BEARING pointer we emit a preceding RFC6902
|
|
13513
|
-
* `test` precondition asserting the addressed location still equals the value classify saw
|
|
13514
|
-
*
|
|
13515
|
-
*
|
|
13516
|
-
*
|
|
13517
|
-
*
|
|
13518
|
-
*
|
|
13631
|
+
* `test` precondition asserting the addressed location still equals the value classify saw.
|
|
13632
|
+
* Cloud Control accepts standard RFC6902 and evaluates `test` atomically before the mutation,
|
|
13633
|
+
* so a shifted index makes it REJECT the whole patch instead of writing the wrong element —
|
|
13634
|
+
* fail-closed, the same intent as the writer-path re-read. Scalar non-indexed pointers carry
|
|
13635
|
+
* no aliasing risk (a named property is stable regardless of array order), so they get NO
|
|
13636
|
+
* `test` op — the patch stays minimal.
|
|
13637
|
+
*
|
|
13638
|
+
* #853: the `test` value must come from the RAW live model, NOT `op.prior` (= the finding's
|
|
13639
|
+
* canonicalized `f.actual`). Findings are built from `normalizeLiveModel` output — aws:* tags
|
|
13640
|
+
* stripped, readOnly/writeOnly paths stripped, `canonicalizeIdArraysDeep` sorts sg-/subnet-id
|
|
13641
|
+
* arrays, policy documents canonicalized, WAF `SearchString` base64-decoded. Cloud Control,
|
|
13642
|
+
* however, evaluates `test` against its RAW resource model. Whenever normalization transformed
|
|
13643
|
+
* the value at (or under) the tested pointer, asserting the canonical value against the raw
|
|
13644
|
+
* model fails though nothing raced (LIVE-confirmed on AWS::ECR::RegistryPolicy: the Action
|
|
13645
|
+
* array is canonicalize-SORTED vs the raw model's append-last order) → the whole patch is
|
|
13646
|
+
* rejected → revert of genuine drift always fails. So resolve the test value from the raw
|
|
13647
|
+
* live model passed by the apply path (the same UN-stripped `liveByLogical` model the
|
|
13648
|
+
* tag-preserving / empty-husk-strip paths already use). Fall back to `op.prior` only when the
|
|
13649
|
+
* raw model is unavailable (offline / no gather) or the pointer does not resolve against it
|
|
13650
|
+
* (then the index has genuinely shifted and the guard should still fire and fail-close).
|
|
13519
13651
|
*/
|
|
13520
|
-
function toPatchDocument(item) {
|
|
13652
|
+
function toPatchDocument(item, liveRaw = item.liveRaw) {
|
|
13521
13653
|
const doc = [];
|
|
13522
13654
|
for (const { op, path, value, prior } of item.ops) {
|
|
13523
|
-
if (hasArrayIndexSegment(path) && prior !== void 0)
|
|
13524
|
-
|
|
13525
|
-
|
|
13526
|
-
|
|
13527
|
-
|
|
13655
|
+
if (hasArrayIndexSegment(path) && prior !== void 0) {
|
|
13656
|
+
const rawValue = liveRaw ? rawValueAtPointer(liveRaw, path) : POINTER_ABSENT;
|
|
13657
|
+
const testValue = rawValue === POINTER_ABSENT ? prior : rawValue;
|
|
13658
|
+
doc.push({
|
|
13659
|
+
op: "test",
|
|
13660
|
+
path,
|
|
13661
|
+
value: testValue
|
|
13662
|
+
});
|
|
13663
|
+
}
|
|
13528
13664
|
doc.push(op === "remove" ? {
|
|
13529
13665
|
op,
|
|
13530
13666
|
path
|
|
@@ -13549,6 +13685,11 @@ function isAlreadyGone(e) {
|
|
|
13549
13685
|
const m = (typeof o.message === "string" ? o.message : "").toLowerCase();
|
|
13550
13686
|
return m.includes("not found") || m.includes("does not exist") || m.includes("notfound");
|
|
13551
13687
|
}
|
|
13688
|
+
function isDependencyViolation(error) {
|
|
13689
|
+
if (!error) return false;
|
|
13690
|
+
return /DependencyViolation|dependent object|still (in use|referenced|being used|depends on|contains|has (a |an |dependent |associated ))|cannot (be )?delete[d]?[^.]*because[^.]*(referenced|in use|dependent|attached|associated|member|child)|is (still )?(referenced|attached|associated|in use)/i.test(error);
|
|
13691
|
+
}
|
|
13692
|
+
const DEP_VIOLATION_TERMINAL = "dependency-violation deferred to delete-batch pass loop";
|
|
13552
13693
|
const sleep$1 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
13553
13694
|
async function pollToCompletion(cc, first, poll = {}) {
|
|
13554
13695
|
const doSleep = poll.sleep ?? sleep$1;
|
|
@@ -13635,7 +13776,7 @@ async function applyRevertDeletes(deleteItems, applyOne) {
|
|
|
13635
13776
|
}));
|
|
13636
13777
|
}
|
|
13637
13778
|
async function applyRevertDelete(cc, item, identifier = item.physicalId, retry = {}) {
|
|
13638
|
-
|
|
13779
|
+
const oneDelete = async () => {
|
|
13639
13780
|
try {
|
|
13640
13781
|
const result = await pollToCompletion(cc, (await cc.send(new DeleteResourceCommand({
|
|
13641
13782
|
TypeName: item.resourceType,
|
|
@@ -13650,7 +13791,25 @@ async function applyRevertDelete(cc, item, identifier = item.physicalId, retry =
|
|
|
13650
13791
|
error: errorText(e)
|
|
13651
13792
|
};
|
|
13652
13793
|
}
|
|
13653
|
-
}
|
|
13794
|
+
};
|
|
13795
|
+
let deferredDepError;
|
|
13796
|
+
const guardedDelete = async () => {
|
|
13797
|
+
const r = await oneDelete();
|
|
13798
|
+
if (!r.ok && isDependencyViolation(r.error)) {
|
|
13799
|
+
deferredDepError = r.error;
|
|
13800
|
+
return {
|
|
13801
|
+
ok: false,
|
|
13802
|
+
error: DEP_VIOLATION_TERMINAL
|
|
13803
|
+
};
|
|
13804
|
+
}
|
|
13805
|
+
return r;
|
|
13806
|
+
};
|
|
13807
|
+
const r = await retryTransient(guardedDelete, retry);
|
|
13808
|
+
if (!r.ok && r.error === DEP_VIOLATION_TERMINAL) return {
|
|
13809
|
+
ok: false,
|
|
13810
|
+
error: deferredDepError ?? DEP_VIOLATION_TERMINAL
|
|
13811
|
+
};
|
|
13812
|
+
return r;
|
|
13654
13813
|
}
|
|
13655
13814
|
|
|
13656
13815
|
//#endregion
|