feat(client): inbox mechanism, write-guard, SPARQL injection hardening

Polyfill capabilities landed for Festipod's T02 features (all generic,
zero-domain — the consumer injects the domain).

- inbox: implement the previously-stubbed namespace. post(target,{from?,
  payload,ts?}) deposits {from,payload,ts} as RDF via docs.sparqlUpdate (the
  real injected ng, never makeNg); read/materialize + watch emulate the curator
  in-lib (deposits read via docs.sparqlQuery). `from` optional = anonymity.
- write-guard: caps.hasWritePolicy() + ng-proxy.sparql_update rejects when the
  target doc is under a write policy and the current user lacks its write cap;
  passthrough otherwise (no regression). Read-cap registry unchanged.
- sparql.ts (new): escapeLiteral / escapeIri / assertNuri, exported from index.
  store-registry now escapes every literal and validates/encodes every IRI-
  position value — closes a SPARQL-injection hole where an untrusted username
  could inject triples into the shim (the account→doc-NURI trust root).

Tests: inbox, sparql (incl. injection), ng-proxy write-guard, isolation-active.
68 tests pass; tsc --noEmit rc=0.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Sylvain Duchesne
2026-07-03 15:51:00 +02:00
parent 654cb90d99
commit d804a436d7
12 changed files with 924 additions and 42 deletions
+113 -6
View File
@@ -43,13 +43,31 @@ test("throws a clear error when configureStoreRegistry() was not called", async
interface Quad { g: string; s: string; p: string; o: string }
/** Reverse of the lib's escapeLiteral: single left-to-right pass over `\x`. */
function unescapeLiteral(s: string): string {
let out = "";
for (let i = 0; i < s.length; i++) {
if (s[i] === "\\" && i + 1 < s.length) {
const next = s[++i];
out +=
next === "n" ? "\n" : next === "r" ? "\r" : next === "t" ? "\t" : next;
} else {
out += s[i];
}
}
return out;
}
function makeFakeNg() {
const quads: Quad[] = [];
let docCounter = 0;
const doc_create = mock(async (..._a: unknown[]) => `did:ng:o:doc${++docCounter}`);
// Parses `INSERT DATA { GRAPH <g> { <s> <p> "o"/<o>/;-lists } }`.
// Parses `INSERT DATA { GRAPH <g> { <s> <p> "o"/<o>/;-lists } }`. The literal
// pattern honours backslash-escapes (`\"`, `\\`, `\n`…) so an escaped quote
// inside a value does NOT terminate the literal — this is what proves the
// injection escaping keeps the query well-formed.
const sparql_update = mock(async (...a: unknown[]) => {
const query = a[1] as string;
const gm = query.match(/GRAPH <([^>]+)>\s*\{([\s\S]*)\}/);
@@ -60,16 +78,14 @@ function makeFakeNg() {
const sm = body.match(/<([^>]+)>/);
if (!sm) return undefined;
const s = sm[1]!;
// Predicate/object pairs: `<p> "o"` or `<p> <o>` (a == rdf:type ignored form
// handled as literal-free; here the registry only uses <p> "literal" and
// <p> <iri> and `a <type>`).
const pairRe = /(?:a|<([^>]+)>)\s+(?:"([^"]*)"|<([^>]+)>)/g;
// Predicate/object pairs: `<p> "o"` (escape-aware) or `<p> <o>`; `a <type>`.
const pairRe = /(?:a|<([^>]+)>)\s+(?:"((?:[^"\\]|\\.)*)"|<([^>]+)>)/g;
let m: RegExpExecArray | null;
// Skip the subject token so we don't treat it as a predicate.
const after = body.slice(body.indexOf(sm[0]) + sm[0].length);
while ((m = pairRe.exec(after)) !== null) {
const p = m[1] ?? "urn:ng-eventually:shim:Account"; // `a` → rdf:type-ish
const o = m[2] ?? m[3] ?? "";
const o = m[2] !== undefined ? unescapeLiteral(m[2]) : (m[3] ?? "");
quads.push({ g, s, p, o });
}
return undefined;
@@ -190,6 +206,97 @@ test("allAccounts reflects every ensured account", async () => {
expect(names).toEqual(["Gina", "Hank"]);
});
// --- SPARQL injection hardening (F1) --------------------------------------
//
// A malicious username must NOT be able to break out of the literal / IRI it
// lands in and inject arbitrary triples into the shim (the account→doc trust
// root). We inspect the exact SPARQL string the registry hands to sparql_update.
/** The raw INSERT DATA string produced by ensureAccount for `username`. */
async function insertFor(username: string): Promise<string> {
await ensureAccount(username);
const calls = fake.sparql_update.mock.calls;
return calls[calls.length - 1]![1] as string;
}
/** Count RAW (un-escaped) double-quotes — i.e. `"` not preceded by a `\`.
* Strip escaped pairs (`\\`, `\"`, …) first so only delimiter quotes remain. */
function rawQuoteCount(s: string): number {
const withoutEscapes = s.replace(/\\./g, "");
return (withoutEscapes.match(/"/g) ?? []).length;
}
test("injection: username with a quote cannot open extra literals", async () => {
const evil = 'x" ; <urn:evil> "pwn';
const update = await insertFor(evil);
// A well-formed INSERT DATA with 4 predicate literals has exactly 8 raw
// quotes (the delimiters). The injected `"` must have been escaped, so the
// count stays 8 — no extra literal was opened.
expect(rawQuoteCount(update)).toBe(8);
// The escaped username is present as a single literal value — the injected
// `<urn:evil>` survives only as INERT text inside that literal (its
// surrounding quotes are escaped `\"`), never as query syntax.
expect(update).toContain('"x\\" ; <urn:evil> \\"pwn"');
});
test("injection: username with '>' cannot break out of the account-subject IRI", async () => {
const evil = "x> <urn:evil";
const update = await insertFor(evil);
// The account subject is `<urn:ng-eventually:shim:account:...>` — the encoded
// username must NOT contain a raw `>` that would close the IRI early.
const subjMatch = update.match(/<urn:ng-eventually:shim:account:([^>]*)>/)!;
expect(subjMatch).not.toBeNull();
expect(subjMatch[1]).not.toMatch(/[<>" ]/); // fully percent-encoded
expect(subjMatch[1]).toContain("%3E"); // the `>` became %3E
});
test("injection: newline / control chars in username are neutralised", async () => {
const evil = "a\nb\tc";
const update = await insertFor(evil);
// In the literal: escaped to \n / \t (no raw control char).
expect(update).toContain('"a\\nb\\tc"');
// In the IRI subject: percent-encoded.
const subjMatch = update.match(/<urn:ng-eventually:shim:account:([^>]*)>/)!;
expect(subjMatch[1]).toContain("%0A");
expect(subjMatch[1]).toContain("%09");
});
test("injection: '; DELETE'-style payload stays inert inside the literal", async () => {
const evil = 'x"} ; DELETE WHERE { ?s ?p ?o } ; INSERT DATA { <a> <b> "';
const update = await insertFor(evil);
// The whole attack survives, escaped, as ONE literal value — the injected
// `"}` cannot close the literal/graph, so DELETE/second-INSERT stay text.
expect(update).toContain(escapeLiteralRef(evil));
// Quote count stays even (all delimiters balanced; the injected `"` escaped):
// 4 predicate literals → 8 raw delimiter quotes, nothing extra opened.
expect(rawQuoteCount(update)).toBe(8);
// The injected `"}` did not survive as raw syntax (it was escaped to `\"}`).
expect(update).not.toMatch(/[^\\]"} ; DELETE/);
});
// Local mirror of the lib's escapeLiteral so the assertion is self-checking.
function escapeLiteralRef(v: string): string {
return `"${v
.replace(/\\/g, "\\\\")
.replace(/"/g, '\\"')
.replace(/\n/g, "\\n")
.replace(/\r/g, "\\r")
.replace(/\t/g, "\\t")}"`;
}
test("injection: a malicious username still round-trips through the shim", async () => {
const evil = 'eve" ; <urn:evil> "x';
const rec = await ensureAccount(evil);
expect(rec.username).toBe(evil);
resetRegistryCache();
const map = await loadShim();
// The stored username came back verbatim (escaping is lossless) under its
// normalized key, and exactly ONE account exists (no injected extra subject).
const key = evil.trim().replace(/^@+/, "").toLowerCase();
expect(map.get(key)?.username).toBe(evil);
expect(map.size).toBe(1);
});
test("normalizeUser defaults to trim when not provided", async () => {
const ng = makeFakeNg();
configure({ ng: ng as any, useShape: (() => {}) as any });