diff --git a/packages/@aws-cdk/cloud-assembly-api/lib/validation/loading.ts b/packages/@aws-cdk/cloud-assembly-api/lib/validation/loading.ts index 27f86ce8e..9428b6619 100644 --- a/packages/@aws-cdk/cloud-assembly-api/lib/validation/loading.ts +++ b/packages/@aws-cdk/cloud-assembly-api/lib/validation/loading.ts @@ -4,7 +4,7 @@ import { Manifest } from '@aws-cdk/cloud-assembly-schema'; import type * as cxschema from '@aws-cdk/cloud-assembly-schema'; import type { CloudFormationStackArtifact } from '../artifacts/cloudformation-artifact'; import { SynthesisMessageLevel } from '../metadata'; -import { ANNOTATION_PLUGIN_NAME } from './parsing'; +import { ANNOTATION_PLUGIN_NAME, escapeValidationRuleName } from './parsing'; import { StackTrace } from '../stack-trace'; const VALIDATION_REPORT_FILE = 'validation-report.json'; @@ -165,7 +165,7 @@ function splitDescriptionAndId(message: string): { message: string; ruleName?: s // The `Validations.of().addWarning()` API already added an `Annotation::` prefix, that we need // to maintain. const annotationPrefix = ackMatch[1].startsWith('Annotation::') ? 'Annotation::' : ''; - const ruleName = ackMatch[1].slice(annotationPrefix.length).replace(/::/g, '_'); + const ruleName = escapeValidationRuleName(ackMatch[1].slice(annotationPrefix.length)); return { message: message.replace(ackMatch[0], '').trim(), diff --git a/packages/@aws-cdk/cloud-assembly-api/lib/validation/parsing.ts b/packages/@aws-cdk/cloud-assembly-api/lib/validation/parsing.ts index c0f7de2c8..85263e96d 100644 --- a/packages/@aws-cdk/cloud-assembly-api/lib/validation/parsing.ts +++ b/packages/@aws-cdk/cloud-assembly-api/lib/validation/parsing.ts @@ -1,12 +1,22 @@ +/** + * Marks a violation that may not be suppressed, whatever its severity. + * + * Set by whoever produces the violation, for a findings where we cannot construct a reasonable + * rule name. + */ +export const NOT_SUPPRESSIBLE_RULE_METADATA_KEY = 'cdk:not-suppressible'; + /** * Report whether it is possible to suppress this violation. * - * Violations that are reported as "fatal", or that have been converted from annotations, cannot be suppressed. + * Violations that are reported as "fatal", that have been converted from annotations, or that + * are explicitly marked `cdk:not-suppressible`, cannot be suppressed. */ export function isSuppressibleViolation(violation: { severity?: string; ruleMetadata?: { [key: string]: string } }): boolean { const isFatal = violation.severity?.toLowerCase() === 'fatal'; const isErrorAnnotation = violation.ruleMetadata?.['cdk:annotation'] && violation.severity?.toLowerCase() === 'error'; - return !isFatal && !isErrorAnnotation; + const isMarkedUnsuppressible = violation.ruleMetadata?.[NOT_SUPPRESSIBLE_RULE_METADATA_KEY] !== undefined; + return !isFatal && !isErrorAnnotation && !isMarkedUnsuppressible; } export interface ValidationId { @@ -71,6 +81,17 @@ export function parseValidationId(id: string): ValidationId { return { namespace, ruleId }; } +/** + * Escape a string so that it is safe to use as the rule name half of a validation ID. + * + * `::` is reserved for separating the namespace from the rule name. Replace it in any + * perspective rule names that have it, these will usually come from CloudFormation early + * validation rules. + */ +export function escapeValidationRuleName(ruleName: string): string { + return ruleName.replace(/::/g, '_'); +} + /** * Normalize the given validation ID to a fully qualified ID, using the `annotation` namespace if no namespace is provided. */ diff --git a/packages/@aws-cdk/cloud-assembly-api/test/validation/formatting.test.ts b/packages/@aws-cdk/cloud-assembly-api/test/validation/formatting.test.ts index d0f45c494..c49009cac 100644 --- a/packages/@aws-cdk/cloud-assembly-api/test/validation/formatting.test.ts +++ b/packages/@aws-cdk/cloud-assembly-api/test/validation/formatting.test.ts @@ -80,6 +80,32 @@ ERROR Test violation (test-plugin) `); }); +test('a violation marked not suppressible is not offered an acknowledgement', () => { + // There is nothing for a user to name in an acknowledgement, so the rule is shown for + // reference only. + const output = defaultFormatValidateReports([ + { + conclusion: 'success', + pluginName: 'CloudFormation', + violations: [ + { + severity: 'warning', + description: 'Something may be wrong', + ruleName: 'CloudFormationValidation', + ruleMetadata: { 'cdk:not-suppressible': 'true' }, + violatingConstructs: [{ constructPath: 'Stack/MyConstruct' }], + }, + ], + }, + ]); + + expect(stripAnsi(output)).toMatchInlineSnapshot(` +"WARNING Something may be wrong (CloudFormation) + Stack/MyConstruct + Rule CloudFormation::CloudFormationValidation" +`); +}); + function defaultFormatValidateReports(reports: PluginReportJson[]): string { return new ValidationReportFormatter({ fileLocationRenderer: relativeFileLocationRenderer('/root'), diff --git a/packages/@aws-cdk/cloud-assembly-api/test/validation/parsing.test.ts b/packages/@aws-cdk/cloud-assembly-api/test/validation/parsing.test.ts index d91a3f706..36dda0b1c 100644 --- a/packages/@aws-cdk/cloud-assembly-api/test/validation/parsing.test.ts +++ b/packages/@aws-cdk/cloud-assembly-api/test/validation/parsing.test.ts @@ -1,6 +1,7 @@ import { ANNOTATION_PLUGIN_NAME, ANNOTATION_PLUGIN_NAMESPACE, + escapeValidationRuleName, isSuppressibleViolation, namespaceFromPluginName, normalizeValidationId, @@ -41,6 +42,21 @@ describe('parseValidationId', () => { }); }); +describe('escapeValidationRuleName', () => { + test.each([ + ['leaves a plain name alone', 'MyRule', 'MyRule'], + ['leaves single colons alone', 'a:b', 'a:b'], + ['escapes every delimiter', 'SQS_QUEUE_REMOVED | AWS::Controls::SQSQueueRemoved_VALIDATION_ERROR', 'SQS_QUEUE_REMOVED | AWS_Controls_SQSQueueRemoved_VALIDATION_ERROR'], + ])('%s', (_what, input, expected) => { + expect(escapeValidationRuleName(input)).toBe(expected); + }); + + test('the result parses as a bare rule id', () => { + const escaped = escapeValidationRuleName('AWS::Controls::SQSQueueRemoved'); + expect(parseValidationId(escaped)).toEqual({ ruleId: escaped }); + }); +}); + describe('normalizeValidationId', () => { const defaultNs = namespaceFromPluginName('fallback-plugin'); @@ -91,10 +107,12 @@ describe('isSuppressibleViolation', () => { ['a warning', { severity: 'warning' }, true], ['no severity at all', {}, true], ['a warning annotation', { severity: 'warning', ruleMetadata: { 'cdk:annotation': 'true' } }, true], - // Fatal findings and error-level annotations are the two things a user may not wave away. + // Fatal findings, error-level annotations and explicitly marked findings are the things a + // user may not wave away. ['a fatal violation', { severity: 'fatal' }, false], ['a fatal violation in any casing', { severity: 'FATAL' }, false], ['an error annotation', { severity: 'error', ruleMetadata: { 'cdk:annotation': 'true' } }, false], + ['a violation marked not suppressible', { severity: 'warning', ruleMetadata: { 'cdk:not-suppressible': 'true' } }, false], ])('%s -> %s', (_what, violation, expected) => { expect(isSuppressibleViolation(violation)).toBe(expected); }); diff --git a/packages/@aws-cdk/toolkit-lib/docs/message-registry.md b/packages/@aws-cdk/toolkit-lib/docs/message-registry.md index 22e921d10..c18d550b8 100644 --- a/packages/@aws-cdk/toolkit-lib/docs/message-registry.md +++ b/packages/@aws-cdk/toolkit-lib/docs/message-registry.md @@ -84,6 +84,7 @@ Please let us know by [opening an issue](https://github.com/aws/aws-cdk-cli/issu | `CDK_TOOLKIT_I5002` | Provides time for resource migration | `info` | {@link Duration} | | `CDK_TOOLKIT_W5021` | Empty non-existent stack, deployment is skipped | `warn` | n/a | | `CDK_TOOLKIT_W5022` | Empty existing stack, stack will be destroyed | `warn` | n/a | +| `CDK_TOOLKIT_W5023` | CloudFormation early validation reported warnings for a stack being deployed | `warn` | n/a | | `CDK_TOOLKIT_I5031` | Informs about any log groups that are traced as part of the deployment | `info` | n/a | | `CDK_TOOLKIT_I5032` | Start monitoring log groups | `debug` | {@link CloudWatchLogMonitorControlEvent} | | `CDK_TOOLKIT_I5033` | A log event received from Cloud Watch | `info` | {@link CloudWatchLogEvent} | @@ -117,6 +118,7 @@ Please let us know by [opening an issue](https://github.com/aws/aws-cdk-cli/issu | `CDK_TOOLKIT_I5900` | Deployment results on success | `result` | {@link SuccessfulDeployStackResult} | | `CDK_TOOLKIT_I5901` | Generic deployment success messages | `info` | n/a | | `CDK_TOOLKIT_W5902` | Express Mode deployment completed with resources still stabilizing | `warn` | n/a | +| `CDK_TOOLKIT_W5903` | How many early validation warnings the deployment reported in total | `warn` | n/a | | `CDK_TOOLKIT_W5400` | Hotswap disclosure message | `warn` | n/a | | `CDK_TOOLKIT_E5001` | No stacks found | `error` | n/a | | `CDK_TOOLKIT_E5500` | Stack Monitoring error | `error` | {@link ErrorPayload} | diff --git a/packages/@aws-cdk/toolkit-lib/lib/actions/diagnose/index.ts b/packages/@aws-cdk/toolkit-lib/lib/actions/diagnose/index.ts index 7e1936c41..24fc7151b 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/actions/diagnose/index.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/actions/diagnose/index.ts @@ -28,10 +28,18 @@ export interface DiagnoseResult { readonly stacks: DiagnosedStack[]; } -export type StackDiagnosis = +export type StackDiagnosis = { + /** + * Findings that did not cause the operation failed. + * + * @default - no warnings + */ + readonly warnings?: TracedResourceError[]; +} & ( | { type: 'no-problem' } | { type: 'problem'; detectedBy: StackProblemSource; problems: TracedResourceError[] } - | { type: 'error-diagnosing'; message: string }; + | { type: 'error-diagnosing'; message: string } +); export type StackProblemSource = | { type: 'deployment'; stackStatus: string; statusReason: string } @@ -85,6 +93,9 @@ export interface TracedResourceError { /** * Error code of the resource + * + * For an early-validation finding this is the ID of the rule that produced it, which + * is also the ID a user names to acknowledge the finding. */ readonly errorCode?: string; diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/deployments/deploy-stack.ts b/packages/@aws-cdk/toolkit-lib/lib/api/deployments/deploy-stack.ts index 9a8ced3e3..820b2329b 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/deployments/deploy-stack.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/deployments/deploy-stack.ts @@ -37,6 +37,7 @@ import type { ChangeSetReport, ChangeSetTemplates } from '../change-sets'; import { ChangeSetDescriber } from '../change-sets'; import type { TemplateBodyParameter } from '../cloudformation'; import { makeBodyParameter, CfnEvaluationException, CloudFormationStack } from '../cloudformation'; +import { formatDiagnosisWarnings } from '../diagnosing/diagnosis-formatting'; import type { CloudFormationStackDiagnoser } from '../diagnosing/stack-diagnoser'; import { changeSetHasNoChanges } from '../diagnosing/stack-diagnoser'; import type { EnvironmentResources, StringWithoutPlaceholders } from '../environment'; @@ -44,6 +45,7 @@ import { HotswapPropertyOverrides, ICON, createHotswapPropertyOverrides } from ' import { tryHotswapDeployment } from '../hotswap/hotswap-deployments'; import { invalidateHotswapTemplateCache, readHotswapTemplateCache } from '../hotswap/hotswap-template-cache'; import type { IoHelper } from '../io/private'; +import { IO } from '../io/private'; import type { ResourcesToImport } from '../resource-import'; import { StackActivityMonitor } from '../stack-events'; import type { ResourceErrors } from '../stack-events/resource-errors'; @@ -429,6 +431,13 @@ class FullCloudFormationDeployment { private readonly verb: string; private readonly uuid: string; + /** + * How many early validation warnings the change set this deployment created reported. + * + * Count is not updated for deployments which don't create a changeset as a part of their deploy command. + */ + private earlyValidationWarnings = 0; + constructor( private readonly deploymentMethod: DirectDeployment | ChangeSetDeployment | ExecuteChangeSetDeployment, private readonly options: DeployStackOptions, @@ -512,6 +521,7 @@ class FullCloudFormationDeployment { stackArn: changeSetDescription.StackId!, deleteFailures: [], stabilizingResources: [], + earlyValidationWarnings: this.earlyValidationWarnings, }; } @@ -530,6 +540,7 @@ class FullCloudFormationDeployment { changeSet: changeSetDescription, deleteFailures: [], stabilizingResources: [], + earlyValidationWarnings: this.earlyValidationWarnings, }; } @@ -645,7 +656,7 @@ class FullCloudFormationDeployment { }); await this.ioHelper.defaults.debug(format('Initiated creation of changeset: %s; waiting for it to finish creating...', changeSet.Id)); - return new ChangeSetDescriber({ + const report = await new ChangeSetDescriber({ cfn: this.cfn, ioHelper: this.ioHelper, stackNameOrArn: changeSet.StackId ?? this.stackName, @@ -654,6 +665,15 @@ class FullCloudFormationDeployment { }).waitAndThrowOnProblem({ diagnoser: this.diagnoser, }); + + // Report warnings from changeset before we start executing it + const warnings = report.diagnosis.warnings; + if (warnings.length > 0) { + this.earlyValidationWarnings += warnings.length; + await this.ioHelper.notify(IO.CDK_TOOLKIT_W5023.msg(formatDiagnosisWarnings(warnings, report.changeSet.ChangeSetName))); + } + + return report; } private async cleanupOldChangeset(changeSetNameOrArn: string) { @@ -796,6 +816,7 @@ class FullCloudFormationDeployment { stackArn: finalState.stackId, deleteFailures: this.update ? monitor.deleteFailures : [], stabilizingResources: monitor.stabilizingResources, + earlyValidationWarnings: this.earlyValidationWarnings, }; } diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/deployments/deployment-result.ts b/packages/@aws-cdk/toolkit-lib/lib/api/deployments/deployment-result.ts index cf3b6cc33..b5d349867 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/deployments/deployment-result.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/deployments/deployment-result.ts @@ -33,6 +33,14 @@ export interface SuccessfulDeployStackResult { * resources as complete with a stabilization status reason. */ readonly stabilizingResources: StabilizingResource[]; + + /** + * How many early validation warnings CloudFormation reported while creating this stack's + * change set. + * + * @default - not a change-set deployment, or no warnings + */ + readonly earlyValidationWarnings?: number; } /** The stack is currently in a failpaused state, and needs to be rolled back before the deployment */ diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/diagnosing/changeset-error-fetcher.ts b/packages/@aws-cdk/toolkit-lib/lib/api/diagnosing/changeset-error-fetcher.ts index 90fa496e5..714f5ebcf 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/diagnosing/changeset-error-fetcher.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/diagnosing/changeset-error-fetcher.ts @@ -60,15 +60,8 @@ export class ChangeSetResourceErrorFetcher { return { type: 'resource-errors', - errors: operationEvents.map((ev) => ({ - eventType: ev.EventType ?? '', - logicalId: ev.LogicalResourceId ?? '', - message: ev.ValidationStatusReason ?? '', - physicalId: ev.PhysicalResourceId ? ev.PhysicalResourceId : undefined, - validationName: ev.ValidationName ?? '', - documentPath: ev.ValidationPath ?? '', - resourceType: ev.ResourceType, - } satisfies ChangeSetResourceError)), + errors: operationEvents.filter(ev => ev.ValidationFailureMode !== 'WARN').map(changeSetResourceError), + warnings: operationEvents.filter(ev => ev.ValidationFailureMode === 'WARN').map(changeSetResourceError), }; } @@ -83,9 +76,21 @@ export class ChangeSetResourceErrorFetcher { } } +function changeSetResourceError(ev: OperationEvent): ChangeSetResourceError { + return { + eventType: ev.EventType ?? '', + logicalId: ev.LogicalResourceId ?? '', + message: ev.ValidationStatusReason ?? '', + physicalId: ev.PhysicalResourceId ? ev.PhysicalResourceId : undefined, + validationName: ev.ValidationName ?? '', + documentPath: ev.ValidationPath ?? '', + resourceType: ev.ResourceType, + }; +} + export type ChangeSetErrorCheckResult = | { type: 'could-not-check'; message: string } - | { type: 'resource-errors'; errors: ChangeSetResourceError[] }; + | { type: 'resource-errors'; errors: ChangeSetResourceError[]; warnings: ChangeSetResourceError[] }; export interface ChangeSetResourceError { readonly logicalId: string; diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/diagnosing/diagnosis-formatting.ts b/packages/@aws-cdk/toolkit-lib/lib/api/diagnosing/diagnosis-formatting.ts index 1b0e8df24..fc0126b9a 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/diagnosing/diagnosis-formatting.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/diagnosing/diagnosis-formatting.ts @@ -68,6 +68,11 @@ function formatChangeSetNotReady(detectedBy: Extract): string { const caption = `Early validation failed for change set ${detectedBy.changeSetName}`; if (problems.length > 0) { diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/diagnosing/diagnosis.ts b/packages/@aws-cdk/toolkit-lib/lib/api/diagnosing/diagnosis.ts index 1a8ed58b5..f44e741b9 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/diagnosing/diagnosis.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/diagnosing/diagnosis.ts @@ -40,11 +40,32 @@ export class Diagnosis { /** * Whether this diagnosis represents a healthy stack. + * + * Stacks with warnings (and no errors) will also have this designation. */ public get isNoProblem(): boolean { return this.result.type === 'no-problem'; } + /** + * The findings that do not cause failed operations. + */ + public get warnings(): TracedResourceError[] { + return this.result.warnings ?? []; + } + + /** + * Return this diagnosis with the given warnings added to it. + * + * Warnings never make `isNoProblem` false and `throwOnError` ignores them. + */ + public withWarnings(warnings: TracedResourceError[]): Diagnosis { + if (warnings.length === 0) { + return this; + } + return new Diagnosis({ ...this.result, warnings: [...this.warnings, ...warnings] }); + } + /** * Throw a `DeploymentError` describing the diagnosis, unless there is no problem. */ diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/diagnosing/stack-diagnoser.ts b/packages/@aws-cdk/toolkit-lib/lib/api/diagnosing/stack-diagnoser.ts index b56b88e5f..866a52569 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/diagnosing/stack-diagnoser.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/diagnosing/stack-diagnoser.ts @@ -15,6 +15,7 @@ import { PollRange, StackEventPoller } from '../stack-events'; import { fetchHookResultDetails, formatHookResultDetails, isFailedHookStatus, normalizeHookMessage } from '../stack-events/hook-result-details'; import type { ResourceError, ResourceErrors } from '../stack-events/resource-errors'; import { StackStatus } from '../stack-events/stack-status'; +import { earlyValidationErrorCode } from '../validate/early-validation-acknowledgements'; export interface CloudFormationStackDiagnoserProps { readonly sdk: SDK; @@ -295,9 +296,42 @@ export class CloudFormationStackDiagnoser { }, []); } + // A change set that was created successfully can still carry early validation warnings, and + // the only way to tell if a stack has warnings is via `DescribeEvents`. + if (changeSet.Status === ChangeSetStatus.CREATE_COMPLETE) { + return diagnosis.withWarnings(await this._checkForChangeSetWarnings(changeSet)); + } + return diagnosis; } + /** + * Fetch the early validation warnings of a change set that was created successfully. + * + * An early validation whose failure mode is `WARN` does not fail the change set: CloudFormation + * records the finding, reports the change set as `CREATE_COMPLETE`, and gives no other sign that + * anything is wrong with it. `DescribeEvents` is the only way to see them. + * + * Best-effort: if we fail to get access to the warnings, will report the issue at debug level since + * missing warnings should not cause an otherwise health stack to fail. + */ + private async _checkForChangeSetWarnings(changeSet: ChangeSetSummary): Promise { + try { + const ev = await new ChangeSetResourceErrorFetcher(this.props.sdk, this.props.envResources) + .fetchDetailsStructured(changeSet.ChangeSetName!, changeSet.StackName!); + + if (ev.type === 'could-not-check') { + await this.props.ioHelper.defaults.debug(ev.message); + return []; + } + + return await this.enhanceErrors(ev.warnings.map((w) => resourceErrorFromEarlyValidationError(changeSet.StackId ?? '', this.parentStackLogicalIds, w))); + } catch (e: any) { + await this.props.ioHelper.defaults.debug(`Could not check change set ${changeSet.ChangeSetName} for early validation warnings: ${e.message}`); + return []; + } + } + private async _diagnoseChangeSetProblems(changeSet: ChangeSetSummary): Promise { if (changeSet.Status !== ChangeSetStatus.FAILED) { return Diagnosis.noProblem(); @@ -359,12 +393,12 @@ export class CloudFormationStackDiagnoser { const ev = await new ChangeSetResourceErrorFetcher(this.props.sdk, this.props.envResources) .fetchDetailsStructured(changeSet.ChangeSetName!, changeSet.StackName!); - // If we have errors to return, return them + // if we have errors (and warnings) return them if (ev.type === 'resource-errors' && ev.errors.length > 0) { return Diagnosis.problem( detectedBy, await this.enhanceErrors(ev.errors.map((e) => resourceErrorFromEarlyValidationError(changeSet.StackId ?? '', this.parentStackLogicalIds, e))), - ); + ).withWarnings(await this.enhanceErrors(ev.warnings.map((w) => resourceErrorFromEarlyValidationError(changeSet.StackId ?? '', this.parentStackLogicalIds, w)))); } // Otherwise, we will return a generic changeset error message. If there was a problem @@ -687,7 +721,7 @@ function resourceErrorFromEarlyValidationError(stackId: string, parentStackLogic physicalId: ev.physicalId, resourceType: ev.resourceType, message: `${ev.message} (at ${ev.documentPath})`, - errorCode: `${ev.validationName}_${ev.eventType}`, + errorCode: earlyValidationErrorCode(ev.validationName), parentStackLogicalIds, stackArn: stackId, }; diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/io/private/messages.ts b/packages/@aws-cdk/toolkit-lib/lib/api/io/private/messages.ts index 6001cbca9..a9fa0c0c2 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/io/private/messages.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/io/private/messages.ts @@ -163,6 +163,10 @@ export const IO = { code: 'CDK_TOOLKIT_W5022', description: 'Empty existing stack, stack will be destroyed', }), + CDK_TOOLKIT_W5023: make.warn({ + code: 'CDK_TOOLKIT_W5023', + description: 'CloudFormation early validation reported warnings for a stack being deployed', + }), CDK_TOOLKIT_I5031: make.info({ code: 'CDK_TOOLKIT_I5031', description: 'Informs about any log groups that are traced as part of the deployment', @@ -334,6 +338,10 @@ export const IO = { code: 'CDK_TOOLKIT_W5902', description: 'Express Mode deployment completed with resources still stabilizing', }), + CDK_TOOLKIT_W5903: make.warn({ + code: 'CDK_TOOLKIT_W5903', + description: 'How many early validation warnings the deployment reported in total', + }), CDK_TOOLKIT_W5400: make.warn({ code: 'CDK_TOOLKIT_W5400', description: 'Hotswap disclosure message', diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/stack-events/resource-errors.ts b/packages/@aws-cdk/toolkit-lib/lib/api/stack-events/resource-errors.ts index 3ff879454..05eaf869b 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/stack-events/resource-errors.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/stack-events/resource-errors.ts @@ -66,6 +66,8 @@ export interface ResourceError { /** * Error code of the resource + * + * For an early-validation finding this is the ID of the rule that produced it. */ readonly errorCode?: string; diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/validate/early-validation-acknowledgements.ts b/packages/@aws-cdk/toolkit-lib/lib/api/validate/early-validation-acknowledgements.ts new file mode 100644 index 000000000..8cd830680 --- /dev/null +++ b/packages/@aws-cdk/toolkit-lib/lib/api/validate/early-validation-acknowledgements.ts @@ -0,0 +1,185 @@ +import * as cxapi from '@aws-cdk/cloud-assembly-api'; +import type { PolicyViolationJson, SuppressedViolationJson } from '@aws-cdk/cloud-assembly-schema'; + +/** + * The metadata entry type the framework records an acknowledgement under. + */ +export const ACKNOWLEDGED_RULES_METADATA_TYPE = 'aws:cdk:acknowledged-rules'; + +/** + * The plugin name the early validation findings are reported under. + */ +export const EARLY_VALIDATION_PLUGIN_NAME = 'CloudFormation'; + +/** + * The rule name used for a finding CloudFormation does not have a name for. + */ +export const UNNAMED_EARLY_VALIDATION_RULE = 'CloudFormationValidation'; + +/** + * An acknowledgement declared in the CDK app. + */ +export interface EarlyValidationAcknowledgement { + /** + * The acknowledged rule ID, as the framework normalized it (`CloudFormation::MyRule`). + */ + readonly id: string; + + /** + * The construct path the acknowledgement was declared on, without a leading slash. + */ + readonly acknowledgedAt: string; + + /** + * The reason given for the acknowledgement, if any. + */ + readonly reason?: string; + + /** + * Where in the user's code the acknowledgement was declared, if the app recorded a trace. + */ + readonly acknowledgedStackTrace?: string; +} + +/** + * Derive the error code of an early validation finding from the name CloudFormation gave it. + * + * The error code doubles as the rule ID a user names in an acknowledgement, so it must identify + * the rule and nothing else: not the event it was reported on, and not the type of the control it + * came from. A validation that comes from a control is named ` | `, and + * gets the control ID. Anything else keeps the name as given. + * + * A finding CloudFormation did not name gets a code to display, but cannot be acknowledged: the + * only name we could offer is shared by every unnamed finding, so acknowledging one would silence + * all other findings that are missing a name. + */ +export function earlyValidationErrorCode(validationName: string | undefined): string { + const name = validationName?.trim(); + if (!name) { + return UNNAMED_EARLY_VALIDATION_RULE; + } + + const [controlId] = name.split(' | '); + + return cxapi.escapeValidationRuleName(controlId.trim() || name); +} + +/** + * The rule fields to report an early validation finding under. + * + * The finding's error code is the rule ID, and marks an unnamed finding unsuppressible. + */ +export function violationRuleFields(errorCode: string | undefined): Pick { + const ruleName = errorCode ? cxapi.escapeValidationRuleName(errorCode) : UNNAMED_EARLY_VALIDATION_RULE; + + return { + ruleName, + ...(ruleName === UNNAMED_EARLY_VALIDATION_RULE ? { ruleMetadata: { [cxapi.NOT_SUPPRESSIBLE_RULE_METADATA_KEY]: 'true' } } : {}), + }; +} + +/** + * Read the acknowledgements that were declared inside the given stack. + */ +export function readAcknowledgements(stack: cxapi.CloudFormationStackArtifact): EarlyValidationAcknowledgement[] { + const ret: EarlyValidationAcknowledgement[] = []; + + for (const entry of stack.findMetadataByType(ACKNOWLEDGED_RULES_METADATA_TYPE)) { + // Metadata paths have a leading slash; construct paths elsewhere in the assembly do not. + const acknowledgedAt = entry.path.replace(/^\//, ''); + const acknowledgedStackTrace = entry.trace?.join('\n'); + + for (const [id, reason] of Object.entries((entry.data ?? {}) as Record)) { + ret.push({ + id, + acknowledgedAt, + reason: typeof reason === 'string' && reason !== '' ? reason : undefined, + acknowledgedStackTrace, + }); + } + } + + return ret; +} + +/** + * Split violations into the ones still to report and the ones an acknowledgement covers. + * + * An acknowledgement applies to a violation when it names the violation's rule and was declared on + * the construct the violation is about, or on one of its ancestors. A violation about the stack + * rather than a specific construct is covered by any acknowledgement of its rule in that stack. + */ +export function partitionAcknowledged( + violations: PolicyViolationJson[], + acknowledgements: EarlyValidationAcknowledgement[], +): { violations: PolicyViolationJson[]; suppressedViolations: SuppressedViolationJson[] } { + if (acknowledgements.length === 0) { + return { violations, suppressedViolations: [] }; + } + + const pluginNs = cxapi.namespaceFromPluginName(EARLY_VALIDATION_PLUGIN_NAME); + + const kept: PolicyViolationJson[] = []; + const suppressed: SuppressedViolationJson[] = []; + + for (const violation of violations) { + const ack = findAcknowledgement(violation, acknowledgements, pluginNs); + if (!ack) { + kept.push(violation); + continue; + } + + suppressed.push({ + ...violation, + acknowledgedId: ack.id, + ...(ack.reason !== undefined ? { reason: ack.reason } : {}), + acknowledgedAt: ack.acknowledgedAt, + ...(ack.acknowledgedStackTrace !== undefined ? { acknowledgedStackTrace: ack.acknowledgedStackTrace } : {}), + }); + } + + return { violations: kept, suppressedViolations: suppressed }; +} + +/** + * The acknowledgement that covers this violation, if any. + * + * When several apply, the one declared closest to the violating construct wins, so the reason and + * the source location reported for the suppression are the ones the user would expect. + */ +function findAcknowledgement( + violation: PolicyViolationJson, + acknowledgements: EarlyValidationAcknowledgement[], + pluginNs: cxapi.Namespace, +): EarlyValidationAcknowledgement | undefined { + if (!cxapi.isSuppressibleViolation(violation)) { + return undefined; + } + + const ruleId = cxapi.normalizeValidationId(violation.ruleName, pluginNs); + const candidates = acknowledgements.filter((ack) => cxapi.normalizeValidationId(ack.id, pluginNs) === ruleId); + if (candidates.length === 0) { + return undefined; + } + + const constructPath = violation.violatingConstructs + .map((c) => c.constructPath) + .find((p): p is string => p !== undefined && p !== ''); + + // A finding about the stack itself has no construct to scope against, so any acknowledgement of + // its rule in this stack covers it. + if (constructPath === undefined) { + return candidates[0]; + } + + const applicable = candidates.filter((ack) => coversPath(ack.acknowledgedAt, constructPath)); + + return applicable.sort((a, b) => b.acknowledgedAt.length - a.acknowledgedAt.length)[0]; +} + +/** + * Whether an acknowledgement declared at `ackPath` covers a construct at `constructPath`. + */ +function coversPath(ackPath: string, constructPath: string): boolean { + return ackPath === '' || constructPath === ackPath || constructPath.startsWith(`${ackPath}/`); +} diff --git a/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts b/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts index 104cc7ec1..8ac2b1e29 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts @@ -2,7 +2,7 @@ import '../private/dispose-polyfill'; import { randomUUID } from 'node:crypto'; import * as path from 'node:path'; import * as cxapi from '@aws-cdk/cloud-assembly-api'; -import type { FeatureFlagReportProperties, PluginReportJson } from '@aws-cdk/cloud-assembly-schema'; +import type { FeatureFlagReportProperties, PluginReportJson, PolicyViolationJson, PolicyViolationSeverity, SuppressedViolationJson } from '@aws-cdk/cloud-assembly-schema'; import { ArtifactType } from '@aws-cdk/cloud-assembly-schema'; import type { TemplateDiff } from '@aws-cdk/cloudformation-diff'; import chalk from 'chalk'; @@ -48,7 +48,7 @@ import { toExecuteChangeSetDeployment, } from '../actions/deploy/private'; import { type DestroyOptions } from '../actions/destroy'; -import type { DiagnosedStack, DiagnoseOptions, DiagnoseResult } from '../actions/diagnose'; +import type { DiagnosedStack, DiagnoseOptions, DiagnoseResult, TracedResourceError } from '../actions/diagnose'; import type { DiffOptions } from '../actions/diff'; import { appendObject, prepareDiff } from '../actions/diff/private'; import type { DriftOptions, DriftResult } from '../actions/drift'; @@ -107,6 +107,12 @@ import { ResourceMigrator } from '../api/resource-import'; import { StackArtifactSourceTracer } from '../api/source-tracing/private/stack-source-tracing'; import { tagsForStack } from '../api/tags/private'; import { DEFAULT_TOOLKIT_STACK_NAME } from '../api/toolkit-info'; +import { + EARLY_VALIDATION_PLUGIN_NAME, + partitionAcknowledged, + readAcknowledgements, + violationRuleFields, +} from '../api/validate/early-validation-acknowledgements'; import { hostMessageFromValidation } from '../api/validate/validate-formatting'; import type { AssetBuildNode, AssetPublishNode, Concurrency, StackNode } from '../api/work-graph'; import { WorkGraph, WorkGraphBuilder, buildDestroyWorkGraph } from '../api/work-graph'; @@ -736,7 +742,8 @@ export class Toolkit extends CloudAssemblySourceBuilder { stacks: StackCollection, deployments: Deployments, ): Promise { - const violations: PluginReportJson['violations'] = []; + const violations: PolicyViolationJson[] = []; + const suppressedViolations: SuppressedViolationJson[] = []; for (const stack of stacks.stackArtifacts) { try { @@ -748,37 +755,54 @@ export class Toolkit extends CloudAssemblySourceBuilder { failOnError: true, }); + const violation = (finding: TracedResourceError, severity: PolicyViolationSeverity): PolicyViolationJson => ({ + // A finding's error code is the ID of the rule that produced it, which is the ID a user + // names to acknowledge it. + ...violationRuleFields(finding.errorCode), + description: finding.message.replace(/\s*\(at\s+\/Resources\/[^)]+\)\s*$/, ''), + severity, + violatingConstructs: [{ + constructPath: finding.sourceTrace?.constructPath ?? (finding.logicalId ? `${stack.hierarchicalId}/${finding.logicalId}` : stack.hierarchicalId), + cloudFormationResource: finding.logicalId ? { + templatePath: `${stack.stackName}.template.json`, + logicalId: finding.logicalId, + } : undefined, + stackTraces: finding.sourceTrace?.creationStackTrace ? [finding.sourceTrace.creationStackTrace.join('\n')] : undefined, + }], + }); + + const stackViolations: PolicyViolationJson[] = []; const diagnosis = report.diagnosis.result; if (diagnosis.type === 'problem') { - for (const problem of diagnosis.problems) { - violations.push({ - ruleName: problem.errorCode ?? 'CloudFormationValidation', - description: problem.message.replace(/\s*\(at\s+\/Resources\/[^)]+\)\s*$/, ''), - severity: 'fatal', - violatingConstructs: [{ - constructPath: problem.sourceTrace?.constructPath ?? (problem.logicalId ? `${stack.hierarchicalId}/${problem.logicalId}` : stack.hierarchicalId), - cloudFormationResource: problem.logicalId ? { - templatePath: `${stack.stackName}.template.json`, - logicalId: problem.logicalId, - } : undefined, - stackTraces: problem.sourceTrace?.creationStackTrace ? [problem.sourceTrace.creationStackTrace.join('\n')] : undefined, - }], - }); - } + stackViolations.push(...diagnosis.problems.map((p) => violation(p, 'fatal'))); } + stackViolations.push(...report.diagnosis.warnings.map((w) => violation(w, 'warning'))); + + // Acknowledgements are declared per construct, so they can only be applied per stack. + // `partitionAcknowledged` leaves anything unsuppressible where it is, which is what keeps + // the fatal problems above from being acknowledged away. + const partitioned = partitionAcknowledged( + stackViolations, + stackViolations.length > 0 ? readAcknowledgements(stack) : [], + ); + violations.push(...partitioned.violations); + suppressedViolations.push(...partitioned.suppressedViolations); } catch (e: any) { await ioHelper.notify(IO.CDK_TOOLKIT_W9602.msg(`Online validation could not be completed for stack '${stack.hierarchicalId}': ${e.message}`)); } } - if (violations.length === 0) { + // A report with nothing but suppressed violations still goes out: it reports nothing to the + // user, but it is the audit trail of what their acknowledgements hid. + if (violations.length === 0 && suppressedViolations.length === 0) { return undefined; } return { - pluginName: 'CloudFormation', - conclusion: 'failure', + pluginName: EARLY_VALIDATION_PLUGIN_NAME, + conclusion: violations.some((v) => v.severity === 'fatal') ? 'failure' : 'success', violations, + ...(suppressedViolations.length > 0 ? { suppressedViolations } : {}), }; } @@ -807,6 +831,9 @@ export class Toolkit extends CloudAssemblySourceBuilder { stacks: [], }; + // Number of early validation warnings in a stack + let earlyValidationWarnings = 0; + if (stackCollection.stackCount === 0) { await ioHelper.notify(IO.CDK_TOOLKIT_E5001.msg('This app contains no stacks')); return ret; @@ -1074,6 +1101,8 @@ export class Toolkit extends CloudAssemblySourceBuilder { await ioHelper.notify(IO.CDK_TOOLKIT_I5900.msg(chalk.green('\n' + message), deployResult)); deployDuration = await deploySpan.timing(IO.CDK_TOOLKIT_I5000); + earlyValidationWarnings += deployResult.earlyValidationWarnings ?? 0; + if (options.express) { const warning = formatExpressStabilizationWarning(deployResult.stabilizingResources, 'deploy'); if (warning) { @@ -1169,6 +1198,12 @@ export class Toolkit extends CloudAssemblySourceBuilder { marker: WorkGraph.NOOP, }); + if (earlyValidationWarnings > 0) { + await ioHelper.notify(IO.CDK_TOOLKIT_W5903.msg( + `⚠️ Completed with ${earlyValidationWarnings} ${earlyValidationWarnings === 1 ? 'warning' : 'warnings'} from change set creation.\n`, + )); + } + return ret; } diff --git a/packages/@aws-cdk/toolkit-lib/test/_fixtures/stack-with-acknowledged-rules/cdk.out/Stack1.assets.json b/packages/@aws-cdk/toolkit-lib/test/_fixtures/stack-with-acknowledged-rules/cdk.out/Stack1.assets.json new file mode 100644 index 000000000..996ea74b7 --- /dev/null +++ b/packages/@aws-cdk/toolkit-lib/test/_fixtures/stack-with-acknowledged-rules/cdk.out/Stack1.assets.json @@ -0,0 +1,21 @@ +{ + "version": "53.0.0", + "files": { + "0b94555154840be84b75bd70846794c140a97ec39d47373114e0dab537e1cb82": { + "displayName": "Stack1 Template", + "source": { + "path": "Stack1.template.json", + "packaging": "file" + }, + "destinations": { + "123456789012-us-east-1-602ae211": { + "bucketName": "cdk-hnb659fds-assets-123456789012-us-east-1", + "objectKey": "0b94555154840be84b75bd70846794c140a97ec39d47373114e0dab537e1cb82.json", + "region": "us-east-1", + "assumeRoleArn": "arn:${AWS::Partition}:iam::123456789012:role/cdk-hnb659fds-file-publishing-role-123456789012-us-east-1" + } + } + } + }, + "dockerImages": {} +} \ No newline at end of file diff --git a/packages/@aws-cdk/toolkit-lib/test/_fixtures/stack-with-acknowledged-rules/cdk.out/Stack1.metadata.json b/packages/@aws-cdk/toolkit-lib/test/_fixtures/stack-with-acknowledged-rules/cdk.out/Stack1.metadata.json new file mode 100644 index 000000000..fd7a9c147 --- /dev/null +++ b/packages/@aws-cdk/toolkit-lib/test/_fixtures/stack-with-acknowledged-rules/cdk.out/Stack1.metadata.json @@ -0,0 +1,37 @@ +{ + "/Stack1": [ + { + "type": "aws:cdk:acknowledged-rules", + "data": { + "CloudFormation::SQS_QUEUE_REMOVED": "the queue moved to another stack" + }, + "trace": [ + "at Object. (/app/lib/app.ts:12:28)" + ] + } + ], + "/Stack1/BootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "BootstrapVersion" + } + ], + "/Stack1/CheckBootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "CheckBootstrapVersion" + } + ], + "/Stack1/MyBucket/Resource": [ + { + "type": "aws:cdk:logicalId", + "data": "MyBucketF68F3FF0" + } + ], + "/Stack1/CDKMetadata/Default": [ + { + "type": "aws:cdk:logicalId", + "data": "CDKMetadata" + } + ] +} diff --git a/packages/@aws-cdk/toolkit-lib/test/_fixtures/stack-with-acknowledged-rules/cdk.out/Stack1.template.json b/packages/@aws-cdk/toolkit-lib/test/_fixtures/stack-with-acknowledged-rules/cdk.out/Stack1.template.json new file mode 100644 index 000000000..88d09130c --- /dev/null +++ b/packages/@aws-cdk/toolkit-lib/test/_fixtures/stack-with-acknowledged-rules/cdk.out/Stack1.template.json @@ -0,0 +1,55 @@ +{ + "Resources": { + "MyBucketF68F3FF0": { + "Type": "AWS::S3::Bucket", + "UpdateReplacePolicy": "Retain", + "DeletionPolicy": "Retain", + "Metadata": { + "aws:cdk:path": "Stack1/MyBucket/Resource" + } + }, + "CDKMetadata": { + "Type": "AWS::CDK::Metadata", + "Properties": { + "Analytics": "v2:deflate64:H4sIAAAAAAAA/zPSMzIx1TNQTCwv1k1OydbNyUzSqw4uSUzO1kksL44vNtardipNzk4t0XFOy4Owamt18vJTUvWyivXLjEz0DE30DBSzijMzdYtK80oyc1P1giA0AGuqxf1bAAAA" + }, + "Metadata": { + "aws:cdk:path": "Stack1/CDKMetadata/Default" + } + } + }, + "Parameters": { + "BootstrapVersion": { + "Type": "AWS::SSM::Parameter::Value", + "Default": "/cdk-bootstrap/hnb659fds/version", + "Description": "Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store. [cdk:skip]" + } + }, + "Rules": { + "CheckBootstrapVersion": { + "Assertions": [ + { + "Assert": { + "Fn::Not": [ + { + "Fn::Contains": [ + [ + "1", + "2", + "3", + "4", + "5" + ], + { + "Ref": "BootstrapVersion" + } + ] + } + ] + }, + "AssertDescription": "CDK bootstrap stack version 6 required. Please run 'cdk bootstrap' with a recent version of the CDK CLI." + } + ] + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk/toolkit-lib/test/_fixtures/stack-with-acknowledged-rules/cdk.out/cdk.out b/packages/@aws-cdk/toolkit-lib/test/_fixtures/stack-with-acknowledged-rules/cdk.out/cdk.out new file mode 100644 index 000000000..60aa68e15 --- /dev/null +++ b/packages/@aws-cdk/toolkit-lib/test/_fixtures/stack-with-acknowledged-rules/cdk.out/cdk.out @@ -0,0 +1 @@ +{"version":"53.0.0"} \ No newline at end of file diff --git a/packages/@aws-cdk/toolkit-lib/test/_fixtures/stack-with-acknowledged-rules/cdk.out/manifest.json b/packages/@aws-cdk/toolkit-lib/test/_fixtures/stack-with-acknowledged-rules/cdk.out/manifest.json new file mode 100644 index 000000000..0730cda91 --- /dev/null +++ b/packages/@aws-cdk/toolkit-lib/test/_fixtures/stack-with-acknowledged-rules/cdk.out/manifest.json @@ -0,0 +1,481 @@ +{ + "version": "53.0.0", + "artifacts": { + "Stack1.assets": { + "type": "cdk:asset-manifest", + "properties": { + "file": "Stack1.assets.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "Stack1": { + "type": "aws:cloudformation:stack", + "environment": "aws://123456789012/us-east-1", + "properties": { + "templateFile": "Stack1.template.json", + "terminationProtection": false, + "validateOnSynth": false, + "assumeRoleArn": "arn:${AWS::Partition}:iam::123456789012:role/cdk-hnb659fds-deploy-role-123456789012-us-east-1", + "cloudFormationExecutionRoleArn": "arn:${AWS::Partition}:iam::123456789012:role/cdk-hnb659fds-cfn-exec-role-123456789012-us-east-1", + "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-123456789012-us-east-1/0b94555154840be84b75bd70846794c140a97ec39d47373114e0dab537e1cb82.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version", + "additionalDependencies": [ + "Stack1.assets" + ], + "lookupRole": { + "arn": "arn:${AWS::Partition}:iam::123456789012:role/cdk-hnb659fds-lookup-role-123456789012-us-east-1", + "requiresBootstrapStackVersion": 8, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "dependencies": [ + "Stack1.assets" + ], + "additionalMetadataFile": "Stack1.metadata.json", + "displayName": "Stack1" + }, + "Tree": { + "type": "cdk:tree", + "properties": { + "file": "tree.json" + } + }, + "aws-cdk-lib/feature-flag-report": { + "type": "cdk:feature-flag-report", + "properties": { + "module": "aws-cdk-lib", + "flags": { + "@aws-cdk/aws-signer:signingProfileNamePassedToCfn": { + "recommendedValue": true, + "explanation": "Pass signingProfileName to CfnSigningProfile" + }, + "@aws-cdk/core:newStyleStackSynthesis": { + "recommendedValue": true, + "explanation": "Switch to new stack synthesis method which enables CI/CD", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/core:stackRelativeExports": { + "recommendedValue": true, + "explanation": "Name exports based on the construct paths relative to the stack, rather than the global construct path", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-ecs-patterns:secGroupsDisablesImplicitOpenListener": { + "recommendedValue": true, + "explanation": "Disable implicit openListener when custom security groups are provided" + }, + "@aws-cdk/aws-rds:lowercaseDbIdentifier": { + "recommendedValue": true, + "explanation": "Force lowercasing of RDS Cluster names in CDK", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId": { + "recommendedValue": true, + "explanation": "Allow adding/removing multiple UsagePlanKeys independently", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-lambda:recognizeVersionProps": { + "recommendedValue": true, + "explanation": "Enable this feature flag to opt in to the updated logical id calculation for Lambda Version created using the `fn.currentVersion`.", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-lambda:recognizeLayerVersion": { + "recommendedValue": true, + "explanation": "Enable this feature flag to opt in to the updated logical id calculation for Lambda Version created using the `fn.currentVersion`." + }, + "@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021": { + "recommendedValue": true, + "explanation": "Enable this feature flag to have cloudfront distributions use the security policy TLSv1.2_2021 by default.", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/core:checkSecretUsage": { + "recommendedValue": true, + "explanation": "Enable this flag to make it impossible to accidentally use SecretValues in unsafe locations" + }, + "@aws-cdk/core:target-partitions": { + "recommendedValue": [ + "aws", + "aws-cn" + ], + "explanation": "What regions to include in lookup tables of environment agnostic stacks" + }, + "@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": { + "recommendedValue": true, + "explanation": "ECS extensions will automatically add an `awslogs` driver if no logging is specified" + }, + "@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": { + "recommendedValue": true, + "explanation": "Enable this feature flag to have Launch Templates generated by the `InstanceRequireImdsv2Aspect` use unique names." + }, + "@aws-cdk/aws-ecs:arnFormatIncludesClusterName": { + "recommendedValue": true, + "explanation": "ARN format used by ECS. In the new ARN format, the cluster name is part of the resource ID." + }, + "@aws-cdk/aws-iam:minimizePolicies": { + "recommendedValue": true, + "explanation": "Minimize IAM policies by combining Statements" + }, + "@aws-cdk/core:validateSnapshotRemovalPolicy": { + "recommendedValue": true, + "explanation": "Error on snapshot removal policies on resources that do not support it." + }, + "@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": { + "recommendedValue": true, + "explanation": "Generate key aliases that include the stack name" + }, + "@aws-cdk/aws-s3:createDefaultLoggingPolicy": { + "recommendedValue": true, + "explanation": "Enable this feature flag to create an S3 bucket policy by default in cases where an AWS service would automatically create the Policy if one does not exist." + }, + "@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": { + "recommendedValue": true, + "explanation": "Restrict KMS key policy for encrypted Queues a bit more" + }, + "@aws-cdk/aws-apigateway:disableCloudWatchRole": { + "recommendedValue": true, + "explanation": "Make default CloudWatch Role behavior safe for multiple API Gateways in one environment" + }, + "@aws-cdk/core:enablePartitionLiterals": { + "recommendedValue": true, + "explanation": "Make ARNs concrete if AWS partition is known" + }, + "@aws-cdk/aws-events:eventsTargetQueueSameAccount": { + "recommendedValue": true, + "explanation": "Event Rules may only push to encrypted SQS queues in the same account" + }, + "@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": { + "recommendedValue": true, + "explanation": "Avoid setting the \"ECS\" deployment controller when adding a circuit breaker" + }, + "@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": { + "recommendedValue": true, + "explanation": "Enable this feature to create default policy names for imported roles that depend on the stack the role is in." + }, + "@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": { + "recommendedValue": true, + "explanation": "Use S3 Bucket Policy instead of ACLs for Server Access Logging" + }, + "@aws-cdk/aws-route53-patters:useCertificate": { + "recommendedValue": true, + "explanation": "Use the official `Certificate` resource instead of `DnsValidatedCertificate`" + }, + "@aws-cdk/customresources:installLatestAwsSdkDefault": { + "recommendedValue": false, + "explanation": "Whether to install the latest SDK by default in AwsCustomResource" + }, + "@aws-cdk/aws-rds:databaseProxyUniqueResourceName": { + "recommendedValue": true, + "explanation": "Use unique resource name for Database Proxy" + }, + "@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": { + "recommendedValue": true, + "explanation": "Remove CloudWatch alarms from deployment group" + }, + "@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": { + "recommendedValue": true, + "explanation": "Include authorizer configuration in the calculation of the API deployment logical ID." + }, + "@aws-cdk/aws-ec2:launchTemplateDefaultUserData": { + "recommendedValue": true, + "explanation": "Define user data for a launch template by default when a machine image is provided." + }, + "@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": { + "recommendedValue": true, + "explanation": "SecretTargetAttachments uses the ResourcePolicy of the attached Secret." + }, + "@aws-cdk/aws-redshift:columnId": { + "recommendedValue": true, + "explanation": "Whether to use an ID to track Redshift column changes" + }, + "@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": { + "recommendedValue": true, + "explanation": "Enable AmazonEMRServicePolicy_v2 managed policies" + }, + "@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": { + "recommendedValue": true, + "explanation": "Restrict access to the VPC default security group" + }, + "@aws-cdk/aws-apigateway:requestValidatorUniqueId": { + "recommendedValue": true, + "explanation": "Generate a unique id for each RequestValidator added to a method" + }, + "@aws-cdk/aws-kms:aliasNameRef": { + "recommendedValue": true, + "explanation": "KMS Alias name and keyArn will have implicit reference to KMS Key" + }, + "@aws-cdk/aws-kms:applyImportedAliasPermissionsToPrincipal": { + "recommendedValue": true, + "explanation": "Enable grant methods on Aliases imported by name to use kms:ResourceAliases condition" + }, + "@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": { + "recommendedValue": true, + "explanation": "Generate a launch template when creating an AutoScalingGroup" + }, + "@aws-cdk/core:includePrefixInUniqueNameGeneration": { + "recommendedValue": true, + "explanation": "Include the stack prefix in the stack name generation process" + }, + "@aws-cdk/aws-efs:denyAnonymousAccess": { + "recommendedValue": true, + "explanation": "EFS denies anonymous clients accesses" + }, + "@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": { + "recommendedValue": true, + "explanation": "Enables support for Multi-AZ with Standby deployment for opensearch domains" + }, + "@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": { + "recommendedValue": true, + "explanation": "Enables aws-lambda-nodejs.Function to use the latest available NodeJs runtime as the default" + }, + "@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": { + "recommendedValue": true, + "explanation": "When enabled, mount targets will have a stable logicalId that is linked to the associated subnet." + }, + "@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": { + "recommendedValue": true, + "explanation": "When enabled, a scope of InstanceParameterGroup for AuroraClusterInstance with each parameters will change." + }, + "@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": { + "recommendedValue": true, + "explanation": "When enabled, will always use the arn for identifiers for CfnSourceApiAssociation in the GraphqlApi construct rather than id." + }, + "@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": { + "recommendedValue": true, + "explanation": "When enabled, creating an RDS database cluster from a snapshot will only render credentials for snapshot credentials." + }, + "@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForCodeCommitSource": { + "recommendedValue": true, + "explanation": "When enabled, the CodeCommit source action is using the default branch name 'main'." + }, + "@aws-cdk/aws-cloudwatch-actions:changeLambdaPermissionLogicalIdForLambdaAction": { + "recommendedValue": true, + "explanation": "When enabled, the logical ID of a Lambda permission for a Lambda action includes an alarm ID." + }, + "@aws-cdk/aws-codepipeline:crossAccountKeysDefaultValueToFalse": { + "recommendedValue": true, + "explanation": "Enables Pipeline to set the default value for crossAccountKeys to false." + }, + "@aws-cdk/aws-codepipeline:defaultPipelineTypeToV2": { + "recommendedValue": true, + "explanation": "Enables Pipeline to set the default pipeline type to V2." + }, + "@aws-cdk/aws-kms:reduceCrossAccountRegionPolicyScope": { + "recommendedValue": true, + "explanation": "When enabled, IAM Policy created from KMS key grant will reduce the resource scope to this key only." + }, + "@aws-cdk/pipelines:reduceAssetRoleTrustScope": { + "recommendedValue": true, + "explanation": "Remove the root account principal from PipelineAssetsFileRole trust policy", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-eks:nodegroupNameAttribute": { + "recommendedValue": true, + "explanation": "When enabled, nodegroupName attribute of the provisioned EKS NodeGroup will not have the cluster name prefix." + }, + "@aws-cdk/aws-eks:useNativeOidcProvider": { + "recommendedValue": true, + "explanation": "When enabled, EKS V2 clusters will use the native OIDC provider resource AWS::IAM::OIDCProvider instead of creating the OIDCProvider with a custom resource (iam.OpenIDConnectProvider)." + }, + "@aws-cdk/aws-ec2:ebsDefaultGp3Volume": { + "recommendedValue": true, + "explanation": "When enabled, the default volume type of the EBS volume will be GP3" + }, + "@aws-cdk/aws-ecs:removeDefaultDeploymentAlarm": { + "recommendedValue": true, + "explanation": "When enabled, remove default deployment alarm settings" + }, + "@aws-cdk/custom-resources:logApiResponseDataPropertyTrueDefault": { + "recommendedValue": false, + "explanation": "When enabled, the custom resource used for `AwsCustomResource` will configure the `logApiResponseData` property as true by default" + }, + "@aws-cdk/aws-s3:keepNotificationInImportedBucket": { + "recommendedValue": false, + "explanation": "When enabled, Adding notifications to a bucket in the current stack will not remove notification from imported stack." + }, + "@aws-cdk/aws-stepfunctions-tasks:useNewS3UriParametersForBedrockInvokeModelTask": { + "recommendedValue": true, + "explanation": "When enabled, use new props for S3 URI field in task definition of state machine for bedrock invoke model.", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/core:explicitStackTags": { + "recommendedValue": true, + "explanation": "When enabled, stack tags need to be assigned explicitly on a Stack." + }, + "@aws-cdk/aws-ecs:reduceEc2FargateCloudWatchPermissions": { + "recommendedValue": true, + "explanation": "When enabled, we will only grant the necessary permissions when users specify cloudwatch log group through logConfiguration" + }, + "@aws-cdk/aws-dynamodb:resourcePolicyPerReplica": { + "recommendedValue": true, + "explanation": "When enabled will allow you to specify a resource policy per replica, and not copy the source table policy to all replicas" + }, + "@aws-cdk/aws-ec2:ec2SumTImeoutEnabled": { + "recommendedValue": true, + "explanation": "When enabled, initOptions.timeout and resourceSignalTimeout values will be summed together." + }, + "@aws-cdk/aws-appsync:appSyncGraphQLAPIScopeLambdaPermission": { + "recommendedValue": true, + "explanation": "When enabled, a Lambda authorizer Permission created when using GraphqlApi will be properly scoped with a SourceArn." + }, + "@aws-cdk/aws-rds:setCorrectValueForDatabaseInstanceReadReplicaInstanceResourceId": { + "recommendedValue": true, + "explanation": "When enabled, the value of property `instanceResourceId` in construct `DatabaseInstanceReadReplica` will be set to the correct value which is `DbiResourceId` instead of currently `DbInstanceArn`" + }, + "@aws-cdk/core:cfnIncludeRejectComplexResourceUpdateCreatePolicyIntrinsics": { + "recommendedValue": true, + "explanation": "When enabled, CFN templates added with `cfn-include` will error if the template contains Resource Update or Create policies with CFN Intrinsics that include non-primitive values." + }, + "@aws-cdk/aws-lambda-nodejs:sdkV3ExcludeSmithyPackages": { + "recommendedValue": true, + "explanation": "When enabled, both `@aws-sdk` and `@smithy` packages will be excluded from the Lambda Node.js 18.x runtime to prevent version mismatches in bundled applications." + }, + "@aws-cdk/aws-stepfunctions-tasks:fixRunEcsTaskPolicy": { + "recommendedValue": true, + "explanation": "When enabled, the resource of IAM Run Ecs policy generated by SFN EcsRunTask will reference the definition, instead of constructing ARN." + }, + "@aws-cdk/aws-ec2:bastionHostUseAmazonLinux2023ByDefault": { + "recommendedValue": true, + "explanation": "When enabled, the BastionHost construct will use the latest Amazon Linux 2023 AMI, instead of Amazon Linux 2." + }, + "@aws-cdk/core:aspectStabilization": { + "recommendedValue": true, + "explanation": "When enabled, a stabilization loop will be run when invoking Aspects during synthesis.", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-route53-targets:userPoolDomainNameMethodWithoutCustomResource": { + "recommendedValue": true, + "explanation": "When enabled, use a new method for DNS Name of user pool domain target without creating a custom resource." + }, + "@aws-cdk/aws-elasticloadbalancingV2:albDualstackWithoutPublicIpv4SecurityGroupRulesDefault": { + "recommendedValue": true, + "explanation": "When enabled, the default security group ingress rules will allow IPv6 ingress from anywhere" + }, + "@aws-cdk/aws-iam:oidcRejectUnauthorizedConnections": { + "recommendedValue": true, + "explanation": "When enabled, the default behaviour of OIDC provider will reject unauthorized connections" + }, + "@aws-cdk/core:enableAdditionalMetadataCollection": { + "recommendedValue": true, + "explanation": "When enabled, CDK will expand the scope of usage data collected to better inform CDK development and improve communication for security concerns and emerging issues." + }, + "@aws-cdk/aws-lambda:createNewPoliciesWithAddToRolePolicy": { + "recommendedValue": false, + "explanation": "[Deprecated] When enabled, Lambda will create new inline policies with AddToRolePolicy instead of adding to the Default Policy Statement" + }, + "@aws-cdk/aws-s3:setUniqueReplicationRoleName": { + "recommendedValue": true, + "explanation": "When enabled, CDK will automatically generate a unique role name that is used for s3 object replication." + }, + "@aws-cdk/pipelines:reduceStageRoleTrustScope": { + "recommendedValue": true, + "explanation": "Remove the root account principal from Stage addActions trust policy", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-events:requireEventBusPolicySid": { + "recommendedValue": true, + "explanation": "When enabled, grantPutEventsTo() will use resource policies with Statement IDs for service principals." + }, + "@aws-cdk/core:aspectPrioritiesMutating": { + "recommendedValue": true, + "explanation": "When set to true, Aspects added by the construct library on your behalf will be given a priority of MUTATING." + }, + "@aws-cdk/aws-dynamodb:retainTableReplica": { + "recommendedValue": true, + "explanation": "When enabled, table replica will be default to the removal policy of source table unless specified otherwise." + }, + "@aws-cdk/cognito:logUserPoolClientSecretValue": { + "recommendedValue": false, + "explanation": "When disabled, the value of the user pool client secret will not be logged in the custom resource lambda function logs." + }, + "@aws-cdk/pipelines:reduceCrossAccountActionRoleTrustScope": { + "recommendedValue": true, + "explanation": "When enabled, scopes down the trust policy for the cross-account action role", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-stepfunctions:useDistributedMapResultWriterV2": { + "recommendedValue": true, + "explanation": "When enabled, the resultWriterV2 property of DistributedMap will be used insted of resultWriter" + }, + "@aws-cdk/s3-notifications:addS3TrustKeyPolicyForSnsSubscriptions": { + "recommendedValue": true, + "explanation": "Add an S3 trust policy to a KMS key resource policy for SNS subscriptions." + }, + "@aws-cdk/aws-ec2:requirePrivateSubnetsForEgressOnlyInternetGateway": { + "recommendedValue": true, + "explanation": "When enabled, the EgressOnlyGateway resource is only created if private subnets are defined in the dual-stack VPC." + }, + "@aws-cdk/aws-ec2-alpha:useResourceIdForVpcV2Migration": { + "recommendedValue": false, + "explanation": "When enabled, use resource IDs for VPC V2 migration" + }, + "@aws-cdk/aws-s3:publicAccessBlockedByDefault": { + "recommendedValue": true, + "explanation": "When enabled, setting any combination of options for BlockPublicAccess will automatically set true for any options not defined." + }, + "@aws-cdk/aws-lambda:useCdkManagedLogGroup": { + "recommendedValue": true, + "explanation": "When enabled, CDK creates and manages loggroup for the lambda function" + }, + "@aws-cdk/aws-elasticloadbalancingv2:networkLoadBalancerWithSecurityGroupByDefault": { + "recommendedValue": true, + "explanation": "When enabled, Network Load Balancer will be created with a security group by default." + }, + "@aws-cdk/aws-stepfunctions-tasks:httpInvokeDynamicJsonPathEndpoint": { + "recommendedValue": true, + "explanation": "When enabled, allows using a dynamic apiEndpoint with JSONPath format in HttpInvoke tasks.", + "unconfiguredBehavesLike": { + "v2": true + } + }, + "@aws-cdk/aws-ecs-patterns:uniqueTargetGroupId": { + "recommendedValue": true, + "explanation": "When enabled, ECS patterns will generate unique target group IDs to prevent conflicts during load balancer replacement" + }, + "@aws-cdk/aws-route53-patterns:useDistribution": { + "recommendedValue": true, + "explanation": "Use the `Distribution` resource instead of `CloudFrontWebDistribution`" + }, + "@aws-cdk/aws-cloudfront:defaultFunctionRuntimeV2_0": { + "recommendedValue": true, + "explanation": "Use cloudfront-js-2.0 as the default runtime for CloudFront Functions" + }, + "@aws-cdk/aws-elasticloadbalancingv2:usePostQuantumTlsPolicy": { + "recommendedValue": true, + "explanation": "When enabled, HTTPS/TLS listeners use post-quantum TLS policy by default" + }, + "@aws-cdk/core:automaticL1Traits": { + "recommendedValue": true, + "explanation": "Automatically use the default L1 traits for L1 constructs`", + "unconfiguredBehavesLike": { + "v2": true + } + } + } + } + } + }, + "minimumCliVersion": "2.1114.1" +} \ No newline at end of file diff --git a/packages/@aws-cdk/toolkit-lib/test/_fixtures/stack-with-acknowledged-rules/cdk.out/tree.json b/packages/@aws-cdk/toolkit-lib/test/_fixtures/stack-with-acknowledged-rules/cdk.out/tree.json new file mode 100644 index 000000000..20e77ba76 --- /dev/null +++ b/packages/@aws-cdk/toolkit-lib/test/_fixtures/stack-with-acknowledged-rules/cdk.out/tree.json @@ -0,0 +1 @@ +{"version":"tree-0.1","tree":{"id":"App","path":"","constructInfo":{"fqn":"aws-cdk-lib.App","version":"2.245.0"},"children":{"Stack1":{"id":"Stack1","path":"Stack1","constructInfo":{"fqn":"aws-cdk-lib.Stack","version":"2.245.0"},"children":{"MyBucket":{"id":"MyBucket","path":"Stack1/MyBucket","constructInfo":{"fqn":"aws-cdk-lib.aws_s3.Bucket","version":"2.245.0"},"children":{"Resource":{"id":"Resource","path":"Stack1/MyBucket/Resource","constructInfo":{"fqn":"aws-cdk-lib.aws_s3.CfnBucket","version":"2.245.0"},"attributes":{"aws:cdk:cloudformation:type":"AWS::S3::Bucket","aws:cdk:cloudformation:props":{}}}}},"CDKMetadata":{"id":"CDKMetadata","path":"Stack1/CDKMetadata","constructInfo":{"fqn":"constructs.Construct","version":"10.6.0"},"children":{"Default":{"id":"Default","path":"Stack1/CDKMetadata/Default","constructInfo":{"fqn":"aws-cdk-lib.CfnResource","version":"2.245.0"}}}},"BootstrapVersion":{"id":"BootstrapVersion","path":"Stack1/BootstrapVersion","constructInfo":{"fqn":"aws-cdk-lib.CfnParameter","version":"2.245.0"}},"CheckBootstrapVersion":{"id":"CheckBootstrapVersion","path":"Stack1/CheckBootstrapVersion","constructInfo":{"fqn":"aws-cdk-lib.CfnRule","version":"2.245.0"}}}},"Tree":{"id":"Tree","path":"Tree","constructInfo":{"fqn":"constructs.Construct","version":"10.6.0"}}}}} \ No newline at end of file diff --git a/packages/@aws-cdk/toolkit-lib/test/actions/deploy.test.ts b/packages/@aws-cdk/toolkit-lib/test/actions/deploy.test.ts index 3111bd3ae..556821dd4 100644 --- a/packages/@aws-cdk/toolkit-lib/test/actions/deploy.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/actions/deploy.test.ts @@ -440,6 +440,54 @@ IAM Statement Changes successfulDeployment(); }); + test('reports how many early validation warnings the deployment produced', async () => { + // GIVEN + mockDeployStack.mockResolvedValueOnce({ + type: 'did-deploy-stack', + stackArn: 'arn:aws:cloudformation:region:account:stack/test-stack', + outputs: {}, + noOp: false, + deleteFailures: [], + stabilizingResources: [], + earlyValidationWarnings: 2, + }); + + // WHEN + const cx = await cdkOutFixture(toolkit, 'stack-with-role'); + await toolkit.deploy(cx); + + // THEN + expect(ioHost.notifySpy).toHaveBeenCalledWith(expect.objectContaining({ + code: 'CDK_TOOLKIT_W5903', + level: 'warn', + message: expect.stringContaining('2 warnings'), + })); + }); + + test('does not report a warning count when there were none', async () => { + // A direct or hotswap deployment never populates the count, so it must stay silent. + const cx = await cdkOutFixture(toolkit, 'stack-with-role'); + await toolkit.deploy(cx); + + expect(ioHost.notifySpy).not.toHaveBeenCalledWith(expect.objectContaining({ + code: 'CDK_TOOLKIT_W5903', + })); + }); + + test('does not report a warning count when the deployment failed', async () => { + // GIVEN + mockDeployStack.mockRejectedValueOnce(new Error('deployment blew up')); + + // WHEN + const cx = await cdkOutFixture(toolkit, 'stack-with-role'); + await expect(toolkit.deploy(cx)).rejects.toThrow('deployment blew up'); + + // THEN + expect(ioHost.notifySpy).not.toHaveBeenCalledWith(expect.objectContaining({ + code: 'CDK_TOOLKIT_W5903', + })); + }); + test('warns about resources still stabilizing in Express Mode', async () => { // GIVEN mockDeployStack.mockResolvedValueOnce({ diff --git a/packages/@aws-cdk/toolkit-lib/test/actions/validate.test.ts b/packages/@aws-cdk/toolkit-lib/test/actions/validate.test.ts index cefbb1bc8..4b5516947 100644 --- a/packages/@aws-cdk/toolkit-lib/test/actions/validate.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/actions/validate.test.ts @@ -2,6 +2,7 @@ import * as awsauth from '../../lib/api/aws-auth/private'; import { StackSelectionStrategy } from '../../lib/api/cloud-assembly'; import * as cfnApi from '../../lib/api/deployments/cfn-api'; import { Diagnosis } from '../../lib/api/diagnosing/diagnosis'; +import { UNNAMED_EARLY_VALIDATION_RULE } from '../../lib/api/validate/early-validation-acknowledgements'; import { Toolkit } from '../../lib/toolkit'; import { builderFixture, cdkOutFixture, TestIoHost } from '../_helpers'; import { MockSdk, restoreSdkMocksToDefault, setDefaultSTSMocks } from '../_helpers/mock-sdk'; @@ -202,6 +203,151 @@ describe('validate --online', () => { expect(result.pluginReports).toHaveLength(0); }); + test('reports early validation warnings as warnings, not failures', async () => { + jest.spyOn(cfnApi, 'createValidationChangeSet').mockResolvedValue({ + changeSet: { $metadata: {} } as any, + diagnosis: Diagnosis.noProblem().withWarnings([ + { + stackArn: 'arn:aws:cloudformation:us-east-1:123456789012:stack/Stack1', + topLevelStackHierarchicalId: 'Stack1', + parentStackLogicalIds: [], + logicalId: 'MyBucket', + resourceType: 'AWS::S3::Bucket', + message: 'Bucket name may already be taken', + errorCode: 'NAME_CONFLICT_VALIDATION', + sourceTrace: undefined, + }, + ]), + }); + + const cx = await cdkOutFixture(toolkit, 'stack-with-bucket'); + const result = await toolkit.validate(cx, { online: true }); + + // A WARN-mode early validation failed nothing, so the run is not a failure. + expect(result.conclusion).toBe('success'); + expect(result.pluginReports[0].conclusion).toBe('success'); + expect(result.pluginReports[0].violations).toHaveLength(1); + expect(result.pluginReports[0].violations[0]).toMatchObject({ + // A finding is named after the rule that produced it, which is its error code. + ruleName: 'NAME_CONFLICT_VALIDATION', + description: 'Bucket name may already be taken', + severity: 'warning', + }); + }); + + test('a stack with both problems and warnings concludes failure and keeps both severities', async () => { + jest.spyOn(cfnApi, 'createValidationChangeSet').mockResolvedValue({ + changeSet: { $metadata: {} } as any, + diagnosis: Diagnosis.problem( + { type: 'early-validation', changeSetName: 'cdk-validate-change-set' }, + [ + { + stackArn: 'arn:aws:cloudformation:us-east-1:123456789012:stack/Stack1', + topLevelStackHierarchicalId: 'Stack1', + parentStackLogicalIds: [], + logicalId: 'BadPolicy', + message: 'Required property [PolicyDocument] not found', + errorCode: 'PropertyValidation', + sourceTrace: undefined, + }, + ], + ).withWarnings([ + { + stackArn: 'arn:aws:cloudformation:us-east-1:123456789012:stack/Stack1', + topLevelStackHierarchicalId: 'Stack1', + parentStackLogicalIds: [], + logicalId: 'MyBucket', + message: 'Bucket name may already be taken', + errorCode: 'NameConflictValidation', + sourceTrace: undefined, + }, + ]), + }); + + const cx = await cdkOutFixture(toolkit, 'stack-with-bucket'); + const result = await toolkit.validate(cx, { online: true }); + + expect(result.conclusion).toBe('failure'); + expect(result.pluginReports[0].conclusion).toBe('failure'); + expect(result.pluginReports[0].violations.map((v) => v.severity)).toEqual(['fatal', 'warning']); + }); + + test('strips the document path suffix from a warning description', async () => { + jest.spyOn(cfnApi, 'createValidationChangeSet').mockResolvedValue({ + changeSet: { $metadata: {} } as any, + diagnosis: Diagnosis.noProblem().withWarnings([ + { + stackArn: 'arn:aws:cloudformation:us-east-1:123456789012:stack/Stack1', + topLevelStackHierarchicalId: 'Stack1', + parentStackLogicalIds: [], + logicalId: 'MyBucket', + message: 'Bucket name may already be taken (at /Resources/MyBucket)', + sourceTrace: undefined, + }, + ]), + }); + + const cx = await cdkOutFixture(toolkit, 'stack-with-bucket'); + const result = await toolkit.validate(cx, { online: true }); + + expect(result.pluginReports[0].violations[0]).toMatchObject({ + ruleName: 'CloudFormationValidation', + description: 'Bucket name may already be taken', + }); + }); + + test('an error code containing `::` is escaped so the rule ID stays parseable', async () => { + // `::` separates a namespace from a rule name in a validation ID, so an error code that + // contains it used to make the ID unparseable and threw 'Invalid validation rule ID' out of + // `validate()` instead of reporting the finding. + jest.spyOn(cfnApi, 'createValidationChangeSet').mockResolvedValue({ + changeSet: { $metadata: {} } as any, + diagnosis: Diagnosis.noProblem().withWarnings([ + { + stackArn: 'arn:aws:cloudformation:us-east-1:123456789012:stack/Stack1', + topLevelStackHierarchicalId: 'Stack1', + parentStackLogicalIds: [], + logicalId: 'MyQueue', + message: 'Queue would be removed', + errorCode: 'AWS::Hooks::SomeHook', + sourceTrace: undefined, + }, + ]), + }); + + const cx = await cdkOutFixture(toolkit, 'stack-with-bucket'); + const result = await toolkit.validate(cx, { online: true }); + + expect(result.pluginReports[0].violations[0]).toMatchObject({ + ruleName: 'AWS_Hooks_SomeHook', + }); + }); + + test('a warning CloudFormation did not name cannot be acknowledged', async () => { + jest.spyOn(cfnApi, 'createValidationChangeSet').mockResolvedValue({ + changeSet: { $metadata: {} } as any, + diagnosis: Diagnosis.noProblem().withWarnings([ + { + stackArn: 'arn:aws:cloudformation:us-east-1:123456789012:stack/Stack1', + topLevelStackHierarchicalId: 'Stack1', + parentStackLogicalIds: [], + logicalId: 'MyBucket', + message: 'Bucket name may already be taken', + errorCode: UNNAMED_EARLY_VALIDATION_RULE, + sourceTrace: undefined, + }, + ]), + }); + + const cx = await cdkOutFixture(toolkit, 'stack-with-bucket'); + const result = await toolkit.validate(cx, { online: true }); + + expect(result.pluginReports[0].violations[0]).toMatchObject({ + ruleName: 'CloudFormationValidation', + ruleMetadata: { 'cdk:not-suppressible': 'true' }, + }); + }); + test('merges offline and online results', async () => { jest.spyOn(cfnApi, 'createValidationChangeSet').mockResolvedValue({ changeSet: { $metadata: {} } as any, @@ -261,3 +407,126 @@ describe('validate --online', () => { })); }); }); + +/** + * The `stack-with-acknowledged-rules` fixture acknowledges `CloudFormation::SQS_QUEUE_REMOVED` on + * `/Stack1`, the way `Validations.of(stack).acknowledge({ ... })` records it in the assembly. + */ +describe('validate --online acknowledgements', () => { + beforeEach(() => { + jest.spyOn(awsauth.SdkProvider.prototype, '_makeSdk').mockReturnValue(new MockSdk()); + }); + + function warningDiagnosis(props: { errorCode?: string; logicalId?: string } = {}) { + return Diagnosis.noProblem().withWarnings([ + { + stackArn: 'arn:aws:cloudformation:us-east-1:123456789012:stack/Stack1', + topLevelStackHierarchicalId: 'Stack1', + parentStackLogicalIds: [], + logicalId: props.logicalId ?? 'MyQueue', + message: 'Queue would be removed', + errorCode: 'errorCode' in props ? props.errorCode : 'SQS_QUEUE_REMOVED', + sourceTrace: undefined, + }, + ]); + } + + test('an acknowledged warning is not reported', async () => { + jest.spyOn(cfnApi, 'createValidationChangeSet').mockResolvedValue({ + changeSet: { $metadata: {} } as any, + diagnosis: warningDiagnosis(), + }); + + const cx = await cdkOutFixture(toolkit, 'stack-with-acknowledged-rules'); + const result = await toolkit.validate(cx, { online: true }); + + expect(result.conclusion).toBe('success'); + expect(result.pluginReports[0].violations).toEqual([]); + }); + + test('an acknowledged warning is kept as an audit trail', async () => { + jest.spyOn(cfnApi, 'createValidationChangeSet').mockResolvedValue({ + changeSet: { $metadata: {} } as any, + diagnosis: warningDiagnosis(), + }); + + const cx = await cdkOutFixture(toolkit, 'stack-with-acknowledged-rules'); + const result = await toolkit.validate(cx, { online: true }); + + expect(result.pluginReports[0].suppressedViolations).toEqual([expect.objectContaining({ + ruleName: 'SQS_QUEUE_REMOVED', + acknowledgedId: 'CloudFormation::SQS_QUEUE_REMOVED', + acknowledgedAt: 'Stack1', + reason: 'the queue moved to another stack', + acknowledgedStackTrace: 'at Object. (/app/lib/app.ts:12:28)', + })]); + }); + + test('the same warning is reported in a stack that does not acknowledge it', async () => { + jest.spyOn(cfnApi, 'createValidationChangeSet').mockResolvedValue({ + changeSet: { $metadata: {} } as any, + diagnosis: warningDiagnosis(), + }); + + const cx = await cdkOutFixture(toolkit, 'stack-with-bucket'); + const result = await toolkit.validate(cx, { online: true }); + + expect(result.pluginReports[0].violations).toHaveLength(1); + expect(result.pluginReports[0].suppressedViolations).toBeUndefined(); + }); + + test('an acknowledgement of one rule does not silence another', async () => { + jest.spyOn(cfnApi, 'createValidationChangeSet').mockResolvedValue({ + changeSet: { $metadata: {} } as any, + diagnosis: warningDiagnosis({ errorCode: 'PROPERTY_VALIDATION' }), + }); + + const cx = await cdkOutFixture(toolkit, 'stack-with-acknowledged-rules'); + const result = await toolkit.validate(cx, { online: true }); + + expect(result.pluginReports[0].violations).toHaveLength(1); + expect(result.pluginReports[0].violations[0].ruleName).toBe('PROPERTY_VALIDATION'); + }); + + test('a warning CloudFormation did not name stays, acknowledgements or not', async () => { + jest.spyOn(cfnApi, 'createValidationChangeSet').mockResolvedValue({ + changeSet: { $metadata: {} } as any, + diagnosis: warningDiagnosis({ errorCode: UNNAMED_EARLY_VALIDATION_RULE }), + }); + + const cx = await cdkOutFixture(toolkit, 'stack-with-acknowledged-rules'); + const result = await toolkit.validate(cx, { online: true }); + + expect(result.pluginReports[0].violations).toHaveLength(1); + expect(result.pluginReports[0].violations[0].ruleName).toBe('CloudFormationValidation'); + }); + + test('an acknowledgement cannot silence a fatal problem', async () => { + // Same rule name as the acknowledgement in the fixture, but a failed early validation is not + // something a user may wave away. + jest.spyOn(cfnApi, 'createValidationChangeSet').mockResolvedValue({ + changeSet: { $metadata: {} } as any, + diagnosis: Diagnosis.problem( + { type: 'early-validation', changeSetName: 'cdk-validate-change-set' }, + [ + { + stackArn: 'arn:aws:cloudformation:us-east-1:123456789012:stack/Stack1', + topLevelStackHierarchicalId: 'Stack1', + parentStackLogicalIds: [], + logicalId: 'MyQueue', + message: 'Queue would be removed', + errorCode: 'SQS_QUEUE_REMOVED', + sourceTrace: undefined, + }, + ], + ), + }); + + const cx = await cdkOutFixture(toolkit, 'stack-with-acknowledged-rules'); + const result = await toolkit.validate(cx, { online: true }); + + expect(result.conclusion).toBe('failure'); + expect(result.pluginReports[0].violations).toHaveLength(1); + expect(result.pluginReports[0].violations[0].severity).toBe('fatal'); + }); +}); diff --git a/packages/@aws-cdk/toolkit-lib/test/api/diagnosing/diagnosis-formatting.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/diagnosing/diagnosis-formatting.test.ts index f1e1e4ebd..8025307f1 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/diagnosing/diagnosis-formatting.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/diagnosing/diagnosis-formatting.test.ts @@ -1,6 +1,6 @@ import type { DiagnosedStack, StackDiagnosis, TracedResourceError } from '../../../lib/actions/diagnose'; import { Diagnosis } from '../../../lib/api/diagnosing/diagnosis'; -import { hostMessageFromDiagnosis } from '../../../lib/api/diagnosing/diagnosis-formatting'; +import { formatDiagnosisWarnings, hostMessageFromDiagnosis } from '../../../lib/api/diagnosing/diagnosis-formatting'; import type { ActionLessMessage } from '../../../lib/api/io/private'; import { DeploymentError } from '../../../lib/toolkit/toolkit-error'; @@ -127,7 +127,7 @@ describe('hostMessageFromDiagnosis', () => { }, problems: [ { - errorCode: 'PROPERTY_VALIDATION_VALIDATION_ERROR', + errorCode: 'PROPERTY_VALIDATION', logicalId: 'BadPolicy', message: 'Required property [PolicyDocument] not found (at /Resources/BadPolicy/Properties)', parentStackLogicalIds: [], @@ -138,7 +138,7 @@ describe('hostMessageFromDiagnosis', () => { topLevelStackHierarchicalId: 'TestStack', }, { - errorCode: 'PROPERTY_VALIDATION_VALIDATION_ERROR', + errorCode: 'PROPERTY_VALIDATION', logicalId: 'BadPolicy', message: 'Required property [PolicyName] not found (at /Resources/BadPolicy/Properties)', parentStackLogicalIds: [], @@ -257,6 +257,32 @@ describe('StackDiagnosis.throwOnError', () => { }); }); +describe('formatDiagnosisWarnings', () => { + test('captions the findings as warnings, not failures', () => { + const output = formatDiagnosisWarnings([tracedError({ message: 'bucket name may be taken' })], 'MyChangeset'); + + expect(output).toContain('MyChangeset'); + expect(output).toContain('bucket name may be taken'); + expect(output.toLowerCase()).not.toContain('failed'); + }); + + test('pluralizes the count', () => { + const output = formatDiagnosisWarnings([ + tracedError({ logicalId: 'BucketA', message: 'first' }), + tracedError({ logicalId: 'BucketB', message: 'second' }), + ], 'MyChangeset'); + + expect(output).toContain('first'); + expect(output).toContain('second'); + }); + + test('renders the construct path of each warning', () => { + const output = formatDiagnosisWarnings([tracedError({ logicalId: 'MyBucket' })], 'MyChangeset'); + + expect(output).toContain('MyStack/MyBucket'); + }); +}); + function redactTime>(msg: A): A { (msg as any).time = new Date(0); return msg; diff --git a/packages/@aws-cdk/toolkit-lib/test/api/diagnosing/stack-diagnoser.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/diagnosing/stack-diagnoser.test.ts index 557d8a9d0..42d679572 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/diagnosing/stack-diagnoser.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/diagnosing/stack-diagnoser.test.ts @@ -1,15 +1,16 @@ -import type { Change } from '@aws-sdk/client-cloudformation'; +import type { Change, OperationEvent } from '@aws-sdk/client-cloudformation'; import { ChangeSetStatus, DescribeChangeSetCommand, + DescribeEventsCommand, GetHookResultCommand, ListHookResultsCommand, ListStackResourcesCommand, ResourceStatus, } from '@aws-sdk/client-cloudformation'; import { LookupEventsCommand } from '@aws-sdk/client-cloudtrail'; -import type { StackDiagnosis } from '../../../lib/actions/diagnose'; -import type { Diagnosis } from '../../../lib/api/diagnosing/diagnosis'; +import type { StackDiagnosis, TracedResourceError } from '../../../lib/actions/diagnose'; +import { Diagnosis } from '../../../lib/api/diagnosing/diagnosis'; import { CloudFormationStackDiagnoser } from '../../../lib/api/diagnosing/stack-diagnoser'; import type { ISourceTracer } from '../../../lib/api/source-tracing/private/source-tracing'; import type { SourceTrace } from '../../../lib/api/source-tracing/types'; @@ -546,7 +547,7 @@ describe('CloudFormationStackDiagnoser', () => { }, problems: [ { - errorCode: 'PROPERTY_VALIDATION_VALIDATION_ERROR', + errorCode: 'PROPERTY_VALIDATION', logicalId: 'BadPolicy', message: 'Required property [PolicyDocument] not found (at /Resources/BadPolicy/Properties)', parentStackLogicalIds: [], @@ -557,7 +558,7 @@ describe('CloudFormationStackDiagnoser', () => { topLevelStackHierarchicalId: 'TestStack', }, { - errorCode: 'PROPERTY_VALIDATION_VALIDATION_ERROR', + errorCode: 'PROPERTY_VALIDATION', logicalId: 'BadPolicy', message: 'Required property [PolicyName] not found (at /Resources/BadPolicy/Properties)', parentStackLogicalIds: [], @@ -572,6 +573,194 @@ describe('CloudFormationStackDiagnoser', () => { }); }); + describe('early validation warnings', () => { + const STACK_ARN = 'arn:aws:cloudformation:us-east-1:123456789012:stack/MyStack/123'; + + // An early validation finding whose failure mode is WARN. + function warnEvent(overrides: Partial = {}): OperationEvent { + return { + EventId: 'a1b2c3d4-0000-0000-0000-000000000001', + StackId: STACK_ARN, + OperationId: '345a3ffd-e545-437c-b32f-f71647308416', + OperationType: 'CREATE_CHANGESET', + EventType: 'VALIDATION_ERROR', + LogicalResourceId: 'MyBucket', + PhysicalResourceId: '', + ResourceType: 'AWS::S3::Bucket', + Timestamp: new Date(), + ValidationFailureMode: 'WARN', + ValidationName: 'NAME_CONFLICT_VALIDATION', + ValidationStatus: 'FAILED', + ValidationStatusReason: 'Bucket name may already be taken', + ValidationPath: '/Resources/MyBucket', + ...overrides, + }; + } + + function failEvent(overrides: Partial = {}): OperationEvent { + return warnEvent({ + EventId: 'a1b2c3d4-0000-0000-0000-000000000002', + LogicalResourceId: 'BadPolicy', + ResourceType: 'AWS::IAM::Policy', + ValidationFailureMode: 'FAIL', + ValidationName: 'PROPERTY_VALIDATION', + ValidationStatusReason: 'Required property [PolicyDocument] not found', + ValidationPath: '/Resources/BadPolicy/Properties', + ...overrides, + }); + } + + /** + * Prime a change set in the given state with the given events, and return the summary to + * hand to the diagnoser. + */ + function givenChangeSet(status: ChangeSetStatus, events: OperationEvent[]) { + fakeCfn.createStackSync({ StackName: 'MyStack', StackId: STACK_ARN }); + fakeCfn.createChangeSetSync({ + StackName: 'MyStack', + ChangeSetName: 'my-cs', + Status: status, + StatusReason: status === ChangeSetStatus.FAILED ? 'AWS::EarlyValidation failed' : undefined, + }); + fakeCfn.accessChangeSet('MyStack', 'my-cs').changeSetFailureEvents = events; + + return { + ChangeSetName: 'my-cs', + StackName: 'MyStack', + StackId: STACK_ARN, + Status: status, + StatusReason: status === ChangeSetStatus.FAILED ? 'AWS::EarlyValidation failed' : undefined, + }; + } + + test('attaches WARN findings to a change set that was created successfully', async () => { + const cs = givenChangeSet(ChangeSetStatus.CREATE_COMPLETE, [warnEvent()]); + + const result = await makeDiagnoser().diagnoseChangeSet(cs); + + expect(result.result.type).toBe('no-problem'); + expect(result.warnings).toEqual([ + expect.objectContaining({ + errorCode: 'NAME_CONFLICT_VALIDATION', + logicalId: 'MyBucket', + message: 'Bucket name may already be taken (at /Resources/MyBucket)', + resourceType: 'AWS::S3::Bucket', + stackArn: STACK_ARN, + topLevelStackHierarchicalId: 'TestStack', + }), + ]); + }); + + test('codes a control finding after its control ID, so it can be acknowledged', async () => { + // CloudFormation names a control validation ' | '. The error code is + // the ID a user names in an acknowledgement, so only the control ID belongs in it: the type + // half is redundant and its `::` is reserved for separating a namespace from a rule name. + const cs = givenChangeSet(ChangeSetStatus.CREATE_COMPLETE, [ + warnEvent({ ValidationName: 'SQS_QUEUE_REMOVED | AWS::Controls::SQSQueueRemoved' }), + ]); + + const result = await makeDiagnoser().diagnoseChangeSet(cs); + + expect(result.warnings).toEqual([expect.objectContaining({ errorCode: 'SQS_QUEUE_REMOVED' })]); + }); + + test('codes a finding CloudFormation did not name so that it cannot be acknowledged', async () => { + const cs = givenChangeSet(ChangeSetStatus.CREATE_COMPLETE, [warnEvent({ ValidationName: undefined })]); + + const result = await makeDiagnoser().diagnoseChangeSet(cs); + + expect(result.warnings).toEqual([expect.objectContaining({ errorCode: 'CloudFormationValidation' })]); + }); + + test('a change set carrying only warnings is still healthy and does not throw', async () => { + const cs = givenChangeSet(ChangeSetStatus.CREATE_COMPLETE, [warnEvent()]); + + const result = await makeDiagnoser().diagnoseChangeSet(cs); + + // Warnings are not problems: a deployment must not be stopped or rolled back for them. + expect(result.isNoProblem).toBe(true); + expect(() => result.throwOnError()).not.toThrow(); + }); + + test('a change set carrying only warnings is still executable', async () => { + const cs = givenChangeSet(ChangeSetStatus.CREATE_COMPLETE, [warnEvent()]); + + const result = await makeDiagnoser().diagnoseChangeSet(cs, { requireExecutable: true }); + + expect(result.result.type).toBe('no-problem'); + expect(result.warnings).toHaveLength(1); + }); + + test('reports no warnings when the change set has none', async () => { + const cs = givenChangeSet(ChangeSetStatus.CREATE_COMPLETE, []); + + const result = await makeDiagnoser().diagnoseChangeSet(cs); + + expect(result.result).toEqual({ type: 'no-problem' }); + expect(result.warnings).toEqual([]); + }); + + test('splits FAIL and WARN findings of a failed change set into problems and warnings', async () => { + const cs = givenChangeSet(ChangeSetStatus.FAILED, [failEvent(), warnEvent()]); + + const result = await makeDiagnoser().diagnoseChangeSet(cs); + + const problem = assertProblem(result); + expect(problem.detectedBy).toMatchObject({ type: 'early-validation' }); + expect(problem.problems).toEqual([ + expect.objectContaining({ + logicalId: 'BadPolicy', + message: 'Required property [PolicyDocument] not found (at /Resources/BadPolicy/Properties)', + }), + ]); + expect(result.warnings).toEqual([ + expect.objectContaining({ + logicalId: 'MyBucket', + message: 'Bucket name may already be taken (at /Resources/MyBucket)', + }), + ]); + }); + + test('an event with no validation failure mode is a problem, not a warning', async () => { + const cs = givenChangeSet(ChangeSetStatus.FAILED, [ + failEvent({ ValidationFailureMode: undefined, ValidationName: undefined, ValidationStatus: undefined }), + ]); + + const result = await makeDiagnoser().diagnoseChangeSet(cs); + + expect(assertProblem(result).problems).toHaveLength(1); + expect(result.warnings).toEqual([]); + }); + + test('a DescribeEvents failure costs the warnings but not the diagnosis', async () => { + // The reason is only reported at debug level, so the host has to be listening for it. + ioHost.level = 'debug'; + const cs = givenChangeSet(ChangeSetStatus.CREATE_COMPLETE, [warnEvent()]); + mockCloudFormationClient.on(DescribeEventsCommand).rejects(new Error('User is not authorized to perform cloudformation:DescribeEvents')); + + const result = await makeDiagnoser().diagnoseChangeSet(cs); + + expect(result.result.type).toBe('no-problem'); + expect(result.warnings).toEqual([]); + expect(() => result.throwOnError()).not.toThrow(); + expect(ioHost.messages).toContainEqual(expect.objectContaining({ + level: 'debug', + message: expect.stringContaining('DescribeEvents'), + })); + }); + + test('does not look for warnings on a change set that is not CREATE_COMPLETE', async () => { + const cs = givenChangeSet(ChangeSetStatus.DELETE_COMPLETE, [warnEvent()]); + const describeEvents = jest.fn(); + mockCloudFormationClient.on(DescribeEventsCommand).callsFake(describeEvents); + + const result = await makeDiagnoser().diagnoseChangeSet(cs); + + expect(result.result.type).toBe('no-problem'); + expect(describeEvents).not.toHaveBeenCalled(); + }); + }); + describe('change set hook failures', () => { const CS_ARN = 'arn:aws:cloudformation:us-east-1:123456789012:changeSet/my-cs/00000000-0000-0000-0000-000000000000'; const STACK_ARN = 'arn:aws:cloudformation:us-east-1:123456789012:stack/MyStack/123'; @@ -1093,3 +1282,73 @@ describe('CloudFormationStackDiagnoser', () => { }); }); }); + +describe('Diagnosis warnings', () => { + function finding(message: string): TracedResourceError { + return { + stackArn: 'arn:aws:cloudformation:us-east-1:123456789012:stack/MyStack/123', + topLevelStackHierarchicalId: 'MyStack', + parentStackLogicalIds: [], + logicalId: 'MyBucket', + message, + sourceTrace: undefined, + }; + } + + test('a diagnosis has no warnings by default', () => { + expect(Diagnosis.noProblem().warnings).toEqual([]); + expect(Diagnosis.problem({ type: 'early-validation', changeSetName: 'cs' }, []).warnings).toEqual([]); + expect(Diagnosis.errorDiagnosing('nope').warnings).toEqual([]); + }); + + test('withWarnings attaches them without changing the diagnosis type', () => { + const diagnosis = Diagnosis.noProblem().withWarnings([finding('bucket name may be taken')]); + + expect(diagnosis.type).toBe('no-problem'); + expect(diagnosis.warnings).toEqual([finding('bucket name may be taken')]); + }); + + test('warnings do not make a stack unhealthy', () => { + // A WARN-mode early validation failed nothing, so there is nothing to stop or roll back. + // `requireExecutable` deployments rely on this. + const diagnosis = Diagnosis.noProblem().withWarnings([finding('a warning')]); + + expect(diagnosis.isNoProblem).toBe(true); + }); + + test('throwOnError ignores warnings', () => { + const diagnosis = Diagnosis.noProblem().withWarnings([finding('a warning')]); + + expect(() => diagnosis.throwOnError()).not.toThrow(); + }); + + test('throwOnError still throws for a problem that also carries warnings', () => { + const diagnosis = Diagnosis.problem( + { type: 'early-validation', changeSetName: 'cs' }, + [finding('a real failure')], + ).withWarnings([finding('a warning')]); + + expect(() => diagnosis.throwOnError()).toThrow('a real failure'); + }); + + test('withWarnings accumulates across calls', () => { + const diagnosis = Diagnosis.noProblem() + .withWarnings([finding('first')]) + .withWarnings([finding('second')]); + + expect(diagnosis.warnings.map((w) => w.message)).toEqual(['first', 'second']); + }); + + test('withWarnings is a no-op for an empty list', () => { + const original = Diagnosis.noProblem(); + + expect(original.withWarnings([])).toBe(original); + }); + + test('withWarnings does not mutate the diagnosis it was called on', () => { + const original = Diagnosis.noProblem(); + original.withWarnings([finding('a warning')]); + + expect(original.warnings).toEqual([]); + }); +}); diff --git a/packages/@aws-cdk/toolkit-lib/test/api/validate/early-validation-acknowledgements.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/validate/early-validation-acknowledgements.test.ts new file mode 100644 index 000000000..b45139313 --- /dev/null +++ b/packages/@aws-cdk/toolkit-lib/test/api/validate/early-validation-acknowledgements.test.ts @@ -0,0 +1,268 @@ +import type { CloudFormationStackArtifact, MetadataEntryResult } from '@aws-cdk/cloud-assembly-api'; +import type { PolicyViolationJson } from '@aws-cdk/cloud-assembly-schema'; +import type { EarlyValidationAcknowledgement } from '../../../lib/api/validate/early-validation-acknowledgements'; +import { + ACKNOWLEDGED_RULES_METADATA_TYPE, + UNNAMED_EARLY_VALIDATION_RULE, + earlyValidationErrorCode, + partitionAcknowledged, + readAcknowledgements, + violationRuleFields, +} from '../../../lib/api/validate/early-validation-acknowledgements'; + +const CONTROL_VALIDATION_NAME = 'SQS_QUEUE_REMOVED | AWS::Controls::SQSQueueRemoved'; + +function warning(props: Partial & { constructPath?: string } = {}): PolicyViolationJson { + const { constructPath, ...overrides } = props; + return { + ruleName: 'SQS_QUEUE_REMOVED', + description: 'the queue would be removed', + severity: 'warning', + violatingConstructs: [{ constructPath: constructPath ?? 'Stack1/MyQueue/Resource' }], + ...overrides, + }; +} + +function ack(props: Partial = {}): EarlyValidationAcknowledgement { + return { + id: 'CloudFormation::SQS_QUEUE_REMOVED', + acknowledgedAt: 'Stack1/MyQueue/Resource', + ...props, + }; +} + +/** + * A stand-in for a stack artifact that only has to answer `findMetadataByType`. + */ +function stackWithMetadata(entries: MetadataEntryResult[]): CloudFormationStackArtifact { + return { + findMetadataByType: (type: string) => entries.filter((e) => e.type === type), + } as unknown as CloudFormationStackArtifact; +} + +describe('earlyValidationErrorCode', () => { + test('a control is coded after its control ID, not its type', () => { + // The type name is redundant with the ID and is full of `::`, which is reserved in a rule ID. + expect(earlyValidationErrorCode(CONTROL_VALIDATION_NAME)).toBe('SQS_QUEUE_REMOVED'); + }); + + test('a built-in validation keeps its name', () => { + expect(earlyValidationErrorCode('PROPERTY_VALIDATION')).toBe('PROPERTY_VALIDATION'); + }); + + test.each([ + ['undefined', undefined], + ['an empty string', ''], + ['whitespace', ' '], + ])('a validation named %s gets the unnamed code', (_what, validationName) => { + // Nothing identifies it, so there is nothing a user could name in an acknowledgement. + expect(earlyValidationErrorCode(validationName)).toBe(UNNAMED_EARLY_VALIDATION_RULE); + }); + + test('a type-shaped name that is not a control composite is escaped', () => { + expect(earlyValidationErrorCode('AWS::Hooks::SomeHook')).toBe('AWS_Hooks_SomeHook'); + }); + + test('surrounding whitespace is ignored', () => { + expect(earlyValidationErrorCode(' PROPERTY_VALIDATION ')).toBe('PROPERTY_VALIDATION'); + }); +}); + +describe('violationRuleFields', () => { + test('reports a finding under its error code', () => { + expect(violationRuleFields('SQS_QUEUE_REMOVED')).toEqual({ + ruleName: 'SQS_QUEUE_REMOVED', + }); + }); + + test('escapes an error code that is not already a valid rule name', () => { + // Error codes of findings that are not early validations are not escaped at the source. + expect(violationRuleFields('AWS::Hooks::SomeHook')).toEqual({ + ruleName: 'AWS_Hooks_SomeHook', + }); + }); + + test.each([ + ['the unnamed code', UNNAMED_EARLY_VALIDATION_RULE], + ['no code at all', undefined], + ])('marks a finding with %s unsuppressible', (_what, errorCode) => { + expect(violationRuleFields(errorCode)).toEqual({ + ruleName: UNNAMED_EARLY_VALIDATION_RULE, + ruleMetadata: { 'cdk:not-suppressible': 'true' }, + }); + }); +}); + +describe('readAcknowledgements', () => { + test('reads one acknowledgement per rule ID in an entry', () => { + const stack = stackWithMetadata([{ + path: '/Stack1/MyQueue', + type: ACKNOWLEDGED_RULES_METADATA_TYPE, + data: { + 'CloudFormation::SQS_QUEUE_REMOVED': 'on purpose', + 'CloudFormation::PROPERTY_VALIDATION': 'also on purpose', + }, + trace: ['at myApp (/app/lib/app.ts:5:3)', 'at Object.'], + } as unknown as MetadataEntryResult]); + + expect(readAcknowledgements(stack)).toEqual([ + { + id: 'CloudFormation::SQS_QUEUE_REMOVED', + // The leading slash of a metadata path is not part of a construct path. + acknowledgedAt: 'Stack1/MyQueue', + reason: 'on purpose', + acknowledgedStackTrace: 'at myApp (/app/lib/app.ts:5:3)\nat Object.', + }, + { + id: 'CloudFormation::PROPERTY_VALIDATION', + acknowledgedAt: 'Stack1/MyQueue', + reason: 'also on purpose', + acknowledgedStackTrace: 'at myApp (/app/lib/app.ts:5:3)\nat Object.', + }, + ]); + }); + + test('an acknowledgement without a reason or trace reports neither', () => { + const stack = stackWithMetadata([{ + path: '/Stack1', + type: ACKNOWLEDGED_RULES_METADATA_TYPE, + data: { 'CloudFormation::SQS_QUEUE_REMOVED': '' }, + } as unknown as MetadataEntryResult]); + + expect(readAcknowledgements(stack)).toEqual([{ + id: 'CloudFormation::SQS_QUEUE_REMOVED', + acknowledgedAt: 'Stack1', + reason: undefined, + acknowledgedStackTrace: undefined, + }]); + }); + + test('ignores metadata of other types', () => { + const stack = stackWithMetadata([{ + path: '/Stack1/MyQueue/Resource', + type: 'aws:cdk:logicalId', + data: 'MyQueueE6CA6235', + } as unknown as MetadataEntryResult]); + + expect(readAcknowledgements(stack)).toEqual([]); + }); + + test('a stack with no metadata has no acknowledgements', () => { + expect(readAcknowledgements(stackWithMetadata([]))).toEqual([]); + }); +}); + +describe('partitionAcknowledged', () => { + test('suppresses a warning acknowledged on its own construct', () => { + const result = partitionAcknowledged([warning()], [ack()]); + + expect(result.violations).toEqual([]); + expect(result.suppressedViolations).toHaveLength(1); + }); + + test('suppresses a warning acknowledged on an ancestor construct', () => { + const result = partitionAcknowledged([warning()], [ack({ acknowledgedAt: 'Stack1' })]); + + expect(result.suppressedViolations).toHaveLength(1); + }); + + test('leaves a warning acknowledged on an unrelated construct', () => { + const result = partitionAcknowledged([warning()], [ack({ acknowledgedAt: 'Stack1/OtherQueue' })]); + + expect(result.violations).toHaveLength(1); + expect(result.suppressedViolations).toEqual([]); + }); + + test('a construct path is not matched on a partial segment', () => { + // 'Stack1/MyQueue2' is not an ancestor of 'Stack1/MyQueue/Resource' despite the shared prefix. + const result = partitionAcknowledged([warning()], [ack({ acknowledgedAt: 'Stack1/MyQu' })]); + + expect(result.violations).toHaveLength(1); + }); + + test('leaves a warning whose rule nothing acknowledges', () => { + const result = partitionAcknowledged([warning()], [ack({ id: 'CloudFormation::SOMETHING_ELSE' })]); + + expect(result.violations).toHaveLength(1); + }); + + test('an acknowledgement in another namespace does not match', () => { + // A bare id written in app code is stored under the annotation namespace, so it cannot + // acknowledge a CloudFormation early validation finding. + const result = partitionAcknowledged([warning()], [ack({ id: 'Annotation::SQS_QUEUE_REMOVED' })]); + + expect(result.violations).toHaveLength(1); + }); + + test('without acknowledgements everything is kept, by identity', () => { + const violations = [warning()]; + const result = partitionAcknowledged(violations, []); + + expect(result.violations).toBe(violations); + expect(result.suppressedViolations).toEqual([]); + }); + + describe('findings that may not be acknowledged', () => { + test('a fatal problem is never suppressed', () => { + const fatal = warning({ severity: 'fatal' }); + const result = partitionAcknowledged([fatal], [ack({ acknowledgedAt: 'Stack1' })]); + + expect(result.violations).toEqual([fatal]); + expect(result.suppressedViolations).toEqual([]); + }); + + test('a finding marked unsuppressible is never suppressed', () => { + const unnamed = warning({ + ruleName: UNNAMED_EARLY_VALIDATION_RULE, + ruleMetadata: { 'cdk:not-suppressible': 'true' }, + }); + const result = partitionAcknowledged([unnamed], [ack({ id: `CloudFormation::${UNNAMED_EARLY_VALIDATION_RULE}`, acknowledgedAt: 'Stack1' })]); + + expect(result.violations).toEqual([unnamed]); + expect(result.suppressedViolations).toEqual([]); + }); + }); + + describe('the suppressed violation', () => { + test('records the acknowledgement it matched', () => { + const result = partitionAcknowledged([warning()], [ack({ + acknowledgedAt: 'Stack1', + reason: 'the queue moved to another stack', + acknowledgedStackTrace: 'at myApp (/app/lib/app.ts:5:3)', + })]); + + expect(result.suppressedViolations[0]).toEqual({ + ...warning(), + acknowledgedId: 'CloudFormation::SQS_QUEUE_REMOVED', + acknowledgedAt: 'Stack1', + reason: 'the queue moved to another stack', + acknowledgedStackTrace: 'at myApp (/app/lib/app.ts:5:3)', + }); + }); + + test('omits a reason that was not given', () => { + const result = partitionAcknowledged([warning()], [ack()]); + + expect(result.suppressedViolations[0]).not.toHaveProperty('reason'); + expect(result.suppressedViolations[0]).not.toHaveProperty('acknowledgedStackTrace'); + }); + + test('is attributed to the acknowledgement closest to the construct', () => { + // Both apply; the one the user put on the resource is the one that explains this suppression. + const result = partitionAcknowledged([warning()], [ + ack({ acknowledgedAt: 'Stack1', reason: 'stack-wide' }), + ack({ acknowledgedAt: 'Stack1/MyQueue', reason: 'this queue only' }), + ]); + + expect(result.suppressedViolations[0].reason).toBe('this queue only'); + }); + }); + + test('partitions a mixed set of findings', () => { + const kept = warning({ ruleName: 'PROPERTY_VALIDATION', constructPath: 'Stack1/MyBucket/Resource' }); + const result = partitionAcknowledged([warning(), kept], [ack({ acknowledgedAt: 'Stack1' })]); + + expect(result.violations).toEqual([kept]); + expect(result.suppressedViolations.map((v) => v.ruleName)).toEqual(['SQS_QUEUE_REMOVED']); + }); +}); diff --git a/packages/aws-cdk/lib/cli/cdk-toolkit.ts b/packages/aws-cdk/lib/cli/cdk-toolkit.ts index 617bd050a..08765d5a4 100644 --- a/packages/aws-cdk/lib/cli/cdk-toolkit.ts +++ b/packages/aws-cdk/lib/cli/cdk-toolkit.ts @@ -2683,6 +2683,10 @@ class WorkGraphDeploymentActions implements WorkGraphActions { elapsedDeployTime = new Date().getTime() - startDeployTime; await this.ioHost.asIoHelper().defaults.info(`\n✨ Deployment time: ${formatTime(elapsedDeployTime)}s\n`); + if (deployResult.earlyValidationWarnings && deployResult.earlyValidationWarnings > 0) { + this.ioHost.asIoHelper().defaults.warn(`⚠️ Completed with ${deployResult.earlyValidationWarnings} ${deployResult.earlyValidationWarnings > 1 ? 'warnings' : 'warning'} from changeset creation.\n`); + } + if (this.options.express) { const warning = formatExpressStabilizationWarning(deployResult.stabilizingResources, 'deploy'); if (warning) {