Skip to content

Commit e2c20f4

Browse files
[Agent: Claude] fix(lws): PATCH parses stored form by its media type; JSON Merge Patch; bodied writes require Content-Type (review JavaScriptSolidServer#7, P1, P2)
- handlePatch dispatches on the stored media type: verbatim Turtle-family resources parse via toDataset, patch on the JSON-LD projection, and serialize back in the stored format (Solid #server-patch-n3-accept MUST) - application/merge-patch+json accepted under --lws (RFC 7386, new src/patch/merge-patch.js); non-JSON stored answers a teaching 415; Accept-Patch advertises it (--lws-off value byte-identical) - bodied PUT/POST/PATCH without Content-Type answers 400 problem+json under --lws (Solid #server-content-type-missing MUST) — the wildcard content parser buffers such bodies, nothing upstream guards it - datasetToJsonLd exported from serve.js for the patch projection Co-Authored-By: Claude Opus 4.8 <[email protected]>
1 parent 245b440 commit e2c20f4

8 files changed

Lines changed: 349 additions & 11 deletions

File tree

‎src/handlers/container.js‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import * as storage from '../storage/filesystem.js';
22
import { initializeQuota, checkQuota, updateQuotaUsage } from '../storage/quota.js';
33
import { getAllHeaders } from '../ldp/headers.js';
4-
import { isContainer, getEffectiveUrlPath, getPodName } from '../utils/url.js';
4+
import { isContainer, getEffectiveUrlPath, getPodName, isBodiedWithoutContentType, missingContentTypeProblem } from '../utils/url.js';
55
import { generateProfile, generatePreferences, generateTypeIndex, serialize } from '../webid/profile.js';
66
import { generateOwnerAcl, generatePrivateAcl, generateInboxAcl, generatePublicFolderAcl, serializeAcl, relativizeOwnerWebId } from '../wac/parser.js';
77
import { provisionOwnerKey, assertProvisionKeysCompatible } from '../keys/provision.js';
@@ -37,6 +37,16 @@ export async function handlePost(request, reply) {
3737

3838
const { urlPath, storagePath } = getRequestPaths(request);
3939

40+
// P2 (Solid #server-content-type-missing MUST): a bodied write with no
41+
// Content-Type must 400, not silently fall through to canAcceptInput('').
42+
// (The target resource URL isn't assigned yet at POST time — the
43+
// container URL is the closest "instance" available.)
44+
if (request.lwsEnabled && isBodiedWithoutContentType(request)) {
45+
const containerUrl = `${request.protocol}://${request.hostname}${urlPath}`;
46+
return reply.code(400).type('application/problem+json')
47+
.send(JSON.stringify(missingContentTypeProblem(containerUrl), null, 2));
48+
}
49+
4050
// Ensure target is a container
4151
if (!isContainer(urlPath)) {
4252
return reply.code(405).send({ error: 'POST only allowed on containers' });

‎src/handlers/resource.js‎

Lines changed: 151 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@ import { getAllHeaders, getNotFoundHeaders, representationLinks } from '../ldp/h
55
import { generateContainerJsonLd, generateLwsContainer, serializeJsonLd } from '../ldp/container.js';
66
import { generateLinkset } from '../lws/linkset.js';
77
import { describedbyTargets, conformsToTargets } from '../lws/constraint.js';
8-
import { isContainer, getContentType, isRdfContentType, getEffectiveUrlPath, safeJsonParse, getPodName, parentContainerUrl } from '../utils/url.js';
8+
import { isContainer, getContentType, isRdfContentType, getEffectiveUrlPath, safeJsonParse, getPodName, parentContainerUrl, isBodiedWithoutContentType, missingContentTypeProblem } from '../utils/url.js';
99
import { parseN3Patch, applyN3Patch, validatePatch } from '../patch/n3-patch.js';
1010
import { parseSparqlUpdate, applySparqlUpdate } from '../patch/sparql-update.js';
11+
import { applyMergePatch } from '../patch/merge-patch.js';
12+
import { toDataset } from '../rdf/dataset.js';
1113
import {
1214
selectContentType,
1315
canAcceptInput,
@@ -29,7 +31,7 @@ import { constraintProblem } from '../lws/admission.js';
2931
import { parseTypeLinks, typeStorePath, readDeclaredTypes } from '../lws/type-metadata.js';
3032
import { applyLwsWrite } from '../lws/write.js';
3133
import { filterReadableEntries } from '../lws/authorized-listing.js';
32-
import { serveStoredRdf, checkServable, isRdfSourceType, QUADS_OUTPUTS, nonRdfNotAcceptable } from '../rdf/serve.js';
34+
import { serveStoredRdf, checkServable, isRdfSourceType, QUADS_OUTPUTS, nonRdfNotAcceptable, datasetToJsonLd, datasetToFormat } from '../rdf/serve.js';
3335

3436
/**
3537
* Live reload script - injected into HTML when --live-reload is enabled
@@ -42,6 +44,13 @@ const LIVE_RELOAD_SCRIPT = `<script>(function(){var ws=new WebSocket((location.p
4244
// where a cached data variant was served on top-level navigation (#315).
4345
const RDF_CACHE_CONTROL = 'private, no-cache, must-revalidate';
4446

47+
// #7 (Solid #server-patch-n3-accept MUST): stored types PATCH must parse by
48+
// real media type rather than blind JSON — the n3 family (verbatim under
49+
// --lws). JSON/JSON-LD stays on the legacy safeJsonParse-first flow below.
50+
const PATCH_TURTLE_FAMILY = new Set([
51+
RDF_TYPES.TURTLE, RDF_TYPES.N3, RDF_TYPES.NTRIPLES, RDF_TYPES.NQUADS,
52+
]);
53+
4554
// Detects when the request's Accept header explicitly names a JSON
4655
// media type. Used by the container/index.html branches of GET and HEAD
4756
// to decide whether to surface the embedded JSON-LD data island —
@@ -1783,6 +1792,15 @@ export async function handlePut(request, reply) {
17831792
}
17841793

17851794
const { urlPath, storagePath, resourceUrl } = getRequestPaths(request);
1795+
1796+
// P2 (Solid #server-content-type-missing MUST): a bodied write with no
1797+
// Content-Type must 400, not silently fall through to canAcceptInput('')
1798+
// (which treats absence as accept-anything).
1799+
if (request.lwsEnabled && isBodiedWithoutContentType(request)) {
1800+
return reply.code(400).type('application/problem+json')
1801+
.send(JSON.stringify(missingContentTypeProblem(resourceUrl), null, 2));
1802+
}
1803+
17861804
const connegEnabled = request.connegEnabled || false;
17871805
// Spec §4a: --lws mandates the negotiation surface; conneg is implied by it.
17881806
const negotiate = connegEnabled || request.lwsEnabled;
@@ -2065,6 +2083,94 @@ export async function handleOptions(request, reply) {
20652083
return reply.code(204).send();
20662084
}
20672085

2086+
/**
2087+
* #7 (Solid #server-patch-n3-accept MUST): PATCH a verbatim-stored
2088+
* Turtle-family resource (resourceExists && storedType is Turtle/N3/NT/NQ).
2089+
* Projects stored bytes -> RDF dataset -> expanded JSON-LD (the same seam
2090+
* the serving arm uses, src/rdf/serve.js datasetToJsonLd) since both
2091+
* n3-patch.js and sparql-update.js operate at the JSON-LD document level,
2092+
* then serializes back through toDataset/datasetToFormat so the write lands
2093+
* in the SAME stored format — Content-Type identity is preserved.
2094+
*/
2095+
async function patchTurtleFamilyResource(request, reply, { storagePath, resourceUrl, storedType, isSparqlUpdate }) {
2096+
const existingContent = await storage.read(storagePath);
2097+
if (existingContent === null) {
2098+
return reply.code(500).send({ error: 'Read error' });
2099+
}
2100+
2101+
let dataset;
2102+
try {
2103+
dataset = await toDataset(existingContent, storedType, resourceUrl);
2104+
} catch (e) {
2105+
return reply.code(409).type('application/problem+json').send(JSON.stringify({
2106+
type: 'about:blank', title: 'Conflict', status: 409,
2107+
detail: `the stored document did not parse as ${storedType} (${e.message}).`,
2108+
instance: resourceUrl,
2109+
}, null, 2));
2110+
}
2111+
// datasetToJsonLd returns a bare array of expanded nodes (jsonld.fromRDF's
2112+
// default-graph form) — neither patch applier's native shape (n3-patch.js
2113+
// wants {'@graph': [...]}, sparql-update.js wants the bare array), so each
2114+
// branch below adapts on the way in/out rather than changing the appliers.
2115+
const nodes = await datasetToJsonLd(dataset);
2116+
2117+
const patchContent = Buffer.isBuffer(request.body) ? request.body.toString() : request.body;
2118+
let updatedNodes;
2119+
2120+
if (isSparqlUpdate) {
2121+
let update;
2122+
try {
2123+
update = parseSparqlUpdate(patchContent, resourceUrl);
2124+
} catch (e) {
2125+
return reply.code(400).send({ error: 'Bad Request', message: 'Invalid SPARQL Update: ' + e.message });
2126+
}
2127+
try {
2128+
const result = applySparqlUpdate(nodes, update, resourceUrl);
2129+
// applySparqlUpdate collapses a single-node result to a bare object.
2130+
updatedNodes = Array.isArray(result) ? result : [result];
2131+
} catch (e) {
2132+
return reply.code(409).send({ error: 'Conflict', message: 'Failed to apply SPARQL Update: ' + e.message });
2133+
}
2134+
} else {
2135+
let patch;
2136+
try {
2137+
patch = parseN3Patch(patchContent, resourceUrl);
2138+
} catch (e) {
2139+
return reply.code(400).send({ error: 'Bad Request', message: 'Invalid N3 Patch format: ' + e.message });
2140+
}
2141+
try {
2142+
const result = applyN3Patch({ '@graph': nodes }, patch, resourceUrl);
2143+
updatedNodes = Array.isArray(result['@graph']) ? result['@graph'] : nodes;
2144+
} catch (e) {
2145+
return reply.code(409).send({ error: 'Conflict', message: 'Failed to apply patch: ' + e.message });
2146+
}
2147+
}
2148+
2149+
let updatedDataset;
2150+
try {
2151+
updatedDataset = await toDataset(JSON.stringify(updatedNodes), RDF_TYPES.JSON_LD, resourceUrl);
2152+
} catch (e) {
2153+
return reply.code(409).send({ error: 'Conflict', message: 'Patch produced an invalid document: ' + e.message });
2154+
}
2155+
const updatedContent = await datasetToFormat(updatedDataset, QUADS_OUTPUTS[storedType] || RDF_TYPES.NQUADS);
2156+
2157+
const success = await storage.write(storagePath, Buffer.from(updatedContent));
2158+
if (!success) {
2159+
return reply.code(500).send({ error: 'Write failed' });
2160+
}
2161+
2162+
const origin = request.headers.origin;
2163+
const headers = getAllHeaders({ isContainer: false, origin, resourceUrl, lwsEnabled: request.lwsEnabled });
2164+
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
2165+
2166+
if (request.notificationsEnabled) {
2167+
emitChange(resourceUrl);
2168+
}
2169+
2170+
// The resource already existed (dispatch precondition) — always 204.
2171+
return reply.code(204).send();
2172+
}
2173+
20682174
/**
20692175
* Handle PATCH request
20702176
* Supports N3 Patch format (text/n3) and SPARQL Update for updating RDF resources
@@ -2077,6 +2183,13 @@ export async function handlePatch(request, reply) {
20772183

20782184
const { urlPath, storagePath, resourceUrl } = getRequestPaths(request);
20792185

2186+
// P2 (Solid #server-content-type-missing MUST): a bodied write with no
2187+
// Content-Type must 400, not fall through to a guessed patch type.
2188+
if (request.lwsEnabled && isBodiedWithoutContentType(request)) {
2189+
return reply.code(400).type('application/problem+json')
2190+
.send(JSON.stringify(missingContentTypeProblem(resourceUrl), null, 2));
2191+
}
2192+
20802193
// Don't allow PATCH to containers
20812194
if (isContainer(urlPath)) {
20822195
return reply.code(409).send({ error: 'Cannot PATCH containers' });
@@ -2086,11 +2199,16 @@ export async function handlePatch(request, reply) {
20862199
const contentType = request.headers['content-type'] || '';
20872200
const isN3Patch = contentType.includes('text/n3') || contentType.includes('application/n3');
20882201
const isSparqlUpdate = contentType.includes('application/sparql-update');
2202+
// P1 (LWS update-resource MUST: JSON Merge Patch, RFC 7386) — --lws only;
2203+
// the --lws-off 415 gate below stays byte-identical (isMergePatch false).
2204+
const isMergePatch = request.lwsEnabled
2205+
&& contentType.split(';')[0].trim().toLowerCase() === 'application/merge-patch+json';
20892206

2090-
if (!isN3Patch && !isSparqlUpdate) {
2207+
if (!isN3Patch && !isSparqlUpdate && !isMergePatch) {
20912208
return reply.code(415).send({
20922209
error: 'Unsupported Media Type',
2093-
message: 'PATCH requires Content-Type: text/n3 (N3 Patch) or application/sparql-update (SPARQL Update)'
2210+
message: 'PATCH requires Content-Type: text/n3 (N3 Patch), application/sparql-update (SPARQL Update)'
2211+
+ (request.lwsEnabled ? ', or application/merge-patch+json (JSON Merge Patch)' : '')
20942212
});
20952213
}
20962214

@@ -2109,6 +2227,21 @@ export async function handlePatch(request, reply) {
21092227
}
21102228
}
21112229

2230+
// #7: a verbatim-stored Turtle-family resource is parsed by its real media
2231+
// type (src/rdf/dataset.js toDataset), not blindly as JSON-LD — the legacy
2232+
// flow below assumes JSON-LD and 409s every Turtle/N3/NT/NQ PATCH target.
2233+
const storedType = (request.lwsEnabled && resourceExists) ? getContentType(storagePath) : null;
2234+
if (storedType && PATCH_TURTLE_FAMILY.has(storedType)) {
2235+
if (isMergePatch) {
2236+
return reply.code(415).type('application/problem+json').send(JSON.stringify({
2237+
type: 'about:blank', title: 'Unsupported Media Type', status: 415,
2238+
detail: `JSON Merge Patch applies to JSON documents; this resource is ${storedType} — use text/n3 (N3 Patch) or application/sparql-update.`,
2239+
instance: resourceUrl,
2240+
}, null, 2));
2241+
}
2242+
return patchTurtleFamilyResource(request, reply, { storagePath, resourceUrl, storedType, isSparqlUpdate });
2243+
}
2244+
21122245
// Read existing content or start with empty JSON-LD document
21132246
let document;
21142247
let htmlWrapper = null; // Track HTML wrapper for data island re-embedding
@@ -2250,7 +2383,20 @@ export async function handlePatch(request, reply) {
22502383

22512384
let updatedDocument;
22522385

2253-
if (isSparqlUpdate) {
2386+
if (isMergePatch) {
2387+
// P1 (LWS update-resource MUST, RFC 7386): merge-patch applies straight
2388+
// to the stored JSON/JSON-LD document — no triple-level projection needed.
2389+
let patchObj;
2390+
try {
2391+
patchObj = safeJsonParse(patchContent);
2392+
} catch (e) {
2393+
return reply.code(400).send({
2394+
error: 'Bad Request',
2395+
message: 'Invalid JSON Merge Patch: ' + e.message
2396+
});
2397+
}
2398+
updatedDocument = applyMergePatch(document, patchObj);
2399+
} else if (isSparqlUpdate) {
22542400
// Handle SPARQL Update
22552401
let update;
22562402
try {

‎src/ldp/headers.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,8 @@ export function getResponseHeaders({ isContainer = false, etag = null, contentTy
6868
headers['WAC-Allow'] = wacAllow;
6969
}
7070

71-
// Add Accept-* headers (conneg-aware)
72-
const acceptHeaders = getAcceptHeaders(connegEnabled, isContainer);
71+
// Add Accept-* headers (conneg-aware; lwsEnabled adds merge-patch to Accept-Patch — P1)
72+
const acceptHeaders = getAcceptHeaders(connegEnabled, isContainer, lwsEnabled);
7373
Object.assign(headers, acceptHeaders);
7474

7575
// Add Updates-Via header for WebSocket notifications discovery

‎src/patch/merge-patch.js‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// RFC 7386 JSON Merge Patch (P1 — LWS update-resource MUST: "MUST minimally
2+
// support JSON Merge Patch"). `null` deletes a key; nested objects merge
3+
// recursively; anything else (array, scalar) replaces wholesale.
4+
export function applyMergePatch(target, patch) {
5+
if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) return patch;
6+
const out = (target && typeof target === 'object' && !Array.isArray(target)) ? { ...target } : {};
7+
for (const [k, v] of Object.entries(patch)) {
8+
if (v === null) delete out[k];
9+
else out[k] = applyMergePatch(out[k], v);
10+
}
11+
return out;
12+
}

‎src/rdf/conneg.js‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -319,8 +319,12 @@ export function getVaryHeader(connegEnabled, mashlibEnabled = false, lwsEnabled
319319
* strict contract that every media type matching the wildcard will be
320320
* accepted by canAcceptInput() (e.g., application/n-triples and
321321
* application/rdf+xml are not accepted).
322+
*
323+
* @param {boolean} lwsEnabled - P1 (LWS update-resource MUST: JSON Merge
324+
* Patch, RFC 7386): under --lws, PATCH also accepts merge-patch+json, so
325+
* advertise it. The --lws-off Accept-Patch value stays byte-identical.
322326
*/
323-
export function getAcceptHeaders(connegEnabled, isContainer = false) {
327+
export function getAcceptHeaders(connegEnabled, isContainer = false, lwsEnabled = false) {
324328
const headers = {};
325329

326330
if (isContainer) {
@@ -333,7 +337,8 @@ export function getAcceptHeaders(connegEnabled, isContainer = false) {
333337
? `${RDF_TYPES.JSON_LD}, application/json, ${RDF_TYPES.TURTLE}, ${RDF_TYPES.N3}, */*`
334338
: `${RDF_TYPES.JSON_LD}, application/json, */*`;
335339

336-
headers['Accept-Patch'] = 'text/n3, application/sparql-update';
340+
headers['Accept-Patch'] = 'text/n3, application/sparql-update'
341+
+ (lwsEnabled ? ', application/merge-patch+json' : '');
337342

338343
return headers;
339344
}

‎src/rdf/serve.js‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,9 @@ export function datasetToFormat(dataset, targetType) {
6565
// RDF-to-JSON-LD algorithm) — not a hand-rolled quad walk. The dataset seam
6666
// already produces N-Quads for the n-quads serving arm (the n3 Writer via
6767
// datasetToFormat); reuse that string as jsonld.fromRDF's input.
68-
async function datasetToJsonLd(dataset) {
68+
// Exported for handlePatch (#7): applying N3-Patch/SPARQL-Update to
69+
// verbatim-stored Turtle-family bytes projects through this same expansion.
70+
export async function datasetToJsonLd(dataset) {
6971
const nquads = await datasetToFormat(dataset, RDF_TYPES.NQUADS);
7072
return jsonld.fromRDF(nquads, { format: 'application/n-quads' });
7173
}

‎src/utils/url.js‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,43 @@ export function isRdfContentType(contentType) {
291291
return rdfTypes.includes(contentType);
292292
}
293293

294+
/**
295+
* P2 (Solid #server-content-type-missing MUST): a request that carries a
296+
* body must carry Content-Type. Fastify's wildcard content-type parser
297+
* (server.js addContentTypeParser('*')) happily buffers a body under a
298+
* missing/empty Content-Type — nothing upstream 400s this, so the write
299+
* handlers (PUT/POST/PATCH) must guard it themselves. Content-Length is
300+
* the ground truth for "carries a body" (set by the client on the wire);
301+
* request.body is a fallback for transports that omit it.
302+
* @param {import('fastify').FastifyRequest} request
303+
* @returns {boolean}
304+
*/
305+
export function isBodiedWithoutContentType(request) {
306+
const ct = (request.headers['content-type'] || '').trim();
307+
if (ct) return false;
308+
const len = request.headers['content-length'];
309+
if (len !== undefined) return parseInt(len, 10) > 0;
310+
const body = request.body;
311+
if (Buffer.isBuffer(body)) return body.length > 0;
312+
if (typeof body === 'string') return body.length > 0;
313+
if (body && typeof body === 'object') return Object.keys(body).length > 0;
314+
return false;
315+
}
316+
317+
/**
318+
* Build the P2 400 problem+json body. Callers gate the call on
319+
* request.lwsEnabled and isBodiedWithoutContentType(request).
320+
* @param {string} instance - resourceUrl
321+
* @returns {object}
322+
*/
323+
export function missingContentTypeProblem(instance) {
324+
return {
325+
type: 'about:blank', title: 'Bad Request', status: 400,
326+
detail: 'a request with content must carry Content-Type (Solid #server-content-type-missing)',
327+
instance,
328+
};
329+
}
330+
294331
// Security: Maximum JSON size for parsing (10MB)
295332
const MAX_JSON_SIZE = 10 * 1024 * 1024;
296333

0 commit comments

Comments
 (0)