Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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(),
Expand Down
25 changes: 23 additions & 2 deletions packages/@aws-cdk/cloud-assembly-api/lib/validation/parsing.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
ANNOTATION_PLUGIN_NAME,
ANNOTATION_PLUGIN_NAMESPACE,
escapeValidationRuleName,
isSuppressibleViolation,
namespaceFromPluginName,
normalizeValidationId,
Expand Down Expand Up @@ -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');

Expand Down Expand Up @@ -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);
});
Expand Down
2 changes: 2 additions & 0 deletions packages/@aws-cdk/toolkit-lib/docs/message-registry.md
Original file line number Diff line number Diff line change
Expand Up @@ -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} |
Expand Down Expand Up @@ -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} |
Expand Down
15 changes: 13 additions & 2 deletions packages/@aws-cdk/toolkit-lib/lib/actions/diagnose/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down Expand Up @@ -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;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,15 @@ 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';
import { HotswapPropertyOverrides, ICON, createHotswapPropertyOverrides } from '../hotswap/common';
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';
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -512,6 +521,7 @@ class FullCloudFormationDeployment {
stackArn: changeSetDescription.StackId!,
deleteFailures: [],
stabilizingResources: [],
earlyValidationWarnings: this.earlyValidationWarnings,
};
}

Expand All @@ -530,6 +540,7 @@ class FullCloudFormationDeployment {
changeSet: changeSetDescription,
deleteFailures: [],
stabilizingResources: [],
earlyValidationWarnings: this.earlyValidationWarnings,
};
}

Expand Down Expand Up @@ -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,
Expand All @@ -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) {
Expand Down Expand Up @@ -796,6 +816,7 @@ class FullCloudFormationDeployment {
stackArn: finalState.stackId,
deleteFailures: this.update ? monitor.deleteFailures : [],
stabilizingResources: monitor.stabilizingResources,
earlyValidationWarnings: this.earlyValidationWarnings,
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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),
};
}

Expand All @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@ function formatChangeSetNotReady(detectedBy: Extract<StackProblemSource, { type:
}
}

export function formatDiagnosisWarnings(warnings: TracedResourceError[], changeSetName?: string): string {
const caption = `⚠️ Changeset ${changeSetName ? changeSetName : ''} was successfully created with some warnings`;
return `${caption}:\n${formatResourceErrors(warnings)}\n`;
}

function formatEarlyValidationProblems(problems: TracedResourceError[], detectedBy: Extract<StackProblemSource, { type: 'early-validation' }>): string {
const caption = `Early validation failed for change set ${detectedBy.changeSetName}`;
if (problems.length > 0) {
Expand Down
21 changes: 21 additions & 0 deletions packages/@aws-cdk/toolkit-lib/lib/api/diagnosing/diagnosis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down
Loading
Loading