8000 GitHub - dogwood-policy/dogwood-wasm · GitHub
[go: up one dir, main page]

Skip to content

About

No description, website, or topics provided.

Resources

Code of conduct

Contributing

Security policy

Stars

15 stars

Watchers

0 watching

Forks

Dogwood — TypeScript / WebAssembly Bindings

Typed WASM bindings for Dogwood, the Cedar-derived governance language for AI agents (temporal conditions + information providers).

Two shapes are exposed:

  • Batch operations (validate, lower, replay, explain, schema checks) — source strings in, typed report objects out. For policy authoring, CI, and tooling.
  • Live authorizer (DogwoodAuthorizer) — lower once, feed events as they happen, get a decision per event with temporal history accumulating across calls. For agent gateways, MCP proxies, and anything deciding in real time.

The bindings are a thin wasm-bindgen shell over dogwood-ops, the operations the dogwood CLI and the other language bindings share: every report, error, the live authorizer's event contract, the input limits and the fail-closed rules come from there. This crate converts JS values, declares the TypeScript types, and turns errors into thrown DogwoodErrors — see Taking a new Dogwood release.

Layout

dogwood-wasm/
├── src/
│   ├── lib.rs          # wasm-bindgen surface (batch ops + error projection)
│   ├── live.rs         # DogwoodAuthorizer class over dogwood_ops::LiveAuthorizer
│   ├── bounds.rs       # input limits, walked over raw JS values
│   └── types.rs        # TypeScript declarations of the dogwood-ops report types
├── scripts/
│   ├── prepare-release.sh # pre-publish checks on pkg/ (run by the release workflow)
│   └── third-party-notices.sh # THIRD-PARTY-NOTICES for the npm package (cargo-about)
├── pkg/                # generated by `npm run build` (git-ignored)
├── test.cjs            # batch-operation smoke tests
├── test-live.cjs       # live-authorizer semantics (parity with replay)
├── test-coverage.cjs   # full surface coverage (every function, field, error path)
├── test-bounds.cjs     # oversized / deep / cyclic input never traps the module
├── example.ts          # strict-mode type-check of the generated .d.ts
├── package.json        # build / test / typecheck scripts
├── RELEASING.md        # npm release procedure
└── .github/workflows/  # ci (build, tests, audits), release

Build

Requires Rust ≥ 1.85 (edition 2024), the wasm target, wasm-pack, and Node ≥ 16.

rustup target add wasm32-unknown-unknown
cargo install wasm-pack

git clone https://github.com/dogwood-policy/dogwood-wasm.git
cd dogwood-wasm
npm run build                   # → pkg/ (Node/CommonJS target, uses wasm-pack)
npm install && npm run verify   # runtime tests + tsc --strict typecheck

Other targets: npm run build:bundler (Vite/webpack, ESM) and npm run build:web (no bundler).

npm run build:dev is an unoptimized debug build with the dev feature, which logs Rust panic messages to console.error. Release builds leave the panic hook out, because a panic message can contain policy or event data.

Batch Operations

All take source strings and return typed report objects. Fatal errors are thrown as DogwoodError; non-fatal findings come back in the report.

Function Purpose Returns
checkParse(src, …) parse + macro-expand CheckParseReport
validate(src, actionSchema, …) lower + type-check ValidateReport
lower(src, actionSchema, …) emit Cedar artifacts LowerArtifacts
replay(src, actionSchema, log, …) lower + replay a .log trace ReplayReport
explain(src, actionSchema?, …) informalize rules into semi-English ExplainReport
checkActionSchema(src) validate a .cedarschema SchemaCheckReport
checkEventSchema(src) validate a .dwschema SchemaCheckReport
checkProviders(json) validate a providers.json SchemaCheckReport
mcpToCedarSchema(json) MCP tools/list → Cedar action schema string

The trailing eventSchema? / providers? / macros? arguments are optional service-schema overrides. Omit for defaults.

const dw = require("./pkg/dogwood_wasm.js");

const actionSchema = `namespace Drupe {
  entity User; entity Gateway;
  action "Read" appliesTo {
    principal: [User], resource: [Gateway],
    context: { input: { document: String, user: String } }
  };
}`;

const policy = `permit(principal, action == Drupe::Action::"Read", resource)
when { context.input.document like "*report*" };`;

const report = dw.validate(policy, actionSchema);
console.log(report.passed); // true

Live Authorizer

const auth = new dw.DogwoodAuthorizer(policy, actionSchema);

const decision = auth.isAuthorized({
  action: "Drupe::Action::Read",
  kind: "request",
  timestamp: Math.floor(Date.now() / 1000),
  principal: { type: "Drupe::User", id: "alice" },
  resource:  { type: "Drupe::Gateway", id: "gw1" },
  logged:  { input: { document: "quarterly report", user: "alice" } },
  context: { input: { document: "quarterly report", user: "alice" } },
  entities: [{ type: "Drupe::User", id: "alice", attrs: { dept: "eng" } }],
});

if (!decision.allowed) throw new Error("denied");

History-only events (anything other than kind: "request" by default) return undefined — they update temporal state but yield no verdict.

Key Semantics

  • Timestamps are seconds, not milliseconds. A within 1h window is 3600. Passing Date.now() raw inflates every window by 1000×.
  • logged and context are distinct. logged is the durable temporal record; context is the ephemeral Cedar request bag. A field both need (typically input) must appear in both.
  • Entity references are structured ({ type, id }), never string literals. The id is escaped exactly once — no double-escaping footgun.
  • Any evaluation error is a deny. Cedar skips a rule whose condition errors (for example, a context argument of the wrong type, or a missing one) and decides from the remaining rules, so an errored forbid could otherwise let a permit through. The authorizer returns allowed: false whenever errors is non-empty, and replay applies the same rule to every verdict, so a deny with errors is a fail-closed evaluation failure, not "policy said no."

Input Validation

The authorizer rejects (without observing into history):

Rejected Why
Unknown action The engine would deny it with a terse cause; the rejection lists the declared actions and suggests the qualified id for a bare one
Unknown kind The engine would not decide it; the rejection lists the declared kinds and which are decision points
Missing or backwards timestamp Would silently produce wrong temporal answers
Number with no Cedar rendering (an integer outside the 64-bit range, a float only expressible in exponent form) Would become invalid decimal text and fail closed with no clear cause; pass exact decimals as { __decimal: "…" }
Nonconforming history event (e.g. a response with a wrong-typed or missing required field) The authorizer does not record it, so it would return undefined like a recorded event while later temporal checks never see it
Oversized event (see below) Would overflow the wasm stack and leave the module unusable

Input limits

Event data usually comes from a model's tool arguments, so its size and shape are untrusted. Each limit is checked before any recursive code sees the event, and an event over a limit throws a DogwoodError rather than being decided:

Limit Value
Nesting depth of a value, counting each context / logged group (context.input) or entity attribute as level 0 128 levels, the same limit replay applies to .log values
Values in one event (scalars, arrays and objects at any depth) 100,000
Total length of all strings in one event, object keys included 16 Mi characters (string.length units)

mcpToCedarSchema rejects a manifest over 4 MiB or nested deeper than 128 levels.

A thrown isAuthorized call means no decision. The host must treat it as a deny.

If a call traps

A WebAssembly.RuntimeError (for example out-of-memory) is not a DogwoodError. It means the wasm module itself is in an undefined state, not just one instance: every later call into the module, on any DogwoodAuthorizer, may fail or trap. Deny the current request, stop using the module, and restart the process or worker that loaded it. The input limits above exist so that event data cannot cause a trap.

Introspection getters (actions, eventKinds, decisionKinds, lastTimestamp) let a host verify its wiring at startup.

Lifecycle

DogwoodAuthorizer owns wasm-heap memory that GC does not reclaim. Free it explicitly:

const auth = new DogwoodAuthorizer(policy, actionSchema);
try { /* … */ } finally { auth.free(); }

// or with explicit resource management (TS ≥ 5.2):
using auth = new DogwoodAuthorizer(policy, actionSchema);

reset() drops accumulated history and re-lowers the same sources. decisionCount tracks decisions returned.

Temporal history is never pruned: every event is kept until reset() or free() (on the order of 1.6 KB per event). Use one instance per session or per principal, and reset() or replace it when the session ends, so history does not grow without limit.

Errors

Fatal failures throw a DogwoodError with structured .diagnostic:

import { validate, type DogwoodError } from "./pkg/dogwood_wasm.js";

try {
  validate("permit(", actionSchema);
} catch (e) {
  const err = e as DogwoodError;
  // err.diagnostic: { message, severity, code?, labels[], help?, related? }
}

Byte offsets in labels index the source string you passed in.

Information Providers

Rhai providers work — the interpreter compiles to wasm. But the script must be inline (implementation.script). A scriptFile reference is rejected up front with an actionable error, because wasm32-unknown-unknown has no filesystem and an unresolvable reference would silently fail closed at authorize time.

Testing

npm run verify runs 109 checks across four suites plus tsc --strict.

Suite Coverage
test.cjs Smoke: does each batch operation work?
test-live.cjs Replay-parity: does the live authorizer produce identical verdicts to replay on the same scenario?
test-coverage.cjs Every exported function, field, optional argument, error path, and value-conversion branch
test-bounds.cjs Oversized, deeply nested and cyclic input is rejected without trapping the module

Taking a new Dogwood release

dogwood-ops (and through it dogwood-language) is the only Dogwood dependency, so there is nothing to keep in sync by hand:

  1. Bump dogwood-ops in Cargo.toml (cargo update -p dogwood-ops).
  2. If a report type gained or changed a field, update its declaration in src/types.rs (the TS shapes are declared there, matching the serde output).
  3. Expose any new operation in src/lib.rs, then npm run build && npm run verify.

Limitations

  • Dogwood is a reference interpreter, not for production; these bindings inherit that.
  • The net feature (HTTP providers) is off — cannot work in wasm.
  • Temporal history is never pruned. Growth is ~1.6 KB/event with no plateau. Long-lived instances must reset() periodically or cap their lifetime.
  • The live authorizer's input checks do not apply to replay (which uses the frontend's internal parser): backwards timestamps in a .log trace pass through unremarked. (A bare action id now denies with a stated cause.)
  • Module size is ~8.7 MB (~2.6 MB gzipped). Cedar, Rhai, and the parser dominate.

Contributing, security, and license

See CONTRIBUTING.md and CODE_OF_CONDUCT.md. To report a security issue, follow SECURITY.md rather than opening a public issue. Releases are published to npm by CI only; see RELEASING.md. Licensed under Apache-2.0; see NOTICE.

About

No description, website, or topics provided.

Resources

Code of conduct

Contributing

Security policy

Stars

15 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages

0