UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

794 lines (793 loc) • 38.6 kB
import { closeSync, constants as FS, existsSync, fsyncSync, lstatSync } from "node:fs"; import { mkdirSync, openSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "./descriptor-seat.js"; import { basename, join } from "node:path"; import { createHash, randomBytes } from "node:crypto"; import { isRuleBehavior } from "../../core/permission-rule-model.js"; import { posixModeBitsMeaningful } from "../../core/posix-mode-face.js"; import { readRecordedRuleOwner } from "../../core/rule-owner.js"; import { holdsUnpairedSurrogate, principalNameFault, readPrincipal, recordedPrincipalNameOf, unpairedSurrogateRefusal } from "../../core/principal-name.js"; import { PERMISSION_RULES_DAMAGED_BUCKET_CODE, PERMISSION_RULES_LATER_GRAMMAR_CODE, PERMISSION_RULES_UNREADABLE_BUCKET_CODE, PERMISSION_RULE_WRITER, applySyncJoin, applyTombstones, assertDeleteDeltaCarriesNoAdd, assertRedemptionNotQuarantined, assertWriteDeltaScopeDurable, foldDelta, unknownRuleWriteDeltaError, } from "../../core/permission-rule-store.js"; import { sameOrgPolicyContent } from "../../core/permission-rule-org.js"; import { SESSION_RULES_GRAMMAR, readRuleGrammarStamp } from "../../core/session-policy-store.js"; import { canonicalize, textContentHashOf } from "../../core/canonical-json.js"; import { BootLock, FileStoreLockError, rewordedLockRefusal } from "./fs-atomic.js"; import { lockRefusalClause } from "./lock-reading.js"; import { fsyncDir } from "../../core/durable-sync.js"; import { assertAdoptionBootGate } from "./adoption/marker.js"; import { CONFIG_RECEIPT_MODE, optionKeys, receiptRefusal, receiveMembers, receiveOptions } from "../../core/own-property-receipt.js"; import { describeFault, receive } from "../../core/mods/kernel/receive.js"; import { thrownText } from "../../core/thrown-value.js"; function isRuleFile(v) { const p = v; return typeof p === "object" && p !== null && p.schemaVersion === 4 && Array.isArray(p.rules) && Array.isArray(p.tombstones) && typeof p.rev === "number" && (p.quarantined === undefined || Array.isArray(p.quarantined)); } function isOrgStateFile(v) { const p = v; return typeof p === "object" && p !== null && p.schemaVersion === 1 && typeof p.state === "object" && p.state !== null; } function schemaVersionWord(v) { return typeof v === "object" && v !== null ? v.schemaVersion : undefined; } function jsonForm(v) { return JSON.parse(JSON.stringify(v)); } export const ORG_STATE_FILE = "org.json"; export class OrgRevisionRefusal extends Error { } const LOCAL_OWNER_FILE = "local-owner.json"; const HASHED_BUCKET_FILE = /^[0-9a-f]{64}\.json$/; function isBucketFileName(name) { return name === LOCAL_OWNER_FILE || HASHED_BUCKET_FILE.test(name); } function foldCase(s) { return s.toUpperCase().toLowerCase(); } function isCaseVariantBucketName(name) { return !isBucketFileName(name) && isBucketFileName(foldCase(name)); } const CASE_VARIANT_FAULT = "is named like a permission-rule bucket in another letter case — only a file spelled exactly as a bucket's name is one; rename it to lower case, or remove it"; function entrySpelling(dir, name) { const entries = readdirSync(dir); if (entries.includes(name)) return name; const folded = foldCase(name); return entries.find((entry) => foldCase(entry) === folded); } const ADOPTION_FILE = "PERMISSION-RULES-ADOPTION.json"; function adoptionFlipped(adoption) { return "adopted" in adoption || adoption.marker.phase >= 4; } function judgeRuleAdoptionFile(dir) { let raw; try { raw = readFileSync(join(dir, ADOPTION_FILE), "utf8"); } catch (err) { if (err?.code === "ENOENT") return { marker: undefined }; return { corrupt: `could not be read (${err?.code ?? err?.name ?? "unknown"})`, detail: thrownText(err), readFailure: err }; } let parsed; try { parsed = JSON.parse(raw); } catch (err) { return { corrupt: `is not valid JSON (${err.message})` }; } return isRuleAdoptionFileShape(parsed) ? { marker: parsed } : { corrupt: "does not carry a readable shape" }; } export function readRuleAdoptionFile(dir) { const judged = judgeRuleAdoptionFile(dir); if ("corrupt" in judged) { throw new Error(`the permission-rule adoption marker in ${dir} ${judged.corrupt}${judged.detail !== undefined ? `: ${judged.detail}` : ""} — refusing to resolve owners until it is repaired`); } return judged.marker; } function isRuleAdoptionFileShape(v) { if (v === null || typeof v !== "object" || v.schemaVersion !== 1) return false; const hasMarker = "marker" in v; const hasAdopted = "adopted" in v; if (hasMarker === hasAdopted) return false; const rec = (hasMarker ? v.marker : v.adopted); if (rec === null || typeof rec !== "object") return false; if (readRecordedRuleOwner(rec.from) === undefined || recordedPrincipalNameOf(rec.toPrincipal) === undefined) return false; return hasMarker ? rec.phase === 2 || rec.phase === 3 || rec.phase === 4 || rec.phase === 5 : typeof rec.atMs === "number" && Number.isFinite(rec.atMs); } export function writeRuleAdoptionFile(dir, content) { assertSafeDir(dir); atomicPublish(dir, join(dir, ADOPTION_FILE), JSON.stringify(content, null, 2)); } function atomicPublish(dir, file, payload) { const tmp = join(dir, `.${randomBytes(8).toString("hex")}.tmp`); let fd; try { fd = openSync(tmp, FS.O_WRONLY | FS.O_CREAT | FS.O_EXCL | (FS.O_NOFOLLOW ?? 0), 0o600); writeFileSync(fd, payload); fsyncSync(fd); closeSync(fd); fd = undefined; renameSync(tmp, file); fsyncDir(dir); } catch (err) { if (fd !== undefined) { try { closeSync(fd); } catch { } } try { unlinkSync(tmp); } catch { } throw err; } } const EMPTY_READ = { rules: [], tombstones: [], rev: 0 }; function checksumOf(body) { return textContentHashOf(canonicalize(body)); } function unsafeDirFault(dir, vetting) { mkdirSync(dir, { recursive: true, mode: 0o700 }); const st = lstatSync(dir); if (st.isSymbolicLink() || !st.isDirectory()) return { text: "is a symlink or not a directory" }; if (typeof process.getuid === "function" && st.uid !== process.getuid()) return { text: "is owned by another user", unsafe: "owner" }; if (!posixModeBitsMeaningful(vetting?.platform)) { vetting?.modeBitsUnjudged?.(dir); return undefined; } if ((st.mode & 0o022) !== 0) return { text: `is writable by group or others (mode ${(st.mode & 0o777).toString(8)}) — anyone who can write there can grant themselves permissions`, unsafe: "permissions" }; return undefined; } function assertSafeDir(dir) { const fault = unsafeDirFault(dir); if (fault !== undefined) throw new Error(`permission-rule store directory ${dir} ${fault.text}; refusing to use it`); } function refusalText(onError, sentence, location) { discloseTo(onError, `${sentence} (at ${location})`); return `${sentence}. The location is reported to the store's error disclosure (onError), not in this message.`; } function unreadableError(r, sentence = r.unreadable) { return Object.assign(new Error(sentence), { code: r.code, ...(r.errno !== undefined ? { errno: r.errno } : {}), ...(r.unsafe !== undefined ? { unsafe: r.unsafe } : {}) }); } function errnoOf(err) { const code = err?.code; return typeof code === "string" && /^E[A-Z0-9]+$/.test(code) ? code : undefined; } function systemFaultRefusal(onError, err, sentence, location) { const errno = errnoOf(err); const unreadable = refusalText(onError, sentence, location); if (errno === "EEXIST" || errno === "ENOTDIR") return { unreadable, code: PERMISSION_RULES_DAMAGED_BUCKET_CODE }; return { unreadable, code: PERMISSION_RULES_UNREADABLE_BUCKET_CODE, ...(errno !== undefined ? { errno } : {}) }; } function discloseTo(onError, message) { try { onError?.(message); } catch { } } function caseVariantRefusal(onError, vetting, sentence, location) { const sink = vetting?.caseVariantFirstMet?.(location) === false ? undefined : onError; return { unreadable: refusalText(sink, sentence, location), code: PERMISSION_RULES_DAMAGED_BUCKET_CODE }; } function assertSafeDirAtRequest(dir, onError, act, vetting) { let fault; try { fault = unsafeDirFault(dir, vetting); } catch (err) { throw unreadableError(systemFaultRefusal(onError, err, `the permission-rule store directory could not be examined (${err?.code ?? err?.name ?? "unknown"}); refusing to ${act} it`, `${dir}: ${thrownText(err)}`)); } if (fault !== undefined) throw unreadableError({ unreadable: refusalText(onError, `the permission-rule store directory ${fault.text}; refusing to ${act} it`, dir), code: PERMISSION_RULES_DAMAGED_BUCKET_CODE, ...(fault.unsafe !== undefined ? { unsafe: fault.unsafe } : {}) }); } const WRITER_LOCK = "the permission-rule writer lock (see lockPath)"; function writerLockRefusal(err, onError) { let sentence; switch (err.code) { case "store.dir_in_use": case "store.lock_unreadable": sentence = err.holder !== undefined || err.remedies.length > 0 ? `${lockRefusalClause(err, WRITER_LOCK)}; refusing to write` : `${WRITER_LOCK} is held; refusing to write`; break; case "store.dir_claiming": sentence = `another process is taking over ${WRITER_LOCK} from a holder that is gone — retry`; break; case "store.lock_lost": sentence = `this process lost ${WRITER_LOCK} — restart it`; break; default: { const unhandled = err.code; sentence = `${WRITER_LOCK} refused (${String(unhandled)})`; } } discloseTo(onError, `${sentence} (at ${err.lockPath}: ${err.message})`); return rewordedLockRefusal(err, `${sentence}.`, err.lockPath); } function retireOnlyRefusal(rest) { return receiptRefusal(`a listed permission-rule bucket's handle only retires rows (a tighten-delete, and the nextDot its tombstone takes) — ${rest}`); } class FileDurableRulePartition { dir; file; writeLock; origin; onError; vetting; durability = "durable"; fidelity = "json"; name; constructor(dir, file, writeLock, origin, onError, vetting) { this.dir = dir; this.file = file; this.writeLock = writeLock; this.origin = origin; this.onError = onError; this.vetting = vetting; this.name = basename(file); } read() { const bucket = "this owner's permission-rule bucket"; const whole = "refusing the whole file and loading zero rules — repair the file, or remove it (removing it gives up every rule and tombstone it held)"; const unreadable = (sentence, location = this.file) => ({ unreadable: refusalText(this.onError, sentence, location), code: PERMISSION_RULES_DAMAGED_BUCKET_CODE }); let raw; try { const dirFault = unsafeDirFault(this.dir, this.vetting); if (dirFault !== undefined) return { ...unreadable(`the permission-rule store directory ${dirFault.text}; loading zero rules`, this.dir), ...(dirFault.unsafe !== undefined ? { unsafe: dirFault.unsafe } : {}) }; const st = lstatSync(this.file); if (st.isSymbolicLink() || !st.isFile()) return unreadable(`${bucket} is a symlink or not a regular file; refusing to load any rule from it`); const spelled = entrySpelling(this.dir, this.name); if (spelled === undefined) return { absent: true }; if (spelled !== this.name) return caseVariantRefusal(this.onError, this.vetting, `the file ${bucket} would open ${CASE_VARIANT_FAULT}; loading zero rules`, join(this.dir, spelled)); raw = readFileSync(this.file, "utf8"); } catch (err) { const e = err; if (e?.code === "ENOENT") return { absent: true }; return systemFaultRefusal(this.onError, err, `${bucket} could not be read (${e?.code ?? err?.name ?? "unknown"}); loading zero rules`, `${this.file}: ${thrownText(err)}`); } let parsed; try { parsed = JSON.parse(raw); } catch (err) { return unreadable(`${bucket} is not valid JSON (${err.message}); ${whole}`); } if (!isRuleFile(parsed)) { const sv = schemaVersionWord(parsed); return unreadable(typeof sv === "number" ? `${bucket} is a schema ${String(sv)} bucket; this engine reads schema 4 only and does not migrate an older engine's bucket — refusing the whole file and loading zero rules (the bytes are left for a person to look at)` : `${bucket} does not carry a readable rule-file shape; ${whole}`); } const { checksum, ...body } = parsed; if (checksum !== checksumOf(body)) return unreadable(`${bucket} failed its integrity check; ${whole}`); const grammar = readRuleGrammarStamp(parsed.grammar, SESSION_RULES_GRAMMAR, { rules: `the rules in ${bucket}`, held: "rows" }); if ("got" in grammar) { return grammar.later === true ? { ...unreadable(`${grammar.sentence} — loading zero rules and refusing every write until then; the file is left as it is`), code: PERMISSION_RULES_LATER_GRAMMAR_CODE } : unreadable(`${grammar.sentence}; ${whole}`); } const rowKinds = [ ["tombstone", parsed.tombstones], ["quarantined", parsed.quarantined ?? []], ]; for (const [kind, rows] of rowKinds) { const bad = rows.findIndex((r) => !isRuleBehavior(r?.behavior)); if (bad !== -1) return unreadable(`${bucket} carries a ${kind} row (#${bad}) whose behavior word is outside deny/ask/allow — a schema 4 row must name its behavior; ${whole}`); } return { file: parsed }; } disclose(message) { discloseTo(this.onError, message); } screenDurableRows(file) { const isSession = (scope) => scope?.kind === "session"; const rules = file.rules.filter((r) => !isSession(r?.scope)); const tombstones = file.tombstones.filter((t) => !isSession(t?.scope)); const quarantined = (file.quarantined ?? []).filter((q) => !isSession(q?.scope)); const dropped = file.rules.length - rules.length + (file.tombstones.length - tombstones.length) + ((file.quarantined ?? []).length - quarantined.length); if (dropped > 0) { this.disclose(`${this.file} carries ${dropped} session-scope row(s) — a session authorization cannot live in the durable store; those rows are ignored on every read face and never ride sync (they can be left where they are: the file is integrity-checked, and removing or changing them without updating its checksum makes the store refuse the whole file)`); } return { rules, tombstones, quarantined }; } write(next) { assertSafeDirAtRequest(this.dir, this.onError, "write through", this.vetting); const body = { ...next, grammar: SESSION_RULES_GRAMMAR }; const checksum = checksumOf(body); atomicPublish(this.dir, this.file, JSON.stringify({ ...body, checksum }, null, 2)); return checksum; } async list() { const r = this.read(); if ("unreadable" in r) throw unreadableError(r); if (!("file" in r)) return { ...EMPTY_READ }; const screened = this.screenDurableRows(r.file); return { rules: applyTombstones(screened.rules, screened.tombstones), tombstones: screened.tombstones, rev: r.file.rev, checksum: r.file.checksum, }; } async quarantined() { const r = this.read(); if ("unreadable" in r) throw unreadableError(r); return "file" in r ? this.screenDurableRows(r.file).quarantined : []; } current() { this.writeLock.acquire(); if (!this.origin.stillOpens()) { throw new Error("this permission-rule bucket is no longer this handle's to write — an adoption names its file; open it again through its owner"); } const r = this.read(); if ("unreadable" in r) { throw unreadableError(r, `refusing to write the permission-rule store while it cannot be read: ${r.unreadable}`); } if ("absent" in r) { if (this.origin.posture === "retire-only") { throw unreadableError({ unreadable: refusalText(this.onError, "this listed permission-rule bucket is no longer there (ENOENT); refusing to write it — list the store directory again", this.file), code: PERMISSION_RULES_UNREADABLE_BUCKET_CODE, errno: "ENOENT" }); } return { schemaVersion: 4, actor: `file-${randomBytes(6).toString("hex")}`, counter: 0, rev: 0, rules: [], tombstones: [] }; } return { schemaVersion: r.file.schemaVersion, actor: r.file.actor, counter: r.file.counter, rev: r.file.rev, rules: r.file.rules, tombstones: r.file.tombstones, ...(r.file.sync !== undefined ? { sync: r.file.sync } : {}), ...(r.file.quarantined !== undefined ? { quarantined: r.file.quarantined } : {}), }; } writeAndVerify(next) { const expected = this.write(next); const after = this.read(); return "file" in after && after.file.checksum === expected; } writeChain = Promise.resolve(); serialize(fn) { const run = this.writeChain.then(fn, fn); this.writeChain = run.then(() => undefined, () => undefined); return run; } get [PERMISSION_RULE_WRITER]() { this.writeLock.acquire(); return this.writer; } writerHeld() { return this.writeLock.held(); } writer = { nextDot: async () => this.serialize(() => { const cur = this.current(); const dot = { actor: cur.actor, counter: cur.counter + 1 }; if (!this.writeAndVerify({ ...cur, counter: dot.counter })) { throw new Error("the permission-rule store did not survive its own write; refusing to hand out an identity"); } return dot; }), readRaw: async () => this.serialize(() => { if (this.origin.posture === "retire-only") throw retireOnlyRefusal("its raw sync state is read through its owner"); const cur = this.current(); const screened = this.screenDurableRows(cur); return { actor: cur.actor, counter: cur.counter, rev: cur.rev, rules: structuredClone(screened.rules), tombstones: structuredClone(screened.tombstones), ...(cur.sync?.observedVector !== undefined ? { observedVector: structuredClone(cur.sync.observedVector) } : {}), quarantined: structuredClone(screened.quarantined), }; }), apply: async (delta, opts) => this.serialize(() => { delta = structuredClone(delta); const { expectedRev } = opts; if (this.origin.posture === "retire-only" && delta?.kind !== "tighten-delete") { throw retireOnlyRefusal("every other write goes through its owner"); } const cur = this.current(); if (cur.rev !== expectedRev) return { conflict: true, rev: cur.rev }; let next; switch (delta.kind) { case "sync-join": { const { next: joined, report } = applySyncJoin({ actor: cur.actor, counter: cur.counter, rules: cur.rules, tombstones: cur.tombstones, quarantined: cur.quarantined ?? [], ...(cur.sync?.observedVector !== undefined ? { observedVector: cur.sync.observedVector } : {}), }, delta, Date.now()); const landed = { ...cur, rev: cur.rev + 1, rules: joined.rules, tombstones: joined.tombstones, sync: { ...(joined.observedVector !== undefined ? { observedVector: joined.observedVector } : {}), lastRoundAtMs: Date.now(), }, ...(joined.quarantined.length > 0 ? { quarantined: joined.quarantined } : {}), }; if (!this.writeAndVerify(landed)) { throw new Error("the permission-rule store did not read back as the version just written; whether the change reached the bytes on disk is unobservable from here — reconcile by reading the store"); } return { rev: cur.rev + 1, sync: report }; } case "redemption-add": { assertWriteDeltaScopeDurable(delta); assertRedemptionNotQuarantined(cur.quarantined ?? [], delta); next = { ...cur, rev: cur.rev + 1, rules: foldDelta(cur.rules, delta) }; break; } case "tighten-add": { assertWriteDeltaScopeDurable(delta); next = { ...cur, rev: cur.rev + 1, rules: foldDelta(cur.rules, delta) }; break; } case "tighten-delete": { assertWriteDeltaScopeDurable(delta); assertDeleteDeltaCarriesNoAdd(delta); next = { ...cur, rev: cur.rev + 1, tombstones: [...cur.tombstones, delta.tombstone] }; break; } default: { const unhandled = delta; throw unknownRuleWriteDeltaError(unhandled); } } if (!this.writeAndVerify(next)) { throw new Error("the permission-rule store did not read back as the version just written; whether the change reached the bytes on disk is unobservable from here — reconcile by reading the store"); } return { rev: cur.rev + 1 }; }), }; } const FILE_DURABLE_RULE_PARTITION_PROVIDER_OPTION_KEYS = optionKeys()({ dataRoot: 0, platform: 0 }); const LIST_BUCKET_OWNERS_OPTION_KEYS = optionKeys()({ knownOwners: 0 }); function receiveKnownOwners(opts) { if (opts === undefined) return []; const given = receiveMembers(opts, { subject: "listBucketOwners options", unit: "option", moment: "at listBucketOwners" }, LIST_BUCKET_OWNERS_OPTION_KEYS).knownOwners; if (given === undefined) return []; const received = receive(given, CONFIG_RECEIPT_MODE); if (!received.ok) throw receiptRefusal(`listBucketOwners options.knownOwners could not be read — ${describeFault(received.fault)}; refused rather than read as "no known owners"`); const list = received.value; if (!Array.isArray(list) || list === given) { throw receiptRefusal(`listBucketOwners options.knownOwners must be an array of principal names (got ${given === null ? "null" : Array.isArray(given) ? "an array the engine cannot copy" : typeof given}); refused rather than read as "no known owners"`); } const names = new Set(); for (let index = 0; index < list.length; index++) { const element = Object.hasOwn(list, index) ? list[index] : undefined; const name = recordedPrincipalNameOf(element); if (name === undefined) { throw receiptRefusal(`listBucketOwners options.knownOwners[${index}] is not a principal name (got ${principalNameFault(element)}); refused rather than skipped — a skipped name would leave its bucket unlabelled`); } if (holdsUnpairedSurrogate(name)) throw receiptRefusal(unpairedSurrogateRefusal(`listBucketOwners options.knownOwners[${index}]`)); names.add(name); } return [...names]; } function adoptionBucketFiles(rec) { return { source: rec.from.kind === "local-owner" ? LOCAL_OWNER_FILE : principalRuleFileName(rec.from.principal), target: principalRuleFileName(rec.toPrincipal) }; } export function bucketCensusOf(names, adoption, knownOwners) { const present = new Set(names); const [variant] = [...present].filter(isCaseVariantBucketName).sort(); if (variant !== undefined) return { caseVariant: variant }; const owners = []; if (present.has(LOCAL_OWNER_FILE)) owners.push({ kind: "local-owner" }); const owned = new Set(); if (adoption !== undefined) { const rec = "adopted" in adoption ? adoption.adopted : adoption.marker; const named = adoptionBucketFiles(rec); owned.add(named.target); if (present.has(named.target)) owners.push({ kind: "principal", principal: rec.toPrincipal }); if (rec.from.kind === "principal" && named.source !== named.target && !adoptionFlipped(adoption)) { owned.add(named.source); if (present.has(named.source)) owners.push({ kind: "principal", principal: rec.from.principal }); } } const knownFiles = []; for (const principal of knownOwners) knownFiles.push({ file: principalRuleFileName(principal), principal }); const unnamed = []; for (const name of [...present].filter((n) => HASHED_BUCKET_FILE.test(n) && !owned.has(n)).sort()) { const knownAs = knownFiles.find((known) => known.file === name)?.principal; unnamed.push({ bucketId: name.slice(0, -".json".length), ...(knownAs !== undefined ? { knownAs } : {}) }); } return { owners, unnamed }; } export class FileDurableRulePartitionProvider { dir; onError; lock; orgPersistence; vetting; constructor(dir, onError, opts) { this.dir = dir; this.onError = onError; const options = receiveOptions(opts, "FileDurableRulePartitionProvider", FILE_DURABLE_RULE_PARTITION_PROVIDER_OPTION_KEYS); if (options.dataRoot !== undefined) assertAdoptionBootGate(options.dataRoot, "FileDurableRulePartitionProvider"); let said = false; const caseVariantsMet = new Set(); this.vetting = { platform: options.platform, modeBitsUnjudged: (where) => { if (said) return; said = true; discloseTo(this.onError, `the permission-rule store directory is not checked for being writable by other accounts: this platform reports no POSIX permission bits, so who else can write there is not verified here (at ${where})`); }, caseVariantFirstMet: (location) => { if (caseVariantsMet.has(location)) return false; caseVariantsMet.add(location); return true; }, }; } adoptionMarker() { const judged = judgeRuleAdoptionFile(this.dir); if ("corrupt" in judged) { const location = `${join(this.dir, ADOPTION_FILE)}${judged.detail !== undefined ? `: ${judged.detail}` : ""}`; const sentence = `the permission-rule store's adoption marker ${judged.corrupt}; refusing to resolve whose bucket this is until it is repaired`; throw unreadableError("readFailure" in judged ? systemFaultRefusal(this.onError, judged.readFailure, sentence, location) : { unreadable: refusalText(this.onError, sentence, location), code: PERMISSION_RULES_DAMAGED_BUCKET_CODE }); } return judged.marker; } markerFiles() { const adoption = this.adoptionMarker(); return adoption === undefined ? undefined : adoptionBucketFiles("adopted" in adoption ? adoption.adopted : adoption.marker); } originOf(name, door) { return { posture: door === "owner" ? "full" : "retire-only", stillOpens: () => { const named = this.markerFiles(); return named === undefined || (named.source !== name && (door === "owner" || named.target !== name)); }, }; } orgStatePersistence() { return this.fileOrgPersistence(); } fileOrgPersistence() { this.orgPersistence ??= new FileOrgRuleStatePersistence(this.dir, this.acquireWriteLock, this.onError, this.vetting); return this.orgPersistence; } acquireWriteLock = () => { if (this.lock !== undefined) return; assertSafeDirAtRequest(this.dir, this.onError, "write through", this.vetting); const lock = BootLock.fence(this.dir, "PERMISSION-RULES-WRITER-LOCK"); try { lock.acquire(); } catch (err) { throw err instanceof FileStoreLockError ? writerLockRefusal(err, this.onError) : err; } this.lock = lock; }; writerLock = { acquire: () => this.acquireWriteLock(), held: () => this.lock !== undefined }; forPrincipal(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"`); } if (reading.kind === "absent") { return { list: async () => ({ ...EMPTY_READ }), durability: "process-local" }; } const name = reading.name; const adoption = this.adoptionMarker(); if (adoption !== undefined) { const rec = "adopted" in adoption ? adoption.adopted : adoption.marker; if (rec.from.kind === "principal" && rec.from.principal === name) { return this.readOnlySourceView(principalRuleFileName(name), principalRuleFileName(rec.toPrincipal), adoptionFlipped(adoption)); } } return this.ownerPartition(principalRuleFileName(name)); } ownerPartition(name) { return new FileDurableRulePartition(this.dir, join(this.dir, name), this.writerLock, this.originOf(name, "owner"), this.onError, this.vetting); } readOnlySourceView(sourceName, targetName, flipped) { const pick = flipped ? targetName : existsSync(join(this.dir, sourceName)) ? sourceName : targetName; return readOnlyRuleStoreView(this.ownerPartition(pick)); } forLocalOwner() { const adoption = this.adoptionMarker(); if (adoption !== undefined) { const rec = "adopted" in adoption ? adoption.adopted : adoption.marker; if (rec.from.kind === "local-owner") { return this.readOnlySourceView(LOCAL_OWNER_FILE, principalRuleFileName(rec.toPrincipal), adoptionFlipped(adoption)); } } return this.ownerPartition(LOCAL_OWNER_FILE); } listBucketOwners(opts) { const knownOwners = receiveKnownOwners(opts); const faulted = (err, what) => unreadableError(systemFaultRefusal(this.onError, err, `the permission-rule store directory could not be ${what} (${err?.code ?? err?.name ?? "unknown"})`, `${this.dir}: ${thrownText(err)}`)); try { lstatSync(this.dir); } catch (err) { if (err?.code === "ENOENT") return Object.freeze({ owners: Object.freeze([]), unnamedBuckets: Object.freeze([]) }); throw faulted(err, "examined"); } let dirFault; try { dirFault = unsafeDirFault(this.dir, this.vetting); } catch (err) { throw faulted(err, "examined"); } if (dirFault !== undefined) { throw unreadableError({ unreadable: refusalText(this.onError, `the permission-rule store directory ${dirFault.text}; refusing to list its buckets`, this.dir), code: PERMISSION_RULES_DAMAGED_BUCKET_CODE, ...(dirFault.unsafe !== undefined ? { unsafe: dirFault.unsafe } : {}) }); } const adoption = this.adoptionMarker(); let names; try { names = readdirSync(this.dir); } catch (err) { throw faulted(err, "listed"); } const census = bucketCensusOf(names, adoption, knownOwners); if ("caseVariant" in census) { throw unreadableError(caseVariantRefusal(this.onError, this.vetting, `a file in the permission-rule store directory ${CASE_VARIANT_FAULT}; refusing to list its buckets`, join(this.dir, census.caseVariant))); } const unnamedBuckets = census.unnamed.map(({ bucketId, knownAs }) => { const file = `${bucketId}.json`; const partition = new FileDurableRulePartition(this.dir, join(this.dir, file), this.writerLock, this.originOf(file, "listed"), this.onError, this.vetting); return Object.freeze({ bucketId, ...(knownAs !== undefined ? { knownAs } : {}), partition }); }); return Object.freeze({ owners: Object.freeze([...census.owners]), unnamedBuckets: Object.freeze(unnamedBuckets) }); } dispose() { this.lock?.release(); this.lock = undefined; } } class FileOrgRuleStatePersistence { dir; acquireWriteLock; onError; vetting; file; writeChain = Promise.resolve(); constructor(dir, acquireWriteLock, onError, vetting) { this.dir = dir; this.acquireWriteLock = acquireWriteLock; this.onError = onError; this.vetting = vetting; this.file = join(dir, ORG_STATE_FILE); } readSync() { const refuse = (sentence, location = this.file) => { throw new Error(refusalText(this.onError, `${sentence}; refusing it whole — repair the file, or remove it (removing it gives up the last-known-good org snapshot and its anti-rollback mark)`, location)); }; const ioFault = (err) => `could not be read (${err?.code ?? err?.name ?? "unknown"})`; let dirFault; try { dirFault = unsafeDirFault(this.dir, this.vetting); } catch (err) { return refuse(`the permission-rule store directory ${ioFault(err)}`, `${this.dir}: ${thrownText(err)}`); } if (dirFault !== undefined) return refuse(`the permission-rule store directory ${dirFault.text}`, this.dir); const unreadable = (err) => { if (err?.code === "ENOENT") return undefined; return refuse(`the org state file ${ioFault(err)}`, `${this.file}: ${thrownText(err)}`); }; let st; try { st = lstatSync(this.file); } catch (err) { return unreadable(err); } if (st.isSymbolicLink() || !st.isFile()) return refuse("the org state file is a symlink or not a regular file"); let raw; try { raw = readFileSync(this.file, "utf8"); } catch (err) { return unreadable(err); } let parsed; try { parsed = JSON.parse(raw); } catch (err) { return refuse(`the org state file is not valid JSON (${err.message})`); } if (!isOrgStateFile(parsed)) return refuse("the org state file does not carry a readable org-state shape"); const { checksum, ...body } = parsed; if (checksum !== checksumOf(body)) return refuse("the org state file failed its integrity check"); return parsed.state; } async readOrgState() { return this.readSync(); } installOrgStateSync(state) { this.acquireWriteLock(); assertSafeDirAtRequest(this.dir, this.onError, "write through", this.vetting); state = jsonForm(state); const cur = this.readSync(); if (cur !== undefined && state.revisionHighWater < cur.revisionHighWater) { throw new OrgRevisionRefusal(`refusing to lower the org revision high-water mark (${cur.revisionHighWater} → ${state.revisionHighWater}) — an interleaved install must re-read and re-compare`); } if (cur !== undefined && state.snapshot.revision === cur.snapshot.revision && !sameOrgPolicyContent(state.snapshot, cur.snapshot)) { throw new OrgRevisionRefusal(`refusing to replace org revision ${state.snapshot.revision} with DIFFERENT policy content under the same revision — content changes must bump the revision`); } if (cur !== undefined && state.snapshot.revision === cur.snapshot.revision && state.snapshot.fetchedAtMs <= cur.snapshot.fetchedAtMs) return; const body = { schemaVersion: 1, state }; atomicPublish(this.dir, this.file, JSON.stringify({ ...body, checksum: checksumOf(body) }, null, 2)); const after = this.readSync(); if (after === undefined || canonicalize(after) !== canonicalize(state)) { const why = "the org state file did not read back as the version just written; whether the snapshot reached the bytes on disk is unobservable from here — reconcile by reading the file"; this.onError?.(why); throw new Error(why); } } async installOrgState(state) { const run = this.writeChain.then(() => this.installOrgStateSync(state), () => this.installOrgStateSync(state)); this.writeChain = run.then(() => undefined, () => undefined); await run; } } function readOnlyRuleStoreView(store) { return { list: () => store.list(), ...(store.quarantined !== undefined ? { quarantined: () => store.quarantined() } : {}), ...(store.durability !== undefined ? { durability: store.durability } : {}), ...(store.fidelity !== undefined ? { fidelity: store.fidelity } : {}), }; } export function principalRuleFileName(principal) { return `${createHash("sha256").update(principal, "utf8").digest("hex")}.json`; } export { LOCAL_OWNER_FILE };