diff --git a/packages/@aws-cdk/toolkit-lib/lib/actions/diff/private/helpers.ts b/packages/@aws-cdk/toolkit-lib/lib/actions/diff/private/helpers.ts index 94a073e24..d4954b0fe 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/actions/diff/private/helpers.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/actions/diff/private/helpers.ts @@ -122,6 +122,7 @@ async function cfnDiff( changeSet, mappings, environment, + deployedStackProperties: templateWithNestedStacks.deployedStackProperties, }); } diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/cloudformation/nested-stack-helpers.ts b/packages/@aws-cdk/toolkit-lib/lib/api/cloudformation/nested-stack-helpers.ts index 9b1c0dd96..c0499e9c4 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/cloudformation/nested-stack-helpers.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/cloudformation/nested-stack-helpers.ts @@ -12,6 +12,23 @@ export interface RootTemplateWithNestedStacks { readonly nestedStacks: { [nestedStackLogicalId: string]: NestedStackTemplates; }; + + /** + * Properties of the deployed root stack that are not part of its template + * + * @default undefined - the stack does not exist, or the properties were not read + */ + readonly deployedStackProperties?: CloudFormationStackProperties; +} + +/** + * Properties of a deployed CloudFormation stack that are not part of its template + */ +export interface CloudFormationStackProperties { + /** + * Whether termination protection is enabled on the stack + */ + readonly terminationProtection: boolean; } /** @@ -22,7 +39,8 @@ export async function loadCurrentTemplateWithNestedStacks( sdk: SDK, retrieveProcessedTemplate: boolean = false, ): Promise { - const deployedRootTemplate = await loadCurrentTemplate(rootStackArtifact, sdk, retrieveProcessedTemplate); + const rootStack = await CloudFormationStack.lookup(sdk.cloudFormation(), rootStackArtifact.stackName, retrieveProcessedTemplate); + const deployedRootTemplate = await rootStack.template(); const nestedStacks = await loadNestedStacks(rootStackArtifact, sdk, { generatedTemplate: rootStackArtifact.template, deployedTemplate: deployedRootTemplate, @@ -32,9 +50,17 @@ export async function loadCurrentTemplateWithNestedStacks( return { deployedRootTemplate, nestedStacks, + deployedStackProperties: hasBeenDeployed(rootStack) ? { terminationProtection: !!rootStack.terminationProtection } : undefined, }; } +/** + * Whether the stack exists and is not just a placeholder for a change set that was never executed + */ +function hasBeenDeployed(stack: CloudFormationStack): boolean { + return stack.exists && !stack.stackStatus.isReviewInProgress; +} + /** * Returns the currently deployed template from CloudFormation that corresponds to `stackArtifact`. */ diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/diff/diff-formatter.ts b/packages/@aws-cdk/toolkit-lib/lib/api/diff/diff-formatter.ts index c4ac7df60..558148dd3 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/diff/diff-formatter.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/diff/diff-formatter.ts @@ -1,17 +1,19 @@ import { format } from 'node:util'; import * as cxapi from '@aws-cdk/cloud-assembly-api'; import { + Difference, formatDifferences, formatSecurityChanges, fullDiff, mangleLikeCloudFormation, type DescribeChangeSetOutput, + type IDifference, type ResourceDifference, type TemplateDiff, } from '@aws-cdk/cloudformation-diff'; import chalk from 'chalk'; import { PermissionChangeType } from '../../payloads'; -import type { NestedStackTemplates, Template } from '../cloudformation'; +import type { CloudFormationStackProperties, NestedStackTemplates, Template } from '../cloudformation'; import { buildLogicalToPathMap } from '../cloudformation/logical-id-map'; import { StringWriteStream } from '../streams'; @@ -49,6 +51,13 @@ interface FormatStackDiffOutput { * Complete formatted diff */ readonly formattedDiff: string; + + /** + * The change in termination protection of the root stack + * + * @default undefined - termination protection does not change, or was not compared + */ + readonly terminationProtectionChange?: IDifference; } /** @@ -158,6 +167,16 @@ export interface TemplateInfo { * @default undefined - no environment is shown */ readonly environment?: cxapi.Environment; + + /** + * Properties of the deployed stack that are not part of its template. + * + * Any that differ from the properties of `newTemplate` are shown as stack property changes. + * Only set this when comparing against a deployed stack. + * + * @default undefined - stack properties are not compared + */ + readonly deployedStackProperties?: CloudFormationStackProperties; } /** @@ -270,9 +289,22 @@ export class DiffFormatter { mappings: this.mappings, logicalIdMap: buildLogicalToPathMap(this.templateInfo.newTemplate).toPath, environmentString: this.environmentString, + terminationProtectionChange: this.terminationProtectionChange(), }, options); } + /** + * The change in termination protection of the root stack, if there is one + */ + private terminationProtectionChange(): IDifference | undefined { + const oldValue = this.templateInfo.deployedStackProperties?.terminationProtection; + const newValue = this.templateInfo.newTemplate.terminationProtection ?? false; + if (oldValue === undefined || oldValue === newValue) { + return undefined; + } + return new Difference(oldValue, newValue); + } + private formatStackDiffHelper(params: { oldTemplate: Template; newTemplate: Template; @@ -283,8 +315,12 @@ export class DiffFormatter { logicalIdMap: Record; // Only set for the root stack; nested stacks share their parent's environment. environmentString?: string; + // Only set for the root stack; termination protection is a property of the root stack. + terminationProtectionChange?: IDifference; }, options: ReusableStackDiffOptions = {}): FormatStackDiffOutput { - const { oldTemplate, newTemplate, stackName, nestedStacks, changeSet, mappings, logicalIdMap, environmentString } = params; + const { + oldTemplate, newTemplate, stackName, nestedStacks, changeSet, mappings, logicalIdMap, environmentString, terminationProtectionChange, + } = params; const diff = this.computeDiff(stackName, oldTemplate, newTemplate, changeSet, mappings); const pathMap = this.recordPaths(stackName, oldTemplate, newTemplate, logicalIdMap); @@ -296,7 +332,7 @@ export class DiffFormatter { try { // must output the stack name if there are differences, even if quiet - if (stackName && (!options.quiet || !diff.isEmpty)) { + if (stackName && (!options.quiet || !diff.isEmpty || terminationProtectionChange)) { stream.write(format(`Stack ${chalk.bold(stackName)}${formatEnvironment(environmentString)}\n`)); } @@ -325,11 +361,17 @@ export class DiffFormatter { } const metadataWasFiltered = diffWasNonEmpty && activeDiff.isEmpty; - if (!activeDiff.isEmpty) { + if (terminationProtectionChange) { + stream.write(formatTerminationProtectionChange(terminationProtectionChange)); + } + + if (!activeDiff.isEmpty || terminationProtectionChange) { numStacksWithChanges++; + } + if (!activeDiff.isEmpty) { formatDifferences(stream, activeDiff, pathMap, options.contextLines); - } else if (!options.quiet) { + } else if (!options.quiet && !terminationProtectionChange) { const hint = metadataWasFiltered ? chalk.grey(' (CDK metadata changes were hidden, run cdk diff --strict to show)') : ''; stream.write(`${chalk.green('There were no differences')}${hint}\n`); } @@ -357,7 +399,7 @@ export class DiffFormatter { formattedDiff += nextDiff.formattedDiff; } - return { numStacksWithChanges, formattedDiff }; + return { numStacksWithChanges, formattedDiff, terminationProtectionChange }; } /** @@ -526,3 +568,13 @@ function annotateMoves(templateDiff: TemplateDiff, stackName: string, mappings: } }); } + +function formatTerminationProtectionChange(change: IDifference): string { + const describe = (enabled?: boolean) => enabled ? 'enabled' : 'disabled'; + return [ + chalk.underline(chalk.bold('Stack Properties')), + `${chalk.yellow('[~]')} TerminationProtection: ${describe(change.oldValue)} to ${describe(change.newValue)}`, + '', + '', + ].join('\n'); +} diff --git a/packages/@aws-cdk/toolkit-lib/lib/payloads/diff.ts b/packages/@aws-cdk/toolkit-lib/lib/payloads/diff.ts index 13839b95b..7391600f4 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/payloads/diff.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/payloads/diff.ts @@ -1,4 +1,4 @@ -import type { ITemplateDiff, Move, ResourceImpact } from '@aws-cdk/cloudformation-diff'; +import type { IDifference, ITemplateDiff, Move, ResourceImpact } from '@aws-cdk/cloudformation-diff'; import type { Duration, SingleStack } from './types'; /** @@ -112,6 +112,16 @@ export interface StackDiff extends SingleStack { * The changes that replace, delete or orphan an existing resource, including in nested stacks */ readonly destructiveChanges: DestructiveChange[]; + + /** + * The change in termination protection of the stack + * + * Termination protection is not part of the template, so this change is not included in `diffs`. + * It is counted in `numStacksWithChanges`. + * + * @default undefined - termination protection does not change, or was not compared + */ + readonly terminationProtectionChange?: IDifference; } /** diff --git a/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts b/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts index 104cc7ec1..88f224d86 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts @@ -443,6 +443,7 @@ export class Toolkit extends CloudAssemblySourceBuilder { numStacksWithSecurityChanges: securityDiff.numStacksWithChanges, permissionChanges: securityDiff.permissionChangeType, destructiveChanges: findDestructiveChanges(formatter.displayedDiffs, formatter.constructPaths), + terminationProtectionChange: stackDiff.terminationProtectionChange, formattedDiff: { diff: stackDiff.formattedDiff, security: formattedSecurityDiff, diff --git a/packages/@aws-cdk/toolkit-lib/test/actions/diff.test.ts b/packages/@aws-cdk/toolkit-lib/test/actions/diff.test.ts index f3063cdad..7b5955747 100644 --- a/packages/@aws-cdk/toolkit-lib/test/actions/diff.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/actions/diff.test.ts @@ -419,6 +419,34 @@ describe('diff', () => { })); }); + test('shows a change in termination protection of the deployed stack', async () => { + // GIVEN + jest.spyOn(deployments.Deployments.prototype, 'readCurrentTemplateWithNestedStacks').mockResolvedValue({ + deployedRootTemplate: {}, + nestedStacks: {}, + deployedStackProperties: { terminationProtection: true }, + }); + + // WHEN + const cx = await cdkOutFixture(toolkit, 'stack-with-bucket'); + await toolkit.diff(cx, { + stacks: { strategy: StackSelectionStrategy.ALL_STACKS }, + method: DiffMethod.TemplateOnly(), + }); + + // THEN + expect(ioHost.notifySpy).toHaveBeenCalledWith(expect.objectContaining({ + action: 'diff', + level: 'result', + code: 'CDK_TOOLKIT_I4002', + message: expect.stringContaining('TerminationProtection: enabled to disabled'), + data: expect.objectContaining({ + numStacksWithChanges: 1, + terminationProtectionChange: expect.objectContaining({ oldValue: true, newValue: false }), + }), + })); + }); + describe('DiffMethod.ChangeSet', () => { test('ChangeSet diff method falls back to template only if changeset not found', async () => { // WHEN diff --git a/packages/@aws-cdk/toolkit-lib/test/api/deployments/cloudformation-deployments.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/deployments/cloudformation-deployments.test.ts index 36527c312..561ccdba8 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/deployments/cloudformation-deployments.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/deployments/cloudformation-deployments.test.ts @@ -4,6 +4,7 @@ import { DescribeStackEventsCommand, type DescribeStackEventsCommandInput, DescribeStacksCommand, + GetTemplateCommand, ListStackResourcesCommand, RollbackStackCommand, type StackResourceSummary, @@ -405,6 +406,41 @@ test.each([false, true])( }, ); +test.each([ + [true, true], + [false, false], + [undefined, false], +])('readCurrentTemplateWithNestedStacks() returns termination protection %p of the deployed stack as %p', async (enabled, expected) => { + // GIVEN + jest.spyOn(CloudFormationStack, 'lookup').mockImplementation(async (cfn, stackName) => CloudFormationStack.fromStaticInformation(cfn, stackName, { + StackName: stackName, + CreationTime: new Date(), + StackStatus: StackStatus.CREATE_COMPLETE, + EnableTerminationProtection: enabled, + })); + mockCloudFormationClient.on(GetTemplateCommand).resolves({ TemplateBody: '{}' }); + + // WHEN + const result = await deployments.readCurrentTemplateWithNestedStacks(testStack({ stackName: 'boop' })); + + // THEN + expect(result.deployedStackProperties).toEqual({ terminationProtection: expected }); +}); + +test.each([ + ['does not exist', undefined], + ['has not been deployed yet', StackStatus.REVIEW_IN_PROGRESS], +])('readCurrentTemplateWithNestedStacks() does not return termination protection if the stack %s', async (_, stackStatus) => { + // GIVEN + givenStacks(stackStatus ? { boop: { template: {}, stackStatus } } : {}); + + // WHEN + const result = await deployments.readCurrentTemplateWithNestedStacks(testStack({ stackName: 'boop' })); + + // THEN + expect(result.deployedStackProperties).toBeUndefined(); +}); + test('readCurrentTemplateWithNestedStacks() can handle non-Resources in the template', async () => { const stackSummary = stackSummaryOf( 'NestedStack', diff --git a/packages/@aws-cdk/toolkit-lib/test/api/diff/diff.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/diff/diff.test.ts index 49d4d7ec7..1099f0538 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/diff/diff.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/diff/diff.test.ts @@ -383,6 +383,125 @@ describe('formatStackDiff', () => { }); }); +describe('termination protection', () => { + const template = { + Resources: { + Queue: { Type: 'AWS::SQS::Queue' }, + }, + }; + + function stackArtifact(terminationProtection?: boolean): cxapi.CloudFormationStackArtifact { + return { + template, + templateFile: 'template.json', + stackName: 'test-stack', + terminationProtection, + findMetadataByType: () => [], + } as any; + } + + test('shows enabling termination protection as a stack property change', () => { + // WHEN + const formatter = new DiffFormatter({ + templateInfo: { + oldTemplate: template, + newTemplate: stackArtifact(true), + deployedStackProperties: { terminationProtection: false }, + }, + }); + const result = formatter.formatStackDiff(); + + // THEN + expect(result.numStacksWithChanges).toBe(1); + expect(result.terminationProtectionChange).toMatchObject({ oldValue: false, newValue: true, isUpdate: true }); + expect(stripAnsi(result.formattedDiff!).trim()).toBe( + 'Stack test-stack\n' + + 'Stack Properties\n' + + '[~] TerminationProtection: disabled to enabled', + ); + }); + + test('treats unset termination protection in the app as disabled', () => { + // WHEN + const formatter = new DiffFormatter({ + templateInfo: { + oldTemplate: template, + newTemplate: stackArtifact(undefined), + deployedStackProperties: { terminationProtection: true }, + }, + }); + const result = formatter.formatStackDiff(); + + // THEN + expect(result.numStacksWithChanges).toBe(1); + expect(result.terminationProtectionChange).toMatchObject({ oldValue: true, newValue: false, isUpdate: true }); + expect(stripAnsi(result.formattedDiff!)).toContain('[~] TerminationProtection: enabled to disabled'); + }); + + test('shows the stack property change alongside template changes and counts the stack once', () => { + // WHEN + const formatter = new DiffFormatter({ + templateInfo: { + oldTemplate: {}, + newTemplate: stackArtifact(true), + deployedStackProperties: { terminationProtection: false }, + }, + }); + const result = formatter.formatStackDiff(); + + // THEN + expect(result.numStacksWithChanges).toBe(1); + expect(stripAnsi(result.formattedDiff!).trim()).toBe( + 'Stack test-stack\n' + + 'Stack Properties\n' + + '[~] TerminationProtection: disabled to enabled\n' + + '\n' + + 'Resources\n' + + '[+] AWS::SQS::Queue Queue', + ); + }); + + test('shows the stack header and change in quiet mode', () => { + // WHEN + const formatter = new DiffFormatter({ + templateInfo: { + oldTemplate: template, + newTemplate: stackArtifact(true), + deployedStackProperties: { terminationProtection: false }, + }, + }); + const result = formatter.formatStackDiff({ quiet: true }); + + // THEN + expect(result.numStacksWithChanges).toBe(1); + expect(stripAnsi(result.formattedDiff!)).toContain('Stack test-stack\n'); + expect(stripAnsi(result.formattedDiff!)).toContain('[~] TerminationProtection: disabled to enabled'); + }); + + test.each([ + ['unchanged', true as boolean | undefined], + ['not compared', undefined], + ])('shows nothing when termination protection is %s', (_, terminationProtection) => { + // WHEN + const formatter = new DiffFormatter({ + templateInfo: { + oldTemplate: template, + newTemplate: stackArtifact(true), + deployedStackProperties: terminationProtection === undefined ? undefined : { terminationProtection }, + }, + }); + const result = formatter.formatStackDiff(); + + // THEN + expect(result.numStacksWithChanges).toBe(0); + expect(result.terminationProtectionChange).toBeUndefined(); + expect(stripAnsi(result.formattedDiff!).trim()).toBe( + 'Stack test-stack\n' + + 'There were no differences', + ); + }); +}); + describe('formatSecurityDiff', () => { let mockNewTemplate: cxapi.CloudFormationStackArtifact; diff --git a/packages/aws-cdk/lib/cli/cdk-toolkit.ts b/packages/aws-cdk/lib/cli/cdk-toolkit.ts index 9f62e95e2..a61b7cce2 100644 --- a/packages/aws-cdk/lib/cli/cdk-toolkit.ts +++ b/packages/aws-cdk/lib/cli/cdk-toolkit.ts @@ -392,6 +392,7 @@ export class CdkToolkit { nestedStacks, mappings, environment, + deployedStackProperties: templateWithNestedStacks.deployedStackProperties, }, }); diff --git a/packages/aws-cdk/test/commands/diff.test.ts b/packages/aws-cdk/test/commands/diff.test.ts index 8bd55fb65..741e760ef 100644 --- a/packages/aws-cdk/test/commands/diff.test.ts +++ b/packages/aws-cdk/test/commands/diff.test.ts @@ -114,6 +114,50 @@ describe('fixed template', () => { }); }); +describe('termination protection', () => { + const template = { + Resources: { + Queue: { Type: 'AWS::SQS::Queue' }, + }, + }; + + beforeEach(async () => { + cloudFormation = instanceMockFrom(Deployments); + cloudFormation.readCurrentTemplateWithNestedStacks.mockResolvedValue({ + deployedRootTemplate: template, + nestedStacks: {}, + deployedStackProperties: { terminationProtection: false }, + }); + cloudFormation.stackExists = jest.fn().mockReturnValue(Promise.resolve(true)); + cloudExecutable = await MockCloudExecutable.create({ + stacks: [{ stackName: 'A', template, terminationProtection: true }], + }, undefined, ioHost); + + toolkit = new CdkToolkit({ + cloudExecutable, + deployments: cloudFormation, + configuration: cloudExecutable.configuration, + sdkProvider: cloudExecutable.sdkProvider, + }); + }); + + test('a change in termination protection of the deployed stack is shown and counted', async () => { + // WHEN + const exitCode = await toolkit.diff({ + stackNames: ['A'], + method: 'template', + failOn: cxschema.RequireApproval.ANYCHANGE, + }); + + // THEN + expect(output()).toContain('[~] TerminationProtection: disabled to enabled'); + expect(notifySpy).toHaveBeenCalledWith(expect.objectContaining({ + message: expect.stringContaining('✨ Number of stacks with differences: 1'), + })); + expect(exitCode).toBe(1); + }); +}); + describe('import existing resources', () => { let createDiffChangeSet: jest.SpyInstance< Promise,