Skip to content

Commit 06aae62

Browse files
[Agent: Claude] fix(lws): name/type gate moves into applyLwsWrite — the write choke point (review #2, JavaScriptSolidServer#10)
- writeTypeConsistency runs inside applyLwsWrite: HTTP PUT/POST and all three MCP write tools share ONE gate; the MCP bypass is closed - application/json gates as JSON-LD (pipeline parity) - non-RDF body at an RDF-extension name is refused (the SHACL-skip lie) - callers handle the new problem return; HTTP local gate calls deleted Co-Authored-By: Claude Opus 4.8 <[email protected]>
1 parent 4824fe2 commit 06aae62

6 files changed

Lines changed: 111 additions & 23 deletions

File tree

‎src/handlers/container.js‎

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ import { emitChange } from '../notifications/events.js';
1111
import { constraintProblem } from '../lws/admission.js';
1212
import { parseTypeLinks } from '../lws/type-metadata.js';
1313
import { applyLwsWrite } from '../lws/write.js';
14-
import { writeTypeConsistency } from '../lws/write-consistency.js';
1514

1615
/**
1716
* Get the storage path and resource URL for a request
@@ -110,16 +109,13 @@ export async function handlePost(request, reply) {
110109
content = Buffer.from('');
111110
}
112111

113-
// Spec §2: under --lws, store the submitted bytes verbatim; enforce
114-
// write-time name/type consistency instead of converting (B1 root fix).
115-
// The FINAL resource name (container path + slug) is what must agree
116-
// with the submitted type — not the container's own path.
112+
// Spec §2: under --lws, store the submitted bytes verbatim; the name/type
113+
// gate now runs inside applyLwsWrite (review #2 — the choke point every
114+
// write surface shares) against storagePath, which is the FINAL resource
115+
// name (container path + slug) — not here.
117116
// --lws-off keeps the byte-identical legacy Turtle/N3→JSON-LD conversion.
118117
const inputType = contentType.split(';')[0].trim().toLowerCase();
119-
if (request.lwsEnabled) {
120-
const c = writeTypeConsistency({ urlPath: newUrlPath, submittedType: contentType, lwsEnabled: true });
121-
if (!c.ok) return reply.code(400).type('application/problem+json').send(JSON.stringify(c.problem, null, 2));
122-
} else if (connegEnabled && (inputType === RDF_TYPES.TURTLE || inputType === RDF_TYPES.N3)) {
118+
if (!request.lwsEnabled && connegEnabled && (inputType === RDF_TYPES.TURTLE || inputType === RDF_TYPES.N3)) {
123119
try {
124120
const jsonLd = await toJsonLd(content, contentType, resourceUrl, connegEnabled, { graphEnvelope: false });
125121
content = Buffer.from(JSON.stringify(jsonLd, null, 2));
@@ -153,6 +149,9 @@ export async function handlePost(request, reply) {
153149
lwsEnabled: request.lwsEnabled,
154150
});
155151
if (!w.ok) {
152+
if (w.problem) {
153+
return reply.code(400).type('application/problem+json').send(JSON.stringify(w.problem, null, 2));
154+
}
156155
reply.header('content-type', 'application/problem+json');
157156
if (w.shapeUrl) reply.header('Link', `<${w.shapeUrl}>; rel="describedby"`);
158157
return reply.code(400).send(constraintProblem({

‎src/handlers/resource.js‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ import { turtleToJsonLd } from '../rdf/turtle.js';
2828
import { constraintProblem } from '../lws/admission.js';
2929
import { parseTypeLinks, typeStorePath, readDeclaredTypes } from '../lws/type-metadata.js';
3030
import { applyLwsWrite } from '../lws/write.js';
31-
import { writeTypeConsistency } from '../lws/write-consistency.js';
3231
import { filterReadableEntries } from '../lws/authorized-listing.js';
3332
import { serveStoredRdf, checkServable, isRdfSourceType, QUADS_OUTPUTS, nonRdfNotAcceptable } from '../rdf/serve.js';
3433

@@ -1824,14 +1823,12 @@ export async function handlePut(request, reply) {
18241823
content = Buffer.from('');
18251824
}
18261825

1827-
// Spec §2: under --lws, store the submitted bytes verbatim; enforce
1828-
// write-time name/type consistency instead of converting (B1 root fix).
1826+
// Spec §2: under --lws, store the submitted bytes verbatim; the name/type
1827+
// gate now runs inside applyLwsWrite (review #2 — the choke point every
1828+
// write surface shares), not here.
18291829
// --lws-off keeps the byte-identical legacy Turtle/N3→JSON-LD conversion.
18301830
const inputType = contentType.split(';')[0].trim().toLowerCase();
1831-
if (request.lwsEnabled) {
1832-
const c = writeTypeConsistency({ urlPath, submittedType: contentType, lwsEnabled: true });
1833-
if (!c.ok) return reply.code(400).type('application/problem+json').send(JSON.stringify(c.problem, null, 2));
1834-
} else if (connegEnabled && (inputType === RDF_TYPES.TURTLE || inputType === RDF_TYPES.N3)) {
1831+
if (!request.lwsEnabled && connegEnabled && (inputType === RDF_TYPES.TURTLE || inputType === RDF_TYPES.N3)) {
18351832
try {
18361833
const jsonLd = await toJsonLd(content, contentType, resourceUrl, connegEnabled, { graphEnvelope: false });
18371834
content = Buffer.from(JSON.stringify(jsonLd, null, 2));
@@ -1866,6 +1863,9 @@ export async function handlePut(request, reply) {
18661863
lwsEnabled: request.lwsEnabled,
18671864
});
18681865
if (!w.ok) {
1866+
if (w.problem) {
1867+
return reply.code(400).type('application/problem+json').send(JSON.stringify(w.problem, null, 2));
1868+
}
18691869
reply.header('content-type', 'application/problem+json');
18701870
if (w.shapeUrl) reply.header('Link', `<${w.shapeUrl}>; rel="describedby"`);
18711871
return reply.code(400).send(constraintProblem({

‎src/lws/write-consistency.js‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,20 +12,42 @@
1212
// ACL/.meta) and `.jsonld` (application/ld+json) — getContentType() maps both .acl
1313
// and .meta basenames straight to application/ld+json too, so those fall into the
1414
// second shape rather than needing a special case.
15+
//
16+
// Review 2026-07-12 (#2, #10): the gate runs inside applyLwsWrite now — the
17+
// choke point every write surface (HTTP PUT/POST + all MCP write tools)
18+
// shares — instead of at 2 HTTP call sites only. Two strengthenings: plain
19+
// application/json gates as JSON-LD (#10, asRdf below); a non-RDF body at an
20+
// RDF-extension name is refused (#2 — admission would skip SHACL for it on
21+
// write, yet the serving path RDF-serves the name on read).
1522
import { getContentType } from '../utils/url.js';
1623
import { RDF_TYPES } from '../rdf/conneg.js';
1724

1825
// The other RDF serializations — the only names a JSON-LD body may NOT sit at.
1926
const OTHER_RDF = new Set([RDF_TYPES.TURTLE, RDF_TYPES.N3, RDF_TYPES.NTRIPLES, RDF_TYPES.NQUADS]);
2027
const RDF = new Set([...OTHER_RDF, RDF_TYPES.JSON_LD]);
2128
const main = (t) => (t || '').split(';')[0].trim().toLowerCase();
29+
// #10 (review 2026-07-12): plain application/json gates as JSON-LD — the rest
30+
// of the pipeline already reads it that way (isRdfType/toJsonLd/isRdfBody).
31+
const asRdf = (t) => (t === 'application/json' ? RDF_TYPES.JSON_LD : t);
2232

2333
export function writeTypeConsistency({ urlPath, submittedType, lwsEnabled }) {
2434
if (!lwsEnabled) return { ok: true };
25-
const sub = main(submittedType);
26-
if (!RDF.has(sub)) return { ok: true }; // non-RDF bodies: not our concern
35+
const sub = asRdf(main(submittedType));
2736
const nameType = main(getContentType(urlPath)); // extension-derived (octet-stream if none)
2837

38+
if (!RDF.has(sub)) {
39+
// #2 worst case (review 2026-07-12): a non-RDF body at an RDF-extension
40+
// name would be admission-skipped on write yet RDF-served on read.
41+
// Refuse the lie in this direction too — symmetric with the RDF-body-at-
42+
// wrong-name check below. Extensionless and non-RDF names stay legitimate
43+
// (not our concern).
44+
if (RDF.has(nameType)) {
45+
return problem(urlPath, sub || 'unspecified',
46+
`the resource name implies ${nameType} but the body is ${sub || 'unspecified'}; rename to a non-RDF extension or submit the body as ${nameType}`);
47+
}
48+
return { ok: true };
49+
}
50+
2951
if (sub === RDF_TYPES.JSON_LD) {
3052
// Only reject when the name implies a DIFFERENT RDF serialization — that's the
3153
// lie (B1). Extensionless and .jsonld/.acl/.meta (nameType === application/ld+json)

‎src/lws/write.js‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,23 @@
11
import { admit, urlToStoragePath } from './admission.js';
22
import { captureDeclaredTypes, typeStorePath } from './type-metadata.js';
3+
import { writeTypeConsistency } from './write-consistency.js';
34

45
/**
5-
* Shared LWS write pipeline: SHACL admission → storage.write → type-capture.
6-
* Request-agnostic so both the HTTP handlers and the MCP write tools use ONE
7-
* enforcement path (the drift that let MCP bypass admission becomes impossible).
6+
* Shared LWS write pipeline: name/type gate → SHACL admission → storage.write
7+
* → type-capture. Request-agnostic so both the HTTP handlers and the MCP
8+
* write tools use ONE enforcement path (the drift that let MCP bypass both
9+
* the gate and admission becomes impossible — review #2/#10).
810
* Callers own their own reply/tool framing; this returns data only.
911
*/
1012
export async function applyLwsWrite({
1113
storage, storagePath, resourceUrl, content, contentType, declaredTypes = [], lwsEnabled,
1214
}) {
15+
// #2 (review 2026-07-12): the gate runs at THE choke point every write
16+
// surface shares (HTTP PUT/POST + all MCP write tools) — no surface can
17+
// store a name/type lie or an admission-skipped body at an RDF name.
18+
const c = writeTypeConsistency({ urlPath: storagePath, submittedType: contentType, lwsEnabled });
19+
if (!c.ok) return { ok: false, problem: c.problem };
20+
1321
let shapeUrl = null;
1422
let advisories = [];
1523

‎src/mcp/tools.js‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ async function write_resource({ path, content, contentType, types }, ctx) {
5959
declaredTypes: Array.isArray(types) ? types : [],
6060
lwsEnabled: ctx.lwsEnabled
6161
});
62-
if (!w.ok) return admissionError(path, { violations: w.violations, shapeUrl: w.shapeUrl });
62+
if (!w.ok) return w.problem ? toolError(w.problem.detail) : admissionError(path, { violations: w.violations, shapeUrl: w.shapeUrl });
6363
if (!w.wrote) return toolError(`write failed: ${path}`);
6464
emitChange(buildUrl(ctx, path));
6565
return toolText(`wrote ${path} (${Buffer.byteLength(content, 'utf8')} bytes)`);
@@ -91,7 +91,7 @@ async function create_resource({ container, slug, content, contentType, isContai
9191
declaredTypes: Array.isArray(types) ? types : [],
9292
lwsEnabled: ctx.lwsEnabled
9393
});
94-
if (!w.ok) return admissionError(childPath, { violations: w.violations, shapeUrl: w.shapeUrl });
94+
if (!w.ok) return w.problem ? toolError(w.problem.detail) : admissionError(childPath, { violations: w.violations, shapeUrl: w.shapeUrl });
9595
if (!w.wrote) return toolError(`write failed: ${childPath}`);
9696
emitChange(buildUrl(ctx, childPath));
9797
return toolText(`created ${childPath}`);
@@ -372,6 +372,7 @@ async function put_typed_resource({ path, content, contentType, types, described
372372
if (metaSnapshot === null) await storage.remove(metaPath);
373373
else await storage.write(metaPath, metaSnapshot, { contentType: 'application/ld+json' });
374374
}
375+
if (w.problem) return toolError(w.problem.detail); // gate reject (review #2/#10)
375376
return w.ok ? toolError(`write failed: ${path}`) : admissionError(path, { violations: w.violations, shapeUrl: w.shapeUrl });
376377
}
377378
emitChange(buildUrl(ctx, path));
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// test/lws-write-gate-chokepoint.test.js
2+
// Review 2026-07-12 #2/#10: the name/type gate must hold at EVERY write
3+
// surface (it lived at the 2 HTTP call sites only), and application/json
4+
// must gate as JSON-LD (the rest of the pipeline already treats it so).
5+
import { test } from 'node:test';
6+
import assert from 'node:assert/strict';
7+
import { callTool } from '../src/mcp/tools.js';
8+
import { startLwsPod, ownerCtx, request, createTestPod, startTestServer, stopTestServer, assertStatus } from './helpers.js';
9+
10+
test('MCP write_resource: text/plain body at a .ttl name is refused (gate at choke point)', async (t) => {
11+
const p = await startLwsPod(t);
12+
const ctx = { ...ownerCtx(p), lwsEnabled: true };
13+
const r = await callTool('write_resource', {
14+
path: `/${p.podName}/evil.ttl`, content: 'not turtle at all', // contentType omitted -> text/plain
15+
}, ctx);
16+
assert.equal(r.isError, true);
17+
assert.match(r.content[0].text, /name implies text\/turtle/);
18+
});
19+
20+
test('MCP write_resource: Turtle body at a .jsonld name is refused', async (t) => {
21+
const p = await startLwsPod(t);
22+
const ctx = { ...ownerCtx(p), lwsEnabled: true };
23+
const r = await callTool('write_resource', {
24+
path: `/${p.podName}/lie.jsonld`, content: '<#s> <#p> <#o>.', contentType: 'text/turtle',
25+
}, ctx);
26+
assert.equal(r.isError, true);
27+
});
28+
29+
test('MCP put_typed_resource: extensionless write still passes (JSS idiom preserved)', async (t) => {
30+
const p = await startLwsPod(t);
31+
const ctx = { ...ownerCtx(p), lwsEnabled: true };
32+
const r = await callTool('put_typed_resource', {
33+
path: `/${p.podName}/shape1`, content: JSON.stringify({ '@id': '#it' }), contentType: 'application/ld+json',
34+
}, ctx);
35+
assert.equal(r.isError, false);
36+
});
37+
38+
test('HTTP PUT: application/json at .ttl name 400s; at .jsonld name passes (#10)', async () => {
39+
await startTestServer({ lws: true, conneg: true });
40+
try {
41+
await createTestPod('gatejson');
42+
const bad = await request('/gatejson/x.ttl', {
43+
method: 'PUT', auth: 'gatejson',
44+
headers: { 'Content-Type': 'application/json' }, body: '{"a":1}',
45+
});
46+
assertStatus(bad, 400);
47+
const ok = await request('/gatejson/x.jsonld', {
48+
method: 'PUT', auth: 'gatejson',
49+
headers: { 'Content-Type': 'application/json' }, body: '{"a":1}',
50+
});
51+
assert.ok(ok.status === 201 || ok.status === 204 || ok.status === 200);
52+
const plain = await request('/gatejson/y.ttl', {
53+
method: 'PUT', auth: 'gatejson',
54+
headers: { 'Content-Type': 'text/plain' }, body: 'junk',
55+
});
56+
assertStatus(plain, 400);
57+
} finally { await stopTestServer(); }
58+
});

0 commit comments

Comments
 (0)