Skip to content

Agent Mesh

sdk/js: run the Datalog pass to completion under the SDK's own budget

Antonio Ojeaefae2bf3a869
diff --git a/sdk/js/src/authorizer.ts b/sdk/js/src/authorizer.ts
index 2b5ac840..3812cb5c 100644
--- a/sdk/js/src/authorizer.ts
+++ b/sdk/js/src/authorizer.ts
@@ -17,7 +17,7 @@
// api/datalog.go (gen/datalog.ts) and the mesh policy rules the control
// plane renders (GET /policies). Nothing here derives rules from roles.
-import { AUTHORIZER_LIMITS, BiscuitVerificationError, loadBiscuit, verifyPeerBiscuit, type VerifiedBiscuit } from "./biscuit.ts";
+import { AUTHORIZER_LIMITS, BiscuitVerificationError, loadBiscuit, verifyPeerBiscuit, withinLimits, type VerifiedBiscuit } from "./biscuit.ts";
import { parseServiceTarget } from "./discovery.ts";
import { BASELINE_DATALOG } from "./gen/datalog.ts";
@@ -171,7 +171,7 @@ export async function authorizeCaller(req: AuthorizeRequest, options: ProviderAu
const authorizer = b.buildAuthenticated(token);
try {
- authorizer.authorizeWithLimits(AUTHORIZER_LIMITS);
+ withinLimits(() => authorizer.authorizeWithLimits(AUTHORIZER_LIMITS));
} catch (err) {
throw new AuthorizationError(req.peerId, describe(err));
}
@@ -200,10 +200,10 @@ async function identityTargetFacts(ownBiscuit: Uint8Array, keys: Uint8Array[], n
b.addFact(wasm.Fact.fromString(timeFact(now)));
b.addPolicy(wasm.Policy.fromString(BASELINE_DATALOG.allow_if_true));
const authorizer = b.buildAuthenticated(token);
- authorizer.authorizeWithLimits(AUTHORIZER_LIMITS);
+ withinLimits(() => authorizer.authorizeWithLimits(AUTHORIZER_LIMITS));
const facts: WasmFact[] = [];
for (const r of BASELINE_DATALOG.target_fact_rules) {
- facts.push(...(authorizer.queryWithLimits(wasm.Rule.fromString(r), AUTHORIZER_LIMITS) as WasmFact[]));
+ facts.push(...withinLimits(() => authorizer.queryWithLimits(wasm.Rule.fromString(r), AUTHORIZER_LIMITS) as WasmFact[]));
}
return facts;
}
@@ -218,7 +218,7 @@ async function boundPeer(biscuit: Uint8Array, keys: Uint8Array[]): Promise<strin
const b = new wasm.AuthorizerBuilder();
b.addPolicy(wasm.Policy.fromString(BASELINE_DATALOG.allow_if_true));
const authorizer = b.buildAuthenticated(token);
- const bound = (authorizer.queryWithLimits(wasm.Rule.fromString("p($p) <- node($p)"), AUTHORIZER_LIMITS) as WasmFact[])
+ const bound = withinLimits(() => authorizer.queryWithLimits(wasm.Rule.fromString("p($p) <- node($p)"), AUTHORIZER_LIMITS) as WasmFact[])
.map((f) => f.terms()[0])
.find((t): t is string => typeof t === "string");
if (bound === undefined) {
diff --git a/sdk/js/src/biscuit.test.ts b/sdk/js/src/biscuit.test.ts
index f9980d8c..f41ace53 100644
--- a/sdk/js/src/biscuit.test.ts
+++ b/sdk/js/src/biscuit.test.ts
@@ -15,7 +15,7 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "node:test";
-import { BiscuitVerificationError, ROLE_ROUTER, loadBiscuit, requireRole, verifyPeerBiscuit } from "./biscuit.ts";
+import { AUTHORIZER_LIMITS, BiscuitVerificationError, ROLE_ROUTER, loadBiscuit, requireRole, verifyPeerBiscuit, withinLimits } from "./biscuit.ts";
import { ROLE_NODE } from "./controlplane.ts";
interface Vector {
@@ -93,3 +93,36 @@ test("tokens minted here verify and report their facts", async () => {
assert.deepEqual(verified.labels, { team: 'plat"form' });
assert.deepEqual(verified.roles, ["sam:role:node"]);
});
+
+test("a fact-generation pass longer than biscuit-wasm's own 1 ms budget still completes", async () => {
+ const wasm = await loadBiscuit();
+ const kp = new wasm.KeyPair(wasm.SignatureAlgorithm.Ed25519);
+ const token = wasm.Biscuit.builder().build(kp.getPrivateKey());
+ // A join over a few hundred facts takes well over a millisecond in wasm;
+ // before withinLimits the fixpoint was cut short there and the request
+ // refused with RunLimit Timeout however generous AUTHORIZER_LIMITS were.
+ const b = new wasm.AuthorizerBuilder();
+ for (let i = 0; i < 300; i++) {
+ b.addFact(wasm.Fact.fromString(`f(${i})`));
+ }
+ b.addRule(wasm.Rule.fromString("g($a, $b) <- f($a), f($b), $a + 1 == $b"));
+ b.addCheck(wasm.Check.fromString("check if g(298, 299)"));
+ b.addPolicy(wasm.Policy.fromString("allow if true"));
+ const authorizer = b.buildAuthenticated(token);
+ const limits = { ...AUTHORIZER_LIMITS, max_facts: 100_000 };
+
+ const start = performance.now();
+ assert.equal(withinLimits(() => authorizer.authorizeWithLimits(limits)), 0);
+ assert.ok(performance.now() - start > 1, "the pass has to be slow enough to exercise the retry");
+
+ // Only the budget is retried; a denial after the same slow pass stands.
+ const denied = new wasm.AuthorizerBuilder();
+ for (let i = 0; i < 300; i++) {
+ denied.addFact(wasm.Fact.fromString(`f(${i})`));
+ }
+ denied.addRule(wasm.Rule.fromString("g($a, $b) <- f($a), f($b), $a + 1 == $b"));
+ denied.addCheck(wasm.Check.fromString("check if g(299, 298)"));
+ denied.addPolicy(wasm.Policy.fromString("allow if true"));
+ const a2 = denied.buildAuthenticated(token);
+ assert.throws(() => withinLimits(() => a2.authorizeWithLimits(limits)), (err: unknown) => "FailedLogic" in (err as object));
+});
diff --git a/sdk/js/src/biscuit.ts b/sdk/js/src/biscuit.ts
index 9e2f6d32..629aa904 100644
--- a/sdk/js/src/biscuit.ts
+++ b/sdk/js/src/biscuit.ts
@@ -29,6 +29,33 @@ export function loadBiscuit(): Promise<BiscuitWasm> {
/** Datalog evaluation budget, as in internal/identity.AuthorizerOptions. */
export const AUTHORIZER_LIMITS = { max_facts: 1000, max_iterations: 100, max_time_micro: 1_000_000 };
+/**
+ * Runs an authorize or query call under AUTHORIZER_LIMITS. biscuit-wasm
+ * applies the limits it is passed to the checks and policies only; the
+ * fact-generation pass runs under the builder's own limits, 1 ms of wall
+ * clock, which it does not let a caller change. A paused event loop or a
+ * throttled CPU then answers a valid request with RunLimit Timeout. The
+ * facts derived before that deadline stay in the authorizer and the next
+ * call resumes from them, so the pass is driven to completion here until
+ * the budget above is spent.
+ */
+export function withinLimits<T>(run: () => T): T {
+ const deadline = performance.now() + AUTHORIZER_LIMITS.max_time_micro / 1000;
+ for (;;) {
+ try {
+ return run();
+ } catch (err) {
+ if (!isTimeout(err) || performance.now() >= deadline) {
+ throw err;
+ }
+ }
+ }
+}
+
+function isTimeout(err: unknown): boolean {
+ return typeof err === "object" && err !== null && (err as { RunLimit?: unknown }).RunLimit === "Timeout";
+}
+
export const ROLE_ROUTER = "sam:role:router";
export class BiscuitVerificationError extends Error {
@@ -107,12 +134,12 @@ export async function verifyPeerBiscuit(
builder.addPolicy(wasm.Policy.fromString("allow if true"));
const authorizer = builder.buildAuthenticated(token);
try {
- authorizer.authorizeWithLimits(AUTHORIZER_LIMITS);
+ withinLimits(() => authorizer.authorizeWithLimits(AUTHORIZER_LIMITS));
} catch (err) {
throw new BiscuitVerificationError(`biscuit is expired or fails its checks: ${describe(err)}`);
}
- const query = (rule: string) => authorizer.queryWithLimits(wasm.Rule.fromString(rule), AUTHORIZER_LIMITS) as QueriedFact[];
+ const query = (rule: string) => withinLimits(() => authorizer.queryWithLimits(wasm.Rule.fromString(rule), AUTHORIZER_LIMITS) as QueriedFact[]);
const strings = (facts: QueriedFact[]) => facts.map((f) => f.terms()[0]).filter((t): t is string => typeof t === "string");
const bound = strings(query("p($p) <- node($p)"));