@sema-agent/core
Version:
Stateless, task-oriented AI agent core
407 lines (406 loc) • 24.3 kB
JavaScript
import { escapeForDisclosure, isRuleBehavior, parseRuleText } from "./permission-rule-model.js";
import { PERMISSION_RULES_DAMAGED_BUCKET_CODE, PERMISSION_RULE_WRITER, TOMBSTONE_ROW_MEMBERS, errText, holdsRuleWriter, memberValueOf, normalizePersistedRule, readDurableRuleRow, ruleRowReadOf, sameRuleIdentity, servedLengthOf, servedRowOf, servedValueOf, sessionRevokeArmOf, unreadableRowsLine, writerOf, } from "./permission-rule-store.js";
import { readRuleOwner } from "./rule-owner.js";
import { identityUnread } from "./runner/unreadable-person-rows.js";
import { ruleStoreFaultReasonOf } from "./rule-store-fault.js";
import { readPrincipal } from "./principal-name.js";
import { optionKeys, receiveMembers } from "./own-property-receipt.js";
import { UNGOVERNED_ORG_RESOLUTION, compileOrgShadowPredicate, createOrgRulePartition } from "./permission-rule-org.js";
import { SESSION_PARTITION_ADDRESSINGS, sessionRowKeyOf } from "./permission-rule-session.js";
import { storedRowAutoStrip } from "./auto-strip.js";
import { seatStampOf, storedRowBindingOf } from "./a2a-bound-grant.js";
import { addStampsOf } from "./permission-rule-model.js";
export function ruleSourceOf(scope) {
return scope.kind === "global" ? "user" : scope.kind;
}
export function ownerStoreOf(provider, principal, localOwnerDeclared) {
const name = principalForBucket(principal);
if (name !== undefined)
return provider.forPrincipal(name);
return localOwnerDeclared && provider.forLocalOwner !== undefined ? provider.forLocalOwner() : provider.forPrincipal(undefined);
}
function principalForBucket(principal) {
const reading = readPrincipal(principal);
if (reading.kind === "invalid") {
throw new Error(`the principal given is not a principal name (got ${reading.fault}) — refusing to resolve a bucket for it; a provided value that names nobody is not "no principal"`);
}
return reading.kind === "name" ? reading.name : undefined;
}
function usableSessionId(sessionId) {
return typeof sessionId === "string" && sessionId !== "" ? sessionId : undefined;
}
const EMPTY_DURABLE = { rules: [], tombstones: [], rev: 0 };
function tombstoneWordDamaged(at, row) {
return {
ok: false,
e: Object.assign(new Error(`the persisted rule partition served a tombstone row (#${at}, ${escapeForDisclosure(row?.rule)}) whose behavior word ${escapeForDisclosure(row?.behavior)} is outside deny/ask/allow — which rows it retired is unknown, so the partition is read as one that could not be read`), { code: PERMISSION_RULES_DAMAGED_BUCKET_CODE }),
};
}
function durableSnapshotOf(served) {
const damaged = (what) => ({ ok: false, e: Object.assign(new Error(`the persisted rule partition served ${what} — what it refuses is unknown, so the partition is read as one that could not be read`), { code: PERMISSION_RULES_DAMAGED_BUCKET_CODE }) });
if (served === null || typeof served !== "object")
return damaged("an answer that could not be read as data (no object)");
const unreadAnswer = (why) => damaged(`an answer that could not be read as data (${escapeForDisclosure(why)})`);
const servedRules = memberValueOf(served, "rules");
if (!servedRules.ok)
return unreadAnswer(servedRules.why);
const servedTombstones = memberValueOf(served, "tombstones");
if (!servedTombstones.ok)
return unreadAnswer(servedTombstones.why);
const revGot = memberValueOf(served, "rev");
const rev = revGot.ok ? servedValueOf(revGot.v, "primitive") : revGot;
const revUnread = rev.ok ? undefined : `the persisted rule partition served a revision that could not be read as data (${escapeForDisclosure(rev.why)}) — its rows stand as read, and no write is anchored to this read`;
const notList = (why) => damaged(`an answer whose rules or tombstones are not a list (${escapeForDisclosure(why)})`);
const ruleCount = servedLengthOf(servedRules.v);
if ("why" in ruleCount)
return notList(ruleCount.why);
const tombstoneCount = servedLengthOf(servedTombstones.v);
if ("why" in tombstoneCount)
return notList(tombstoneCount.why);
const rowOf = (list, kind, i) => {
const got = memberValueOf(list, i);
return got.ok ? { row: got.v } : { e: damaged(`a ${kind} row (#${i}) that could not be read as data (${escapeForDisclosure(got.why)})`) };
};
const rules = [];
const unread = [];
const unreadable = [];
const dropped = new Map();
for (let i = 0; i < ruleCount.n; i++) {
const at = rowOf(servedRules.v, "rule", i);
if ("e" in at)
return at.e;
const reading = readDurableRuleRow(at.row);
if (reading.kind === "inert") {
if (reading.unread === true && reading.dropped !== undefined)
unread.push(reading.dropped);
else if (reading.row !== undefined) {
rules.push(reading.row);
if (reading.dropped !== undefined)
dropped.set(reading.row, reading.dropped);
}
}
else {
if (reading.row !== undefined)
rules.push(reading.row);
if (reading.named !== undefined)
unreadable.push(reading.named);
}
}
const tombstones = [];
for (let i = 0; i < tombstoneCount.n; i++) {
const at = rowOf(servedTombstones.v, "tombstone", i);
if ("e" in at)
return at.e;
const t = servedRowOf(at.row, TOMBSTONE_ROW_MEMBERS);
if (!("row" in t))
return damaged(`a tombstone row (#${i}) whose ${t.failed[0].member} could not be read as data (${escapeForDisclosure(t.failed[0].why)})`);
tombstones.push(t.row);
}
const settled = durableReadOf({ ok: true, v: { rules, tombstones, rev: rev.ok ? rev.v : 0 } });
return settled.ok
? {
...settled,
...(unread.length > 0 ? { unread } : {}),
...(unreadable.length > 0 ? { unreadable } : {}),
...(dropped.size > 0 ? { dropped } : {}),
...(revUnread !== undefined ? { revUnread } : {}),
}
: settled;
}
function durableReadOf(settled) {
if (!settled.ok)
return settled;
const rows = settled.v.tombstones;
const at = rows.findIndex((r) => !isRuleBehavior(r?.behavior));
return at < 0 ? settled : tombstoneWordDamaged(at, rows[at]);
}
export function createPermissionRuleStoreProvider(cfg) {
if (cfg === null || typeof cfg !== "object") {
throw new Error("createPermissionRuleStoreProvider takes a config object naming the partitions to compose");
}
const durable = cfg.durable;
const org = cfg.org !== undefined ? createOrgRulePartition(cfg.org) : undefined;
const session = cfg.session;
if (session !== undefined && (typeof session.read !== "function" || typeof session.apply !== "function")) {
throw new Error("the session partition must implement read(key) and apply(key, add) — refusing a partial face rather than serving a session source that cannot answer");
}
const revokeVerb = session?.revoke;
if (session !== undefined && revokeVerb !== undefined && typeof revokeVerb !== "function") {
throw new Error("the session partition's revoke is present and is not a function — refusing a face whose take-back verb cannot be called (omit it to declare a partition whose rows end only with their session)");
}
const addressedBy = session?.addressedBy;
if (session !== undefined && !SESSION_PARTITION_ADDRESSINGS.some((w) => w === addressedBy)) {
throw Object.assign(new Error('the session partition does not declare addressedBy: "session-row-key" — its verbs are handed the engine\'s key of one owner\'s rows in a session (sessionRowKeyOf), not a session id; refusing a partition that has not said it reads that address'), { code: "config.invalid_argument" });
}
const partitions = Object.freeze({ durable: durable !== undefined, org: org !== undefined, session: session !== undefined });
const a2aPeers = cfg.a2aPeers;
if (a2aPeers !== undefined && typeof a2aPeers !== "function") {
throw Object.assign(new Error("createPermissionRuleStoreProvider's a2aPeers is the mounted-peers seat: a function answering the A2A peers as registered now — refusing a value that is none rather than writing grants without their identity stamp"), { code: "config.invalid_argument" });
}
const storeOver = (partition, owner) => new UnifiedPermissionRuleStore(partition, org, session, owner, a2aPeers);
const provider = {
partitions,
...(a2aPeers !== undefined ? { a2aPeers } : {}),
forPrincipal: (principal) => {
const name = principalForBucket(principal);
return storeOver(durable?.forPrincipal(name), name !== undefined ? { kind: "principal", principal: name } : undefined);
},
...(durable?.forLocalOwner !== undefined ? { forLocalOwner: () => storeOver(durable.forLocalOwner(), { kind: "local-owner" }) } : {}),
...(session !== undefined && typeof revokeVerb === "function"
? {
revokeSessionRule: async (owner, sessionId, target) => {
const read = readRuleOwner(owner);
const key = sessionRowKeyOf(read, sessionId);
const t = Object.freeze({ behavior: target.behavior, rule: target.rule });
const answered = await session.revoke(key, { behavior: t.behavior, rule: t.rule });
const a = answered !== null && typeof answered === "object" ? answered : {};
const revoked = a.revoked;
const refused = a.refused;
const stillLive = sessionRevokeArmOf(revoked, refused) === undefined ? "unknown" : await sessionRowLiveness(new UnifiedPermissionRuleStore(undefined, undefined, session, read, a2aPeers), sessionId, t);
return { ...(revoked !== undefined ? { revoked } : {}), ...(refused !== undefined ? { refused } : {}), stillLive };
},
}
: {}),
};
return provider;
}
async function sessionRowLiveness(store, sessionId, identity) {
try {
const view = await store.effective({ sessionId });
const sources = view.unreadableSources ?? [];
if (sources.includes("session") || (view.unreadable !== undefined && sources.length === 0))
return "unknown";
if (view.rules.some((r) => r.source === "session" && r.behavior === identity.behavior && r.rule === identity.rule))
return "yes";
return (view.unreadableRows ?? []).some((u) => identityUnread(u) && (u.member === "behavior" || u.behavior === identity.behavior)) ? "unknown" : "no";
}
catch {
return "unknown";
}
}
class UnifiedPermissionRuleStore {
durable;
org;
owner;
a2aPeers;
durability;
fidelity;
session;
constructor(durable, org, session, owner, a2aPeers) {
this.durable = durable;
this.org = org;
this.owner = owner;
this.a2aPeers = a2aPeers;
this.session = session;
this.durability = durable?.durability ?? "process-local";
this.fidelity = durable?.fidelity;
if (durable?.quarantined !== undefined) {
this.quarantined = () => durable.quarantined();
}
if (durable !== undefined) {
Object.defineProperty(this, PERMISSION_RULE_WRITER, {
get: () => {
const w = writerOf(durable);
return w === undefined ? undefined : routingWriter(w, this.session, owner);
},
enumerable: false,
});
}
}
quarantined;
writerHeld() {
return this.durable !== undefined && holdsRuleWriter(this.durable);
}
async effective(query) {
const disclosures = [];
const [orgSettled, durableSettled, sessionRows] = await Promise.all([
this.org !== undefined ? this.org.resolve() : Promise.resolve({ ...UNGOVERNED_ORG_RESOLUTION, rules: [], disclosures: [] }),
this.durable !== undefined ? this.durable.list().then(durableSnapshotOf, (e) => ({ ok: false, e })) : Promise.resolve({ ok: true, v: EMPTY_DURABLE }),
this.readSessionRows(usableSessionId(query?.sessionId), disclosures),
]);
const orgResolution = orgSettled;
const unreadable = [];
const faults = [];
if (!durableSettled.ok) {
unreadable.push(errText(durableSettled.e));
faults.push({ sources: ["user", "project"], reason: ruleStoreFaultReasonOf(durableSettled.e) });
}
if ("unreadable" in sessionRows) {
unreadable.push(sessionRows.unreadable);
faults.push({ sources: ["session"], reason: sessionRows.reason });
}
const failed = faults.length > 0 ? { unreadable: unreadable.join("; "), unreadableSources: faults.flatMap((f) => f.sources), unreadableFaults: faults } : {};
const durableRead = durableSettled.ok ? durableSettled.v : EMPTY_DURABLE;
const sessionRead = "unreadable" in sessionRows ? [] : sessionRows.rows;
const shadowed = compileOrgShadowPredicate(orgResolution.rules);
const rules = [];
const dropped = durableSettled.ok && durableSettled.dropped !== undefined ? durableSettled.dropped : new Map();
const illegal = durableRead.rules.filter((r) => dropped.get(r)?.reason === "scope_root_not_absolute");
const misspelt = durableRead.rules.filter((r) => dropped.has(r) && !illegal.includes(r));
const unread = durableSettled.ok ? (durableSettled.unread ?? []) : [];
const durableNamed = durableSettled.ok ? (durableSettled.unreadable ?? []) : [];
const unreadRows = [...durableNamed, ...("unreadable" in sessionRows ? [] : sessionRows.named)];
const unreadableRev = durableSettled.ok ? durableSettled.revUnread : undefined;
if (unreadableRev !== undefined)
disclosures.push(unreadableRev);
const droppedRows = [...unread, ...("unreadable" in sessionRows ? [] : sessionRows.left), ...dropped.values()];
if (unread.length > 0)
disclosures.push(`the persisted rule partition served ${unread.length} allow row(s) a member of which could not be read as data — dropped, not adjudicated: ${unread.slice(0, 3).map((r) => escapeForDisclosure(r.rule)).join(", ")}`);
if (durableNamed.length > 0)
disclosures.push(unreadableRowsLine("persisted", durableNamed));
if (illegal.length > 0)
disclosures.push(`the persisted rule partition served ${illegal.length} row(s) whose project scope root is not a complete absolute path — dropped, not adjudicated: ${illegal.slice(0, 3).map((r) => `${escapeForDisclosure(r.rule)} (${escapeForDisclosure(r.scope.root)})`).join(", ")}`);
if (misspelt.length > 0)
disclosures.push(`the persisted rule partition served ${misspelt.length} allow row(s) whose text is not the canonical spelling of their stored fields — dropped, not adjudicated: ${misspelt.slice(0, 3).map((r) => escapeForDisclosure(r.rule)).join(", ")}`);
for (const r of [...sessionRead, ...durableRead.rules.filter((x) => !dropped.has(x))]) {
const autoStrip = storedRowAutoStrip(r);
rules.push({ ...r, source: ruleSourceOf(r.scope), status: r.behavior === "allow" && shadowed(r) ? "shadowed-by-org" : "live", ...(autoStrip !== undefined ? { autoStrip } : {}), ...rowBindingOf(r, this.a2aPeers) });
}
const removed = [];
for (const t of durableRead.tombstones) {
if (durableRead.rules.some((r) => sameRuleIdentity(r, t)))
continue;
if (removed.some((e) => sameRuleIdentity(e, t)))
continue;
if (t.scope.kind === "session")
continue;
removed.push({ behavior: t.behavior, rule: t.rule, scope: t.scope, source: ruleSourceOf(t.scope), status: "removed" });
}
return { rules, removed, org: orgResolution, rev: durableRead.rev, ...(unreadableRev !== undefined ? { unreadableRev } : {}), disclosures, ...failed, ...(droppedRows.length > 0 ? { droppedRows } : {}), ...(unreadRows.length > 0 ? { unreadableRows: unreadRows.map((u) => u.row) } : {}) };
}
async readSessionRows(sessionId, disclosures) {
if (this.session === undefined || sessionId === undefined || this.owner === undefined)
return { rows: [], named: [], left: [] };
try {
const key = sessionRowKeyOf(this.owner, sessionId);
const served = await this.session.read(key);
const count = servedLengthOf(served);
if ("why" in count)
throw "thrown" in count ? count.thrown : new Error(`an answer that is no list (${count.why})`);
const seat = { session: key };
const ofThisSession = (scope) => scope?.kind === "session" && scope.sessionId === key;
const here = () => ({ kind: "session", sessionId });
const namedHere = (n, stood) => ({ ...n, row: { ...n.row, scope: here() }, ...(stood !== undefined ? { stood } : {}) });
const rows = [];
const named = [];
const left = [];
let taken = 0;
for (let i = 0; i < count.n; i++) {
const got = memberValueOf(served, i);
if (!got.ok)
throw "thrown" in got ? got.thrown : new Error(`a row (#${i}) that could not be read as data (${got.why})`);
const r = ruleRowReadOf(got.v, seat);
if (r.dead === true) {
taken++;
continue;
}
if (r.left !== undefined) {
if (ofThisSession(r.scope))
(left.push(r.left), taken++);
continue;
}
if (!("row" in r)) {
if (r.named !== undefined && ofThisSession(r.named.row.scope))
(named.push(namedHere(r.named)), taken++);
continue;
}
if (!ofThisSession(r.row?.scope))
continue;
const row = { ...r.row, scope: here() };
if ("reject" in normalizePersistedRule(row) && !((row.behavior === "deny" || row.behavior === "ask") && "reject" in parseRuleText(row.rule, row.behavior)))
continue;
rows.push(row);
taken++;
if (r.named !== undefined)
named.push(namedHere(r.named, r.named.stood !== undefined ? row : undefined));
}
if (taken < count.n) {
disclosures.push(`the session rule partition served ${count.n - taken} row(s) that are not canonical session rows of this session — dropped, not adjudicated`);
}
if (left.length > 0)
disclosures.push(`the session rule partition served ${left.length} allow row(s) a member of which could not be read as data — dropped, not adjudicated: ${left.slice(0, 3).map((x) => escapeForDisclosure(x.rule)).join(", ")}`);
if (named.length > 0)
disclosures.push(unreadableRowsLine("session", named));
return { rows, named, left };
}
catch (err) {
const why = `the session rule partition could not be read: ${escapeForDisclosure(errText(err))}`;
disclosures.push(why);
return { unreadable: why, reason: ruleStoreFaultReasonOf(err) };
}
}
}
function rowBindingOf(r, seat) {
if (seat === undefined || r.behavior !== "allow")
return {};
try {
const stamp = seatStampOf(seat, r.tool);
return stamp !== undefined ? { binding: storedRowBindingOf(addStampsOf(r.adds).peerFingerprints, stamp.fingerprint) } : {};
}
catch {
return {};
}
}
function routingWriter(durable, session, owner) {
return {
nextDot: () => durable.nextDot(),
readRaw: () => durable.readRaw(),
apply: async (delta, opts) => {
const isAdd = delta.kind === "redemption-add" || delta.kind === "tighten-add";
const scope = isAdd ? structuredClone(delta.scope) : undefined;
if (!isAdd || scope?.kind !== "session")
return durable.apply(delta, opts);
if (session === undefined) {
const e = new Error(`a session-scope rule has nowhere to land — this deployment configured no session rule partition (createPermissionRuleStoreProvider({ session })); refusing the ${delta.kind}`);
e.code = "unsupported.session_scope_store";
throw e;
}
if (owner === undefined) {
throw Object.assign(new Error(`a session-scope rule has no address on a store with no owner — an anonymous store keeps no session row; refusing the ${delta.kind}`), { code: "unsupported.session_scope_store" });
}
const outcome = await session.apply(sessionRowKeyOf(owner, scope.sessionId), { behavior: delta.behavior, rule: delta.rule, tool: delta.tool, match: delta.match, command: delta.command, add: delta.add });
const answered = outcome !== null && typeof outcome === "object" ? outcome : {};
const landed = answered.landed === true;
const sealed = answered.refused === "session_ended";
if (landed !== sealed)
return landed ? { rev: opts.expectedRev } : { refused: "session_ended", rev: opts.expectedRev };
throw new Error(`the session rule partition answered the ${delta.kind} with ${landed ? "both of its arms at once" : "neither of its two arms"} (landed / refused) — nothing here can say whether the authorization landed; reconcile by reading the session's rules`);
},
};
}
export async function effectiveOrThrow(store, query) {
const view = await store.effective(query);
if (view.unreadable !== undefined)
throw new Error(view.unreadable);
return view;
}
export async function effectivePermissionRules(opts) {
const o = receiveMembers(opts, { subject: "effectivePermissionRules options", unit: "option", moment: "at effectivePermissionRules" }, EFFECTIVE_RULES_OPTION_KEYS);
return await resolveOwnerStore(o).effective(o.sessionId !== undefined ? { sessionId: o.sessionId } : undefined);
}
const EFFECTIVE_RULES_OPTION_KEYS = optionKeys()({ provider: 0, principal: 0, owner: 0, sessionId: 0 });
export function resolveOwnerStore(opts) {
const owner = opts.owner === undefined ? undefined : readRuleOwner(opts.owner);
if (opts.owner !== undefined && owner === undefined) {
throw new Error("the owner given is neither a principal nor the local owner (a principal owner names a principal name) — refusing to resolve a bucket nobody can name");
}
const given = readPrincipal(opts.principal);
if (given.kind === "invalid") {
throw new Error(`the principal given is not a principal name (got ${given.fault}) — pass a verified principal, the local owner, or neither; a provided value that names nobody is not "no principal"`);
}
const principal = given.kind === "name" ? given.name : undefined;
if (owner?.kind === "local-owner") {
if (principal !== undefined) {
throw new Error("pass either a principal or a local-owner, not both — a bucket has one owner");
}
const store = opts.provider.forLocalOwner?.();
if (store === undefined) {
throw new Error("this provider has no local-owner bucket (forLocalOwner is not implemented)");
}
return store;
}
if (owner?.kind === "principal" && principal !== undefined && owner.principal !== principal) {
throw new Error(`contradictory identity: principal "${escapeForDisclosure(principal)}" and owner principal "${escapeForDisclosure(owner.principal)}" disagree`);
}
return opts.provider.forPrincipal(owner?.kind === "principal" ? owner.principal : principal);
}