AWS 云阵验证
校验 JavaScript 或 TypeScript 的 AWS CloudFormation 模板,并捕捉到计划违规,语义错误, 安全风险 以及部署前的最佳做法发现 - 在您的编辑,建设,服务,或CI.
- 离线 - 所有规则和CloudFormation资源计划都捆绑在一起;运行时没有获取任何规则和AWS 需要全权证书.
- 快点 - 引擎和计划一次编译,经过验证后再利用;典型的模板在验证中采用 再来.
- 自成一体 - WebAssembly模块被捆绑在软件包中;没有本地依赖.
软件包输出所有公共切入点和大多数支持类型 @aws/cloudformation-validate。 。 。 .
安装
备查 无 作为 @aws/cloudformation-validate。 。 。 .
npm install @aws/cloudformation-validate
要求节点.js 20或更晚. 软件包没有运行时间依赖性 .
快开始
引擎、模型和验证器 .free() 每个对象完成时:
import { CompositeEngine, TemplateFile } from "@aws/cloudformation-validate";
const engine = new CompositeEngine();
try {
const report = engine.validateTemplate(new TemplateFile("template.yaml"));
for (const d of report.diagnostics) {
console.log(`[${d.severity}] ${d.ruleId}: ${d.message}`);
}
} finally {
engine.free();
}
每项诊断都确认规则、严重程度、受影响实体和财产以及源位置----见 诊断。一个完整的、可运行的项目已进入 实例。 。 。 .
发动机造价昂贵(规则汇编一次),再利用成本低 -- -- 创建一个发动机并验证许多
模板。 校验- 核心失败 扔出信件字符串; JavaScript 参数检查和文件读取保留
本地错误类型 。 处理每个案件 catch (error) { String(error) }打开 wasm32-unknown-unknown内部
愤怒的恐慌无法解除 catch_panics:它困住WebAssembly呼叫和表面可捕捉
WebAssembly.RuntimeError,而不是中止主机进程。 在继续前重新创建 Web Assembly 实例 .
version() 返回捆绑的验证核心版本.
模板作为 Template - 要么是一个 TemplateFile,将引擎读取的文件系统路径包起来,或
TemplateContent,它携带模板文本或字节已经存在内存中,所以没有从磁盘读取。 文件路径
或内容 name 标记报告及其诊断;省略 TemplateContent 名称默认为
"template" (单位:千美元)DEFAULT_TEMPLATE_NAME) (中文(简体) ).
type Template = TemplateFile | TemplateContent;
class TemplateFile {
constructor(path: string); // template read from disk
}
class TemplateContent {
constructor(content: string | Uint8Array, name?: string); // in-memory UTF-8 text or raw bytes
}
const fromDisk = engine.validateTemplate(new TemplateFile("template.yaml"));
const fromMemory = engine.validateTemplate(new TemplateContent("Resources: {}", "inline.yaml"));
TemplateModel 财务报告和审定财务报表 SchemaValidator.validate 接受相同的建议 Template 工会.
发动机
RegoEngine 财务报告和审定财务报表 CelEngine 执行 Engine 接口和可互换 - 它们产生相同的
用于同一模板和配置的诊断. CompositeEngine 执行相同的界面和层自定义Rego,
CEL, 和警卫规则 在内置规则之上 - 看 复合工程。 。 。 .
Engine 接口
interface Engine {
validateTemplate(template: Template, config?: ValidateConfig): ValidationReport;
validateAwsCliCommand(request: AwsCliCommand): AwsCliCommandValidation;
listRules(): RuleInfo[];
engineName(): string;
free(): void;
}
| 方法 | 回返 | 说明 |
|---|---|---|
validateTemplate(template, config?) | ValidationReport | 验证模板并返回报告. config.detailLevel (默认) DETAILED)选择每个诊断上下文的密度: DETAILED 添加文档 URL,规则描述,相位标记,以及 ViolationContext· ; STANDARD 留下这些浓缩场 |
validateAwsCliCommand(request) | AwsCliCommandValidation | 将 AWS CLI 命令建模为 CloudFormation 资源状态并验证它 - 见 AWS CLI 命令验证 |
listRules() | RuleInfo[] | 返回每个内置和装入自定义规则的元数据 |
engineName() | string | "rego", (中文(简体) ), "cel",或 "composite" |
free() | void | 释放引擎的外加内存; 之后不能使用引擎 |
EngineConfig
传给建筑师 所有字段都是可选的:规则列表默认为空并省略
schemaValidatorConfig 只使用捆绑的策略.
interface EngineConfig {
customRules?: RuleSource[]; // engine-native rules (Rego for RegoEngine, CEL for CelEngine)
guardRules?: RuleSource[]; // CloudFormation Guard DSL rules - evaluated by the Guard evaluator
schemaValidatorConfig?: SchemaValidatorConfig; // additional resource provider schemas
}
interface SchemaValidatorConfig {
additionalSchemas?: SchemaSource[]; // resource provider schemas merged over the bundled schemas
}
type RuleSource = ExternalRuleSource | RuleFile;
type SchemaSource = AdditionalSchemaSource | SchemaFile;
interface ExternalRuleSource {
name: string; // identifier shown in diagnostics (e.g. file path)
content: string; // full rule source text
}
interface AdditionalSchemaSource {
typeName?: string; // omit to use the typeName inside the schema JSON
schema: string; // complete resource provider schema JSON
}
class RuleFile {
constructor(path: string); // rule file read from disk; the path becomes the rule source name
}
class SchemaFile {
constructor(path: string, typeName?: string); // schema file; typeName defaults to the value inside the JSON
}
| 外地 | 默认 | 说明 |
|---|---|---|
customRules | [] | 引擎本地规则: RegoEngine,CEL JSON为 CelEngine |
guardRules | [] | CloudFormation Guard DSL规则,每台引擎均由Guard评价员同样评价 |
schemaValidatorConfig | undefined | 可选 SchemaValidatorConfig 谁 additionalSchemas 以捆绑的计谋 |
每个规则都是 ExternalRuleSource - 说吧 name 确定诊断中的规则 content 是规则的全部源
语句。 传出 a RuleFile 从磁盘上装入一个( 模式与 TemplateFile 模板),或一个
ExternalRuleSource 当您在记忆中已有规则文本时。 每个额外的计划是
AdditionalSchemaSource - 一个完整的资源提供者Schema JSON加一个可选 typeName 当
jSON计划包含自己的 typeName· ; SchemaFile 从磁盘上装入一个。 附加计划扩展捆绑
策略或注册资源类型 CloudFormation 尚未发布; 存在畸形、 矛盾或不支持
schema失败了引擎构造而不是默默地削弱验证. 警卫规则由
云形护卫评估员自己 与模板的文字, 所以每个引擎报告 准确的是什么 cfn-guard validate 报表; 不解析的 Guard 文件也失败了引擎构造 。 这两种形式可以自由混合:
import { CelEngine, RuleFile, SchemaFile } from "@aws/cloudformation-validate";
const engine = new CelEngine({
customRules: [new RuleFile("rules/s3_encryption.json")],
guardRules: [new RuleFile("rules/compliance.guard")],
schemaValidatorConfig: {
additionalSchemas: [new SchemaFile("schemas/aws-lambda-function.json")],
},
});
见 自定义规则 用于Rego、CEL和Guard规则格式 额外资源提供者Schemas 计划 合并模型.
CompositeEngine
CompositeEngine 执行相同的 Engine 界面但需要一个 CompositeEngineConfig它评估每个
带有固定内置CEL评价器的内置规则,并将调用器提供的自定义规则分层于上:自定义CEL和
警卫规则与内置引擎同时运行,而自定义Rego规则则运行在单独的外部引擎中,即
只有当 Rego 规则被提供时才构建 。 没有习惯规则,它产生同样的内置诊断
RegoEngine 财务报告和审定财务报表 CelEngine,以及 engineName() 返回时 "composite"。因为复合材料会修正引擎拥有的
内置,配置没有 customRules 字段 - 它只携带上层的自定义规则:
interface CompositeEngineConfig {
regoRules?: RuleSource[]; // custom Rego rules, run by the external engine
celRules?: RuleSource[]; // custom CEL rules, run by the built-in engine
guardRules?: RuleSource[]; // CloudFormation Guard DSL rules, evaluated alongside the built-in engine
schemaValidatorConfig?: SchemaValidatorConfig; // additional resource provider schemas, observed by both inner engines
}
| 外地 | 默认 | 说明 |
|---|---|---|
regoRules | [] | 自定义 Rego 规则在内置规则上分层,由外部引擎运行 |
celRules | [] | 自定义 CEL 规则在内置规则上分层,由内置引擎运行 |
guardRules | [] | CloudFormation Guard DSL 规则分层于内置规则之上,与内置引擎一起评估 |
schemaValidatorConfig | undefined | 可选 SchemaValidatorConfig,由两个内发动机观察到 |
import { CompositeEngine, RuleFile, TemplateFile } from "@aws/cloudformation-validate";
const engine = new CompositeEngine({
regoRules: [new RuleFile("rules/s3_naming.rego")],
guardRules: [new RuleFile("rules/compliance.guard")],
});
try {
const report = engine.validateTemplate(new TemplateFile("template.yaml"));
} finally {
engine.free();
}
校验配置
控制过滤 细节 严重性 参数覆盖 以及一个验证呼叫的行为 所有领域都有
默认 - 省略配置或通过 {} 用他们.
const report = engine.validateTemplate(new TemplateFile("template.yaml"), {
exclude: { ids: ["I1002"] },
severityLevel: "WARN",
});
interface ValidateConfig {
include?: RuleFilterConfig;
exclude?: RuleFilterConfig;
detailLevel?: DetailLevel;
severityLevel?: Severity;
parameterOverrides?: Record<string, string>;
pseudoParameterOverrides?: PseudoParameterOverrides;
strict?: boolean;
disableBuiltinRules?: boolean;
}
| 外地 | 默认 | 说明 |
|---|---|---|
include | {} (所有规则) | 设定时,只有匹配规则产生诊断. 空能入一切相. |
exclude | {} (没有排除) | 相配规则被压制. 之后应用 include。 。 。 . |
detailLevel | "DETAILED" | 临诊上下文. "DETAILED" 填充文档 URL,规则描述,相位标记,以及 ViolationContext· ; "STANDARD" 使这些浓缩场消失. |
severityLevel | "INFO" | 最低严重程度阈值。 低于这一水平的诊断被放弃。 数值 : DEBUG, (中文(简体) ), INFO, (中文(简体) ), WARN, (中文(简体) ), ERROR, (中文(简体) ), FATAL。 。 。 . |
parameterOverrides | {} | 在解析期间覆盖模板参数值 。 密钥是参数逻辑ID. |
pseudoParameterOverrides | 全部 undefined | 覆盖云层伪参数AWS::AccountId, (中文(简体) ), AWS::Region(见a/c.5/49/70,附件). |
strict | false | 何时 true, (中文(简体) ), WARN- 严重诊断升级为 ERROR。 。 。 . |
disableBuiltinRules | false | 何时 true,所有内置规则(schema验证、步骤函数、元数据背景和引擎规则)都会被跳过;只有自定义规则和Guard规则才会被评价. |
规则Filter 配置
两者 include 财务报告和审定财务报表 exclude 使用此结构。 所有字段都是添加剂 -- -- 如果符合任何标准,则规则相符.
interface RuleFilterConfig {
ids?: string[]; // exact rule IDs, e.g. ["E3012", "W3010"]
categories?: string[]; // display names, e.g. ["Security", "Best Practice"]
idRanges?: IdRange[]; // numeric ranges, e.g. { prefix: "E", start: 3000, end: 3099 }
idPatterns?: string[]; // regex patterns matched against rule IDs
resourceIds?: ResourceIdFilter[]; // a rule (or every rule) on a logical resource ID
logicalIds?: LogicalIdFilter[]; // a rule (or every rule) on a named template entity
resourceTypes?: ResourceTypeFilter[]; // a rule (or every rule) on a resource type
services?: ServiceFilter[]; // a rule (or every rule) on a service, e.g. "AWS::AutoScaling"
}
// resourceIds / logicalIds / resourceTypes / services each carry an optional ruleId:
// set it to scope the filter to one rule, or omit it for every rule on the target.
interface ResourceIdFilter { ruleId?: string; resourceId: string; }
interface LogicalIdFilter { ruleId?: string; logicalId: string; entityType?: EntityType; }
interface ResourceTypeFilter { ruleId?: string; resourceType: string; }
interface ServiceFilter { ruleId?: string; service: string; }
这个 service 页:1 service-provider::service-name 资源类型的前缀 - 第一种
两个 ::- 有限区段(例如:. AWS::AutoScaling 内 AWS::AutoScaling::LaunchConfiguration) (中文(简体) ).
这个 resourceIds 维度只匹配归属于资源的诊断; logicalIds 额外匹配
关于参数、产出、绘图、元数据、条件和模板规则的诊断。 关于资源诊断
两个维度具有相同的价值。 可选 entityType 范围 a LogicalIdFilter 给一类实体,所以
MyThing 作为 "Parameter" 匹配时不触及另一类型同名实体.
PseudoParemeter 重叠
覆盖在内在函数分辨率中使用的 CloudFormation 伪参数。 所有字段都是可选的 - 当
undefined,该引擎使用内置默认值(例如区域默认值) us-east-1) (中文(简体) ).
interface PseudoParameterOverrides {
accountId?: string; // AWS::AccountId
notificationArns?: string; // AWS::NotificationARNs
partition?: string; // AWS::Partition
region?: string; // AWS::Region (default: "us-east-1")
stackId?: string; // AWS::StackId
stackName?: string; // AWS::StackName
urlSuffix?: string; // AWS::URLSuffix
}
模板模式
将模板分解为已解决 SemanticModel 直接检查 - 发动机评估规则的同一种模式
反对.
const model = new TemplateModel(new TemplateFile("template.yaml"));
const inMemory = new TemplateModel(new TemplateContent("Resources: {}"));
| 方法 | 回返 | 说明 |
|---|---|---|
resources() | Record<string, ResolvedResource> | 所有财产价值已解决的资源 |
parameters() | Record<string, ParameterInfo> | 带有类型、缺省、限制的参数定义 |
outputs() | Record<string, ResolvedOutput> | 含有已解析值和导出名称的产出 |
conditions() | string[] | 模板中定义的条件名称 |
transforms() | string[] | 变相声明(例如:. AWS::Serverless-2016-10-31(中文(简体) ) |
formatVersion() | string | undefined | AWSTemplateFormatVersion 价值 |
description() | string | undefined | 模板描述 |
toDiagnosticModel() | DiagnosticModel | 完整的诊断模型,包括参考图表、条件影响和分辨率来源 |
sourceLocation(path) | SourceSpan | null | JSON路径的源行/分栏跨度(例如:. Resources/MyBucket/Properties/BucketName(中文(简体) ) |
free() | void | 释放模型的外加内存;以后不得使用模型 |
SchemaValidator 软件
独立于规则引擎运行 schema 验证. 对照编译的资源检查每个资源
CloudFormation提供商计划,并产生致命结构诊断外加由计划衍生出的错误/警告/信息发现.
可选构造器参数相同 SchemaValidatorConfig 已经接受 EngineConfig; 省略其用法
只有捆绑的阴谋.
const validator = new SchemaValidator();
try {
const diagnostics = validator.validate(new TemplateFile("template.yaml"), "us-east-1");
} finally {
validator.free();
}
| 方法 | 回返 | 说明 |
|---|---|---|
new SchemaValidator(config?) | SchemaValidator | 构造验证符; 省略 SchemaValidatorConfig 只使用捆绑的策略 |
validate(template, region?) | Diagnostic[] | A 的外观诊断 Template 时间 STANDARD 细节 - 浓缩场不存在。 省略一个 region 证实反对所有地区的联盟. |
listRules() | RuleInfo[] | Schema 规则元数据 |
schemaCount() | number | 编译提供者计划的数目 |
free() | void | 释放验证器的外加内存; 验证器不得事后使用 |
AWS CLI 命令验证
validateAwsCliCommand 模拟 AWS CLI( 或 SDK) API 调用为 CloudFormation 资源状态并验证其离线
在发送之前。 它通过一个封闭的,生成的,将操作分类,将其映射到 CloudFormation 资源类型
适配器目录,从提供的参数合成出一个模板,并运行上面的普通模板管道. A 类
TemplateBody cloudFormation操作的参数被验证为-is。 任何不能完全模拟的请求..
未注册的操作, 没有无损属性映射的参数, 或 Cloud Formation 以外的值
强制 API 本身不执行 - 有原因跳过, 从未猜到 .
import { AwsCliCommand, CompositeEngine } from "@aws/cloudformation-validate";
const engine = new CompositeEngine();
try {
const request = new AwsCliCommand("s3", "CreateBucket", { Bucket: "example-bucket" });
const validation = engine.validateAwsCliCommand(request);
if (validation.status === "VALIDATED") {
for (const d of validation.report!.diagnostics) {
console.log(`[${d.severity}] ${d.ruleId}: ${d.message}`);
}
} else {
console.log(`skipped (${validation.operationKind}): ${validation.reason}`);
}
} finally {
engine.free();
}
class AwsCliCommand {
constructor(
serviceName: string, // canonical botocore service name, e.g. "s3" or "cloudformation"
operationName: string, // API operation name, e.g. "CreateBucket"
parameters: Record<string, unknown>, // request parameters (a plain object with string keys)
options?: AwsCliCommandOptions,
);
}
interface AwsCliCommandOptions {
servicePrefix?: string; // signing prefix; context only
httpMethod?: string; // classification hint ("GET"/"HEAD"/"DELETE") for unrecognized verbs
isReadOnly?: boolean; // true classifies the operation as READ_ONLY
}
serviceName匹配不敏感大小写。 签名名称、终点别名和ARN前缀从未解决; 先翻译一个SDK的服务身份.parameters接受嵌入式平原对象和阵列; 字符串; 数字(插件必须是安全的 JavaScript 整数);bigint布尔斯,null, (中文(简体) ),Uint8Array,以及Date(序号为ISO 8601). 任何其他价值作为 明确不支持的标记,并且因为合成是全的或无的,所以请求会以一个理由被跳过 命名违法的参数 - 没有参数被默默地删除 .
结果是 AwsCliCommandValidation数字 :
| 外地 | 说明 |
|---|---|
operationKind | AwsCliOperationKind数字 : "READ_ONLY", (中文(简体) ), "CLOUD_FORMATION_CREATE", (中文(简体) ), "CLOUD_FORMATION_UPDATE", (中文(简体) ), "CLOUD_FORMATION_DELETE", (中文(简体) ), "DATA_PLANE_MUTATION",或 "UNMAPPED_MUTATION" |
status | AwsCliCommandValidationStatus数字 : "VALIDATED" 当模型模板穿过管道时, "SKIPPED" 否则 |
templateSource | AwsCliTemplateSource | null数字 : "TEMPLATE_BODY", (中文(简体) ), "CLOUD_CONTROL_DESIRED_STATE", (中文(简体) ), "SYNTHESIZED_CREATE",或 "SYNTHESIZED_UPDATE"· ; null 跳过时 |
resourceTypes | string[] - 云阵资源类型 |
reason | string - 为何请求被验证或跳过 |
report | ValidationReport | null - 到时 "VALIDATED"。配置是固定的: STANDARD 详细级别和a WARN 重度下限 |
template | Uint8Array | null - 经验证的精确模板字节(呼叫者) TemplateBody 不变,或合成的JSON; null 跳过时 |
完整合同 - 适配器目录,全或一无所有映射, 哪些规则被取消用于合成状态 - 记录在 验证引擎/API.md。 。 。 .
报表类型
审定报告
validateTemplate 总是返回 a ValidationReport - 模板语法失败作为报告返回
状态 "ERROR" 还有一个 F1101 诊断; 仅投放基础设施或引擎故障 :
interface ValidationReport {
filePath: string;
status: "OK" | "ANALYSIS_INCOMPLETE" | "ERROR"; // incomplete may omit findings; error = parse failure
version: string;
metadata: ReportMetadata;
performance: PerformanceMetrics;
diagnostics: Diagnostic[];
}
每个发现都是 Diagnostic (见 诊断) (中文(简体) ). 其浓缩场 - documentationUrl, (中文(简体) ),
ruleDescription, (中文(简体) ), phase (单位:千美元)PARSE | SCHEMA | LINT),以及 context (单位:千美元)ViolationContext 与 actualValue, (中文(简体) ),
expectedConstraint, (中文(简体) ), resolutionSource—— 仅居住在 detailLevel "DETAILED" (默认);
验证时间 "STANDARD" 离开他们,保持基础诊断场.
metadata 载有汇总数、抑制诊断数、扫描资源以及
登记规则在排除类别之后计算。 也记录了严格的旗帜、严重门槛和可选性
预算耗尽的记录。 每张唱片都保留一种稳定的机器可读性,还包括一种人可读性
说明句子,数字限制,以及具体用尽是否使分析不完整.
requiredPropertyCombinations 仅为上下文,所以 analysisIncomplete 值为 false 报告可以
保留 "OK"。 。 。 .
诊断
interface Diagnostic {
ruleId: string; // e.g. "E3012", "F1001", "W3010"
severity: Severity; // "FATAL" | "ERROR" | "WARN" | "INFO" | "DEBUG"
message: string;
source: RuleOrigin; // "SCHEMA" | "CFN_LINT" | "ENGINE" | "CUSTOM" | "GUARD"
entity?: Entity; // the named template entity the finding targets, if any
propertyPath?: string; // e.g. "Properties.BucketName", or section-absolute like "Parameters/MyParam/Type"
suggestedFix?: string;
category?: string;
startLine?: number;
startColumn?: number;
endLine?: number;
endColumn?: number;
relatedResources?: RelatedResource[];
conditionScenario?: Record<string, boolean>; // condition truth assignment that triggers this diagnostic
// Enrichment fields: populated at detailLevel "DETAILED" (the default), absent at "STANDARD".
documentationUrl?: string;
ruleDescription?: string;
phase?: "PARSE" | "SCHEMA" | "LINT"; // pipeline stage that produced the finding
context?: ViolationContext; // actualValue, expectedConstraint, resolutionSource, etc.
}
// The named template entity a diagnostic is attributed to. The entity type is the
// singular form of the top-level template section the entity is declared in.
interface Entity {
logicalId: string; // logical ID as declared in the template
entityType: EntityType;
resourceType?: string; // CloudFormation type, when the entity is a resource whose type is known
}
type EntityType = "Resource" | "Parameter" | "Output" | "Mapping" | "Metadata"
| "Rule" | "Condition" | "Transform" | "FormatVersion" | "Description";
Severity, (中文(简体) ), RuleOrigin,以及 DetailLevel 属于字符串-升联盟类型( r)"WARN", (中文(简体) ), "GUARD", (中文(简体) ), "STANDARD",作为
是报告 status (单位:千美元)"OK", (中文(简体) ), "ANALYSIS_INCOMPLETE", (中文(简体) ), "ERROR") (中文(简体) ).