编写你自己的治理插件
本页带你把一个治理插件从插件开发套件的适配器骨架一路做到能拒绝构建。你将复制骨架,在其中写入一条规则,构建 .wasm,在骨架附带的 payload 文件上手动调用它的每个导出,在你工作区自己的目录中将其声明为 Plugin 实体,在某个角色上挂接它,并看着它阻止一个违反规则的构建。
本页是治理插槽的实践配套,后者记录了四个角色、每个角色携带的 payload 以及宿主据以行动的裁决;也是插件开发者指南的配套,后者记录了 Plugin 实体及其生命周期。编写提供程序是针对提供程序客体的同类演练。
关于本页的代码块。 每个显示输出的代码块都复制自按出现顺序真实运行下列步骤的结果,并遵循输出约定:一个代码块要么是完整的,要么是标出了省略行位置的摘录。两个占位符代表在每台机器上都不同的绝对路径:<guest> 是你复制的骨架所在的目录,<workspace> 是挂接该插件的工作区所在的目录。
你需要准备的内容
- Go 工具链,它无需额外工具即可编译为 WebAssembly。
- 插件开发套件的一份检出副本(其中带有骨架),以及该套件所基于的 ABI 包的检出副本:你副本中的
go.mod指向这两者。 aggrega二进制文件。
该套件还为 Rust 提供了同样的骨架,位于 rust/examples/governance-adapter-skeleton,为 TypeScript 提供的位于 typescript/examples/governance-adapter-skeleton。每个都带有相同的四个 payload 文件,且每个未经修改的副本都以相同方式回答它们;本页的每条 aggrega 命令都适用于其中任何一个,只需换成其自身的产物名称,每个的 README 都给出了其构建方法。
成品的形态
与任何插件一样,治理插件由两个产物组成:一个 .wasm 客体,以及一个将其带入目录的 Plugin 实体。挂接它只需在工作区配置中添加一个条目。编译器中没有任何改动。
本演练最终得到的两个目录,不含构建写入工作区的内容:
category-guard/ your copy of the skeleton: the Go module that compiles to the .wasm .gitignore README.md the skeleton's own guide go.mod go.sum main.go the describe() self-report and the shared plumbing evaluator.go the seam, where the rule goes annotations.go the annotation-transform role labels.go the label-transform role verdicts.go the ir-verdict and render-verdict roles build.sh annotation-payload.json label-payload.json ir-verdict-payload.json render-verdict-payload.json my-payload.json a copy you edit in section 4 wrong-payload.json a copy you break in section 5 overlay.yaml the identity you supply to the entity generator dist/governance-adapter-skeleton-go.wasm the compiled guestshop/ the workspace the plugin is attached in catalog/component/example/compute/api/1.0.0/component.yaml catalog/component/example/devtool/db-console/1.0.0/component.yaml catalog/recipe/compose/api/1.0.0/recipe.yaml catalog/recipe/compose/db-console/1.0.0/recipe.yaml catalog/plugin/governance/category-guard/0.1.0/plugin.yaml catalog/plugin/governance/category-guard/0.1.0/governance--category-guard.wasm aggregate.yaml manifest.yaml release.yaml .aggrega-config.yaml该插件强制执行的规则很常见:工作区指明它不交付的组件类别——这里是 devtool,即管理控制台的类别——携带其中某个类别的组件的构建会停止,并指明该组件。
1. 复制骨架
cp -r /path/to/aggrega-pdk/go/examples/governance-adapter-skeleton category-guardcd category-guard骨架的 go.mod 通过相对于其在套件内位置的路径来引用套件和 ABI 包,因此套件之外的副本需要自己指明它们。为模块指定你自己的路径,并让两行 replace 指向你的检出副本:
module example.com/category-guard
go 1.26.0
require ( github.com/aggrega-ai/aggrega-abi/go v0.0.0 github.com/aggrega-ai/aggrega-pdk/go v0.0.0 github.com/extism/go-pdk v1.1.3)
replace github.com/aggrega-ai/aggrega-pdk/go => /path/to/aggrega-pdk/go
replace github.com/aggrega-ai/aggrega-abi/go => /path/to/aggrega-abi/go骨架的 go.sum 保持不变。
2. 构建它,并手动调用每个角色
在修改任何内容之前先构建副本,这样你运行的第一样东西就是并非由你编写的连接代码:
./build.shWrote <guest>/dist/governance-adapter-skeleton-go.wasmaggrega plugin run-local 从一个路径加载客体,检查你指定的导出是否在客体的 describe() 自我报告中声明——并且在使用 --type governance 时,检查客体是否将自己报告为治理插件——然后用你提供的 payload 调用它,并打印其回答。骨架为每个角色附带一个 payload 文件,每个都是其导出的一份小而有效的输入。payload 以 JSON 编写;每个治理角色的线路格式都采用二进制编码,因此该命令在调用导出之前将 payload 转换为该编码,并以 JSON 打印导出的回答。
aggrega plugin run-local --plugin dist/governance-adapter-skeleton-go.wasm \ --type governance --export transform_annotations --with @annotation-payload.json{ "injections": []}run-local 从你给出的路径读取客体和 payload,不需要工作区,因此可以从任意目录运行。
aggrega plugin run-local --plugin dist/governance-adapter-skeleton-go.wasm \ --type governance --export mutate --with @label-payload.json{ "patches": []}aggrega plugin run-local --plugin dist/governance-adapter-skeleton-go.wasm \ --type governance --export verdict_ir --with @ir-verdict-payload.json{ "results": [ { "severity": "info", "message": "this adapter has no policy engine yet: the seam received rules.policy (43 bytes) and some settings" } ]}aggrega plugin run-local --plugin dist/governance-adapter-skeleton-go.wasm \ --type governance --export verdict_render --with @render-verdict-payload.json{ "results": [ { "severity": "info", "message": "this adapter has no policy engine yet: the seam received rules.policy (43 bytes) and some settings" } ]}每个回答都是其角色允许返回的形状:要添加的注解、标签变更和裁决。两个转换角色不返回任何内容,每个裁决角色返回一个 info 裁决——一条记录观察结果、不改变构建结果的提示。这条提示是骨架连接正确的证明。每个 payload 文件都以构建交付时的形式携带挂接的两项输入:sources 下的一个策略文件 rules.policy,以及一个 settings 对象。该提示说明两者都到达了接缝——即骨架其余部分用角色收到的任何内容调用的那个函数。
下面是后面的规则将读取的 payload ir-verdict-payload.json,完整内容如下:
{ "graph": { "apiVersion": "aggrega.ai/v1beta1", "kind": "IR", "metadata": { "aggregate_name": "shop" }, "spec": { "nodes": { "api": { "component": "example/compute/api", "resolved_version": "1.0.0", "labels": { "component.aggrega.ai/type": "server", "component.aggrega.ai/category": "compute" } } }, "edges": [], "values_mapping": {}, "infra_mapping": {}, "feature_values_mapping": {}, "provenance": { "schema_version": "aggrega.ai/v1beta1", "compiler_version": "0.0.0", "aggregate_version": "1.0.0", "manifest_version": "1.0.0", "release_version": "1.0.0" } } }, "precalculated_paths": [], "sources": [ { "path": "rules.policy", "content": "policy text, handed to the engine verbatim\n" } ], "settings": { "max_nodes": 50 }}它是 ir-verdict 角色的输入:包含一个组件的构建图、在图上枚举出的路由路径,以及挂接的 sources 和 settings。每个字段都在该角色的参考页策略插槽 schema 中说明,图本身见构建图 schema;另外三个文件遵循 annotation-transform schema、mutator schema,以及(对于 verdict_render)策略插槽 schema 中的 RenderPolicyInput。
3. 编写一条规则
规则位于骨架的接缝 evaluator.go 中。每个角色都会解码其 payload,将其写成一个 JSON 文档,然后用挂接的策略文件、其设置、该文档以及它希望返回的决策名称调用 Evaluate。裁决角色依次请求三个决策——deny、warn 和 audit——并分别以严重级别 halt、warn 和 info 报告各自的回答;两个转换角色请求 annotations 和 labels。因此,阻止构建的规则回答的是 deny。
将 evaluator.go 替换为:
package main
import ( "encoding/json" "fmt" "slices" "sort")
// Program is one policy program the attachment carried.type Program struct { Path string Text string}
// categoryLabel is the label a catalog Component states its category in.const categoryLabel = "component.aggrega.ai/category"
// Evaluate refuses every component whose category the attachment's settings// list under forbidden_categories.func Evaluate(programs []Program, settings json.RawMessage, payload json.RawMessage, decision string) ([]json.RawMessage, error) { if decision != denyDecision { return nil, nil }
var config struct { ForbiddenCategories []string `json:"forbidden_categories"` } if len(settings) > 0 { if err := json.Unmarshal(settings, &config); err != nil { return nil, fmt.Errorf("reading the settings: %w", err) } }
var input struct { Graph struct { Spec struct { Nodes map[string]struct { Labels map[string]string `json:"labels"` } `json:"nodes"` } `json:"spec"` } `json:"graph"` } if err := json.Unmarshal(payload, &input); err != nil { return nil, fmt.Errorf("reading the build graph: %w", err) }
// A Go map has no order, so the node ids are sorted: identical input must // yield an identical sequence of decisions. ids := make([]string, 0, len(input.Graph.Spec.Nodes)) for id := range input.Graph.Spec.Nodes { ids = append(ids, id) } sort.Strings(ids)
var decisions []json.RawMessage for _, id := range ids { category := input.Graph.Spec.Nodes[id].Labels[categoryLabel] if !slices.Contains(config.ForbiddenCategories, category) { continue } message, err := json.Marshal(fmt.Sprintf( "component %q is a %s component, and this workspace ships none", id, category)) if err != nil { return nil, err } decisions = append(decisions, message) } return decisions, nil}Program 保留,因为角色文件用它构建程序列表。其余部分就是规则,其中有四点值得仔细阅读。
- 它按线路格式给出的名称读取 payload。 节点位于
graph.spec.nodes,以节点 id 为键,每个都带有其labels——与每个角色的 payload 暴露的内容作为input.graph.spec.nodes提供给 Rego 策略的路径相同。为此角色编写的规则在其他角色上读不到任何内容:render-verdict的 payload 不携带图,因此在那里循环找不到节点。 - 禁止什么由运维人员决定,而不是由插件决定。 类别来自挂接的
settings,因此同一个.wasm既能服务禁止devtool的工作区,也能服务什么都不禁止的工作区。 - 它在回答之前先排序。 对相同输入的多次运行,构建输出逐字节一致,而按 Go map 顺序回答的客体会从内部破坏这一点。
- 它会明确地失败。 无法读取的设置或 payload 会返回错误而不是空列表,角色会把该错误转为一次失败的调用。空列表表示策略没有发现需要说明的内容;失败的调用表示策略没有运行,而只有客体区分二者,构建才能区分二者。
规则从不读取 programs。此插件的规则被编译进客体,因此挂接提供设置而不提供策略文件——与围绕预编译引擎构建的客体形状相同,与从 sources 加载规则的客体则相反。
最后,说明插件是什么。在 main.go 中,修改 descriptor() 中的描述:
Description: "Refuse a build that carries a component of a category the attachment forbids.",第 6 节中的实体生成器会将其复制到 Plugin 实体中。
4. 再次构建,并阅读规则的回答
./build.shWrote <guest>/dist/governance-adapter-skeleton-go.wasm在相同的文件上再次调用这四个导出:
aggrega plugin run-local --plugin dist/governance-adapter-skeleton-go.wasm \ --type governance --export transform_annotations --with @annotation-payload.jsonaggrega plugin run-local --plugin dist/governance-adapter-skeleton-go.wasm \ --type governance --export mutate --with @label-payload.jsonaggrega plugin run-local --plugin dist/governance-adapter-skeleton-go.wasm \ --type governance --export verdict_ir --with @ir-verdict-payload.jsonaggrega plugin run-local --plugin dist/governance-adapter-skeleton-go.wasm \ --type governance --export verdict_render --with @render-verdict-payload.json{ "injections": []}{ "patches": []}{ "results": []}{ "results": []}两个裁决角色中的占位提示都消失了,而且两者都不返回裁决:附带 payload 的 settings 不禁止任何类别,因此规则允许它。空的 results 列表就是裁决角色表示构建可以继续的方式。
要看到规则触发,就给它禁止 payload 所携带内容的设置。将 ir-verdict-payload.json 复制为 my-payload.json,并把其中的 settings 替换为:
"settings": { "forbidden_categories": [ "compute" ] }aggrega plugin run-local --plugin dist/governance-adapter-skeleton-go.wasm \ --type governance --export verdict_ir --with @my-payload.json{ "results": [ { "severity": "halt", "message": "component \"api\" is a compute component, and this workspace ships none" } ]}deny 决策以携带规则自身消息的 halt 裁决的形式到达。在构建中,halt 会以该消息作为原因停止构建。
5. 当 payload 不匹配时
该命令将 payload 携带的每个字段转换为其形状声明的类型,并在客体运行之前拒绝无法转换的字段。在名为 wrong-payload.json 的副本中,将某个节点的 labels 写成列表而不是对象:
"labels": [ "server", "compute" ]aggrega plugin run-local --plugin dist/governance-adapter-skeleton-go.wasm \ --type governance --export verdict_ir --with @wrong-payload.jsonunder key "api": expected JSON object, found [命令以非零状态退出,客体从未被调用。
转换会检查 payload 所携带每个字段的类型;它不检查 payload 是否携带了形状要求的每个字段。缺少某个字段的 payload 照样会被转换并交给客体,而规则读取该字段的客体在那里什么也找不到。因此,请对照 schema 参考页检查你手写的 payload:命令没有报错并不表示 payload 是完整的。
6. 在你工作区的目录中将其声明为 Plugin 实体
实体的契约字段是从客体中读出的,而不是手写的,因此实体不能声称拥有二进制文件中没有的导出。你在一个小的覆盖文件 overlay.yaml 中提供身份信息:
apiVersion: aggrega.ai/v1beta1kind: Pluginmetadata: name: category-guardaggrega plugin gen-catalog --plugin dist/governance-adapter-skeleton-go.wasm \ --overlay overlay.yaml --output-dir ../shop/catalog/plugingenerated ../shop/catalog/plugin/governance/category-guard/0.1.0/plugin.yaml生成的实体:
# Generated from the plugin by `aggrega plugin gen-catalog`. You may narrow its capability lists; edit nothing else here.apiVersion: aggrega.ai/v1beta1kind: Pluginmetadata: name: category-guard version: 0.1.0 pluginType: governance description: Refuse a build that carries a component of a category the attachment forbids.spec: abiVersion: v1beta1 exports: - name: transform_annotations - name: mutate - name: verdict_ir - name: verdict_renderversion 是骨架的 build.sh 写入客体的版本,除非 AGGREGA_PLUGIN_VERSION 指定了其他版本,否则为 0.1.0;pluginType 和四个导出是 describe() 报告的内容。治理插件不声明任何能力:它可以返回什么取决于它挂接的角色,而不是实体。
在开发插件期间还没有已发布的内容可以获取,因此构建从目录文件夹中读取它,.wasm 位于其实体旁边。实体旁边的文件根据实体的插件类型和名称命名,位于实体文档所在的目录中——对于 governance/category-guard,文件名为 governance--category-guard.wasm:
cp dist/governance-adapter-skeleton-go.wasm \ ../shop/catalog/plugin/governance/category-guard/0.1.0/governance--category-guard.wasm请复制该文件,而不是链接到它。该位置上的链接只会被跟随到工作区内部的某处——或者,对于列在工作区之外的目录文件夹,跟随到该文件夹内部的某处;指向更远处的链接会使构建和 pull 停止并指明该链接,如工作区边界所述。在该名称下找不到 .wasm 的 pull 会停止并指明它期望的文件,如 A plugin’s .wasm is not on this machine (插件的文件不在这台机器上) 所述。
7. 插件守护的工作区
该工作区是一个小商店:一个 API,以及用 Docker Compose 构建它的文档。其目录中还带有规则将拒绝的管理控制台,即类别为 devtool 的一个 Component。
catalog/component/example/compute/api/1.0.0/component.yaml:
apiVersion: aggrega.ai/v1beta1kind: Componentmetadata: name: example/compute/api version: 1.0.0 description: The shop's HTTP API. labels: component.aggrega.ai/type: server component.aggrega.ai/category: computespec: schema: infra: port: type: integer default: 8080 description: The port the API listens on.catalog/component/example/devtool/db-console/1.0.0/component.yaml:
apiVersion: aggrega.ai/v1beta1kind: Componentmetadata: name: example/devtool/db-console version: 1.0.0 description: A database administration console in the browser. labels: component.aggrega.ai/type: server component.aggrega.ai/category: devtoolspec: schema: infra: port: type: integer default: 8081 description: The port the console listens on.catalog/recipe/compose/api/1.0.0/recipe.yaml:
apiVersion: aggrega.ai/v1beta1kind: Recipemetadata: name: api version: 1.0.0 description: Runs the API as a Docker Compose service.spec: capability: compose implements: example/compute/api:1.0.0 workload: | apiVersion: aggrega.ai/v1beta1 kind: Workload containers: main: image: "registry.example.com/shop/api:1.0.0" ports: http: {{ .infra.port }}catalog/recipe/compose/db-console/1.0.0/recipe.yaml:
apiVersion: aggrega.ai/v1beta1kind: Recipemetadata: name: db-console version: 1.0.0 description: Runs the database console as a Docker Compose service.spec: capability: compose implements: example/devtool/db-console:1.0.0 workload: | apiVersion: aggrega.ai/v1beta1 kind: Workload containers: main: image: "adminer:4" ports: http: {{ .infra.port }}aggregate.yaml:
apiVersion: aggrega.ai/v1beta1kind: Aggregatemetadata: name: shop version: "1.0.0" description: The shop's API.spec: components: api: type: example/compute/apimanifest.yaml:
apiVersion: aggrega.ai/v1beta1kind: Manifestmetadata: name: shop-manifest version: "1.0.0" description: Binds each component type to its Docker Compose recipe.spec: mappings: components: type: example/compute/api:1.0.0: api:1.0.0 example/devtool/db-console:1.0.0: db-console:1.0.0release.yaml:
apiVersion: aggrega.ai/v1beta1kind: Releasemetadata: name: shop-staging environment: staging version: "1.0.0"spec: aggregate: shop manifest: shop-manifest components: api: {}8. 挂接它,然后构建
运维人员在工作区配置中挂接治理插件,指明角色和挂接的设置。.aggrega-config.yaml:
workspace: catalog_dirs: - catalogauto_pull: trueplugins: governance: - uri: governance/category-guard:0.1.0 role: ir-verdict with: settings: forbidden_categories: - devtooluri 按插件类型、名称和版本指明实体。角色是 ir-verdict,因此宿主会在构建图构建完成之后、渲染任何内容之前,用构建图调用 verdict_ir。auto_pull 让构建自行解析 Release,因此第一次构建不需要单独的步骤。
cd ../shopaggrega build --release release.yaml warning: plugin "governance/category-guard" resolved from local with no recorded digest to check it against, so it runs unverified; it is read from beside its Plugin entity in a catalog directory on every build, and a pull records its digest only for a plugin attached at a transform role; otherwise publish the plugin and reference the published entity to have its digest recordedPull complete: release.lock (entities=7, source_artifacts=0, external_inputs=0)[… omitted: a line reporting total build time, which differs on every run]Build completed: 1 file written to <workspace>/dist该商店不包含 devtool 组件,因此规则允许构建,Compose 输出落在 dist/compose/docker-compose.yaml 中。
该警告是预期的,并且只要插件是本地的就会一直存在。 它表示客体运行时没有可供核对的已记录内容摘要——这正是一个一分钟前构建、每次构建都从其实体旁边读取的客体的真实情况。挂接在裁决角色上的插件不塑造任何输出,因此 pull 不会从目录文件夹为它记录摘要;发布插件并引用已发布的实体,才会记录摘要。
9. 植入一个违规
将管理控制台添加到 Aggregate 中,并将其放入 Release:
spec: components: api: type: example/compute/api console: type: example/devtool/db-console components: api: {} console: {}aggrega build --release release.yaml[… omitted: the unverified-plugin warning, and the pull's lines saying the Release could not be rendered to discover its external inputs, which carry the refusal below][POLICY_ERROR E0005] policy plugin "category-guard" rejected the build: component "console" is a devtool component, and this workspace ships none caused by: policy violation构建在渲染任何内容之前停止,并且不写入 dist/。消息是规则自己的句子,以插件名称开头,因此阅读它的作者知道要移除哪个组件、是哪条策略要求的。插件没有移除控制台、没有重命名它,也没有在不含它的情况下渲染构建:裁决角色只接受或拒绝,宿主从不将其回答作为变更应用。
接下来可以修改什么
- 更多规则,或一种策略语言。 用 Go 编写的规则会被编译进客体。若要改为从文件加载规则,请在
Evaluate中读取programs——即挂接的sources,每个都带有其基本名称和文本——并把它们交给一个引擎。ABI 是 Aggrega 自己的描述了一个封装外部策略引擎的客体。 - 其他角色。 同一个
Evaluate服务每个角色;回答annotations或labels会使插件在转换角色上塑造构建。决策的形状在骨架的 README 中,每个角色可以更改什么见四个角色。 - 更少的导出。 只服务
ir-verdict的插件会删除其他角色文件及其在descriptor()中的条目。此后,将某个角色指向客体未声明的导出的挂接会在客体运行之前被按名称拒绝。 - 类型化设置。 客体可以在
describe()中为其设置声明一个 JSON Schema,宿主随后会在客体运行之前根据它验证挂接的设置;参见类型化设置。 - 发布,它把目录文件夹的安排变成一个由 Release 解析并验证、按摘要固定的产物。插件开发者指南涵盖了这一生命周期。
相关参考
- 治理插槽——四个角色、它们的 payload、裁决严重级别,以及运维人员如何挂接插件。
- Plugin 契约 —— 每个 socket 的输入和输出结构,以及每个结构所携带的编码。
- Wasm 插件开发者指南——
Plugin实体、能力面以及发布生命周期。 - 编写提供程序——针对提供程序客体的同类演练。
- 阅读这些页面上的输出 — 上文 输出块所遵循的约定。