撰寫你自己的治理外掛程式
本頁帶你從外掛程式開發套件的配接器鷹架開始,一路走到一個會拒絕的建置。你複製鷹架、把一條規則寫進去、建置 .wasm、在鷹架隨附的酬載檔案上以手動方式呼叫它的每個匯出、把它宣告為你工作區自己目錄中的 Plugin 實體、把它附加到某個角色,並看著它停止一個違反該規則的建置。
它是治理插槽的實作配套說明——後者記載四個角色、各自攜帶的酬載,以及主機據以行動的判定——也是外掛程式開發者指南的配套,後者記載 Plugin 實體及其生命週期。撰寫提供者是針對提供者客體的同類逐步說明。
關於本頁的區塊。 每個顯示輸出的區塊,都是從下列步驟的真實執行中依其出現順序複製而來,並遵循輸出慣例:區塊要麼是完整的,要麼是標示略去哪些行的節錄。兩個預留位置代表每台機器上都不同的絕對路徑:<guest> 是你的鷹架副本所在的目錄,<workspace> 則是附加外掛程式的工作區所在的目錄。
你需要什麼
- Go 工具鏈,可編譯為 WebAssembly,無需額外工具。
- 外掛程式開發套件的簽出(其中帶有鷹架),以及該套件所依據的 ABI 套件的簽出:你副本的
go.mod指向這兩者。 aggrega二進位檔。
該套件也為 Rust 隨附相同的鷹架,位於 rust/examples/governance-adapter-skeleton,並為 TypeScript 隨附,位於 typescript/examples/governance-adapter-skeleton。每一個都帶有同樣的四個酬載檔案,而未修改的副本對它們的回應方式相同;本頁的每個 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 時,還會檢查客體是否回報自己是治理外掛程式——以你提供的酬載呼叫它,並印出回應。鷹架為每個角色隨附一個酬載檔案,每個都是其匯出的小型有效輸入。酬載以 JSON 撰寫;每個治理角色的傳輸都帶有二進位編碼,所以命令會在呼叫匯出之前把酬載轉換成該編碼,並把匯出的回應以 JSON 印出。
aggrega plugin run-local --plugin dist/governance-adapter-skeleton-go.wasm \ --type governance --export transform_annotations --with @annotation-payload.json{ "injections": []}run-local 從你給它的路徑讀取它的客體和酬載,而且不需要工作區,所以可以從任何目錄執行。
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 判定——一則記錄觀察結果並讓建置結果維持不變的註解。這則註解就是鷹架連接正常的證明。每個酬載檔案都帶有建置交出附加項目時的兩個輸入:sources 之下的一個原則檔案 rules.policy,以及一個 settings 物件。這則註解表示兩者都到達了接縫——鷹架其餘部分以角色所收到的任何內容呼叫的那個函式。
以下是下方規則將讀取的酬載 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。每個欄位都在該角色的參考頁面原則插槽結構描述中說明,而圖本身則在建置圖結構描述;其他三個檔案遵循註記轉換結構描述、變異器結構描述,而對於 verdict_render,則遵循原則插槽結構描述的 RenderPolicyInput。
3. 寫一條規則
規則位於 evaluator.go,也就是鷹架的接縫。每個角色都會解碼它的酬載、把它寫成 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 保持不變,因為角色檔案用它來建立自己的程式清單。其餘部分就是規則,其中有四件事值得仔細閱讀。
- 它以傳輸所給的名稱讀取酬載。 節點位於
graph.spec.nodes,以節點識別碼為鍵,每個節點都有它的labels——與各角色的酬載揭露哪些內容給 Rego 原則的input.graph.spec.nodes是同一個路徑。為這個角色寫的規則在其他角色什麼也讀不到:render-verdict酬載不帶有圖,所以在那裡迴圈找不到任何節點。 - 它禁止什麼是由操作員決定,而不是外掛程式。 類別來自附加項目的
settings,所以同一個.wasm既能服務禁止devtool的工作區,也能服務什麼都不禁止的工作區。 - 它先排序再回答。 建置的輸出在相同輸入的多次執行之間是逐位元組相同的,而以 Go 對應表的順序回答的客體,會從內部破壞這一點。
- 它明確地失敗。 無法讀取的設定或酬載會傳回錯誤,而不是空清單,而角色會把該錯誤轉成失敗的呼叫。空清單表示原則沒有發現任何要說的;失敗的呼叫表示它沒有執行,而只有客體這麼做,建置才能分辨這兩者。
規則從不讀取 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": []}預留位置註解已從兩個判定角色中消失,而且兩者都沒有傳回判定:隨附酬載的 settings 沒有禁止任何類別,所以規則放行它。空的 results 清單就是判定角色表示建置可以繼續的方式。
若要看到規則觸發,請給它禁止酬載所帶內容的設定。把 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. 酬載不符時
命令會把酬載所帶的每個欄位轉換成其形狀所宣告的型別,並在客體執行之前拒絕無法轉換的欄位。在名為 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 [命令以非零狀態結束,而且客體從未被呼叫。
轉換會檢查酬載所帶每個欄位的型別;它不會檢查酬載是否帶有形狀所要求的每個欄位。缺少其中一個的酬載仍會被轉換並交給客體,而規則讀取該欄位的客體在那裡什麼也找不到。所以請對照其結構描述參考頁面來檢查你手寫的酬載:命令的沉默並不代表酬載是完整的。
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(外掛程式的 wasm 檔案不在這台機器上)所述。
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 解析並驗證。外掛程式開發者指南涵蓋該生命週期。
相關參考
- 治理插槽 — 四個角色、它們的酬載、判定嚴重性,以及操作員如何附加外掛程式。
- Plugin 契約 — 每個插槽的輸入與輸出形狀,以及各自採用的編碼。
- Wasm 外掛程式開發者指南 —
Plugin實體、能力介面與發布生命週期。 - 撰寫提供者 — 針對提供者客體的同一段逐步說明。
- 閱讀本頁的輸出——上述輸出區塊所遵循的慣例。