import { type IAspect } from 'aws-cdk-lib'; import { type INagLogger, type NagLoggerComplianceData, type NagLoggerErrorData, type NagLoggerNonComplianceData, type NagLoggerNotApplicableData, type NagLoggerSuppressedData, type NagLoggerSuppressedErrorData, NagPack, type NagPackProps } from 'cdk-nag'; import type { IConstruct } from 'constructs'; /** Metadata schema version for tracking compatibility */ declare const CDK_INSIGHTS_METADATA_VERSION = "2.2.0"; /** Prefix used to identify cdk-insights annotations in CloudFormation metadata */ declare const CDK_INSIGHTS_ANNOTATION_PREFIX = "cdk-insights::"; /** * Sub-prefix for nag findings captured by `CdkInsightsNagDelegate` and emitted * as Info annotations. Format: `cdk-insights::nagFinding::`. The scan-side * parser branches on this so nag findings flow through the same findings stream * as cdk-insights' native rules instead of polluting CDK's error/warning channel. */ declare const CDK_INSIGHTS_NAG_FINDING_PREFIX = "cdk-insights::nagFinding::"; /** Confidence level for source location detection */ export type SourceLocationConfidence = 'high' | 'medium' | 'low'; /** Source location information for a construct */ export interface SourceLocation { filePath: string; line: number; column: number; /** End line for multi-line constructs */ endLine?: number; /** End column */ endColumn?: number; /** How confident we are in this location */ confidence?: SourceLocationConfidence; /** The method used to determine this location */ method?: 'creation_stack' | 'metadata_trace' | 'source_analysis' | 'source_map' | 'ast_analysis' | 'fallback'; /** The function or class containing this construct */ enclosingScope?: string; /** Code snippet around the construct definition */ codeSnippet?: string; /** Original TypeScript file if source maps were used */ originalFile?: string; } /** Enhanced metadata captured for each construct */ export interface CdkInsightsMetadata { source: 'cdk_insights'; version: string; stackName: string; stackId: string; constructPath: string; constructType: string; friendlyName: string; id?: string; /** Logical ID in CloudFormation template */ logicalId?: string; sourceLocation?: SourceLocation; /** Parent construct path for hierarchy visualization */ parentPath?: string; /** Number of child constructs */ childCount?: number; /** Resource tags if available */ tags?: Record; timestamp: string; /** The L2 construct type (e.g., "aws_s3.Bucket") if this is an L1 resource under an L2 */ l2ConstructType?: string; /** The L2 construct ID */ l2ConstructId?: string; /** Full construct hierarchy from root to this node */ constructHierarchy?: ConstructHierarchyEntry[]; /** CloudFormation resource type (e.g., "AWS::S3::Bucket") */ cfnResourceType?: string; /** CloudFormation logical IDs this resource depends on */ dependencies?: string[]; /** CloudFormation logical IDs that depend on this resource */ dependents?: string[]; /** Properties that may have security/compliance implications */ sensitiveProperties?: SensitiveProperty[]; /** AWS service category (e.g., "Storage", "Compute", "Security") */ serviceCategory?: string; /** Whether this resource uses default configuration (potential concern) */ usesDefaults?: boolean; /** CDK construct library version if detectable */ cdkVersion?: string; /** * Human-readable description of what created this resource. * Helpful for implicitly created resources like subnets from a VPC. */ createdBy?: string; /** * Source location of the nearest ancestor that has a known source location. * Used when this resource doesn't have a direct source location. */ rootSourceLocation?: SourceLocation; /** * Search hint to help users find this resource in their codebase. * Contains keywords to search for. */ searchHint?: string; } /** Entry in the construct hierarchy */ export interface ConstructHierarchyEntry { id: string; type: string; /** Fully qualified name if available (e.g., "aws-cdk-lib.aws_s3.Bucket") */ fqn?: string; } /** Property that may have security/compliance implications */ export interface SensitiveProperty { /** Property path (e.g., "encryption.enabled") */ path: string; /** Current value (redacted if sensitive) */ value: string | boolean | number | null; /** Whether this is using a default value */ isDefault?: boolean; /** Recommendation for this property */ recommendation?: string; } /** Configuration options for the logger */ export interface CdkInsightsLoggerOptions { /** Log compliant resources (default: false) */ logCompliance?: boolean; /** Log not-applicable rules (default: false) */ logNotApplicable?: boolean; /** Enable verbose/debug logging (default: false) */ verbose?: boolean; } /** Configuration options for the aspect */ export interface CdkInsightsAspectOptions { /** Run CDK-Nag compliance checks (default: true) */ runNagChecks?: boolean; /** Capture source location from stack traces (default: true) */ captureSourceLocation?: boolean; /** Capture resource tags (default: true) */ captureTags?: boolean; /** Capture parent/child relationships (default: true) */ captureRelationships?: boolean; /** Capture full construct hierarchy (default: true) */ captureHierarchy?: boolean; /** Capture resource dependencies (default: true) */ captureDependencies?: boolean; /** Capture sensitive properties that may have security implications (default: true) */ captureSensitiveProperties?: boolean; /** Logger options */ logger?: CdkInsightsLoggerOptions; /** * Enable source file analysis for location detection (default: true) * When enabled, the aspect will search source files to find construct definitions. * This is useful when CDK debug mode is not enabled. */ analyzeSourceFiles?: boolean; /** * Enable source map support for mapping compiled JS back to TS (default: true) * When enabled and source maps are available, the aspect will use them to * provide accurate TypeScript file locations even when stack traces point to * compiled JavaScript files. */ useSourceMaps?: boolean; /** * Include code snippets around construct definitions (default: true) * When enabled, the source location will include a few lines of code * around the construct definition for quick reference. */ includeCodeSnippets?: boolean; /** * Auto-suppress cdk-nag findings for well-known CDK / AWS boilerplate * patterns (default: false). When `true`, the aspect attaches * `NagSuppressions` to matching constructs **before** cdk-nag evaluates * its rules, so the suppressed findings disappear from scan output * entirely. Each suppression carries a named justification. * * Currently covers two universally-noisy rules: * * - **`AwsSolutions-IAM4`** for the AWS-managed Lambda execution * policies CDK auto-attaches based on event sources * (`AWSLambdaBasicExecutionRole`, `AWSLambdaVPCAccessExecutionRole`, * `AWSLambdaSQSQueueExecutionRole`, `AWSLambdaDynamoDBExecutionRole`, * `AWSLambdaKinesisExecutionRole`). Each is narrowly scoped to a * single AWS service; replacing them with customer-managed copies is * busywork with no security gain. The suppression uses `appliesTo` * so any *other* managed policy attached to the same role still * surfaces a finding. * * - **`AwsSolutions-L1`** for current AWS Lambda LTS runtimes * (Node 18/20/22, Python 3.11/3.12/3.13, Java 17/21, .NET 8). * cdk-nag's "latest runtime" check is heuristic and lags new LTS * releases; this allowlist updates with cdk-insights releases. * * Anything not in the lists above continues to surface normally — opt-in * is conservative and additive. * * Recommended for any project that uses cdk-insights' aspect. To * extend with project-specific suppressions, call * `NagSuppressions.addResourceSuppressions(...)` from `cdk-nag` after * constructing your stacks. */ cdkBoilerplateSuppressions?: boolean; /** * Additional cdk-nag rule IDs to suppress globally across the construct * tree. Applied via `NagSuppressions` on the App root with * `applyToChildren: true`, so the suppression is honoured for every * descendant resource regardless of stack. * * Two entry forms: * * - **String shorthand** (`'AwsSolutions-APIG2'`) — gets a generic * auto-reason. Use for quick experiments / triage. * - **Object form** (`{ id: '...', reason: '...' }`) — carries an * explicit written justification. **Recommended for checked-in * code** so suppressions are auditable. * * Composes with `cdkBoilerplateSuppressions`; both can be enabled * simultaneously. For finer-grained control (per-resource, per- * `appliesTo`-pattern), use `NagSuppressions.addResourceSuppressions(...)` * from `cdk-nag` directly after constructing your stacks. * * @example * ```ts * Aspects.of(app).add(createCdkInsightsAspect({ * suppressNagRules: [ * // String shorthand — generic auto-reason, fine for triage * 'AwsSolutions-APIG2', * // Object form — written justification, recommended for prod code * { * id: 'AwsSolutions-COG2', * reason: 'MFA is opt-in by product policy; see RFC-0042.', * }, * ], * })); * ``` */ suppressNagRules?: Array; } /** * Helper function to check if CDK stack traces are enabled. * Three paths CDK honours, in order of how a user typically sets them: * 1. `CDK_DEBUG=true` env var (per-shell, transient). * 2. `CDK_CONTEXT_JSON` env containing the `@aws-cdk/core:stackTrace` flag * (used by `cdk synth --context @aws-cdk/core:stackTrace=true`). * 3. `cdk.json` `context['@aws-cdk/core:stackTrace'] = true` (durable, the * path `cdk-insights setup` configures so users don't have to remember * anything). */ export declare const isCdkDebugEnabled: () => boolean; /** * Creates a configurable CDK-Nag logger with verbosity control. */ export declare const createCdkInsightsLogger: (options?: CdkInsightsLoggerOptions) => INagLogger; /** * Creates a playful logger with more expressive messages. * Useful for development and debugging. */ export declare const createExtremelyHelpfulConsoleLogger: (options?: CdkInsightsLoggerOptions) => INagLogger; /** * Captures a non-compliant nag finding as a cdk-insights Info annotation. * * The on-the-wire shape is intentionally small and stable — the scan-side * parser depends on it. Severity is mapped from cdk-nag's binary * `NagMessageLevel` (ERROR/WARN) into cdk-insights' richer Severity enum: * * - `NagMessageLevel.ERROR` → `HIGH` (rule pack author rated it security-critical) * - `NagMessageLevel.WARN` → `MEDIUM` (advisory) * * `HIGH` is the conservative choice for ERROR — it preserves today's behaviour * when the Validation Plugin is set to `minimumSeverity: "CRITICAL"` (nothing * blocks deploy from nag), while letting users tighten to `HIGH` later to * promote ERROR-rated nag findings into deploy gates. */ interface CdkInsightsNagFinding { source: 'cdk-nag'; ruleId: string; ruleOriginalName: string; ruleInfo: string; ruleExplanation: string; /** Mapped from NagMessageLevel: ERROR→HIGH, WARN→MEDIUM. */ severity: 'HIGH' | 'MEDIUM'; /** Original cdk-nag level — kept so consumers can recover the source signal. */ level: 'Error' | 'Warning'; /** Sub-finding identifier from rules that emit multiple findings per resource. */ findingId?: string; /** Construct path of the resource that failed the rule. */ resourcePath: string; /** CloudFormation logical ID of the resource. */ logicalId: string; } /** * Creates a CDK Insights aspect using functional composition. * This is the recommended approach for new projects. * * @example * ```typescript * import { Aspects } from 'aws-cdk-lib'; * import { createCdkInsightsAspect } from 'cdk-insights'; * * // Basic usage * Aspects.of(app).add(createCdkInsightsAspect()); * * // With options * Aspects.of(app).add(createCdkInsightsAspect({ * runNagChecks: true, * captureSourceLocation: true, * captureTags: true, * logger: { verbose: true } * })); * * // Metadata-only mode (no CDK-Nag) * Aspects.of(app).add(createCdkInsightsAspect({ * runNagChecks: false * })); * ``` */ export declare const createCdkInsightsAspect: (options?: CdkInsightsAspectOptions) => IAspect; /** * Legacy class-based logger for backward compatibility. * @deprecated Use createCdkInsightsLogger() instead */ export declare class ExtremelyHelpfulConsoleLogger implements INagLogger { private readonly options; constructor(options?: CdkInsightsLoggerOptions); onCompliance(data: NagLoggerComplianceData): void; onNonCompliance(data: NagLoggerNonComplianceData): void; onSuppressed(data: NagLoggerSuppressedData): void; onError(data: NagLoggerErrorData): void; onSuppressedError(data: NagLoggerSuppressedErrorData): void; onNotApplicable(data: NagLoggerNotApplicableData): void; } /** * Class-based CDK Insights aspect for backward compatibility. * Extends NagPack for integration with CDK-Nag ecosystem. * * @deprecated Use createCdkInsightsAspect() for new projects * * @example * ```typescript * import { Aspects } from 'aws-cdk-lib'; * import { CdkInsightsAspect } from 'cdk-insights'; * * Aspects.of(app).add(new CdkInsightsAspect()); * ``` */ export declare class CdkInsightsAspect extends NagPack implements IAspect { private readonly delegate; private readonly options; private readonly userSuppressionsApplied; constructor(props?: NagPackProps & CdkInsightsAspectOptions); visit(node: IConstruct): void; } /** Re-export constants for external use */ export { CDK_INSIGHTS_METADATA_VERSION, CDK_INSIGHTS_ANNOTATION_PREFIX, CDK_INSIGHTS_NAG_FINDING_PREFIX, }; export type { CdkInsightsNagFinding }; /** * Clears all internal caches. Useful for testing or when processing * multiple independent CDK apps in the same process. */ export declare const clearCaches: () => void; /** * Returns cache statistics for debugging/monitoring. */ export declare const getCacheStats: () => { sourceFiles: number; constructLocations: number; sourceMaps: number; };