@cdkd/cli 0.363.0 → 0.365.0

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.
Files changed (61) hide show
  1. package/dist/{ambient-client-defaults-B0X_cHw6.js → ambient-client-defaults-AnEvWPy0.js} +4 -3
  2. package/dist/ambient-client-defaults-AnEvWPy0.js.map +1 -0
  3. package/dist/{asg-provider-DTR9KTuD.js → asg-provider-BzCU3XtA.js} +20 -13
  4. package/dist/{asg-provider-DTR9KTuD.js.map → asg-provider-BzCU3XtA.js.map} +1 -1
  5. package/dist/cli.js +3 -3
  6. package/dist/{custom-resource-runtime-D_FKAsKw.js → custom-resource-runtime-SB_NsQMH.js} +6 -6
  7. package/dist/{custom-resource-runtime-D_FKAsKw.js.map → custom-resource-runtime-SB_NsQMH.js.map} +1 -1
  8. package/dist/{db-associated-roles-CuhoLHiQ.js → db-associated-roles-D1wmFO_Y.js} +2 -2
  9. package/dist/{db-associated-roles-CuhoLHiQ.js.map → db-associated-roles-D1wmFO_Y.js.map} +1 -1
  10. package/dist/{delete-started-B-oT5k3k.js → delete-started-BJNrzLUk.js} +13 -9
  11. package/dist/delete-started-BJNrzLUk.js.map +1 -0
  12. package/dist/{deploy-engine-Df4iprdW.js → deploy-engine-BSqVfcSN.js} +893 -416
  13. package/dist/deploy-engine-BSqVfcSN.js.map +1 -0
  14. package/dist/{ec2-termination-protection-DPiykJlb.js → ec2-termination-protection-ekOvhSp9.js} +8 -6
  15. package/dist/ec2-termination-protection-ekOvhSp9.js.map +1 -0
  16. package/dist/{ecr-uri-DmQer3M1.js → ecr-uri-VpDi19pi.js} +2 -2
  17. package/dist/{ecr-uri-DmQer3M1.js.map → ecr-uri-VpDi19pi.js.map} +1 -1
  18. package/dist/{expected-bucket-owner-IZ5-Kowg.js → expected-bucket-owner-CmPtCsrQ.js} +2 -2
  19. package/dist/{expected-bucket-owner-IZ5-Kowg.js.map → expected-bucket-owner-CmPtCsrQ.js.map} +1 -1
  20. package/dist/{iam-role-provider-lpDjrxOC.js → iam-role-provider-Ct6UbKFo.js} +495 -42
  21. package/dist/iam-role-provider-Ct6UbKFo.js.map +1 -0
  22. package/dist/{image-plan-CjcTwOTQ.js → image-plan-gTOaUUbI.js} +8 -8
  23. package/dist/{image-plan-CjcTwOTQ.js.map → image-plan-gTOaUUbI.js.map} +1 -1
  24. package/dist/index.d.ts +4 -1
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +5 -5
  27. package/dist/{logger-BGwxRQKX.js → logger-IBUeRw1z.js} +2 -2
  28. package/dist/{logger-BGwxRQKX.js.map → logger-IBUeRw1z.js.map} +1 -1
  29. package/dist/{neptune-provider-DvqSeTAi.js → neptune-provider-QgaV_sKy.js} +14 -7
  30. package/dist/{neptune-provider-DvqSeTAi.js.map → neptune-provider-QgaV_sKy.js.map} +1 -1
  31. package/dist/{program-DYOdBiyw.js → program-tHhew1Z5.js} +262 -82
  32. package/dist/program-tHhew1Z5.js.map +1 -0
  33. package/dist/{provider-classes-DSmPsWi6.js → provider-classes-DTMnDVMz.js} +2225 -971
  34. package/dist/provider-classes-DTMnDVMz.js.map +1 -0
  35. package/dist/{rds-provider-Brs1PVkX.js → rds-provider-D2dkhl8m.js} +17 -10
  36. package/dist/rds-provider-D2dkhl8m.js.map +1 -0
  37. package/dist/{read-replica-Cnind5V_.js → read-replica-CfbVMoYV.js} +3 -3
  38. package/dist/{read-replica-Cnind5V_.js.map → read-replica-CfbVMoYV.js.map} +1 -1
  39. package/dist/{replacement-rules-D36vABVQ.js → replacement-rules-BiIOJMA-.js} +5 -4
  40. package/dist/{replacement-rules-D36vABVQ.js.map → replacement-rules-BiIOJMA-.js.map} +1 -1
  41. package/dist/{resource-deadline-vWMKeI6W.js → resource-deadline-BSpNiiNd.js} +34 -5
  42. package/dist/resource-deadline-BSpNiiNd.js.map +1 -0
  43. package/dist/{restore-source-guard-B4OUKYQG.js → restore-source-guard-Be6A_rNB.js} +4 -4
  44. package/dist/{restore-source-guard-B4OUKYQG.js.map → restore-source-guard-Be6A_rNB.js.map} +1 -1
  45. package/dist/{run-cli-DYcKa6BY.js → run-cli-BkrNHPD5.js} +2 -2
  46. package/dist/{run-cli-DYcKa6BY.js.map → run-cli-BkrNHPD5.js.map} +1 -1
  47. package/dist/{settle-own-write-members-CvwPYXi7.js → settle-own-write-members-BqAKt1e7.js} +13 -135
  48. package/dist/settle-own-write-members-BqAKt1e7.js.map +1 -0
  49. package/dist/{version-CBDLbnZ4.js → version-0AMFL2lR.js} +2 -2
  50. package/dist/{version-CBDLbnZ4.js.map → version-0AMFL2lR.js.map} +1 -1
  51. package/package.json +4 -4
  52. package/dist/ambient-client-defaults-B0X_cHw6.js.map +0 -1
  53. package/dist/delete-started-B-oT5k3k.js.map +0 -1
  54. package/dist/deploy-engine-Df4iprdW.js.map +0 -1
  55. package/dist/ec2-termination-protection-DPiykJlb.js.map +0 -1
  56. package/dist/iam-role-provider-lpDjrxOC.js.map +0 -1
  57. package/dist/program-DYOdBiyw.js.map +0 -1
  58. package/dist/provider-classes-DSmPsWi6.js.map +0 -1
  59. package/dist/rds-provider-Brs1PVkX.js.map +0 -1
  60. package/dist/resource-deadline-vWMKeI6W.js.map +0 -1
  61. package/dist/settle-own-write-members-CvwPYXi7.js.map +0 -1
@@ -1,13 +1,13 @@
1
- import { U as recordedGeneratedNameKept, V as generateResourceNameWithFallback, n as getLogger, p as safeStringify, u as describeAwsFailure } from "./logger-BGwxRQKX.js";
2
- import { Ba as OWN_WRITE_REREAD_DELAYS_MS, Ha as declaredMemberDocument, Ia as withoutSiblingAttachedArns, Na as collectManagedPolicyArnsAttachedBySiblings, Xa as warnUnsettledMember, qa as policyDocumentMatchesDeclared } from "./deploy-engine-Df4iprdW.js";
1
+ import { U as recordedGeneratedNameKept, V as generateResourceNameWithFallback, n as getLogger, p as safeStringify, u as describeAwsFailure } from "./logger-IBUeRw1z.js";
2
+ import { Fa as withoutSiblingAttachedArns, Ga as OWN_WRITE_REREAD_DELAYS_MS, Ma as collectManagedPolicyArnsAttachedBySiblings, Qa as policyDocumentMatchesDeclared, Va as verifiedIdentityCache, qa as declaredMemberDocument, to as warnUnsettledMember, za as getStackRecords } from "./deploy-engine-BSqVfcSN.js";
3
3
  import { r as getAwsClients } from "./aws-clients-DOkPjjAW.js";
4
- import { G as markRedactedCause, K as wrapMaskedAwsError, O as relayedNameCollision, U as isThrottlingError, W as markNonRetryable, _ as ResourceUpdateNotSupportedError, at as ProvisioningError, t as ambientClientDefaults, z as isTransientServerError } from "./ambient-client-defaults-B0X_cHw6.js";
5
- import { $t as markAuxiliaryFailure, A as assertRegionMatch, B as resolveExplicitPhysicalId, D as withoutServerErrorRetries, H as markNotGone, I as normalizeAwsTagsToCfn, Ut as maskerOrIdentity, Vt as isSecretDerivedValue, Wt as withDerivedNameMasks, Zt as isAuxiliaryFailure, en as markCreatedBeforeFailure, g as retractCreatedResource, h as reportedCreatedResource, k as RESOURCE_NOT_FOUND, l as withRemovalDefaults, m as reportCreatedResource, pt as pasteableAwsCommand, zt as createMaskedLogSinks } from "./resource-deadline-vWMKeI6W.js";
6
- import { c as planTagDiff, f as tagPlanWarning, h as definedAttributes, u as refuseMalformedDesiredTags } from "./restore-source-guard-B4OUKYQG.js";
7
- import { Ct as assertRecordedIdentity, St as RecordedIdentityMismatchError, r as markDeleteStarted, xt as RecordedIdentityError } from "./delete-started-B-oT5k3k.js";
8
- import { P as safeMsg } from "./version-CBDLbnZ4.js";
9
- import { a as principalOwnWriteMembers, o as settleOwnWriteMembers } from "./settle-own-write-members-CvwPYXi7.js";
10
- import { AttachRolePolicyCommand, CreateRoleCommand, DeleteRoleCommand, DeleteRolePermissionsBoundaryCommand, DeleteRolePolicyCommand, DetachRolePolicyCommand, GetRoleCommand, GetRolePolicyCommand, IAMClient, ListAttachedRolePoliciesCommand, ListInstanceProfilesForRoleCommand, ListRolePoliciesCommand, ListRoleTagsCommand, NoSuchEntityException, PutRolePermissionsBoundaryCommand, PutRolePolicyCommand, RemoveRoleFromInstanceProfileCommand, TagRoleCommand, UntagRoleCommand, UpdateAssumeRolePolicyCommand, UpdateRoleCommand } from "@aws-sdk/client-iam";
4
+ import { G as markRedactedCause, K as wrapMaskedAwsError, O as relayedNameCollision, U as isThrottlingError, W as markNonRetryable, _ as ResourceUpdateNotSupportedError, at as ProvisioningError, t as ambientClientDefaults, z as isTransientServerError } from "./ambient-client-defaults-AnEvWPy0.js";
5
+ import { $t as isAuxiliaryFailure, A as assertRegionMatch, Bt as stateOrphanRecordRemedy, D as withoutServerErrorRetries, Gt as maskerOrIdentity, Kt as withDerivedNameMasks, L as normalizeAwsTagsToCfn, U as markNotGone, Ut as isSecretDerivedValue, V as resolveExplicitPhysicalId, Vt as createMaskedLogSinks, bn as injectiveKey, g as retractCreatedResource, h as reportedCreatedResource, j as holderRefusalRun, k as RESOURCE_NOT_FOUND, l as withRemovalDefaults, m as reportCreatedResource, mt as pasteableAwsCommand, nn as markCreatedBeforeFailure, tn as markAuxiliaryFailure } from "./resource-deadline-BSpNiiNd.js";
6
+ import { c as planTagDiff, f as tagPlanWarning, h as definedAttributes, u as refuseMalformedDesiredTags } from "./restore-source-guard-Be6A_rNB.js";
7
+ import { Ct as RecordedIdentityMismatchError, Dt as reAdoptRemedy, Ot as recordedIdentityId, Pt as isUsableIdentityValue, St as RecordedIdentityError, _t as isPermissionDenial, r as markDeleteStarted, wt as assertRecordedIdentity } from "./delete-started-BJNrzLUk.js";
8
+ import { P as safeMsg } from "./version-0AMFL2lR.js";
9
+ import { a as principalOwnWriteMembers, o as settleOwnWriteMembers } from "./settle-own-write-members-BqAKt1e7.js";
10
+ import { AttachRolePolicyCommand, CreateRoleCommand, DeleteConflictException, DeleteRoleCommand, DeleteRolePermissionsBoundaryCommand, DeleteRolePolicyCommand, DetachRolePolicyCommand, GetGroupCommand, GetInstanceProfileCommand, GetRoleCommand, GetRolePolicyCommand, GetUserCommand, IAMClient, ListAttachedRolePoliciesCommand, ListInstanceProfilesForRoleCommand, ListRolePoliciesCommand, ListRoleTagsCommand, NoSuchEntityException, PutRolePermissionsBoundaryCommand, PutRolePolicyCommand, RemoveRoleFromInstanceProfileCommand, TagRoleCommand, UntagRoleCommand, UpdateAssumeRolePolicyCommand, UpdateRoleCommand } from "@aws-sdk/client-iam";
11
11
 
12
12
  // src/provisioning/providers/iam-create-client.ts
13
13
  var IamCreateClientCache = class {
@@ -173,6 +173,315 @@ async function create(logicalId, resourceType, properties, context) {
173
173
  }
174
174
  }
175
175
 
176
+ // src/provisioning/providers/iam-policy/principal-identity.ts
177
+ const PRINCIPAL_SPECS = {
178
+ role: {
179
+ resourceType: "AWS::IAM::Role",
180
+ label: "IAM role",
181
+ attribute: "RoleId",
182
+ permission: "iam:GetRole",
183
+ read: async (client, name) => (await client.send(new GetRoleCommand({ RoleName: name }))).Role?.RoleId
184
+ },
185
+ group: {
186
+ resourceType: "AWS::IAM::Group",
187
+ label: "IAM group",
188
+ attribute: "GroupId",
189
+ permission: "iam:GetGroup",
190
+ read: async (client, name) => (await client.send(new GetGroupCommand({
191
+ GroupName: name,
192
+ MaxItems: 1
193
+ }))).Group?.GroupId
194
+ },
195
+ user: {
196
+ resourceType: "AWS::IAM::User",
197
+ label: "IAM user",
198
+ attribute: "UserId",
199
+ permission: "iam:GetUser",
200
+ read: async (client, name) => (await client.send(new GetUserCommand({ UserName: name }))).User?.UserId
201
+ }
202
+ };
203
+ const INLINE_POLICY_OWNER = {
204
+ label: "IAM policy",
205
+ resourceType: "AWS::IAM::Policy"
206
+ };
207
+ const MANAGED_POLICY_OWNER = {
208
+ label: "IAM managed policy",
209
+ resourceType: "AWS::IAM::ManagedPolicy"
210
+ };
211
+ function inStackRecordedIds(kind, name, skipFresh) {
212
+ const view = getStackRecords();
213
+ if (view === void 0) return void 0;
214
+ const { resourceType } = PRINCIPAL_SPECS[kind];
215
+ let found;
216
+ let allFresh = true;
217
+ for (const [logicalId, record] of view.live()) {
218
+ if (record.resourceType !== resourceType || typeof record.physicalId !== "string" || record.physicalId.toLowerCase() !== name.toLowerCase()) continue;
219
+ const recorded = recordedIdentityId(resourceType, { recordedAttributes: record.attributes });
220
+ if (recorded === void 0) continue;
221
+ if (!(skipFresh && view.writtenFreshThisRun?.(logicalId) === true)) allFresh = false;
222
+ if (found === void 0) found = {
223
+ logicalId,
224
+ key: recorded.key,
225
+ values: []
226
+ };
227
+ if (!found.values.includes(recorded.value)) found.values.push(recorded.value);
228
+ }
229
+ return found === void 0 || allFresh ? void 0 : found;
230
+ }
231
+ async function verifyInlinePolicyPrincipal(params) {
232
+ const { client, kind, name, policyLogicalId, physicalId, operation } = params;
233
+ const owner = params.owner ?? INLINE_POLICY_OWNER;
234
+ const recorded = inStackRecordedIds(kind, name, operation === "attach");
235
+ if (recorded === void 0) return { kind: "unchecked" };
236
+ const spec = PRINCIPAL_SPECS[kind];
237
+ const value = recorded.values[0];
238
+ const read = async () => {
239
+ const id = await spec.read(client, name);
240
+ return id !== void 0 && recorded.values.includes(id) ? value : id;
241
+ };
242
+ const cache = verifiedIdentityCache(getStackRecords());
243
+ const cacheKey = injectiveKey(spec.resourceType, recorded.logicalId, name, ...[...recorded.values].sort());
244
+ let compare = cache?.get(cacheKey);
245
+ if (compare === void 0) {
246
+ const started = (async () => {
247
+ await assertRecordedIdentity({
248
+ label: spec.label,
249
+ resourceType: spec.resourceType,
250
+ logicalId: recorded.logicalId,
251
+ physicalId: name,
252
+ liveId: await read(),
253
+ reread: read,
254
+ context: { recordedAttributes: { [recorded.key]: value } }
255
+ });
256
+ })();
257
+ compare = started;
258
+ if (cache !== void 0) {
259
+ cache.set(cacheKey, started);
260
+ started.catch(() => {
261
+ if (cache.get(cacheKey) === started) cache.delete(cacheKey);
262
+ });
263
+ }
264
+ }
265
+ try {
266
+ await compare;
267
+ return { kind: "verified" };
268
+ } catch (error) {
269
+ if (error instanceof NoSuchEntityException) return { kind: "gone" };
270
+ if (error instanceof RecordedIdentityMismatchError) return {
271
+ kind: "mismatch",
272
+ principalLogicalId: recorded.logicalId,
273
+ label: spec.label,
274
+ attribute: error.attribute
275
+ };
276
+ if (error instanceof RecordedIdentityError) throw new InlinePolicyPrincipalUnconfirmedError(policyLogicalId, physicalId, `${spec.label} ${recorded.logicalId}`, recorded.key, operation, owner);
277
+ if (isPermissionDenial(error)) throw new InlinePolicyPrincipalReadDeniedError({
278
+ policyLogicalId,
279
+ physicalId,
280
+ principal: `${spec.label} ${recorded.logicalId}`,
281
+ permission: spec.permission,
282
+ error,
283
+ operation,
284
+ owner
285
+ });
286
+ throw error;
287
+ }
288
+ }
289
+ const PRINCIPAL_READ_CONCURRENCY = 5;
290
+ async function verifyInlinePolicyPrincipals(params) {
291
+ const { client, principals, policyLogicalId, physicalId, operation, owner } = params;
292
+ const distinct = principals.filter(([kind, name], i) => principals.findIndex(([k, n]) => injectiveKey(k, n) === injectiveKey(kind, name)) === i);
293
+ const results = [];
294
+ let next = 0;
295
+ const worker = async () => {
296
+ while (next < distinct.length) {
297
+ const index = next++;
298
+ const [kind, name] = distinct[index];
299
+ try {
300
+ results[index] = {
301
+ status: "fulfilled",
302
+ value: await verifyInlinePolicyPrincipal({
303
+ client,
304
+ kind,
305
+ name,
306
+ policyLogicalId,
307
+ physicalId,
308
+ operation,
309
+ ...owner && { owner }
310
+ })
311
+ };
312
+ } catch (reason) {
313
+ results[index] = {
314
+ status: "rejected",
315
+ reason
316
+ };
317
+ }
318
+ }
319
+ };
320
+ await Promise.all(Array.from({ length: Math.min(5, distinct.length) }, worker));
321
+ const verdicts = /* @__PURE__ */ new Map();
322
+ for (const [index, result] of results.entries()) {
323
+ if (result.status === "rejected") throw result.reason;
324
+ const [kind, name] = distinct[index];
325
+ verdicts.set(injectiveKey(kind, name), result.value);
326
+ }
327
+ return verdicts;
328
+ }
329
+ function operationPrefix(operation, owner, policyLogicalId, principal) {
330
+ const policy = `${owner.label} ${policyLogicalId}`;
331
+ switch (operation) {
332
+ case "update": return `Cannot remove ${policy} from ${principal} during an update: `;
333
+ case "attach": return `Cannot attach ${policy} to ${principal}: `;
334
+ default: return `Cannot delete ${policy} from ${principal}: `;
335
+ }
336
+ }
337
+ var InlinePolicyPrincipalReadDeniedError = class InlinePolicyPrincipalReadDeniedError extends RecordedIdentityError {
338
+ constructor(params) {
339
+ const { policyLogicalId, physicalId, principal, permission, error, operation, owner } = params;
340
+ const name = error?.name;
341
+ const errorClass = typeof name === "string" && /^[A-Za-z0-9]{1,64}$/.test(name) ? name : "a 403";
342
+ super(operationPrefix(operation, owner, policyLogicalId, principal) + `AWS refused the ${permission} read cdkd makes to confirm it is the one cdkd created (${errorClass}), so cdkd sent nothing to it and kept the record. Allow ${permission} for the identity running cdkd (an IAM policy, permission boundary, SCP or VPC endpoint policy may deny it) and re-run.`, owner.resourceType, policyLogicalId, physicalId);
343
+ Object.setPrototypeOf(this, InlinePolicyPrincipalReadDeniedError.prototype);
344
+ this.name = "InlinePolicyPrincipalReadDeniedError";
345
+ markNonRetryable(this);
346
+ markNotGone(this);
347
+ }
348
+ };
349
+ var InlinePolicyPrincipalUnconfirmedError = class InlinePolicyPrincipalUnconfirmedError extends RecordedIdentityError {
350
+ constructor(policyLogicalId, physicalId, principal, attribute, operation, owner = INLINE_POLICY_OWNER) {
351
+ super(operationPrefix(operation, owner, policyLogicalId, principal) + `AWS answered without its ${attribute}, so cdkd cannot confirm it is the one cdkd created; nothing was sent to it and the record is kept. Re-run the operation.`, owner.resourceType, policyLogicalId, physicalId);
352
+ Object.setPrototypeOf(this, InlinePolicyPrincipalUnconfirmedError.prototype);
353
+ this.name = "InlinePolicyPrincipalUnconfirmedError";
354
+ markNotGone(this);
355
+ }
356
+ };
357
+ var InlinePolicyPrincipalMismatchError = class InlinePolicyPrincipalMismatchError extends RecordedIdentityError {
358
+ constructor(params) {
359
+ const { policyLogicalId, physicalId, mismatches, context } = params;
360
+ const owner = params.owner ?? INLINE_POLICY_OWNER;
361
+ const named = mismatches.map((m) => `${m.label} ${m.principalLogicalId} (its ${m.attribute} differs)`).join(", ");
362
+ super(`Cannot delete ${owner.label} ${policyLogicalId} from ${named}: the principal holding the name cdkd recorded is not the one cdkd created, so cdkd sent it no delete and kept the record (the principal's own record refuses its delete the same way). Leave that principal alone; if the one cdkd created is gone (its ${owner.membership === true ? "membership" : "inline policy"} went with it), drop the record with ${stateOrphanRecordRemedy(context, policyLogicalId)}.`, owner.resourceType, policyLogicalId, physicalId);
363
+ Object.setPrototypeOf(this, InlinePolicyPrincipalMismatchError.prototype);
364
+ this.name = "InlinePolicyPrincipalMismatchError";
365
+ markNonRetryable(this);
366
+ markNotGone(this);
367
+ }
368
+ };
369
+ async function assertInlinePolicyAttachTargets(params) {
370
+ const { client, principals, policyLogicalId, physicalId } = params;
371
+ const owner = params.owner ?? INLINE_POLICY_OWNER;
372
+ const mismatches = [...(await verifyInlinePolicyPrincipals({
373
+ client,
374
+ principals,
375
+ policyLogicalId,
376
+ physicalId,
377
+ operation: "attach",
378
+ owner
379
+ })).values()].filter((verdict) => verdict.kind === "mismatch");
380
+ if (mismatches.length > 0) throw new InlinePolicyAttachMismatchError({
381
+ policyLogicalId,
382
+ physicalId,
383
+ mismatches,
384
+ owner
385
+ });
386
+ }
387
+ var InlinePolicyAttachMismatchError = class InlinePolicyAttachMismatchError extends RecordedIdentityError {
388
+ constructor(params) {
389
+ const { policyLogicalId, physicalId, mismatches, owner } = params;
390
+ const named = mismatches.map((m) => `${m.label} ${m.principalLogicalId} (its ${m.attribute} differs)`).join(", ");
391
+ const remedies = mismatches.map((m) => `For ${m.principalLogicalId}: if you replaced it yourself, adopt the new one with ${reAdoptRemedy(m.principalLogicalId)} and re-run; otherwise leave that ${m.label} alone, and if the one cdkd created is gone, drop its record with ${stateOrphanRecordRemedy(void 0, m.principalLogicalId)}`).join(". ");
392
+ super(`Cannot attach ${owner.label} ${policyLogicalId} to ${named}: the principal holding the name cdkd recorded is not the one cdkd created, so cdkd ` + (owner.membership === true ? `added no membership (granting nothing)` : `sent the policy to no principal (granting nothing)`) + ` and kept the principals' records. ${remedies}.`, owner.resourceType, policyLogicalId, physicalId);
393
+ Object.setPrototypeOf(this, InlinePolicyAttachMismatchError.prototype);
394
+ this.name = "InlinePolicyAttachMismatchError";
395
+ markNonRetryable(this);
396
+ markNotGone(this);
397
+ }
398
+ };
399
+ async function compareMembershipWrites(params) {
400
+ const { client, owner, logicalId, physicalId, operation } = params;
401
+ const verdicts = await verifyInlinePolicyPrincipals({
402
+ client,
403
+ principals: params.removes.flat(),
404
+ policyLogicalId: logicalId,
405
+ physicalId,
406
+ operation,
407
+ owner
408
+ });
409
+ const mismatches = [...verdicts.values()].filter((verdict) => verdict.kind === "mismatch");
410
+ if (operation === "delete" && mismatches.length > 0) throw new InlinePolicyPrincipalMismatchError({
411
+ policyLogicalId: logicalId,
412
+ physicalId,
413
+ mismatches,
414
+ context: params.context,
415
+ owner
416
+ });
417
+ await assertInlinePolicyAttachTargets({
418
+ client,
419
+ principals: params.adds.flat(),
420
+ policyLogicalId: logicalId,
421
+ physicalId,
422
+ owner
423
+ });
424
+ for (const m of mismatches) params.warn(`${owner.label} ${logicalId}: the ${m.label} ${m.principalLogicalId} leaving it is not the one cdkd created (its ${m.attribute} differs from the recorded one), so cdkd sent no membership removal naming it. Leave that ${m.label} alone.`);
425
+ return (principals) => principals.some(([kind, name]) => verdicts.get(injectiveKey(kind, name))?.kind === "mismatch");
426
+ }
427
+ async function verifyOwnIdentityBeforeUpdate(params) {
428
+ const { label, resourceType, permission, logicalId, physicalId } = params;
429
+ const recorded = recordedIdentityId(resourceType, { ...params.recordedAttributes && { recordedAttributes: params.recordedAttributes } });
430
+ if (recorded === void 0) return void 0;
431
+ const view = getStackRecords();
432
+ if (view?.writtenFreshThisRun?.(logicalId) === true) return void 0;
433
+ const cache = verifiedIdentityCache(view);
434
+ const cacheKey = injectiveKey(resourceType, logicalId, physicalId, recorded.value);
435
+ const earlier = cache?.get(cacheKey);
436
+ if (earlier !== void 0) {
437
+ if (await earlier.then(() => true, () => false)) return void 0;
438
+ }
439
+ let latest;
440
+ const readId = async () => {
441
+ latest = await params.read();
442
+ return params.idOf(latest);
443
+ };
444
+ const compare = (async () => {
445
+ await assertRecordedIdentity({
446
+ label,
447
+ resourceType,
448
+ logicalId,
449
+ physicalId,
450
+ liveId: await readId(),
451
+ reread: readId,
452
+ context: { recordedAttributes: { [recorded.key]: recorded.value } }
453
+ });
454
+ })();
455
+ if (cache !== void 0) {
456
+ cache.set(cacheKey, compare);
457
+ compare.catch(() => {
458
+ if (cache.get(cacheKey) === compare) cache.delete(cacheKey);
459
+ });
460
+ }
461
+ try {
462
+ await compare;
463
+ return latest;
464
+ } catch (error) {
465
+ if (error instanceof RecordedIdentityMismatchError) throw new OwnIdentityUpdateRefusal(`Cannot update ${label} ${logicalId}: the ${label} holding the name cdkd recorded is not the one cdkd created (its ${error.attribute} differs from the recorded one), so cdkd sent it no change and kept the record. If you replaced it yourself, adopt the new one with ${reAdoptRemedy(logicalId)} and re-run; otherwise leave that ${label} alone, and if the one cdkd created is gone, drop the record with ${stateOrphanRecordRemedy(void 0, logicalId)}.`, resourceType, logicalId, physicalId, true);
466
+ if (error instanceof RecordedIdentityError) throw new OwnIdentityUpdateRefusal(`Cannot update ${label} ${logicalId}: AWS answered without its ${recorded.key}, so cdkd cannot confirm it is the one cdkd created; nothing was sent and the record is kept. Re-run the operation.`, resourceType, logicalId, physicalId, false);
467
+ if (isPermissionDenial(error)) {
468
+ const name = error?.name;
469
+ const errorClass = typeof name === "string" && /^[A-Za-z0-9]{1,64}$/.test(name) ? name : "a 403";
470
+ throw new OwnIdentityUpdateRefusal(`Cannot update ${label} ${logicalId}: AWS refused the ${permission} read cdkd makes to confirm it is the one cdkd created (${errorClass}), so cdkd sent it no change and kept the record. Allow ${permission} for the identity running cdkd (an IAM policy, permission boundary, SCP or VPC endpoint policy may deny it) and re-run.`, resourceType, logicalId, physicalId, true);
471
+ }
472
+ throw error;
473
+ }
474
+ }
475
+ var OwnIdentityUpdateRefusal = class OwnIdentityUpdateRefusal extends RecordedIdentityError {
476
+ constructor(message, resourceType, logicalId, physicalId, nonRetryable) {
477
+ super(message, resourceType, logicalId, physicalId);
478
+ Object.setPrototypeOf(this, OwnIdentityUpdateRefusal.prototype);
479
+ this.name = "OwnIdentityUpdateRefusal";
480
+ if (nonRetryable) markNonRetryable(this);
481
+ markNotGone(this);
482
+ }
483
+ };
484
+
176
485
  // src/provisioning/own-write-removals.ts
177
486
  const removals = /* @__PURE__ */ new Map();
178
487
  function recordOwnWriteRemoval(resourceType, id, memberKey, identity) {
@@ -259,6 +568,7 @@ async function update(logicalId, physicalId, resourceType, properties, previousP
259
568
  try {
260
569
  const deleteResult = await this.delete(logicalId, physicalId, resourceType, void 0, {
261
570
  maskSecrets: log.mask,
571
+ stackHoldersStillAttached: true,
262
572
  ...context?.recordedAttributes && { recordedAttributes: context.recordedAttributes }
263
573
  });
264
574
  if (deleteResult?.outcome === "skipped") {
@@ -282,6 +592,16 @@ async function update(logicalId, physicalId, resourceType, properties, previousP
282
592
  } : base;
283
593
  }
284
594
  try {
595
+ const ownRead = await verifyOwnIdentityBeforeUpdate({
596
+ label: "IAM role",
597
+ resourceType,
598
+ permission: "iam:GetRole",
599
+ logicalId,
600
+ physicalId,
601
+ recordedAttributes: context?.recordedAttributes,
602
+ read: () => this.iamClient.send(new GetRoleCommand({ RoleName: physicalId })),
603
+ idOf: (response) => response.Role?.RoleId
604
+ });
285
605
  const updateParams = { RoleName: physicalId };
286
606
  const descriptionInput = properties["Description"];
287
607
  if (descriptionInput !== void 0) updateParams.Description = descriptionInput;
@@ -319,7 +639,7 @@ async function update(logicalId, physicalId, resourceType, properties, previousP
319
639
  await this.updateInlinePolicies(physicalId, properties["Policies"], previousProperties["Policies"], log, context?.inlinePolicyClaimed);
320
640
  await this.updateTags(physicalId, resourceType, logicalId, properties["Tags"], previousProperties["Tags"], log);
321
641
  log.debug(`Successfully updated IAM role ${logicalId}`);
322
- const getRoleResponse = await this.iamClient.send(new GetRoleCommand({ RoleName: physicalId }));
642
+ const getRoleResponse = ownRead ?? await this.iamClient.send(new GetRoleCommand({ RoleName: physicalId }));
323
643
  return {
324
644
  physicalId,
325
645
  wasReplaced: false,
@@ -329,6 +649,7 @@ async function update(logicalId, physicalId, resourceType, properties, previousP
329
649
  }
330
650
  };
331
651
  } catch (error) {
652
+ if (error instanceof RecordedIdentityError) throw error;
332
653
  const cause = error instanceof Error ? error : void 0;
333
654
  throw this.wrapMaskedError(log.mask, error, (text) => new ProvisioningError(`Failed to update IAM role ${logicalId}: ${text}`, resourceType, logicalId, physicalId, cause));
334
655
  }
@@ -405,15 +726,62 @@ async function updateTags(roleName, resourceType, logicalId, newTags, oldTags, l
405
726
  }
406
727
  }
407
728
 
729
+ // src/provisioning/stack-own-holders.ts
730
+ function stackOwnHolders(resourceType, physicalId) {
731
+ const view = getStackRecords();
732
+ if (view === void 0) return [];
733
+ const sources = [];
734
+ for (const [lid, record] of view.live()) if (view.retainedLeaving?.(lid) !== true) sources.push(record);
735
+ for (const write of view.journaledWrites?.() ?? []) sources.push(write);
736
+ const target = physicalId.toLowerCase();
737
+ const names = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
738
+ const holders = [];
739
+ const add = (name, id) => {
740
+ if (!isUsableIdentityValue(name)) return;
741
+ holders.push({
742
+ name,
743
+ ...isUsableIdentityValue(id) && { id }
744
+ });
745
+ };
746
+ for (const source of sources) {
747
+ const properties = source.properties ?? {};
748
+ if (resourceType === "AWS::IAM::Role" && source.resourceType === "AWS::IAM::InstanceProfile") {
749
+ if (names(properties["Roles"]).some((role) => role.toLowerCase() === target)) add(source.physicalId, source.attributes?.["InstanceProfileId"]);
750
+ } else if (resourceType === "AWS::IAM::Group" && source.resourceType === "AWS::IAM::User") {
751
+ if (names(properties["Groups"]).some((group) => group.toLowerCase() === target)) add(source.physicalId, source.attributes?.["UserId"]);
752
+ } else if (resourceType === "AWS::IAM::Group" && source.resourceType === "AWS::IAM::UserToGroupAddition") {
753
+ const group = properties["GroupName"];
754
+ if (typeof group === "string" && group.toLowerCase() === target) for (const user of names(properties["Users"])) add(user, void 0);
755
+ }
756
+ }
757
+ return holders;
758
+ }
759
+ function isStackOwnHolder(holders, name, liveId) {
760
+ const key = name.toLowerCase();
761
+ const named = holders.filter((holder) => holder.name.toLowerCase() === key);
762
+ if (named.length === 0) return false;
763
+ const ids = named.flatMap((holder) => holder.id === void 0 ? [] : [holder.id]);
764
+ return ids.length === 0 || liveId !== void 0 && ids.includes(liveId);
765
+ }
766
+ function heldText(held) {
767
+ if (held.names.length === 0) return "past the first page of the listing";
768
+ return `${held.names.join(", ")}${held.truncated ? ", and more" : ""}`;
769
+ }
770
+
408
771
  // src/provisioning/providers/iam-role/delete.ts
409
772
  async function deleteImpl(logicalId, physicalId, resourceType, _properties, context) {
410
773
  const log = createMaskedLogSinks(this.logger, context?.maskSecrets);
411
774
  const { value: v } = log;
412
775
  log.debug(`Deleting IAM role ${logicalId}: ${v(physicalId)}`);
413
776
  const progress = { stripped: false };
777
+ let stepZeroRoleId;
414
778
  try {
415
779
  try {
416
- const readRoleId = async () => (await this.iamClient.send(new GetRoleCommand({ RoleName: physicalId }))).Role?.RoleId;
780
+ const readRoleId = async () => {
781
+ const id = (await this.iamClient.send(new GetRoleCommand({ RoleName: physicalId }))).Role?.RoleId;
782
+ stepZeroRoleId = id;
783
+ return id;
784
+ };
417
785
  await assertRecordedIdentity({
418
786
  label: "IAM role",
419
787
  resourceType,
@@ -433,19 +801,119 @@ async function deleteImpl(logicalId, physicalId, resourceType, _properties, cont
433
801
  }
434
802
  throw error;
435
803
  }
804
+ const refuseHeld = (held, cause) => {
805
+ const run = holderRefusalRun(context);
806
+ const refusal = markNonRetryable(new ProvisioningError(log.mask(`Failed to delete IAM role ${logicalId}: role ${physicalId} is still in instance profile(s) ${heldText(held)}, which this ${run.noun} did not delete (a profile created outside the stack, or retained by a DeletionPolicy). Matching CloudFormation (DeleteConflict), cdkd does not remove the role from them. If nothing still needs the role there, remove it (aws iam remove-role-from-instance-profile --instance-profile-name <profile> --role-name <role>) or delete the profile, then ${run.again}.`), resourceType, logicalId, physicalId, cause));
807
+ PROFILE_REFUSALS.add(refusal);
808
+ throw refusal;
809
+ };
810
+ let ownProfiles = [];
811
+ if (context?.stackHoldersStillAttached === true) {
812
+ const own = stackOwnHolders(resourceType, physicalId);
813
+ const isOwn = (entry) => isStackOwnHolder(own, entry.name, entry.id);
814
+ let listed = {
815
+ entries: [],
816
+ truncated: false
817
+ };
818
+ const foreign = await settledInstanceProfiles.call(this, physicalId, (entry) => !isOwn(entry), (page) => listed = page).catch((listError) => {
819
+ if (listError instanceof NoSuchEntityException) return "empty";
820
+ throw listError;
821
+ });
822
+ if (foreign !== "empty") refuseHeld(foreign);
823
+ if (listed.truncated) refuseHeld({
824
+ names: [],
825
+ truncated: true
826
+ });
827
+ ownProfiles = listed.entries.filter(isOwn).map((entry) => entry.name);
828
+ }
436
829
  await this.detachAllManagedPolicies(physicalId, log, progress);
437
830
  await this.deleteAllInlinePolicies(physicalId, log, progress);
438
- await this.removeFromAllInstanceProfiles(physicalId, log, progress);
439
- await this.iamClient.send(new DeleteRoleCommand({ RoleName: physicalId }));
831
+ if (ownProfiles.length > 0) await this.removeFromStackOwnInstanceProfiles(physicalId, log, progress, ownProfiles);
832
+ for (let attempt = 1;; attempt++) try {
833
+ await this.iamClient.send(new DeleteRoleCommand({ RoleName: physicalId }));
834
+ break;
835
+ } catch (error) {
836
+ if (attempt > 1 || !(error instanceof DeleteConflictException)) throw error;
837
+ const held = await settledInstanceProfiles.call(this, physicalId).catch((listError) => {
838
+ log.debug(`Could not list the instance profiles of role ${v(physicalId)} after DeleteRole was refused: ${listError instanceof Error ? listError.name : typeof listError}`);
839
+ });
840
+ if (held === "empty") {
841
+ let liveId;
842
+ try {
843
+ liveId = (await this.iamClient.send(new GetRoleCommand({ RoleName: physicalId }))).Role?.RoleId;
844
+ } catch (readError) {
845
+ if (readError instanceof NoSuchEntityException) break;
846
+ throw readError;
847
+ }
848
+ if (stepZeroRoleId !== void 0 && liveId !== stepZeroRoleId) {
849
+ const refusal = markNonRetryable(new RecordedIdentityError(log.mask(`Failed to delete IAM role ${logicalId}: DeleteRole on ${physicalId} was refused (DeleteConflict), and the role now holding that name is not the one this delete read before it (its RoleId differs). cdkd sends it no delete and keeps the record. Leave that role alone; if the role cdkd created is gone, drop the record with ${stateOrphanRecordRemedy(context, logicalId)}.`), resourceType, logicalId, physicalId));
850
+ throw progress.stripped ? markDeleteStarted(refusal) : refusal;
851
+ }
852
+ continue;
853
+ }
854
+ if (held === void 0) throw error;
855
+ refuseHeld(held, error);
856
+ }
440
857
  log.debug(`Successfully deleted IAM role ${logicalId}`);
441
858
  } catch (error) {
442
859
  if (error instanceof RecordedIdentityError) throw error;
860
+ if (error instanceof Error && PROFILE_REFUSALS.has(error)) throw progress.stripped ? markDeleteStarted(error) : error;
443
861
  const cause = error instanceof Error ? error : void 0;
444
862
  const failure = this.wrapMaskedError(log.mask, error, (text) => new ProvisioningError(log.mask(`Failed to delete IAM role ${logicalId}: ${text}`), resourceType, logicalId, physicalId, cause));
445
863
  const marked = error instanceof Error && error.name.includes("NotFound") ? markNotGone(failure) : failure;
446
864
  throw progress.stripped ? markDeleteStarted(marked) : marked;
447
865
  }
448
866
  }
867
+ const PROFILE_REFUSALS = /* @__PURE__ */ new WeakSet();
868
+ const HELD_NAME_LIMIT = 5;
869
+ const HELD_POLL_MS = 2e3;
870
+ const HELD_STABLE_POLLS = 5;
871
+ const HELD_MAX_POLLS = 30;
872
+ async function listInstanceProfiles(roleName) {
873
+ const page = await this.iamClient.send(new ListInstanceProfilesForRoleCommand({ RoleName: roleName }));
874
+ return {
875
+ entries: (page.InstanceProfiles ?? []).flatMap((profile) => profile.InstanceProfileName ? [{
876
+ name: profile.InstanceProfileName,
877
+ id: profile.InstanceProfileId
878
+ }] : []),
879
+ truncated: page.IsTruncated === true
880
+ };
881
+ }
882
+ async function settledInstanceProfiles(roleName, counts = () => true, onListing) {
883
+ const key = (held) => JSON.stringify([held.names, held.truncated]);
884
+ const listed = async () => {
885
+ const { entries, truncated } = await listInstanceProfiles.call(this, roleName);
886
+ onListing?.({
887
+ entries,
888
+ truncated
889
+ });
890
+ return {
891
+ names: entries.filter(counts).map((entry) => entry.name),
892
+ truncated
893
+ };
894
+ };
895
+ let held = await listed();
896
+ if (held.names.length === 0) return "empty";
897
+ let unchanged = 0;
898
+ for (let poll = 0; poll < HELD_MAX_POLLS && unchanged < HELD_STABLE_POLLS; poll++) {
899
+ await new Promise((resolve) => setTimeout(resolve, HELD_POLL_MS));
900
+ const next = await listed();
901
+ if (next.names.length === 0) return "empty";
902
+ unchanged = key(next) === key(held) ? unchanged + 1 : 0;
903
+ held = next;
904
+ }
905
+ const names = [];
906
+ for (const name of held.names) try {
907
+ if (((await this.iamClient.send(new GetInstanceProfileCommand({ InstanceProfileName: name }))).InstanceProfile?.Roles ?? []).some((role) => role.RoleName === roleName)) names.push(name);
908
+ } catch (error) {
909
+ if (!(error instanceof NoSuchEntityException)) names.push(name);
910
+ }
911
+ if (names.length === 0) return "empty";
912
+ return {
913
+ names: names.slice(0, HELD_NAME_LIMIT),
914
+ truncated: names.length > HELD_NAME_LIMIT || held.truncated
915
+ };
916
+ }
449
917
  async function detachAllManagedPolicies(roleName, log, progress) {
450
918
  const { value: v } = log;
451
919
  log.debug(`Detaching all managed policies from role ${v(roleName)}`);
@@ -504,33 +972,18 @@ async function deleteAllInlinePolicies(roleName, log, progress) {
504
972
  throw error;
505
973
  }
506
974
  }
507
- async function removeFromAllInstanceProfiles(roleName, log, progress) {
975
+ async function removeFromStackOwnInstanceProfiles(roleName, log, progress, holders) {
508
976
  const { value: v } = log;
509
- log.debug(`Removing role ${v(roleName)} from all instance profiles`);
510
- try {
511
- const profiles = (await this.iamClient.send(new ListInstanceProfilesForRoleCommand({ RoleName: roleName }))).InstanceProfiles || [];
512
- if (profiles.length === 0) {
513
- log.debug(`No instance profiles associated with role ${v(roleName)}`);
514
- return;
515
- }
516
- for (const profile of profiles) if (profile.InstanceProfileName) try {
517
- await this.iamClient.send(new RemoveRoleFromInstanceProfileCommand({
518
- RoleName: roleName,
519
- InstanceProfileName: profile.InstanceProfileName
520
- }));
521
- if (progress) progress.stripped = true;
522
- log.debug(`Removed role ${v(roleName)} from instance profile ${v(profile.InstanceProfileName)}`);
523
- } catch (error) {
524
- if (error instanceof NoSuchEntityException) log.debug(`Role ${v(roleName)} already removed from instance profile ${v(profile.InstanceProfileName)}`);
525
- else throw error;
526
- }
527
- log.debug(`Removed role ${v(roleName)} from ${profiles.length} instance profiles`);
977
+ for (const holder of holders) try {
978
+ await this.iamClient.send(new RemoveRoleFromInstanceProfileCommand({
979
+ RoleName: roleName,
980
+ InstanceProfileName: holder
981
+ }));
982
+ if (progress) progress.stripped = true;
983
+ log.debug(`Removed role ${v(roleName)} from instance profile ${v(holder)}`);
528
984
  } catch (error) {
529
- if (error instanceof NoSuchEntityException) {
530
- log.debug(`Role ${v(roleName)} not found when removing from instance profiles`);
531
- return;
532
- }
533
- throw error;
985
+ if (!(error instanceof NoSuchEntityException)) throw error;
986
+ log.debug(`Role ${v(roleName)} already removed from instance profile ${v(holder)}`);
534
987
  }
535
988
  }
536
989
 
@@ -779,8 +1232,8 @@ var IAMRoleProvider = class {
779
1232
  deleteAllInlinePolicies(roleName, log, progress) {
780
1233
  return deleteAllInlinePolicies.call(this, roleName, log, progress);
781
1234
  }
782
- removeFromAllInstanceProfiles(roleName, log, progress) {
783
- return removeFromAllInstanceProfiles.call(this, roleName, log, progress);
1235
+ removeFromStackOwnInstanceProfiles(roleName, log, progress, holders) {
1236
+ return removeFromStackOwnInstanceProfiles.call(this, roleName, log, progress, holders);
784
1237
  }
785
1238
  updateManagedPolicies(roleName, newPolicies, oldPolicies, log) {
786
1239
  return updateManagedPolicies.call(this, roleName, newPolicies, oldPolicies, log);
@@ -845,5 +1298,5 @@ function collectInlinePolicyNamesManagedBySiblings(targetPhysicalId, context, at
845
1298
  return result;
846
1299
  }
847
1300
 
848
- export { restoreOwnWriteRemovals as a, isEntityAlreadyExists as c, recordOwnWriteRemoval as i, IamCreateClientCache as l, collectInlinePolicyNamesManagedBySiblings as n, takeOwnWriteRemovals as o, clearOwnWriteRemovals as r, iamEntityLeftByThisCreate as s, IAMRoleProvider as t };
849
- //# sourceMappingURL=iam-role-provider-lpDjrxOC.js.map
1301
+ export { isEntityAlreadyExists as _, stackOwnHolders as a, restoreOwnWriteRemovals as c, MANAGED_POLICY_OWNER as d, assertInlinePolicyAttachTargets as f, iamEntityLeftByThisCreate as g, verifyOwnIdentityBeforeUpdate as h, isStackOwnHolder as i, takeOwnWriteRemovals as l, verifyInlinePolicyPrincipals as m, collectInlinePolicyNamesManagedBySiblings as n, clearOwnWriteRemovals as o, compareMembershipWrites as p, heldText as r, recordOwnWriteRemoval as s, IAMRoleProvider as t, InlinePolicyPrincipalMismatchError as u, IamCreateClientCache as v };
1302
+ //# sourceMappingURL=iam-role-provider-Ct6UbKFo.js.map