Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
@@ -1,4 +1,4 @@
|
||||
# @toolctrl/plugin-runtime
|
||||
# @hivegrid/plugin-runtime
|
||||
|
||||
Phase 06 Task #21 foundation — host-side runtime for WebAssembly plugins.
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "@toolctrl/plugin-runtime",
|
||||
"name": "@hivegrid/plugin-runtime",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -16,8 +16,8 @@
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@toolctrl/logger": "workspace:*",
|
||||
"@toolctrl/shared-store": "workspace:*",
|
||||
"@hivegrid/logger": "workspace:*",
|
||||
"@hivegrid/shared-store": "workspace:*",
|
||||
"semver": "^7.7.3",
|
||||
"zod": "^3.23.8"
|
||||
},
|
||||
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import {
|
||||
canonicalisePluginCapabilityUseRow,
|
||||
stampPluginCapabilityUseChain,
|
||||
verifyPluginCapabilityUseChain,
|
||||
type PluginCapabilityUseChainRow,
|
||||
} from "./audit-chain.js";
|
||||
|
||||
/**
|
||||
* Coverage for audit-chain branches not hit by audit-chain.test.ts:
|
||||
* - prev_mismatch where the broken row's prevHash is null (formatted as
|
||||
* "(null)" in the report),
|
||||
* - the non-finite numeric field canonicalisation (Infinity/NaN collapse
|
||||
* to the null marker).
|
||||
*/
|
||||
|
||||
function row(overrides: Partial<PluginCapabilityUseChainRow> = {}): PluginCapabilityUseChainRow {
|
||||
return {
|
||||
id: "row-1",
|
||||
pluginInvocationId: "inv-1",
|
||||
tenantId: "t-1",
|
||||
pluginId: "com.acme.demo",
|
||||
capability: "log",
|
||||
payloadHash: null,
|
||||
outcome: "success",
|
||||
errorCode: null,
|
||||
durationMs: 12,
|
||||
timestamp: "2026-05-19T18:00:00.000Z",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("verifyPluginCapabilityUseChain — null prevHash break", () => {
|
||||
test("reports actual '(null)' when a later row drops its prevHash", () => {
|
||||
const { stamped } = stampPluginCapabilityUseChain({
|
||||
seedPrevHash: null,
|
||||
rows: [row({ id: "r1" }), row({ id: "r2" })],
|
||||
});
|
||||
// r2 keeps its (valid) rowHash but its prevHash is wiped to null — a
|
||||
// mid-chain tamper that severs the link to r1.
|
||||
const tampered = [stamped[0]!, { ...stamped[1]!, prevHash: null }];
|
||||
const result = verifyPluginCapabilityUseChain(tampered);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.reason).toBe("prev_mismatch");
|
||||
expect(result.brokenRowId).toBe("r2");
|
||||
expect(result.actual).toBe("(null)");
|
||||
expect(result.expected).toBe(stamped[0]!.rowHash);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("canonicalisePluginCapabilityUseRow — non-finite numbers", () => {
|
||||
test("collapses a non-finite durationMs to the same canonical form as null", () => {
|
||||
const withInfinity = canonicalisePluginCapabilityUseRow(row({ durationMs: Number.POSITIVE_INFINITY }));
|
||||
const withNull = canonicalisePluginCapabilityUseRow(row({ durationMs: null }));
|
||||
const withNaN = canonicalisePluginCapabilityUseRow(row({ durationMs: Number.NaN }));
|
||||
expect(withInfinity).toBe(withNull);
|
||||
expect(withNaN).toBe(withNull);
|
||||
// A finite value must NOT collapse to the same form.
|
||||
expect(canonicalisePluginCapabilityUseRow(row({ durationMs: 0 }))).not.toBe(withNull);
|
||||
});
|
||||
});
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { createPluginCapabilityUseRecorder } from "./audit.js";
|
||||
|
||||
/**
|
||||
* Coverage for the recorder's error-logging branch when the sink rejects
|
||||
* with a non-Error value — the logger receives the raw thrown value
|
||||
* rather than a {name, message} projection.
|
||||
*/
|
||||
|
||||
describe("createPluginCapabilityUseRecorder — non-Error sink failure", () => {
|
||||
test("logs the raw thrown value when the sink rejects with a non-Error", async () => {
|
||||
const errors: Record<string, unknown>[] = [];
|
||||
const recorder = createPluginCapabilityUseRecorder({
|
||||
tenantId: "t1",
|
||||
pluginId: "p1",
|
||||
sink: {
|
||||
async emit() {
|
||||
// eslint-disable-next-line @typescript-eslint/only-throw-error
|
||||
throw { code: "OUTBOX_DOWN", transient: true };
|
||||
},
|
||||
},
|
||||
logger: {
|
||||
error: (record) => {
|
||||
errors.push(record);
|
||||
},
|
||||
},
|
||||
});
|
||||
recorder.record({ capability: "log", outcome: "success" });
|
||||
|
||||
// Soft-fail (default): flush resolves, the error is only logged.
|
||||
await expect(recorder.flush()).resolves.toBeUndefined();
|
||||
expect(errors).toHaveLength(1);
|
||||
expect(errors[0]?.err).toEqual({ code: "OUTBOX_DOWN", transient: true });
|
||||
expect(errors[0]?.entryCount).toBe(1);
|
||||
});
|
||||
});
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { CapabilityDeniedError, createCapabilityGateway } from "./capability-gateway.js";
|
||||
import type { PluginManifest } from "./manifest.js";
|
||||
|
||||
/**
|
||||
* Coverage for capability-gateway branches not hit by capability-gateway.test.ts:
|
||||
* - an available host binding (log/audit) declared + granted but with no
|
||||
* host-fn wired (the typeof-fn guard, async + sync),
|
||||
* - invokeSync grant-gated paths (not_granted_for_tenant, grant happy path),
|
||||
* - payload-descriptor shapes for object / array / null arguments,
|
||||
* - non-Error throws surfacing errorCode "unknown".
|
||||
*/
|
||||
|
||||
function fixture(capabilities: PluginManifest["capabilities"] = []): PluginManifest {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
id: "de.hivegrid.test",
|
||||
version: "1.0.0",
|
||||
name: "Test",
|
||||
entry: "plugin.wasm",
|
||||
wasmSha256: "0".repeat(64),
|
||||
signature: "0".repeat(128),
|
||||
signedBy: "0".repeat(64),
|
||||
allowedHosts: [],
|
||||
capabilities,
|
||||
hooks: [{ name: "x", export: "x" }],
|
||||
};
|
||||
}
|
||||
|
||||
describe("createCapabilityGateway — additional branches", () => {
|
||||
test("async invoke denies an available, granted capability with no host-fn wired", async () => {
|
||||
const calls: Array<{ capability: string; outcome: string; errorCode?: string }> = [];
|
||||
const gateway = createCapabilityGateway({
|
||||
// "log" IS host-binding-available, so the deny falls through to the
|
||||
// typeof-fn guard rather than the binding-availability guard.
|
||||
manifest: fixture([{ name: "log" }]),
|
||||
approvedGrants: [{ capabilityName: "log", scopeJson: null }],
|
||||
hostFns: {},
|
||||
onCall: (info) => calls.push(info),
|
||||
});
|
||||
|
||||
await expect(gateway.invoke("log")).rejects.toMatchObject({
|
||||
reason: "no_host_implementation",
|
||||
});
|
||||
expect(calls).toEqual([
|
||||
expect.objectContaining({ capability: "log", outcome: "denied", errorCode: "no_host_implementation" }),
|
||||
]);
|
||||
});
|
||||
|
||||
test("invokeSync denies an available, granted capability with no host-fn wired", () => {
|
||||
const gateway = createCapabilityGateway({
|
||||
manifest: fixture([{ name: "audit" }]),
|
||||
approvedGrants: [{ capabilityName: "audit", scopeJson: null }],
|
||||
hostFns: {},
|
||||
});
|
||||
|
||||
expect(() => gateway.invokeSync("audit")).toThrow(CapabilityDeniedError);
|
||||
expect(() => gateway.invokeSync("audit")).toThrow(/no_host_implementation/u);
|
||||
});
|
||||
|
||||
test("invokeSync denies a declared capability without a tenant grant", () => {
|
||||
const calls: Array<{ capability: string; outcome: string; errorCode?: string }> = [];
|
||||
const gateway = createCapabilityGateway({
|
||||
manifest: fixture([{ name: "log" }, { name: "audit" }]),
|
||||
approvedGrants: [{ capabilityName: "log", scopeJson: null }],
|
||||
hostFns: { log: () => "ok", audit: () => "should not run" },
|
||||
onCall: (info) => calls.push(info),
|
||||
});
|
||||
|
||||
expect(() => gateway.invokeSync("audit")).toThrow(CapabilityDeniedError);
|
||||
expect(calls).toEqual([
|
||||
expect.objectContaining({ capability: "audit", outcome: "denied", errorCode: "not_granted_for_tenant" }),
|
||||
]);
|
||||
});
|
||||
|
||||
test("invokeSync runs the scope check for a granted, unscoped capability and records the call", () => {
|
||||
const calls: Array<Record<string, unknown>> = [];
|
||||
const gateway = createCapabilityGateway({
|
||||
manifest: fixture([{ name: "log" }]),
|
||||
approvedGrants: [{ capabilityName: "log", scopeJson: null }],
|
||||
hostFns: { log: (payload: unknown) => ({ echoed: payload }) },
|
||||
onCall: (info) => calls.push(info),
|
||||
});
|
||||
|
||||
// Object argument exercises the object-shaped payload descriptor.
|
||||
const result = gateway.invokeSync<{ echoed: unknown }>("log", { action: "ping", retries: 2 });
|
||||
expect(result).toEqual({ echoed: { action: "ping", retries: 2 } });
|
||||
expect(gateway.fuelCharged()).toBe(100);
|
||||
expect(calls[0]?.outcome).toBe("success");
|
||||
expect(calls[0]?.payloadHash).toMatch(/^[a-f0-9]{64}$/u);
|
||||
// Raw argument values must never leak into the audit record.
|
||||
expect(JSON.stringify(calls)).not.toContain("ping");
|
||||
});
|
||||
|
||||
test("payload descriptor distinguishes object, array and null argument shapes", async () => {
|
||||
const calls: Array<{ payloadHash?: string }> = [];
|
||||
const gateway = createCapabilityGateway({
|
||||
manifest: fixture([{ name: "log" }]),
|
||||
hostFns: { log: () => "ok" },
|
||||
onCall: (info) => calls.push(info),
|
||||
});
|
||||
|
||||
await gateway.invoke("log", { a: 1, b: 2 });
|
||||
await gateway.invoke("log", { b: 2, a: 1 }); // key order must not matter
|
||||
await gateway.invoke("log", [1, 2, 3]);
|
||||
await gateway.invoke("log", null);
|
||||
|
||||
expect(calls).toHaveLength(4);
|
||||
// Object key ordering is normalised → identical hash.
|
||||
expect(calls[1]?.payloadHash).toBe(calls[0]?.payloadHash);
|
||||
// Object vs array vs null produce distinct descriptors.
|
||||
expect(calls[2]?.payloadHash).not.toBe(calls[0]?.payloadHash);
|
||||
expect(calls[3]?.payloadHash).not.toBe(calls[0]?.payloadHash);
|
||||
for (const call of calls) {
|
||||
expect(call.payloadHash).toMatch(/^[a-f0-9]{64}$/u);
|
||||
}
|
||||
});
|
||||
|
||||
test("async host-fn throwing a non-Error reports errorCode 'unknown'", async () => {
|
||||
const calls: Array<{ outcome: string; errorCode?: string }> = [];
|
||||
const gateway = createCapabilityGateway({
|
||||
manifest: fixture([{ name: "log" }]),
|
||||
hostFns: {
|
||||
log: () => {
|
||||
// eslint-disable-next-line @typescript-eslint/only-throw-error
|
||||
throw "raw string failure";
|
||||
},
|
||||
},
|
||||
onCall: (info) => calls.push(info),
|
||||
});
|
||||
|
||||
await expect(gateway.invoke("log")).rejects.toBe("raw string failure");
|
||||
expect(calls).toEqual([expect.objectContaining({ outcome: "error", errorCode: "unknown" })]);
|
||||
});
|
||||
|
||||
test("sync host-fn throwing a non-Error reports errorCode 'unknown'", () => {
|
||||
const calls: Array<{ outcome: string; errorCode?: string }> = [];
|
||||
const gateway = createCapabilityGateway({
|
||||
manifest: fixture([{ name: "log" }]),
|
||||
hostFns: {
|
||||
log: () => {
|
||||
// eslint-disable-next-line @typescript-eslint/only-throw-error
|
||||
throw 42;
|
||||
},
|
||||
},
|
||||
onCall: (info) => calls.push(info),
|
||||
});
|
||||
|
||||
let thrown: unknown;
|
||||
try {
|
||||
gateway.invokeSync("log");
|
||||
} catch (err) {
|
||||
thrown = err;
|
||||
}
|
||||
expect(thrown).toBe(42);
|
||||
expect(calls).toEqual([expect.objectContaining({ outcome: "error", errorCode: "unknown" })]);
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -15,7 +15,7 @@ const DEFERRED_HOST_BINDINGS = [
|
||||
function fixture(capabilities: PluginManifest["capabilities"] = []): PluginManifest {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
id: "de.toolctrl.test",
|
||||
id: "de.hivegrid.test",
|
||||
version: "1.0.0",
|
||||
name: "Test",
|
||||
entry: "plugin.wasm",
|
||||
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { isCapabilityGrantScopeSatisfied } from "./capability-grants.js";
|
||||
|
||||
/**
|
||||
* Coverage for capability-grants branches where the declared scope sets
|
||||
* one dimension but the granted scope additionally claims another the
|
||||
* manifest never declared — each extra dimension must reject the grant.
|
||||
* Also covers the "declared scope present but grant is null" rejection.
|
||||
*/
|
||||
|
||||
describe("isCapabilityGrantScopeSatisfied — broadened dimensions", () => {
|
||||
test("rejects a grant that adds allowedHosts the manifest never declared", () => {
|
||||
expect(
|
||||
isCapabilityGrantScopeSatisfied({
|
||||
declaredScope: { keyPattern: "payment_*" },
|
||||
grantedScopeJson: { keyPattern: "payment_*", allowedHosts: ["api.example.com"] },
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("rejects a grant that adds a keyPattern the manifest never declared", () => {
|
||||
expect(
|
||||
isCapabilityGrantScopeSatisfied({
|
||||
declaredScope: { allowedHosts: ["api.example.com"] },
|
||||
grantedScopeJson: { allowedHosts: ["api.example.com"], keyPattern: "payment_*" },
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("rejects a grant that adds a tablePrefix the manifest never declared", () => {
|
||||
expect(
|
||||
isCapabilityGrantScopeSatisfied({
|
||||
declaredScope: { allowedHosts: ["api.example.com"] },
|
||||
grantedScopeJson: { allowedHosts: ["api.example.com"], tablePrefix: "plugin_" },
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("rejects a null grant when the manifest declares a non-empty scope", () => {
|
||||
expect(
|
||||
isCapabilityGrantScopeSatisfied({
|
||||
declaredScope: { keyPattern: "payment_*" },
|
||||
grantedScopeJson: null,
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("accepts an exact-match multi-dimension grant", () => {
|
||||
expect(
|
||||
isCapabilityGrantScopeSatisfied({
|
||||
declaredScope: { allowedHosts: ["api.example.com"], keyPattern: "payment_*", tablePrefix: "plugin_" },
|
||||
grantedScopeJson: { allowedHosts: ["api.example.com"], keyPattern: "payment_*", tablePrefix: "plugin_" },
|
||||
})
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
+3
-3
@@ -8,7 +8,7 @@ import type { PluginManifest } from "./manifest.js";
|
||||
function manifest(capabilities: PluginManifest["capabilities"]): PluginManifest {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
id: "de.toolctrl.test",
|
||||
id: "de.hivegrid.test",
|
||||
version: "1.0.0",
|
||||
name: "Test",
|
||||
entry: "plugin.wasm",
|
||||
@@ -31,8 +31,8 @@ describe("capability grants", () => {
|
||||
).toBe(true);
|
||||
expect(
|
||||
isCapabilityGrantScopeSatisfied({
|
||||
declaredScope: { keyPattern: "stripe_*", tablePrefix: "plugin_" },
|
||||
grantedScopeJson: { keyPattern: "stripe_*", tablePrefix: "plugin_" },
|
||||
declaredScope: { keyPattern: "payment_*", tablePrefix: "plugin_" },
|
||||
grantedScopeJson: { keyPattern: "payment_*", tablePrefix: "plugin_" },
|
||||
})
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { isCapabilityCallWithinScope } from "./capability-scope.js";
|
||||
|
||||
/**
|
||||
* Coverage for the "structured request is present but the discriminating
|
||||
* field is missing / wrong-typed" branches of each scoped capability —
|
||||
* these short-circuit to a deny before the scope comparison runs.
|
||||
*/
|
||||
|
||||
describe("isCapabilityCallWithinScope — malformed request fields", () => {
|
||||
test("denies http.outbound when the request carries no string url", () => {
|
||||
expect(
|
||||
isCapabilityCallWithinScope({
|
||||
capability: "http.outbound",
|
||||
callArgs: [{ method: "GET" }],
|
||||
scope: { allowedHosts: ["api.example.com"] },
|
||||
})
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
isCapabilityCallWithinScope({
|
||||
capability: "http.outbound",
|
||||
callArgs: [{ url: 1234 }],
|
||||
scope: { allowedHosts: ["api.example.com"] },
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("denies secret.read when the request key is not a string", () => {
|
||||
expect(
|
||||
isCapabilityCallWithinScope({
|
||||
capability: "secret.read",
|
||||
callArgs: [{ key: 42 }],
|
||||
scope: { keyPattern: "payment_*" },
|
||||
})
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
isCapabilityCallWithinScope({
|
||||
capability: "secret.read",
|
||||
callArgs: [{ notKey: "payment_x" }],
|
||||
scope: { keyPattern: "payment_*" },
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("denies db.read / db.write when the request table is not a string", () => {
|
||||
expect(
|
||||
isCapabilityCallWithinScope({
|
||||
capability: "db.read",
|
||||
callArgs: [{ table: 7 }],
|
||||
scope: { tablePrefix: "plugin_" },
|
||||
})
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
isCapabilityCallWithinScope({
|
||||
capability: "db.write",
|
||||
callArgs: [{ rows: [] }],
|
||||
scope: { tablePrefix: "plugin_" },
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
+4
-4
@@ -20,12 +20,12 @@ describe("capability call scope", () => {
|
||||
});
|
||||
|
||||
test("matches secret keys with full-string glob patterns", () => {
|
||||
const scope = { keyPattern: "stripe_*" };
|
||||
const scope = { keyPattern: "payment_*" };
|
||||
|
||||
expect(isCapabilityCallWithinScope({ capability: "secret.read", callArgs: [{ key: "stripe_live_key" }], scope })).toBe(true);
|
||||
expect(isCapabilityCallWithinScope({ capability: "secret.read", callArgs: [{ key: "tenant/stripe_live_key" }], scope })).toBe(false);
|
||||
expect(isCapabilityCallWithinScope({ capability: "secret.read", callArgs: [{ key: "payment_live_key" }], scope })).toBe(true);
|
||||
expect(isCapabilityCallWithinScope({ capability: "secret.read", callArgs: [{ key: "tenant/payment_live_key" }], scope })).toBe(false);
|
||||
expect(isCapabilityCallWithinScope({ capability: "secret.read", callArgs: [{ key: "github_token" }], scope })).toBe(false);
|
||||
expect(isCapabilityCallWithinScope({ capability: "secret.read", callArgs: [{ key: "stripe_live_key" }], scope: null })).toBe(false);
|
||||
expect(isCapabilityCallWithinScope({ capability: "secret.read", callArgs: [{ key: "payment_live_key" }], scope: null })).toBe(false);
|
||||
});
|
||||
|
||||
test("limits database calls to tenant-safe table prefixes and rejects raw query shapes", () => {
|
||||
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
import { createCrashTracker, type CrashTrackerStore } from "./crash-tracker.js";
|
||||
|
||||
/**
|
||||
* Coverage for crash-tracker logging + seam-failure branches not hit by
|
||||
* crash-tracker.test.ts: the warn/info logger calls on the auto-disable
|
||||
* path, the error logs when the disable / notify seams reject (Error and
|
||||
* non-Error), and the non-numeric-counter fallbacks.
|
||||
*/
|
||||
|
||||
function makeMemoryStore(): CrashTrackerStore {
|
||||
const map = new Map<string, number>();
|
||||
return {
|
||||
async incr(k, by = 1) {
|
||||
const next = (map.get(k) ?? 0) + by;
|
||||
map.set(k, next);
|
||||
return next;
|
||||
},
|
||||
async expire() {
|
||||
return true;
|
||||
},
|
||||
async get(k) {
|
||||
const v = map.get(k);
|
||||
return v === undefined ? null : String(v);
|
||||
},
|
||||
async set(k, v) {
|
||||
map.set(k, Number(v));
|
||||
return true;
|
||||
},
|
||||
async del(k) {
|
||||
return map.delete(k) ? 1 : 0;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makeLogger() {
|
||||
return {
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
describe("createCrashTracker — logging + seam failures", () => {
|
||||
test("logs warn-per-failure and info on auto-disable", async () => {
|
||||
const logger = makeLogger();
|
||||
const tracker = createCrashTracker({
|
||||
store: makeMemoryStore(),
|
||||
disablePlugin: vi.fn().mockResolvedValue(undefined),
|
||||
notify: vi.fn().mockResolvedValue(undefined),
|
||||
options: { threshold: 1, logger },
|
||||
});
|
||||
|
||||
const result = await tracker.recordFailure({ pluginId: "p", tenantId: "t", reason: "trap" });
|
||||
expect(result).toEqual({ failureCount: 1, autoDisabled: true });
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ pluginId: "p", failureCount: 1, reason: "trap" }),
|
||||
"plugin.crash.recorded"
|
||||
);
|
||||
expect(logger.info).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ pluginId: "p", failureCount: 1 }),
|
||||
"plugin.crash.auto_disabled"
|
||||
);
|
||||
});
|
||||
|
||||
test("logs an error and stays enabled when the disable seam rejects with an Error", async () => {
|
||||
const logger = makeLogger();
|
||||
const tracker = createCrashTracker({
|
||||
store: makeMemoryStore(),
|
||||
disablePlugin: vi.fn().mockRejectedValue(new Error("db unreachable")),
|
||||
notify: vi.fn().mockResolvedValue(undefined),
|
||||
options: { threshold: 1, logger },
|
||||
});
|
||||
|
||||
const result = await tracker.recordFailure({ pluginId: "p", tenantId: "t", reason: "trap" });
|
||||
expect(result).toEqual({ failureCount: 1, autoDisabled: false });
|
||||
expect(logger.error).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ pluginId: "p", tenantId: "t", error: "db unreachable" }),
|
||||
"plugin.crash.disable_failed"
|
||||
);
|
||||
});
|
||||
|
||||
test("stringifies a non-Error rejection from the disable seam", async () => {
|
||||
const logger = makeLogger();
|
||||
const tracker = createCrashTracker({
|
||||
store: makeMemoryStore(),
|
||||
// eslint-disable-next-line @typescript-eslint/only-throw-error, prefer-promise-reject-errors
|
||||
disablePlugin: vi.fn().mockRejectedValue("string failure"),
|
||||
options: { threshold: 1, logger },
|
||||
});
|
||||
|
||||
const result = await tracker.recordFailure({ pluginId: "p", tenantId: "t", reason: "trap" });
|
||||
expect(result.autoDisabled).toBe(false);
|
||||
expect(logger.error).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ error: "string failure" }),
|
||||
"plugin.crash.disable_failed"
|
||||
);
|
||||
});
|
||||
|
||||
test("logs notify_failed but still auto-disables when the notify seam rejects", async () => {
|
||||
const logger = makeLogger();
|
||||
const disablePlugin = vi.fn().mockResolvedValue(undefined);
|
||||
const tracker = createCrashTracker({
|
||||
store: makeMemoryStore(),
|
||||
disablePlugin,
|
||||
notify: vi.fn().mockRejectedValue(new Error("notify channel down")),
|
||||
options: { threshold: 1, logger },
|
||||
});
|
||||
|
||||
const result = await tracker.recordFailure({ pluginId: "p", tenantId: "t", reason: "trap" });
|
||||
// Disable succeeded → still auto-disabled even though notify failed.
|
||||
expect(result).toEqual({ failureCount: 1, autoDisabled: true });
|
||||
expect(disablePlugin).toHaveBeenCalledOnce();
|
||||
expect(logger.error).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ error: "notify channel down" }),
|
||||
"plugin.crash.notify_failed"
|
||||
);
|
||||
});
|
||||
|
||||
test("treats a non-numeric stored counter as zero", async () => {
|
||||
const garbageStore: CrashTrackerStore = {
|
||||
incr: async () => 1,
|
||||
expire: async () => true,
|
||||
get: async () => "not-a-number",
|
||||
set: async () => true,
|
||||
del: async () => 1,
|
||||
};
|
||||
const tracker = createCrashTracker({ store: garbageStore, disablePlugin: vi.fn() });
|
||||
|
||||
expect(await tracker.getFailureCount({ pluginId: "p", tenantId: "t" })).toBe(0);
|
||||
expect((await tracker.recordSuccess({ pluginId: "p", tenantId: "t" })).failureCount).toBe(0);
|
||||
});
|
||||
});
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
import { z } from "zod";
|
||||
import { emitPluginHook, PluginHookValidationError, type PluginHookOutboxPublisher } from "./emit.js";
|
||||
import type { PluginHookDefinition } from "./registry.js";
|
||||
|
||||
/**
|
||||
* Coverage for emitPluginHook's outbox-arg defaulting: the tenantId /
|
||||
* dispatchKey fall back to null when the optional fields are omitted, and
|
||||
* pass through verbatim when supplied. Plus the validation-failure throw.
|
||||
*/
|
||||
|
||||
type TestPayload = { id: string };
|
||||
|
||||
const DEF: PluginHookDefinition<TestPayload> = {
|
||||
name: "test.created",
|
||||
outboxEventType: "plugin.hook.test.created",
|
||||
payloadSchema: z.object({ id: z.string().min(1) }),
|
||||
};
|
||||
|
||||
const TX = { marker: "tx" };
|
||||
|
||||
describe("emitPluginHook", () => {
|
||||
test("forwards explicit tenantId + dispatchKey to the publisher", async () => {
|
||||
const publish = vi.fn<PluginHookOutboxPublisher>(() => Promise.resolve({ id: "outbox-1" }));
|
||||
|
||||
await emitPluginHook(TX, DEF, { id: "abc" }, publish, {
|
||||
tenantId: "tenant-1",
|
||||
dispatchKey: "dedupe-1",
|
||||
});
|
||||
|
||||
expect(publish).toHaveBeenCalledWith(TX, {
|
||||
tenantId: "tenant-1",
|
||||
type: "plugin.hook.test.created",
|
||||
payload: { id: "abc" },
|
||||
dispatchKey: "dedupe-1",
|
||||
});
|
||||
});
|
||||
|
||||
test("defaults tenantId + dispatchKey to null when options are omitted", async () => {
|
||||
const publish = vi.fn<PluginHookOutboxPublisher>(() => Promise.resolve(null));
|
||||
|
||||
await emitPluginHook(TX, DEF, { id: "abc" }, publish);
|
||||
|
||||
expect(publish).toHaveBeenCalledWith(TX, {
|
||||
tenantId: null,
|
||||
type: "plugin.hook.test.created",
|
||||
payload: { id: "abc" },
|
||||
dispatchKey: null,
|
||||
});
|
||||
});
|
||||
|
||||
test("throws PluginHookValidationError and never publishes on a bad payload", async () => {
|
||||
const publish = vi.fn<PluginHookOutboxPublisher>(() => Promise.resolve(null));
|
||||
|
||||
await expect(
|
||||
emitPluginHook(TX, DEF, { id: "" } as TestPayload, publish)
|
||||
).rejects.toBeInstanceOf(PluginHookValidationError);
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -33,7 +33,7 @@ import {
|
||||
/**
|
||||
* JSON-compatible value type, structurally identical to
|
||||
* `Prisma.InputJsonValue` without taking the dependency on
|
||||
* `@toolctrl/db` (which would cycle through the worker bootstrap).
|
||||
* `@hivegrid/db` (which would cycle through the worker bootstrap).
|
||||
*/
|
||||
export type PluginHookJsonValue =
|
||||
| string
|
||||
@@ -55,10 +55,10 @@ export class PluginHookValidationError extends Error {
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal publish surface — kept identical to the @toolctrl/db helper
|
||||
* so this package does not have to depend on @toolctrl/db directly
|
||||
* Minimal publish surface — kept identical to the @hivegrid/db helper
|
||||
* so this package does not have to depend on @hivegrid/db directly
|
||||
* (avoids a cycle with the worker bootstrap that pulls plugin-runtime
|
||||
* via @toolctrl/db).
|
||||
* via @hivegrid/db).
|
||||
*/
|
||||
export type PluginHookOutboxPublisher = (
|
||||
tx: unknown,
|
||||
@@ -84,7 +84,7 @@ export type EmitPluginHookOptions = {
|
||||
/**
|
||||
* Validate + publish a plugin-hook outbox event inside a transaction.
|
||||
* The transaction client is intentionally typed as `unknown` so this
|
||||
* package keeps zero runtime dependency on @toolctrl/db — the caller
|
||||
* package keeps zero runtime dependency on @hivegrid/db — the caller
|
||||
* (a `.server.ts` file in apps/web) already imports the prisma types
|
||||
* and passes the correct shape.
|
||||
*/
|
||||
|
||||
+2
-2
@@ -233,7 +233,7 @@ describe("plugin hook registry", () => {
|
||||
errorCode: "workflow_execution_failed",
|
||||
appliesToAllTenants: false,
|
||||
occurredAt: "2026-05-26T20:00:00.000Z",
|
||||
error: "Provider failed with token=sk_live_secret",
|
||||
error: "Provider failed with token=payment_live_secret",
|
||||
});
|
||||
expect(withRawError.ok).toBe(false);
|
||||
|
||||
@@ -314,7 +314,7 @@ describe("plugin hook registry", () => {
|
||||
errorCode: "workflow_execution_failed",
|
||||
appliesToAllTenants: false,
|
||||
occurredAt: "2026-05-26T20:00:00.000Z",
|
||||
error: "Provider failed with token=sk_live_secret",
|
||||
error: "Provider failed with token=payment_live_secret",
|
||||
});
|
||||
expect(withRawError.ok).toBe(false);
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* @toolctrl/plugin-runtime — Phase 06 Task #21 foundation.
|
||||
* @hivegrid/plugin-runtime — Phase 06 Task #21 foundation.
|
||||
*
|
||||
* Scaffold-only entry. The real exports are wired in the subsequent
|
||||
* commits of this task (manifest schema, signature verifier, sandbox
|
||||
|
||||
+2
-2
@@ -8,7 +8,7 @@ const settingsHtmlIntegrity = "sha256-VqeGGGmNvXI5np0HtPEqnnkQzUobfeQaL5C9SjPqM4
|
||||
|
||||
const validManifest = {
|
||||
schemaVersion: 1,
|
||||
id: "de.toolctrl.hello",
|
||||
id: "de.hivegrid.hello",
|
||||
version: "1.0.0",
|
||||
name: "Hello",
|
||||
entry: "plugin.wasm",
|
||||
@@ -264,7 +264,7 @@ describe("parsePluginManifest", () => {
|
||||
const result = parsePluginManifest(validManifest);
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) {
|
||||
expect(result.manifest.id).toBe("de.toolctrl.hello");
|
||||
expect(result.manifest.id).toBe("de.hivegrid.hello");
|
||||
expect(result.manifest.capabilities).toHaveLength(2);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -17,7 +17,7 @@ import { PLUGIN_CAPABILITY_NAMES, type PluginCapabilityName } from "./capabiliti
|
||||
|
||||
// Reverse-DNS-style id: at least two dot-separated labels of [a-z0-9-].
|
||||
// Keeps the registry path tree clean and makes signed-by + manifest
|
||||
// canonicalisation easy. Examples: `com.acme.slack`, `de.toolctrl.hello`.
|
||||
// canonicalisation easy. Examples: `com.acme.slack`, `de.hivegrid.hello`.
|
||||
const PLUGIN_ID_PATTERN = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/u;
|
||||
|
||||
// Loose SemVer subset: major.minor.patch with optional pre-release tag.
|
||||
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
import {
|
||||
PluginMigrationError,
|
||||
applyPluginMigration,
|
||||
tokenizeSqlIdentifiers,
|
||||
validatePluginMigration,
|
||||
} from "./migrations.js";
|
||||
|
||||
/**
|
||||
* Coverage for migration validator + applier branches not hit by
|
||||
* migrations.test.ts: the unsupported-shape rejections for CREATE TABLE /
|
||||
* CREATE INDEX, the stage-1 substring fallback for forbidden-token
|
||||
* lookalikes, the tokenizer quote-escape handling, and the execute_failed
|
||||
* path when the raw-exec seam rejects with a non-Error.
|
||||
*/
|
||||
|
||||
describe("validatePluginMigration — unsupported shapes", () => {
|
||||
test("rejects a CREATE TABLE that lacks the column list", () => {
|
||||
let thrown: unknown;
|
||||
try {
|
||||
validatePluginMigration({
|
||||
pluginId: "com.acme.x",
|
||||
sql: "CREATE TABLE plugin_com_acme_x_foo",
|
||||
});
|
||||
} catch (err) {
|
||||
thrown = err;
|
||||
}
|
||||
expect(thrown).toBeInstanceOf(PluginMigrationError);
|
||||
expect((thrown as PluginMigrationError).code).toBe("forbidden_statement");
|
||||
});
|
||||
|
||||
test("rejects a CREATE INDEX whose name does not match the supported shape", () => {
|
||||
let thrown: unknown;
|
||||
try {
|
||||
validatePluginMigration({
|
||||
pluginId: "com.acme.x",
|
||||
sql: "CREATE INDEX 1bad ON plugin_com_acme_x_foo (tenantId)",
|
||||
});
|
||||
} catch (err) {
|
||||
thrown = err;
|
||||
}
|
||||
expect(thrown).toBeInstanceOf(PluginMigrationError);
|
||||
expect((thrown as PluginMigrationError).code).toBe("forbidden_statement");
|
||||
});
|
||||
|
||||
test("stage-1 fallback rejects a forbidden-token lookalike outside a string literal", () => {
|
||||
// "grantor" is not an exact GRANT keyword (stage-2 lets it pass) but
|
||||
// the stage-1 substring scan flags the live token containing "GRANT".
|
||||
let thrown: unknown;
|
||||
try {
|
||||
validatePluginMigration({
|
||||
pluginId: "com.acme.x",
|
||||
sql: "CREATE TABLE plugin_com_acme_x_foo (tenantId TEXT, grantor TEXT)",
|
||||
});
|
||||
} catch (err) {
|
||||
thrown = err;
|
||||
}
|
||||
expect(thrown).toBeInstanceOf(PluginMigrationError);
|
||||
expect((thrown as PluginMigrationError).code).toBe("forbidden_statement");
|
||||
expect((thrown as PluginMigrationError).message).toContain("GRANT");
|
||||
});
|
||||
});
|
||||
|
||||
describe("tokenizeSqlIdentifiers — quote escapes", () => {
|
||||
test("skips a doubled single-quote escape inside a string literal", () => {
|
||||
const tokens = tokenizeSqlIdentifiers("col = 'it''s fine' AND flag");
|
||||
const texts = tokens.map((t) => t.text);
|
||||
expect(texts).toEqual(["COL", "AND", "FLAG"]);
|
||||
// String content (including the escaped quote) is never tokenized.
|
||||
expect(texts.some((t) => t.includes("FINE"))).toBe(false);
|
||||
});
|
||||
|
||||
test("preserves a doubled double-quote escape inside a quoted identifier", () => {
|
||||
const tokens = tokenizeSqlIdentifiers('x "we""ird" y');
|
||||
const texts = tokens.map((t) => t.text);
|
||||
expect(texts).toContain('WE"IRD');
|
||||
expect(texts).toEqual(["X", 'WE"IRD', "Y"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyPluginMigration — execute seam failure", () => {
|
||||
test("wraps a non-Error rejection from the raw-exec seam as execute_failed", async () => {
|
||||
const logger = { info: vi.fn(), error: vi.fn() };
|
||||
const executeRawUnsafe = vi.fn(() =>
|
||||
// eslint-disable-next-line @typescript-eslint/only-throw-error, prefer-promise-reject-errors
|
||||
Promise.reject("connection reset")
|
||||
);
|
||||
|
||||
let thrown: unknown;
|
||||
try {
|
||||
await applyPluginMigration(
|
||||
{
|
||||
pluginId: "com.acme.x",
|
||||
sql: "CREATE TABLE plugin_com_acme_x_foo (tenantId TEXT NOT NULL)",
|
||||
},
|
||||
{ executeRawUnsafe, logger }
|
||||
);
|
||||
} catch (err) {
|
||||
thrown = err;
|
||||
}
|
||||
|
||||
expect(thrown).toBeInstanceOf(PluginMigrationError);
|
||||
expect((thrown as PluginMigrationError).code).toBe("execute_failed");
|
||||
expect((thrown as PluginMigrationError).message).toContain("connection reset");
|
||||
expect(logger.error).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ pluginId: "com.acme.x", error: "connection reset" }),
|
||||
"plugin.migration.execute_failed"
|
||||
);
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -14,7 +14,7 @@ describe("sanitizePluginIdForSql", () => {
|
||||
expect(sanitizePluginIdForSql("com.acme.slack")).toBe("com_acme_slack");
|
||||
});
|
||||
test("hyphens are replaced", () => {
|
||||
expect(sanitizePluginIdForSql("de.tool-ctrl.hello")).toBe("de_tool_ctrl_hello");
|
||||
expect(sanitizePluginIdForSql("de.hivegrid.hello")).toBe("de_hivegrid_hello");
|
||||
});
|
||||
test("rejects identifiers that do not start with a-z", () => {
|
||||
expect(() => sanitizePluginIdForSql("1.bad.id")).toThrow(/cannot be sanitized/u);
|
||||
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { createPluginSandbox } from "./runtime.js";
|
||||
import type { PluginManifest } from "./manifest.js";
|
||||
|
||||
/**
|
||||
* Error-path coverage for the WASM sandbox. The happy path + traps are
|
||||
* covered in runtime.test.ts; this file exercises the failure branches:
|
||||
* instantiate failure, fuel exhaustion, out-of-bounds memory traps, and
|
||||
* host-import exceptions (both Error and non-Error throws).
|
||||
*/
|
||||
|
||||
const FIXTURE_MANIFEST: PluginManifest = {
|
||||
schemaVersion: 1,
|
||||
id: "de.hivegrid.test",
|
||||
version: "1.0.0",
|
||||
name: "Test",
|
||||
entry: "plugin.wasm",
|
||||
wasmSha256: "0".repeat(64),
|
||||
signature: "0".repeat(128),
|
||||
signedBy: "0".repeat(64),
|
||||
allowedHosts: [],
|
||||
capabilities: [],
|
||||
hooks: [{ name: "noop", export: "noop" }],
|
||||
};
|
||||
|
||||
/**
|
||||
* Compiles cleanly but imports `env.missing_fn`, which the host never
|
||||
* provides — instantiation fails with a LinkError.
|
||||
*
|
||||
* WAT:
|
||||
* (module (import "env" "missing_fn" (func)) (func (export "noop")))
|
||||
*/
|
||||
const INSTANTIATE_FAIL_WASM = new Uint8Array([
|
||||
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
|
||||
0x01, 0x04, 0x01, 0x60, 0x00, 0x00,
|
||||
0x02, 0x12, 0x01, 0x03, 0x65, 0x6e, 0x76, 0x0a, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6e, 0x67, 0x5f, 0x66, 0x6e, 0x00, 0x00,
|
||||
0x03, 0x02, 0x01, 0x00,
|
||||
0x07, 0x08, 0x01, 0x04, 0x6e, 0x6f, 0x6f, 0x70, 0x00, 0x01,
|
||||
0x0a, 0x04, 0x01, 0x02, 0x00, 0x0b,
|
||||
]);
|
||||
|
||||
/**
|
||||
* `oob` reads from address 1_000_000 with a single 64 KiB page mapped —
|
||||
* the load traps with "memory access out of bounds".
|
||||
*
|
||||
* WAT:
|
||||
* (module (memory 1)
|
||||
* (func (export "oob") (result i32) i32.const 1000000 i32.load))
|
||||
*/
|
||||
const OOB_WASM = new Uint8Array([
|
||||
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
|
||||
0x01, 0x05, 0x01, 0x60, 0x00, 0x01, 0x7f,
|
||||
0x03, 0x02, 0x01, 0x00,
|
||||
0x05, 0x03, 0x01, 0x00, 0x01,
|
||||
0x07, 0x07, 0x01, 0x03, 0x6f, 0x6f, 0x62, 0x00, 0x00,
|
||||
0x0a, 0x0b, 0x01, 0x09, 0x00, 0x41, 0xc0, 0x84, 0x3d, 0x28, 0x02, 0x00, 0x0b,
|
||||
]);
|
||||
|
||||
/**
|
||||
* `callboom` invokes the imported `env.boom` host function — whatever
|
||||
* `boom` throws propagates back through the WASM frame to the caller.
|
||||
*
|
||||
* WAT:
|
||||
* (module (import "env" "boom" (func $boom))
|
||||
* (func (export "callboom") call $boom))
|
||||
*/
|
||||
const CALLBOOM_WASM = new Uint8Array([
|
||||
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
|
||||
0x01, 0x04, 0x01, 0x60, 0x00, 0x00,
|
||||
0x02, 0x0c, 0x01, 0x03, 0x65, 0x6e, 0x76, 0x04, 0x62, 0x6f, 0x6f, 0x6d, 0x00, 0x00,
|
||||
0x03, 0x02, 0x01, 0x00,
|
||||
0x07, 0x0c, 0x01, 0x08, 0x63, 0x61, 0x6c, 0x6c, 0x62, 0x6f, 0x6f, 0x6d, 0x00, 0x01,
|
||||
0x0a, 0x06, 0x01, 0x04, 0x00, 0x10, 0x00, 0x0b,
|
||||
]);
|
||||
|
||||
const VALID_WASM = new Uint8Array([
|
||||
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
|
||||
0x01, 0x06, 0x01, 0x60, 0x01, 0x7f, 0x01, 0x7f,
|
||||
0x03, 0x02, 0x01, 0x00,
|
||||
0x07, 0x0a, 0x01, 0x06, 0x64, 0x6f, 0x75, 0x62, 0x6c, 0x65, 0x00, 0x00,
|
||||
0x0a, 0x09, 0x01, 0x07, 0x00, 0x20, 0x00, 0x41, 0x02, 0x6c, 0x0b,
|
||||
]);
|
||||
|
||||
describe("createPluginSandbox error paths", () => {
|
||||
test("compile_failed sandbox still honours close() and fuelRemaining()", async () => {
|
||||
const sandbox = createPluginSandbox({
|
||||
wasmBuffer: new Uint8Array([0xde, 0xad, 0xbe, 0xef]),
|
||||
manifest: FIXTURE_MANIFEST,
|
||||
fuelLimit: 17,
|
||||
});
|
||||
const result = await sandbox.invoke("double", 1);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.reason).toBe("compile_failed");
|
||||
// The compile-failed closure exposes a working close()/fuelRemaining().
|
||||
expect(sandbox.fuelRemaining()).toBe(17);
|
||||
expect(() => sandbox.close()).not.toThrow();
|
||||
});
|
||||
|
||||
test("reports instantiate_failed when a required import is missing", async () => {
|
||||
const sandbox = createPluginSandbox({
|
||||
wasmBuffer: INSTANTIATE_FAIL_WASM,
|
||||
manifest: FIXTURE_MANIFEST,
|
||||
fuelLimit: 9,
|
||||
// Intentionally do NOT provide env.missing_fn → LinkError.
|
||||
});
|
||||
const result = await sandbox.invoke("noop", 0);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.reason).toBe("instantiate_failed");
|
||||
expect(result.fuelUsed).toBe(0);
|
||||
expect(result.message).toMatch(/missing_fn|callable|import/iu);
|
||||
}
|
||||
expect(sandbox.fuelRemaining()).toBe(9);
|
||||
expect(() => sandbox.close()).not.toThrow();
|
||||
});
|
||||
|
||||
test("returns fuel_exhausted once the per-invocation budget hits zero", async () => {
|
||||
const sandbox = createPluginSandbox({
|
||||
wasmBuffer: VALID_WASM,
|
||||
manifest: FIXTURE_MANIFEST,
|
||||
fuelLimit: 1,
|
||||
});
|
||||
const first = await sandbox.invoke("double", 3);
|
||||
expect(first.ok).toBe(true);
|
||||
if (first.ok) expect(first.output).toBe(6);
|
||||
expect(sandbox.fuelRemaining()).toBe(0);
|
||||
|
||||
const second = await sandbox.invoke("double", 4);
|
||||
expect(second.ok).toBe(false);
|
||||
if (!second.ok) expect(second.reason).toBe("fuel_exhausted");
|
||||
});
|
||||
|
||||
test("classifies out-of-bounds memory traps as memory_limit_exceeded", async () => {
|
||||
const sandbox = createPluginSandbox({
|
||||
wasmBuffer: OOB_WASM,
|
||||
manifest: FIXTURE_MANIFEST,
|
||||
memoryLimitMb: 1,
|
||||
fuelLimit: 10,
|
||||
});
|
||||
const result = await sandbox.invoke("oob", 0);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.reason).toBe("memory_limit_exceeded");
|
||||
expect(result.message).toMatch(/out of bounds|memory access/iu);
|
||||
}
|
||||
});
|
||||
|
||||
test("classifies a host-import Error throw as a trap with the error message", async () => {
|
||||
const sandbox = createPluginSandbox({
|
||||
wasmBuffer: CALLBOOM_WASM,
|
||||
manifest: FIXTURE_MANIFEST,
|
||||
fuelLimit: 10,
|
||||
hostImports: {
|
||||
env: {
|
||||
boom: () => {
|
||||
throw new Error("host binding exploded");
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const result = await sandbox.invoke("callboom", 0);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.reason).toBe("trap");
|
||||
expect(result.message).toBe("host binding exploded");
|
||||
}
|
||||
});
|
||||
|
||||
test("stringifies a non-Error host-import throw before surfacing the trap", async () => {
|
||||
const sandbox = createPluginSandbox({
|
||||
wasmBuffer: CALLBOOM_WASM,
|
||||
manifest: FIXTURE_MANIFEST,
|
||||
fuelLimit: 10,
|
||||
hostImports: {
|
||||
env: {
|
||||
boom: () => {
|
||||
// eslint-disable-next-line @typescript-eslint/only-throw-error
|
||||
throw "string-shaped failure";
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const result = await sandbox.invoke("callboom", 0);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.reason).toBe("trap");
|
||||
expect(result.message).toBe("string-shaped failure");
|
||||
}
|
||||
});
|
||||
});
|
||||
+2
-2
@@ -37,7 +37,7 @@ const PAYLOAD_IMPORT_WASM = new Uint8Array([
|
||||
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
|
||||
// type section: () -> i32, (i32) -> i32
|
||||
0x01, 0x0a, 0x02, 0x60, 0x00, 0x01, 0x7f, 0x60, 0x01, 0x7f, 0x01, 0x7f,
|
||||
// import section: env.toolctrl_payload_len, env.toolctrl_payload_byte
|
||||
// import section: env.hivegrid_payload_len, env.hivegrid_payload_byte
|
||||
0x02, 0x38, 0x02,
|
||||
0x03, 0x65, 0x6e, 0x76,
|
||||
0x14, 0x74, 0x6f, 0x6f, 0x6c, 0x63, 0x74, 0x72, 0x6c, 0x5f, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x5f, 0x6c, 0x65, 0x6e,
|
||||
@@ -59,7 +59,7 @@ const PAYLOAD_IMPORT_WASM = new Uint8Array([
|
||||
|
||||
const FIXTURE_MANIFEST: PluginManifest = {
|
||||
schemaVersion: 1,
|
||||
id: "de.toolctrl.test",
|
||||
id: "de.hivegrid.test",
|
||||
version: "1.0.0",
|
||||
name: "Test",
|
||||
entry: "plugin.wasm",
|
||||
|
||||
@@ -129,11 +129,15 @@ export function createPluginSandbox(options: PluginSandboxOptions): PluginSandbo
|
||||
memory,
|
||||
...(hostImports.env ?? {}),
|
||||
};
|
||||
envImports.toolctrl_payload_len = () => currentPayloadBytes.byteLength;
|
||||
envImports.toolctrl_payload_byte = (index: number) => {
|
||||
const payloadLen = () => currentPayloadBytes.byteLength;
|
||||
const payloadByte = (index: number) => {
|
||||
if (!Number.isInteger(index) || index < 0 || index >= currentPayloadBytes.byteLength) return 0;
|
||||
return currentPayloadBytes[index] ?? 0;
|
||||
};
|
||||
envImports.toolctrl_payload_len = payloadLen;
|
||||
envImports.toolctrl_payload_byte = payloadByte;
|
||||
envImports.hivegrid_payload_len = payloadLen;
|
||||
envImports.hivegrid_payload_byte = payloadByte;
|
||||
const wrappedImports: WasmImports = { ...hostImports, env: envImports };
|
||||
|
||||
try {
|
||||
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { sanitizePluginOutput } from "./sanitize.js";
|
||||
|
||||
/**
|
||||
* Coverage for sanitize leaf branches not hit by sanitize.test.ts:
|
||||
* - non-JSON leaves (functions / symbols) pass through unchanged,
|
||||
* - a long high-entropy token that is single-case-plus-digits is NOT a
|
||||
* secret (the looksLikeSecret mixed-case requirement).
|
||||
*/
|
||||
|
||||
describe("sanitizePluginOutput — leaf-type + secret-heuristic branches", () => {
|
||||
test("passes function and symbol leaves through unchanged", () => {
|
||||
const fn = (): string => "noop";
|
||||
const sym = Symbol("marker");
|
||||
const result = sanitizePluginOutput({ fn, sym, keep: "plain text" }, "moderate") as {
|
||||
fn: unknown;
|
||||
sym: unknown;
|
||||
keep: unknown;
|
||||
};
|
||||
// Non-JSON leaves are returned by identity (they never appear in
|
||||
// real plugin output, but the walk must not crash on them).
|
||||
expect(result.fn).toBe(fn);
|
||||
expect(result.sym).toBe(sym);
|
||||
expect(result.keep).toBe("plain text");
|
||||
});
|
||||
|
||||
test("does not redact a long single-case-plus-digit token (likely an id, not a secret)", () => {
|
||||
// 32 chars, upper-case + digits, no lower-case → fails the mixed-case
|
||||
// requirement in looksLikeSecret, so it is left intact.
|
||||
const token = "ABCD1234EFGH5678IJKL9012MNOP3456";
|
||||
const result = sanitizePluginOutput({ value: token }, "moderate") as { value: unknown };
|
||||
expect(result.value).toBe(token);
|
||||
});
|
||||
|
||||
test("still redacts a long mixed-case-plus-digit token (high-entropy secret)", () => {
|
||||
const token = "Ab1Cd2Ef3Gh4Ij5Kl6Mn7Op8Qr9St0Uv";
|
||||
const result = sanitizePluginOutput({ value: token }, "moderate") as { value: unknown };
|
||||
expect(result.value).toBe("[REDACTED:api-key]");
|
||||
});
|
||||
});
|
||||
+2
-2
@@ -108,8 +108,8 @@ describe("sanitizePluginOutput — email", () => {
|
||||
});
|
||||
|
||||
describe("sanitizePluginOutput — API key heuristic", () => {
|
||||
test("redacts Stripe-style secret key (sk_live_)", () => {
|
||||
expect(sanitizePluginOutput("Authorization: sk_live_abcdef0123456789ABCDEFxyz")).toBe(
|
||||
test("redacts payment-provider-style secret key (sk_live_)", () => {
|
||||
expect(sanitizePluginOutput("Authorization: payment_live_abcdef0123456789ABCDEFxyz")).toBe(
|
||||
"Authorization: [REDACTED:api-key]"
|
||||
);
|
||||
});
|
||||
|
||||
+2
-2
@@ -41,7 +41,7 @@ describe("verifyPluginSignature", () => {
|
||||
const { privateKey, publicKeyHex } = ed25519Keypair();
|
||||
const manifest = {
|
||||
schemaVersion: 1,
|
||||
id: "de.toolctrl.test",
|
||||
id: "de.hivegrid.test",
|
||||
version: "1.0.0",
|
||||
name: "Test",
|
||||
entry: "plugin.wasm",
|
||||
@@ -67,7 +67,7 @@ describe("verifyPluginSignature", () => {
|
||||
|
||||
test("fails when manifest content changes after signing", () => {
|
||||
const { privateKey, publicKeyHex } = ed25519Keypair();
|
||||
const manifest = { id: "de.toolctrl.test", version: "1.0.0", capabilities: [{ name: "log" }] };
|
||||
const manifest = { id: "de.hivegrid.test", version: "1.0.0", capabilities: [{ name: "log" }] };
|
||||
const signatureHex = signManifestPayload(privateKey, manifest, wasmHash);
|
||||
|
||||
const result = verifyPluginSignature({
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@ const hex128 = "0".repeat(128);
|
||||
function manifest(overrides: PluginVersionConstraints = {}): PluginManifest & PluginVersionConstraints {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
id: "de.toolctrl.hello",
|
||||
id: "de.hivegrid.hello",
|
||||
version: "1.0.0",
|
||||
name: "Hello",
|
||||
entry: "plugin.wasm",
|
||||
|
||||
Reference in new issue
Block a user