diff --git a/config/defaults.js b/config/defaults.js index ab9a15e88..ec4f2215d 100644 --- a/config/defaults.js +++ b/config/defaults.js @@ -13,8 +13,7 @@ module.exports = { 'webid': true, 'strictOrigin': true, 'originsAllowed': ['https://apps.solid.invalid'], - 'dataBrowserPath': 'default', - 'defaultContentType': 'text/turtle' + 'dataBrowserPath': 'default' // For use in Enterprises to configure a HTTP proxy for all outbound HTTP requests from the SOLID server (we use // https://www.npmjs.com/package/global-tunnel-ng). diff --git a/lib/create-app.js b/lib/create-app.js index 6e1b60a5e..1480cb847 100644 --- a/lib/create-app.js +++ b/lib/create-app.js @@ -23,7 +23,7 @@ const options = require('./handlers/options') const debug = require('./debug').authentication const path = require('path') const { routeResolvedFile } = require('./utils') -const LegacyResourceMapper = require('./legacy-resource-mapper') +const ResourceMapper = require('./resource-mapper') const corsSettings = cors({ methods: [ @@ -42,7 +42,7 @@ function createApp (argv = {}) { argv.host = SolidHost.from({ port: argv.port, serverUri: argv.serverUri }) - argv.resourceMapper = new LegacyResourceMapper({ + argv.resourceMapper = new ResourceMapper({ rootUrl: argv.serverUri, rootPath: argv.root || process.cwd(), includeHost: argv.multiuser, diff --git a/lib/handlers/copy.js b/lib/handlers/copy.js index 3e5f11551..4c0012616 100644 --- a/lib/handlers/copy.js +++ b/lib/handlers/copy.js @@ -22,17 +22,16 @@ async function handler (req, res, next) { const ldp = req.app.locals.ldp const serverRoot = ldp.resourceMapper.resolveUrl(req.hostname) const copyFromUrl = fromExternal ? copyFrom : serverRoot + copyFrom - const copyTo = res.locals.path || req.path - const { path: copyToPath } = await ldp.resourceMapper.mapUrlToFile({ url: req }) - ldpCopy(copyToPath, copyFromUrl, function (err) { - if (err) { - let statusCode = err.statusCode || 500 - let errorMessage = err.statusMessage || err.message - debug.handlers('Error with COPY request:' + errorMessage) - return next(error(statusCode, errorMessage)) - } - res.set('Location', copyTo) - res.sendStatus(201) - next() - }) + const copyToUrl = res.locals.path || req.path + try { + await ldpCopy(ldp.resourceMapper, copyToUrl, copyFromUrl) + } catch (err) { + let statusCode = err.statusCode || 500 + let errorMessage = err.statusMessage || err.message + debug.handlers('Error with COPY request:' + errorMessage) + return next(error(statusCode, errorMessage)) + } + res.set('Location', copyToUrl) + res.sendStatus(201) + next() } diff --git a/lib/handlers/get.js b/lib/handlers/get.js index 41015981f..27f70973b 100644 --- a/lib/handlers/get.js +++ b/lib/handlers/get.js @@ -75,16 +75,15 @@ async function handler (req, res, next) { // Till here it must exist if (!includeBody) { debug('HEAD only') - const mappedFile = await ldp.resourceMapper.mapFileToUrl({ path }) - contentType = mappedFile.contentType - res.setHeader('Content-Type', contentType) + res.setHeader('Content-Type', ret.contentType) res.status(200).send('OK') return next() } // Handle dataBrowser if (requestedType && requestedType.includes('text/html')) { - let mimeTypeByExt = mime.lookup(_path.basename(path)) + const { path: filename } = await ldp.resourceMapper.mapUrlToFile({ url: options }) + let mimeTypeByExt = mime.lookup(_path.basename(filename)) let isHtmlResource = mimeTypeByExt && mimeTypeByExt.includes('html') let useDataBrowser = ldp.dataBrowserPath && ( container || @@ -136,7 +135,9 @@ async function handler (req, res, next) { async function globHandler (req, res, next) { const ldp = req.app.locals.ldp - const { path: filename } = await ldp.resourceMapper.mapUrlToFile({ url: req }) + // TODO: This is a hack, that does not check if the target file exists, as this is quite complex with globbing. + // TODO: Proper support for this is not implemented, as globbing support might be removed in the future. + const filename = ldp.resourceMapper._getFullPath(req) const requestUri = (await ldp.resourceMapper.mapFileToUrl({ path: filename, hostname: req.hostname })).url const globOptions = { diff --git a/lib/handlers/index.js b/lib/handlers/index.js index a4999ceef..a72dbde8a 100644 --- a/lib/handlers/index.js +++ b/lib/handlers/index.js @@ -9,9 +9,10 @@ async function handler (req, res, next) { const ldp = req.app.locals.ldp const negotiator = new Negotiator(req) const requestedType = negotiator.mediaType() - const { path: filename } = await req.app.locals.ldp.resourceMapper.mapUrlToFile({ url: req }) try { + const { path: filename } = await req.app.locals.ldp.resourceMapper.mapUrlToFile({ url: req }) + const stats = await ldp.stat(filename) if (!stats.isDirectory()) { return next() diff --git a/lib/handlers/patch.js b/lib/handlers/patch.js index 4b7bf229a..71b7247a8 100644 --- a/lib/handlers/patch.js +++ b/lib/handlers/patch.js @@ -9,6 +9,7 @@ const error = require('../http-error') const $rdf = require('rdflib') const crypto = require('crypto') const overQuota = require('../utils').overQuota +const getContentType = require('../utils').getContentType // Patch parsers by request body content type const PATCH_PARSERS = { @@ -16,6 +17,8 @@ const PATCH_PARSERS = { 'text/n3': require('./patch/n3-patch-parser.js') } +const DEFAULT_FOR_NEW_CONTENT_TYPE = 'text/turtle' + // Handles a PATCH request async function patchHandler (req, res, next) { debug(`PATCH -- ${req.originalUrl}`) @@ -23,7 +26,15 @@ async function patchHandler (req, res, next) { try { // Obtain details of the target resource const ldp = req.app.locals.ldp - const { path, contentType } = await ldp.resourceMapper.mapUrlToFile({ url: req }) + let path, contentType + try { + // First check if the file already exists + ({ path, contentType } = await ldp.resourceMapper.mapUrlToFile({ url: req })) + } catch (err) { + // If the file doesn't exist, request one to be created with the default content type + ({ path, contentType } = await ldp.resourceMapper.mapUrlToFile( + { url: req, createIfNotExists: true, contentType: DEFAULT_FOR_NEW_CONTENT_TYPE })) + } const { url } = await ldp.resourceMapper.mapFileToUrl({ path, hostname: req.hostname }) const resource = { path, contentType, url } debug('PATCH -- Target <%s> (%s)', url, contentType) @@ -32,7 +43,7 @@ async function patchHandler (req, res, next) { const patch = {} patch.text = req.body ? req.body.toString() : '' patch.uri = `${url}#patch-${hash(patch.text)}` - patch.contentType = (req.get('content-type') || '').match(/^[^;\s]*/)[0] + patch.contentType = getContentType(req.headers) debug('PATCH -- Received patch (%d bytes, %s)', patch.text.length, patch.contentType) const parsePatch = PATCH_PARSERS[patch.contentType] if (!parsePatch) { diff --git a/lib/handlers/post.js b/lib/handlers/post.js index 3d0ab7cba..f27261bb2 100644 --- a/lib/handlers/post.js +++ b/lib/handlers/post.js @@ -7,10 +7,11 @@ const header = require('../header') const patch = require('./patch') const error = require('../http-error') const { extensions } = require('mime-types') +const getContentType = require('../utils').getContentType async function handler (req, res, next) { const ldp = req.app.locals.ldp - const contentType = req.get('content-type') + const contentType = getContentType(req.headers) debug('content-type is ', contentType) // Handle SPARQL(-update?) query if (contentType === 'application/sparql' || @@ -58,7 +59,7 @@ async function handler (req, res, next) { const { url: putUrl } = await ldp.resourceMapper.mapFileToUrl( { path: ldp.resourceMapper._rootPath + path.join(containerPath, filename), hostname: req.hostname }) try { - await ldp.put(putUrl, file) + await ldp.put(putUrl, file, mimetype) } catch (err) { busboy.emit('error', err) } diff --git a/lib/handlers/put.js b/lib/handlers/put.js index 7b1c2467f..af9110ba9 100644 --- a/lib/handlers/put.js +++ b/lib/handlers/put.js @@ -1,6 +1,7 @@ module.exports = handler const debug = require('debug')('solid:put') +const getContentType = require('../utils').getContentType async function handler (req, res, next) { const ldp = req.app.locals.ldp @@ -8,7 +9,7 @@ async function handler (req, res, next) { res.header('MS-Author-Via', 'SPARQL') try { - await ldp.put(req, req) + await ldp.put(req, req, getContentType(req.headers)) debug('succeded putting the file') res.sendStatus(201) diff --git a/lib/header.js b/lib/header.js index 9bf18e7e1..1a4c8540b 100644 --- a/lib/header.js +++ b/lib/header.js @@ -43,7 +43,19 @@ function addLinks (res, fileMetadata) { async function linksHandler (req, res, next) { const ldp = req.app.locals.ldp - const { path: filename } = await ldp.resourceMapper.mapUrlToFile(req) + let filename + try { + // Hack: createIfNotExists is set to true for PUT or PATCH requests + // because the file might not exist yet at this point. + // But it will be created afterwards. + // This should be improved with the new server architecture. + ({ path: filename } = await ldp.resourceMapper + .mapUrlToFile({ url: req, createIfNotExists: req.method === 'PUT' || req.method === 'PATCH' })) + } catch (e) { + // Silently ignore errors here + // Later handlers will error as well, but they will be able to given a more concrete error message (like 400 or 404) + return next() + } if (path.extname(filename) === ldp.suffixMeta) { debug.metadata('Trying to access metadata file as regular file.') diff --git a/lib/ldp-copy.js b/lib/ldp-copy.js index a9e1ccf19..c9ebad372 100644 --- a/lib/ldp-copy.js +++ b/lib/ldp-copy.js @@ -3,9 +3,11 @@ module.exports = copy const debug = require('./debug') const fs = require('fs') const mkdirp = require('fs-extra').mkdirp +const error = require('./http-error') const path = require('path') const http = require('http') const https = require('https') +const getContentType = require('./utils').getContentType /** * Cleans up a file write stream (ends stream, deletes the file). @@ -21,47 +23,51 @@ function cleanupFileStream (stream) { /** * Performs an LDP Copy operation, imports a remote resource to a local path. - * @param copyToPath {String} Local path to copy the resource into + * @param resourceMapper {ResourceMapper} A resource mapper instance. + * @param copyToUri {Object} The location (in the current domain) to copy to. * @param copyFromUri {String} Location of remote resource to copy from - * @param callback {Function} Node error callback + * @return A promise resolving when the copy operation is finished */ -function copy (copyToPath, copyFromUri, callback) { - mkdirp(path.dirname(copyToPath), function (err) { - if (err) { - debug.handlers('COPY -- Error creating destination directory: ' + err) - return callback( - new Error('Failed to create the path to the destination resource: ' + - err)) - } - const destinationStream = fs.createWriteStream(copyToPath) - .on('error', function (err) { - cleanupFileStream(this) - return callback(new Error('Error writing data: ' + err)) - }) - .on('finish', function () { - // Success - debug.handlers('COPY -- Wrote data to: ' + copyToPath) - callback() - }) +function copy (resourceMapper, copyToUri, copyFromUri) { + return new Promise((resolve, reject) => { const request = /^https:/.test(copyFromUri) ? https : http request.get(copyFromUri) .on('error', function (err) { debug.handlers('COPY -- Error requesting source file: ' + err) this.end() - cleanupFileStream(destinationStream) - return callback(new Error('Error writing data: ' + err)) + return reject(new Error('Error writing data: ' + err)) }) .on('response', function (response) { if (response.statusCode !== 200) { - debug.handlers('COPY -- HTTP error reading source file: ' + - response.statusMessage) + debug.handlers('COPY -- HTTP error reading source file: ' + response.statusMessage) this.end() - cleanupFileStream(destinationStream) let error = new Error('Error reading source file: ' + response.statusMessage) error.statusCode = response.statusCode - return callback(error) + return reject(error) } - response.pipe(destinationStream) + // Grab the content type from the source + const contentType = getContentType(response.headers) + resourceMapper.mapUrlToFile({ url: copyToUri, createIfNotExists: true, contentType }) + .then(({ path: copyToPath }) => { + mkdirp(path.dirname(copyToPath), function (err) { + if (err) { + debug.handlers('COPY -- Error creating destination directory: ' + err) + return reject(new Error('Failed to create the path to the destination resource: ' + err)) + } + const destinationStream = fs.createWriteStream(copyToPath) + .on('error', function (err) { + cleanupFileStream(this) + return reject(new Error('Error writing data: ' + err)) + }) + .on('finish', function () { + // Success + debug.handlers('COPY -- Wrote data to: ' + copyToPath) + resolve() + }) + response.pipe(destinationStream) + }) + }) + .catch(() => reject(error(500, 'Could not find target file to copy'))) }) }) } diff --git a/lib/ldp.js b/lib/ldp.js index 809ca4c33..4b31074b0 100644 --- a/lib/ldp.js +++ b/lib/ldp.js @@ -1,4 +1,3 @@ -const mime = require('mime-types') const path = require('path') const url = require('url') const fs = require('fs') @@ -6,11 +5,11 @@ const $rdf = require('rdflib') const mkdirp = require('fs-extra').mkdirp const uuid = require('uuid') const debug = require('./debug') -const utils = require('./utils') const error = require('./http-error') const stringToStream = require('./utils').stringToStream const serialize = require('./utils').serialize const overQuota = require('./utils').overQuota +const getContentType = require('./utils').getContentType const extend = require('extend') const rimraf = require('rimraf') const ldpContainer = require('./ldp-container') @@ -18,8 +17,6 @@ const parse = require('./utils').parse const fetch = require('node-fetch') const { promisify } = require('util') -const DEFAULT_CONTENT_TYPE = 'text/turtle' - const RDF_MIME_TYPES = [ 'text/turtle', // .ttl 'text/n3', // .n3 @@ -44,7 +41,6 @@ class LDP { if (!this.suffixMeta) { this.suffixMeta = '.meta' } - this.turtleExtensions = [ '.ttl', this.suffixAcl, this.suffixMeta ] // Error pages folder this.errorPages = null @@ -102,16 +98,12 @@ class LDP { } async readResource (url) { - const { path } = await this.resourceMapper.mapUrlToFile({ url }) - return new Promise((resolve, reject) => { - fs.readFile( - path, - { 'encoding': 'utf8' }, - (err, data) => { - if (err) return reject(error(err, "Can't read file")) - resolve(data) - }) - }) + try { + const { path } = await this.resourceMapper.mapUrlToFile({ url }) + return await promisify(fs.readFile)(path, {'encoding': 'utf8'}) + } catch (err) { + throw error(404, "Can't read file") + } } async readContainerMeta (url) { @@ -204,7 +196,7 @@ class LDP { * * @return {Promise} */ - async putGraph (graph, uri, contentType = DEFAULT_CONTENT_TYPE) { + async putGraph (graph, uri, contentType) { const { path } = url.parse(uri) const content = await serialize(graph, uri, contentType) let stream = stringToStream(content) @@ -212,14 +204,18 @@ class LDP { } async put (url, stream, contentType) { - const { path: filePath } = await this.resourceMapper.mapUrlToFile({ url, contentType, createIfNotExists: true }) - // PUT requests not supported on containers. Use POST instead - if (filePath.endsWith('/')) { + if ((url.url || url).endsWith('/')) { throw error(409, 'PUT not supported on containers, use POST instead') } + // PUT without content type is forbidden + if (!contentType) { + throw error(415, + 'PUT request require a valid content type via the Content-Type header') + } + // First check if we are above quota let isOverQuota try { @@ -232,6 +228,7 @@ class LDP { } // Second, create the enclosing directory, if necessary + const { path: filePath } = await this.resourceMapper.mapUrlToFile({ url, contentType, createIfNotExists: true }) const dirName = path.dirname(filePath) try { await promisify(mkdirp)(dirName) @@ -288,9 +285,7 @@ class LDP { } const body = await response.text() - const contentType = options.contentType || DEFAULT_CONTENT_TYPE - - return promisify(parse)(body, uri, contentType) + return promisify(parse)(body, uri, getContentType(response.headers)) } /** @@ -311,12 +306,15 @@ class LDP { * * @return {Promise} */ - getGraph (uri, contentType = DEFAULT_CONTENT_TYPE) { + getGraph (uri, contentType) { return this.graph(uri, uri, contentType) } - async graph (url, baseUri, contentType = DEFAULT_CONTENT_TYPE) { + async graph (url, baseUri, contentType) { const body = await this.readResource(url) + if (!contentType) { + ({ contentType } = await this.resourceMapper.mapUrlToFile({ url })) + } return new Promise((resolve, reject) => { const graph = $rdf.graph() $rdf.parse(body, graph, baseUri, contentType, @@ -325,15 +323,15 @@ class LDP { } async get (options) { - const { path: filename, contentType } = await this.resourceMapper.mapUrlToFile({ url: options }) - const baseUri = this.resourceMapper.resolveUrl(options.hostname) - - let stats + let filename, contentType, stats try { + ({ path: filename, contentType } = await this.resourceMapper.mapUrlToFile({ url: options })) stats = await this.stat(filename) } catch (err) { - throw error(err, 'Can\'t find file requested: ' + filename) + throw error(404, 'Can\'t find file requested: ' + options) } + const baseUri = this.resourceMapper.resolveUrl(options.hostname) + // Just return, since resource exists if (!options.includeBody) { return { 'stream': stats, 'contentType': contentType, 'container': stats.isDirectory() } @@ -381,10 +379,6 @@ class LDP { }) .on('open', function () { debug.handlers(`GET -- Reading ${filename}`) - let contentType = mime.lookup(filename) || DEFAULT_CONTENT_TYPE - if (utils.hasSuffix(filename, this.turtleExtensions)) { - contentType = 'text/turtle' - } return resolve({ stream, contentType, container: false, contentRange, chunksize }) }) }) @@ -392,21 +386,20 @@ class LDP { } async delete (url) { - const { path } = await this.resourceMapper.mapUrlToFile({ url }) - // First check if the path points to a valid file - let stats + let filePath, stats try { - stats = await this.stat(path) + ({ path: filePath } = await this.resourceMapper.mapUrlToFile({ url })) + stats = await this.stat(filePath) } catch (err) { throw error(404, "Can't find " + err) } // If so, delete the directory or file if (stats.isDirectory()) { - return this.deleteContainer(path) + return this.deleteContainer(filePath) } else { - return this.deleteResource(path) + return this.deleteResource(filePath) } } diff --git a/lib/legacy-resource-mapper.js b/lib/legacy-resource-mapper.js deleted file mode 100644 index de9d44a2b..000000000 --- a/lib/legacy-resource-mapper.js +++ /dev/null @@ -1,21 +0,0 @@ -const ResourceMapper = require('./resource-mapper') - -// A LegacyResourceMapper models the old mapping between HTTP URLs and server filenames, -// and is intended to be replaced by ResourceMapper -class LegacyResourceMapper extends ResourceMapper { - constructor (options) { - super(Object.assign({ defaultContentType: 'text/turtle' }, options)) - } - - // Maps the request for a given resource and representation format to a server file - async mapUrlToFile ({ url }) { - return { path: this._getFullPath(url), contentType: this._getContentTypeByExtension(url) } - } - - // Preserve dollars in paths - _removeDollarExtension (path) { - return path - } -} - -module.exports = LegacyResourceMapper diff --git a/lib/resource-mapper.js b/lib/resource-mapper.js index c200b7bca..cb7cf13f2 100644 --- a/lib/resource-mapper.js +++ b/lib/resource-mapper.js @@ -8,12 +8,21 @@ const readdir = promisify(fs.readdir) // following the principles of the “sweet spot” discussed in // https://www.w3.org/DesignIssues/HTTPFilenameMapping.html class ResourceMapper { - constructor ({ rootUrl, rootPath, includeHost, defaultContentType }) { + constructor ({ + rootUrl, + rootPath, + includeHost = false, + defaultContentType = 'application/octet-stream', + indexFilename = 'index', + overrideTypes = { acl: 'text/turtle', meta: 'text/turtle' } + }) { this._rootUrl = this._removeTrailingSlash(rootUrl) this._rootPath = this._removeTrailingSlash(rootPath) this._includeHost = includeHost this._readdir = readdir this._defaultContentType = defaultContentType + this._indexFilename = indexFilename + this._types = { ...types, ...overrideTypes } // If the host needs to be replaced on every call, pre-split the root URL if (includeHost) { @@ -29,16 +38,29 @@ class ResourceMapper { } // Maps the request for a given resource and representation format to a server file + // When the URL ends with a '/', then files with the prefix 'index.' will be matched, + // such as 'index.html' and 'index.ttl'. async mapUrlToFile ({ url, contentType, createIfNotExists }) { - const fullPath = this._getFullPath(url) + let fullPath = this._getFullPath(url) + let isIndex = fullPath.endsWith('/') let path + // Append index filename if the URL ends with a '/' + if (isIndex) { + fullPath += this._indexFilename + } + // Create the path for a new file if (createIfNotExists) { path = fullPath // If the extension is not correct for the content type, append the correct extension if (this._getContentTypeByExtension(path) !== contentType) { - path += contentType in extensions ? `$.${extensions[contentType][0]}` : '$.unknown' + // Append a '$', unless we map for the index + // Because the index must _always_ have a proper extension when it is being created + if (!isIndex) { + path += '$' + } + path += contentType in extensions ? `.${extensions[contentType][0]}` : '.unknown' } // Determine the path of an existing file } else { @@ -48,9 +70,17 @@ class ResourceMapper { const files = await this._readdir(folder) // Find a file with the same name (minus the dollar extension) - const match = files.find(f => this._removeDollarExtension(f) === filename) + let match = files.find(f => this._removeDollarExtension(f) === filename || + (isIndex && f.startsWith(this._indexFilename + '.'))) if (!match) { - throw new Error('File not found') + // Error if no match was found, + // unless the URL ends with a '/', + // in that case we fallback to the folder itself. + if (isIndex) { + match = '' + } else { + throw new Error(`File not found: ${fullPath}`) + } } path = `${folder}${match}` contentType = this._getContentTypeByExtension(match) @@ -107,7 +137,7 @@ class ResourceMapper { // Gets the expected content type based on the extension of the path _getContentTypeByExtension (path) { const extension = /\.([^/.]+)$/.exec(path) - return extension && types[extension[1].toLowerCase()] || this._defaultContentType + return extension && this._types[extension[1].toLowerCase()] || this._defaultContentType } // Removes a possible trailing slash from a path diff --git a/lib/utils.js b/lib/utils.js index bfd4cd8f6..d7bcd7b36 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -9,6 +9,7 @@ module.exports.fullUrlForReq = fullUrlForReq module.exports.routeResolvedFile = routeResolvedFile module.exports.getQuota = getQuota module.exports.overQuota = overQuota +module.exports.getContentType = getContentType const fs = require('fs') const path = require('path') @@ -222,3 +223,20 @@ function actualSize (root) { function _asyncReadfile (filename) { return util.promisify(fs.readFile)(filename, 'utf-8') } + +/** + * Get the content type from a headers object + * @param headers An Express or Fetch API headers object + * @return {string} A content type string + */ +function getContentType (headers) { + const headerValue = headers.get ? headers.get('content-type') : headers['content-type'] + + // Default content type as stated by RFC 822 + if (!headerValue) { + return 'text/plain' + } + + // Remove charset suffix + return headerValue.split(';')[0] +} diff --git a/test/integration/account-manager-test.js b/test/integration/account-manager-test.js index e047ddfe0..b6d3c5fc9 100644 --- a/test/integration/account-manager-test.js +++ b/test/integration/account-manager-test.js @@ -9,7 +9,7 @@ chai.should() const LDP = require('../../lib/ldp') const SolidHost = require('../../lib/models/solid-host') const AccountManager = require('../../lib/models/account-manager') -const LegacyResourceMapper = require('../../lib/legacy-resource-mapper') +const ResourceMapper = require('../../lib/resource-mapper') const testAccountsDir = path.join(__dirname, '../resources/accounts') const accountTemplatePath = path.join(__dirname, '../../default-templates/new-account') @@ -30,11 +30,10 @@ describe('AccountManager', () => { describe('in multi user mode', () => { let multiuser = true - let resourceMapper = new LegacyResourceMapper({ + let resourceMapper = new ResourceMapper({ rootUrl: 'https://localhost:8443/', rootPath: process.cwd(), - includeHost: multiuser, - defaultContentType: 'text/turtle' + includeHost: multiuser }) let store = new LDP({ multiuser, resourceMapper }) let options = { multiuser, store, host } @@ -61,11 +60,10 @@ describe('AccountManager', () => { let multiuser = false it('resolves to true if root .acl exists in root storage', () => { - let resourceMapper = new LegacyResourceMapper({ + let resourceMapper = new ResourceMapper({ rootUrl: 'https://localhost:8443/', includeHost: multiuser, - rootPath: path.join(testAccountsDir, 'tim.localhost'), - defaultContentType: 'text/turtle' + rootPath: path.join(testAccountsDir, 'tim.localhost') }) let store = new LDP({ multiuser, @@ -81,11 +79,10 @@ describe('AccountManager', () => { }) it('resolves to false if root .acl does not exist in root storage', () => { - let resourceMapper = new LegacyResourceMapper({ + let resourceMapper = new ResourceMapper({ rootUrl: 'https://localhost:8443/', includeHost: multiuser, - rootPath: testAccountsDir, - defaultContentType: 'text/turtle' + rootPath: testAccountsDir }) let store = new LDP({ multiuser, @@ -105,11 +102,10 @@ describe('AccountManager', () => { describe('createAccountFor()', () => { it('should create an account directory', () => { let multiuser = true - let resourceMapper = new LegacyResourceMapper({ + let resourceMapper = new ResourceMapper({ rootUrl: 'https://localhost:8443/', includeHost: multiuser, - rootPath: testAccountsDir, - defaultContentType: 'text/turtle' + rootPath: testAccountsDir }) let store = new LDP({ multiuser, resourceMapper }) let options = { host, multiuser, store, accountTemplatePath } diff --git a/test/integration/acl-oidc-test.js b/test/integration/acl-oidc-test.js index a9623c5c4..1fdb2e320 100644 --- a/test/integration/acl-oidc-test.js +++ b/test/integration/acl-oidc-test.js @@ -92,11 +92,12 @@ describe('ACL with WebID+OIDC over HTTP', function () { const origin1 = 'http://example.org/' const origin2 = 'http://example.com/' - function createOptions (path, user) { + function createOptions (path, user, contentType = 'text/plain') { const options = { url: timAccountUri + path, headers: { - accept: 'text/turtle' + 'accept': 'text/turtle', + 'content-type': contentType } } if (user) { @@ -219,7 +220,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { }) }) it("should create test file's acl file", function (done) { - var options = createOptions('/write-acl/test-file.acl', 'user1') + var options = createOptions('/write-acl/test-file.acl', 'user1', 'text/turtle') options.body = '' request.put(options, function (error, response, body) { assert.equal(error, null) @@ -253,7 +254,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { }) it('should PUT new ACL file', function (done) { - var options = createOptions('/origin/test-folder/.acl', 'user1') + var options = createOptions('/origin/test-folder/.acl', 'user1', 'text/turtle') options.body = '<#Owner> a ;\n' + ' ;\n' + ' <' + user1 + '>;\n' + @@ -361,7 +362,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { }) }) it('user1 should be able to modify ACL file', function (done) { - var options = createOptions('/read-acl/.acl', 'user1') + var options = createOptions('/read-acl/.acl', 'user1', 'text/turtle') options.body = body request.put(options, function (error, response, body) { assert.equal(error, null) @@ -386,7 +387,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { }) }) it('user2 should not be able to modify ACL file', function (done) { - var options = createOptions('/read-acl/.acl', 'user2') + var options = createOptions('/read-acl/.acl', 'user2', 'text/turtle') options.body = ' .' request.put(options, function (error, response, body) { assert.equal(error, null) @@ -403,7 +404,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { }) }) it('agent should not be able to modify ACL file', function (done) { - var options = createOptions('/read-acl/.acl') + var options = createOptions('/read-acl/.acl', null, 'text/turtle') options.body = ' .' request.put(options, function (error, response, body) { assert.equal(error, null) @@ -433,6 +434,16 @@ describe('ACL with WebID+OIDC over HTTP', function () { done() }) }) + it('user1 should be able to PATCH an existing resource', function (done) { + var options = createOptions('/append-inherited/test.ttl', 'user1') + options.body = 'INSERT DATA { :test :hello 789 .}' + options.headers['content-type'] = 'application/sparql-update' + request.patch(options, function (error, response, body) { + assert.equal(error, null) + assert.equal(response.statusCode, 200) + done() + }) + }) it('user1 should be able to access test file', function (done) { var options = createOptions('/append-acl/abc.ttl', 'user1') request.head(options, function (error, response, body) { @@ -443,7 +454,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { }) // TODO POST instead of PUT it('user1 should be able to modify test file', function (done) { - var options = createOptions('/append-acl/abc.ttl', 'user1') + var options = createOptions('/append-acl/abc.ttl', 'user1', 'text/turtle') options.body = ' .\n' request.put(options, function (error, response, body) { assert.equal(error, null) @@ -452,7 +463,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { }) }) it("user2 should not be able to access test file's ACL file", function (done) { - var options = createOptions('/append-acl/abc.ttl.acl', 'user2') + var options = createOptions('/append-acl/abc.ttl.acl', 'user2', 'text/turtle') request.head(options, function (error, response, body) { assert.equal(error, null) assert.equal(response.statusCode, 403) @@ -460,7 +471,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { }) }) it('user2 should not be able to access test file', function (done) { - var options = createOptions('/append-acl/abc.ttl', 'user2') + var options = createOptions('/append-acl/abc.ttl', 'user2', 'text/turtle') request.head(options, function (error, response, body) { assert.equal(error, null) assert.equal(response.statusCode, 403) @@ -468,7 +479,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { }) }) it('user2 (with append permission) cannot use PUT to append', function (done) { - var options = createOptions('/append-acl/abc.ttl', 'user2') + var options = createOptions('/append-acl/abc.ttl', 'user2', 'text/turtle') options.body = ' .\n' request.put(options, function (error, response, body) { assert.equal(error, null) @@ -485,7 +496,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { }) }) it('agent (with append permissions) should not PUT', function (done) { - var options = createOptions('/append-acl/abc.ttl') + var options = createOptions('/append-acl/abc.ttl', null, 'text/turtle') options.body = ' .\n' request.put(options, function (error, response, body) { assert.equal(error, null) @@ -539,7 +550,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { }) it.skip('user2 should be able to write a file in the test directory', function (done) { - var options = createOptions('/group/test-folder/test.ttl', 'user2') + var options = createOptions('/group/test-folder/test.ttl', 'user2', 'text/turtle') options.body = '<#Dahut> a .\n' request.put(options, function (error, response, body) { @@ -549,7 +560,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { }) }) it.skip('user1 should be able to get the file', function (done) { - var options = createOptions('/group/test-folder/test.ttl', 'user1') + var options = createOptions('/group/test-folder/test.ttl', 'user1', 'text/turtle') request.get(options, function (error, response, body) { assert.equal(error, null) @@ -559,7 +570,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { }) it.skip('user2 should not be able to write to the ACL', function (done) { - var options = createOptions('/group/test-folder/.acl', 'user2') + var options = createOptions('/group/test-folder/.acl', 'user2', 'text/turtle') options.body = '<#Dahut> a .\n' request.put(options, function (error, response, body) { @@ -569,7 +580,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { }) }) it.skip('user1 should be able to delete the file', function (done) { - var options = createOptions('/group/test-folder/test.ttl', 'user1') + var options = createOptions('/group/test-folder/test.ttl', 'user1', 'text/turtle') request.delete(options, function (error, response, body) { assert.equal(error, null) @@ -609,7 +620,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { ' <' + user2 + '>;\n' + ' , .\n' it("user1 should be able to modify test file's ACL file", function (done) { - var options = createOptions('/append-acl/abc2.ttl.acl', 'user1') + var options = createOptions('/append-acl/abc2.ttl.acl', 'user1', 'text/turtle') options.body = body request.put(options, function (error, response, body) { assert.equal(error, null) @@ -618,7 +629,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { }) }) it("user1 should be able to access test file's ACL file", function (done) { - var options = createOptions('/append-acl/abc2.ttl.acl', 'user1') + var options = createOptions('/append-acl/abc2.ttl.acl', 'user1', 'text/turtle') request.head(options, function (error, response, body) { assert.equal(error, null) assert.equal(response.statusCode, 200) @@ -626,7 +637,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { }) }) it('user1 should be able to access test file', function (done) { - var options = createOptions('/append-acl/abc2.ttl', 'user1') + var options = createOptions('/append-acl/abc2.ttl', 'user1', 'text/turtle') request.head(options, function (error, response, body) { assert.equal(error, null) assert.equal(response.statusCode, 200) @@ -634,7 +645,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { }) }) it('user1 should be able to modify test file', function (done) { - var options = createOptions('/append-acl/abc2.ttl', 'user1') + var options = createOptions('/append-acl/abc2.ttl', 'user1', 'text/turtle') options.body = ' .\n' request.put(options, function (error, response, body) { assert.equal(error, null) @@ -659,7 +670,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { }) }) it('user2 should be able to modify test file', function (done) { - var options = createOptions('/append-acl/abc2.ttl', 'user2') + var options = createOptions('/append-acl/abc2.ttl', 'user2', 'text/turtle') options.body = ' .\n' request.put(options, function (error, response, body) { assert.equal(error, null) @@ -676,7 +687,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { }) }) it('agent should not be able to modify test file', function (done) { - var options = createOptions('/append-acl/abc2.ttl') + var options = createOptions('/append-acl/abc2.ttl', null, 'text/turtle') options.body = ' .\n' request.put(options, function (error, response, body) { assert.equal(error, null) @@ -703,7 +714,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { ' ;\n' + ' .\n' it("user1 should be able to modify test directory's ACL file", function (done) { - var options = createOptions('/write-acl/default-for-new/.acl', 'user1') + var options = createOptions('/write-acl/default-for-new/.acl', 'user1', 'text/turtle') options.body = body request.put(options, function (error, response, body) { assert.equal(error, null) @@ -720,7 +731,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { }) }) it('user1 should be able to create new test file', function (done) { - var options = createOptions('/write-acl/default-for-new/test-file.ttl', 'user1') + var options = createOptions('/write-acl/default-for-new/test-file.ttl', 'user1', 'text/turtle') options.body = ' .\n' request.put(options, function (error, response, body) { assert.equal(error, null) @@ -753,7 +764,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { }) }) it('user2 should not be able to modify new test file', function (done) { - var options = createOptions('/write-acl/default-for-new/test-file.ttl', 'user2') + var options = createOptions('/write-acl/default-for-new/test-file.ttl', 'user2', 'text/turtle') options.body = ' .\n' request.put(options, function (error, response, body) { assert.equal(error, null) @@ -770,7 +781,7 @@ describe('ACL with WebID+OIDC over HTTP', function () { }) }) it('agent should not be able to modify new test file', function (done) { - var options = createOptions('/write-acl/default-for-new/test-file.ttl') + var options = createOptions('/write-acl/default-for-new/test-file.ttl', null, 'text/turtle') options.body = ' .\n' request.put(options, function (error, response, body) { assert.equal(error, null) diff --git a/test/integration/acl-tls-test.js b/test/integration/acl-tls-test.js index 169761fbf..33965959a 100644 --- a/test/integration/acl-tls-test.js +++ b/test/integration/acl-tls-test.js @@ -77,7 +77,8 @@ describe('ACL with WebID+TLS', function () { var options = { url: address + path, headers: { - accept: 'text/turtle' + accept: 'text/turtle', + 'content-type': 'text/plain' } } if (user) { @@ -271,7 +272,7 @@ describe('ACL with WebID+TLS', function () { }) it('should PUT new ACL file', function (done) { - var options = createOptions('/acl-tls/origin/test-folder/.acl', 'user1') + var options = createOptions('/acl-tls/origin/test-folder/.acl', 'user1', 'text/turtle') options.headers = { 'content-type': 'text/turtle' } @@ -369,7 +370,7 @@ describe('ACL with WebID+TLS', function () { }) it('should PUT new ACL file', function (done) { - var options = createOptions('/acl-tls/origin/test-folder/.acl', 'user1') + var options = createOptions('/acl-tls/origin/test-folder/.acl', 'user1', 'text/turtle') options.headers = { 'content-type': 'text/turtle' } diff --git a/test/integration/formats-test.js b/test/integration/formats-test.js index c82fcb4d1..994a415a3 100644 --- a/test/integration/formats-test.js +++ b/test/integration/formats-test.js @@ -95,8 +95,15 @@ describe('formats', function () { .expect(200, done) }) - it('should return turtle when listing container', function (done) { + it('should return turtle when listing container with an index page', function (done) { server.get('/sampleContainer/') + .set('accept', 'application/rdf+xml;q=0.4, application/xhtml+xml;q=0.3, text/xml;q=0.2, application/xml;q=0.2, text/html;q=0.3, text/plain;q=0.1, text/turtle;q=1.0, application/n3;q=1') + .expect('content-type', /text\/html/) + .expect(200, done) + }) + + it('should return turtle when listing container without an index page', function (done) { + server.get('/sampleContainer2/') .set('accept', 'application/rdf+xml;q=0.4, application/xhtml+xml;q=0.3, text/xml;q=0.2, application/xml;q=0.2, text/html;q=0.3, text/plain;q=0.1, text/turtle;q=1.0, application/n3;q=1') .expect('content-type', /text\/turtle/) .expect(200, done) diff --git a/test/integration/http-test.js b/test/integration/http-test.js index d850d1662..4a2f0a538 100644 --- a/test/integration/http-test.js +++ b/test/integration/http-test.js @@ -58,16 +58,18 @@ function createTestResource (resourceName) { describe('HTTP APIs', function () { var emptyResponse = function (res) { if (res.text) { - console.log('Not empty response') + throw new Error('Not empty response') } } var getLink = function (res, rel) { - var links = res.headers.link.split(',') - for (var i in links) { - var link = links[i] - var parsedLink = li.parse(link) - if (parsedLink[rel]) { - return parsedLink[rel] + if (res.headers.link) { + var links = res.headers.link.split(',') + for (var i in links) { + var link = links[i] + var parsedLink = li.parse(link) + if (parsedLink[rel]) { + return parsedLink[rel] + } } } return undefined @@ -77,10 +79,10 @@ describe('HTTP APIs', function () { var link = getLink(res, rel) if (link) { if (link !== value) { - console.log('Not same value:', value, '!=', link) + throw new Error('Not same value: ' + value + ' != ' + link) } } else { - console.log(rel, 'header does not exist:', link) + throw new Error('header does not exist: ' + rel + ' = ' + value) } } return handler @@ -137,13 +139,13 @@ describe('HTTP APIs', function () { }) it('should return 204 on success', function (done) { - server.options('/sampleContainer/example1.ttl') + server.options('/sampleContainer2/example1.ttl') .expect(204) .end(done) }) it('should have Access-Control-Allow-Origin', function (done) { - server.options('/sampleContainer/example1.ttl') + server.options('/sampleContainer2/example1.ttl') .set('Origin', 'http://example.com') .expect('Access-Control-Allow-Origin', 'http://example.com') .end(done) @@ -151,20 +153,26 @@ describe('HTTP APIs', function () { it('should have set acl and describedBy Links for resource', function (done) { - server.options('/sampleContainer/example1.ttl') + server.options('/sampleContainer2/example1.ttl') .expect(hasHeader('acl', 'example1.ttl' + suffixAcl)) .expect(hasHeader('describedBy', 'example1.ttl' + suffixMeta)) .end(done) }) it('should have set Link as resource', function (done) { - server.options('/sampleContainer/example1.ttl') + server.options('/sampleContainer2/example1.ttl') .expect('Link', /; rel="type"/) .end(done) }) - it('should have set Link as Container/BasicContainer', function (done) { + it('should have set Link as resource on a implicit index page', function (done) { server.options('/sampleContainer/') + .expect('Link', /; rel="type"/) + .end(done) + }) + + it('should have set Link as Container/BasicContainer', function (done) { + server.options('/sampleContainer2/') .set('Origin', 'http://example.com') .expect('Link', /; rel="type"/) .expect('Link', /; rel="type"/) @@ -172,14 +180,14 @@ describe('HTTP APIs', function () { }) it('should have set Accept-Post for containers', function (done) { - server.options('/sampleContainer/') + server.options('/sampleContainer2/') .set('Origin', 'http://example.com') .expect('Accept-Post', '*/*') .end(done) }) it('should have set acl and describedBy Links for container', function (done) { - server.options('/sampleContainer/') + server.options('/sampleContainer2/') .expect(hasHeader('acl', suffixAcl)) .expect(hasHeader('describedBy', suffixMeta)) .end(done) @@ -205,7 +213,7 @@ describe('HTTP APIs', function () { }) it('should have Access-Control-Allow-Origin as Origin on containers', function (done) { - server.get('/sampleContainer/') + server.get('/sampleContainer2/') .set('Origin', 'http://example.com') .expect('content-type', /text\/turtle/) .expect('Access-Control-Allow-Origin', 'http://example.com') @@ -213,40 +221,40 @@ describe('HTTP APIs', function () { }) it('should have Access-Control-Allow-Origin as Origin on resources', function (done) { - server.get('/sampleContainer/example1.ttl') + server.get('/sampleContainer2/example1.ttl') .set('Origin', 'http://example.com') .expect('content-type', /text\/turtle/) .expect('Access-Control-Allow-Origin', 'http://example.com') .expect(200, done) }) it('should have set Link as resource', function (done) { - server.get('/sampleContainer/example1.ttl') + server.get('/sampleContainer2/example1.ttl') .expect('content-type', /text\/turtle/) .expect('Link', /; rel="type"/) .expect(200, done) }) it('should have set Updates-Via to use WebSockets', function (done) { - server.get('/sampleContainer/example1.ttl') + server.get('/sampleContainer2/example1.ttl') .expect('updates-via', /wss?:\/\//) .expect(200, done) }) it('should have set acl and describedBy Links for resource', function (done) { - server.get('/sampleContainer/example1.ttl') + server.get('/sampleContainer2/example1.ttl') .expect('content-type', /text\/turtle/) .expect(hasHeader('acl', 'example1.ttl' + suffixAcl)) .expect(hasHeader('describedBy', 'example1.ttl' + suffixMeta)) .end(done) }) it('should have set Link as Container/BasicContainer', function (done) { - server.get('/sampleContainer/') + server.get('/sampleContainer2/') .expect('content-type', /text\/turtle/) .expect('Link', /; rel="type"/) .expect('Link', /; rel="type"/) .expect(200, done) }) it('should load skin (mashlib) if resource was requested as text/html', function (done) { - server.get('/sampleContainer/example1.ttl') + server.get('/sampleContainer2/example1.ttl') .set('Accept', 'text/html') .expect('content-type', /text\/html/) .expect(function (res) { @@ -276,6 +284,19 @@ describe('HTTP APIs', function () { .end(done) }) + it('should NOT load data browser (mashlib) if directory has an index file', function (done) { + server.get('/sampleContainer/') + .set('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8') + .expect('content-type', /text\/html/) + .expect(200) + .expect((res) => { + if (res.text.includes('TabulatorOutline')) { + throw new Error('Loaded data browser though resource has an .html extension') + } + }) + .end(done) + }) + it('should show data browser if container was requested as text/html', function (done) { server.get('/sampleContainer2/') .set('Accept', 'text/html') @@ -332,7 +353,7 @@ describe('HTTP APIs', function () { }) it('should have set acl and describedBy Links for container', function (done) { - server.get('/sampleContainer/') + server.get('/sampleContainer2/') .expect(hasHeader('acl', suffixAcl)) .expect(hasHeader('describedBy', suffixMeta)) .expect('content-type', /text\/turtle/) @@ -368,14 +389,20 @@ describe('HTTP APIs', function () { }) describe('HEAD API', function () { - it('should return content-type turtle by default', function (done) { + it('should return content-type application/octet-stream by default', function (done) { server.head('/sampleContainer/blank') - .expect('Content-Type', 'text/turtle; charset=utf-8') + .expect('Content-Type', 'application/octet-stream; charset=utf-8') .end(done) }) it('should have set content-type for turtle files', function (done) { - server.head('/sampleContainer/example1.ttl') + server.head('/sampleContainer2/example1.ttl') + .expect('Content-Type', 'text/turtle; charset=utf-8') + .end(done) + }) + it('should have set content-type for implicit turtle files', + function (done) { + server.head('/sampleContainer/example4') .expect('Content-Type', 'text/turtle; charset=utf-8') .end(done) }) @@ -386,7 +413,7 @@ describe('HTTP APIs', function () { .end(done) }) it('should have Access-Control-Allow-Origin as Origin', function (done) { - server.head('/sampleContainer/example1.ttl') + server.head('/sampleContainer2/example1.ttl') .set('Origin', 'http://example.com') .expect('Access-Control-Allow-Origin', 'http://example.com') .expect(200, done) @@ -397,32 +424,32 @@ describe('HTTP APIs', function () { .expect(200, done) }) it('should have set Updates-Via to use WebSockets', function (done) { - server.get('/sampleContainer/example1.ttl') + server.get('/sampleContainer2/example1.ttl') .expect('updates-via', /wss?:\/\//) .expect(200, done) }) it('should have set Link as Resource', function (done) { - server.head('/sampleContainer/example1.ttl') + server.head('/sampleContainer2/example1.ttl') .expect('Link', /; rel="type"/) .expect(200, done) }) it('should have set acl and describedBy Links for resource', function (done) { - server.get('/sampleContainer/example1.ttl') + server.get('/sampleContainer2/example1.ttl') .expect(hasHeader('acl', 'example1.ttl' + suffixAcl)) .expect(hasHeader('describedBy', 'example1.ttl' + suffixMeta)) .end(done) }) it('should have set Link as Container/BasicContainer', function (done) { - server.get('/sampleContainer/') + server.get('/sampleContainer2/') .expect('Link', /; rel="type"/) .expect('Link', /; rel="type"/) .expect(200, done) }) it('should have set acl and describedBy Links for container', function (done) { - server.get('/sampleContainer/') + server.get('/sampleContainer2/') .expect(hasHeader('acl', suffixAcl)) .expect(hasHeader('describedBy', suffixMeta)) .end(done) diff --git a/test/integration/ldp-test.js b/test/integration/ldp-test.js index 4f2492b63..8b769e379 100644 --- a/test/integration/ldp-test.js +++ b/test/integration/ldp-test.js @@ -7,7 +7,7 @@ var LDP = require('../../lib/ldp') var path = require('path') var stringToStream = require('../../lib/utils').stringToStream var randomBytes = require('randombytes') -var LegacyResourceMapper = require('../../lib/legacy-resource-mapper') +var ResourceMapper = require('../../lib/resource-mapper') // Helper functions for the FS var rm = require('./../utils').rm @@ -19,11 +19,10 @@ var fs = require('fs') describe('LDP', function () { var root = path.join(__dirname, '..') - var resourceMapper = new LegacyResourceMapper({ + var resourceMapper = new ResourceMapper({ rootUrl: 'https://localhost:8443/', rootPath: root, - includeHost: false, - defaultContentType: 'text/turtle' + includeHost: false }) var ldp = new LDP({ @@ -124,7 +123,7 @@ describe('LDP', function () { describe('put', function () { it.skip('should write a file in an existing dir', () => { var stream = stringToStream('hello world') - return ldp.put('/resources/testPut.txt', stream).then(() => { + return ldp.put('/resources/testPut.txt', stream, 'text/plain').then(() => { var found = read('testPut.txt') rm('testPut.txt') assert.equal(found, 'hello world') @@ -133,7 +132,7 @@ describe('LDP', function () { it('should fail if a trailing `/` is passed', () => { var stream = stringToStream('hello world') - return ldp.put('/resources/', stream).catch(err => { + return ldp.put('/resources/', stream, 'text/plain').catch(err => { assert.equal(err.status, 409) }) }) @@ -150,6 +149,20 @@ describe('LDP', function () { assert.equal(err.status, 413) }) }) + + it('should fail if a trailing `/` is passed without content type', () => { + var stream = stringToStream('hello world') + return ldp.put('/resources/', stream, null).catch(err => { + assert.equal(err.status, 409) + }) + }) + + it('should fail if no content type is passed', () => { + var stream = stringToStream('hello world') + return ldp.put('/resources/testPut.txt', stream, null).catch(err => { + assert.equal(err.status, 415) + }) + }) }) describe('delete', function () { @@ -160,7 +173,7 @@ describe('LDP', function () { it.skip('should delete a file in an existing dir', async () => { // First create a dummy file var stream = stringToStream('hello world') - await ldp.put('/resources/testPut.txt', stream) + await ldp.put('/resources/testPut.txt', stream, 'text/plain') // Make sure it exists fs.stat(ldp.resourceMapper._rootPath + '/resources/testPut.txt', function (err) { if (err) { @@ -181,7 +194,7 @@ describe('LDP', function () { it.skip('should fail to delete a non-empty folder', async () => { // First create a dummy file var stream = stringToStream('hello world') - await ldp.put('/resources/dummy/testPutBlocking.txt', stream) + await ldp.put('/resources/dummy/testPutBlocking.txt', stream, 'text/plain') // Make sure it exists fs.stat(ldp.resourceMapper._rootPath + '/resources/dummy/testPutBlocking.txt', function (err) { if (err) { @@ -196,7 +209,7 @@ describe('LDP', function () { it.skip('should fail to delete nested non-empty folders', async () => { // First create a dummy file var stream = stringToStream('hello world') - await ldp.put('/resources/dummy/dummy2/testPutBlocking.txt', stream) + await ldp.put('/resources/dummy/dummy2/testPutBlocking.txt', stream, 'text/plain') // Make sure it exists fs.stat(ldp.resourceMapper._rootPath + '/resources/dummy/dummy2/testPutBlocking.txt', function (err) { if (err) { @@ -229,7 +242,7 @@ describe('LDP', function () { ' dcterms:title "This is a magic type" ;' + ' o:limit 500000.00 .', 'sampleContainer/magicType.ttl') - ldp.listContainer(path.join(__dirname, '../resources/sampleContainer/'), 'https://server.tld/resources/sampleContainer/', 'https://server.tld', '', 'text/turtle', function (err, data) { + ldp.listContainer(path.join(__dirname, '../resources/sampleContainer/'), 'https://server.tld/resources/sampleContainer/', 'https://server.tld', '', 'application/octet-stream', function (err, data) { if (err) done(err) var graph = $rdf.graph() $rdf.parse( diff --git a/test/resources/sampleContainer/example4$.ttl b/test/resources/sampleContainer/example4$.ttl new file mode 100644 index 000000000..fd650c9a2 --- /dev/null +++ b/test/resources/sampleContainer/example4$.ttl @@ -0,0 +1,7 @@ +@prefix : . + +:a :b "The first line\nThe second line\n more" . + +:a :b """The first line +The second line + more""" . diff --git a/test/unit/account-manager-test.js b/test/unit/account-manager-test.js index 27999db0f..bf7b4f6a9 100644 --- a/test/unit/account-manager-test.js +++ b/test/unit/account-manager-test.js @@ -17,7 +17,7 @@ const AccountManager = require('../../lib/models/account-manager') const UserAccount = require('../../lib/models/user-account') const TokenService = require('../../lib/services/token-service') const WebIdTlsCertificate = require('../../lib/models/webid-tls-certificate') -const LegacyResourceMapper = require('../../lib/legacy-resource-mapper') +const ResourceMapper = require('../../lib/resource-mapper') const testAccountsDir = path.join(__dirname, '../resources/accounts') @@ -103,11 +103,10 @@ describe('AccountManager', () => { describe('accountDirFor()', () => { it('should match the solid root dir config, in single user mode', () => { let multiuser = false - let resourceMapper = new LegacyResourceMapper({ + let resourceMapper = new ResourceMapper({ rootUrl: 'https://localhost:8443/', includeHost: multiuser, - rootPath: testAccountsDir, - defaultContentType: 'application/octet-stream' + rootPath: testAccountsDir }) let store = new LDP({ multiuser, resourceMapper }) let options = { multiuser, store, host } @@ -119,11 +118,10 @@ describe('AccountManager', () => { it('should compose the account dir in multi user mode', () => { let multiuser = true - let resourceMapper = new LegacyResourceMapper({ + let resourceMapper = new ResourceMapper({ rootUrl: 'https://localhost:8443/', includeHost: multiuser, - rootPath: testAccountsDir, - defaultContentType: 'application/octet-stream' + rootPath: testAccountsDir }) let store = new LDP({ multiuser, resourceMapper }) let host = SolidHost.from({ serverUri: 'https://localhost' }) @@ -315,10 +313,9 @@ describe('AccountManager', () => { describe('rootAclFor()', () => { it('should return the server root .acl in single user mode', () => { - let resourceMapper = new LegacyResourceMapper({ + let resourceMapper = new ResourceMapper({ rootUrl: 'https://localhost:8443/', rootPath: process.cwd(), - defaultContentType: 'application/octet-stream', includeHost: false }) let store = new LDP({ suffixAcl: '.acl', multiuser: false, resourceMapper }) @@ -333,10 +330,9 @@ describe('AccountManager', () => { }) it('should return the profile root .acl in multi user mode', () => { - let resourceMapper = new LegacyResourceMapper({ + let resourceMapper = new ResourceMapper({ rootUrl: 'https://localhost:8443/', rootPath: process.cwd(), - defaultContentType: 'application/octet-stream', includeHost: true }) let store = new LDP({ suffixAcl: '.acl', multiuser: true, resourceMapper }) diff --git a/test/unit/legacy-resource-mapper-test.js b/test/unit/legacy-resource-mapper-test.js deleted file mode 100644 index f9efec22c..000000000 --- a/test/unit/legacy-resource-mapper-test.js +++ /dev/null @@ -1,246 +0,0 @@ -const LegacyResourceMapper = require('../../lib/legacy-resource-mapper') -const chai = require('chai') -const { expect } = chai -chai.use(require('chai-as-promised')) - -const rootUrl = 'http://localhost/' -const rootPath = '/var/www/folder/' - -const itMapsUrl = asserter(mapsUrl) -const itMapsFile = asserter(mapsFile) - -describe('LegacyResourceMapper', () => { - describe('A LegacyResourceMapper instance for a single-host setup', () => { - const mapper = new LegacyResourceMapper({ rootUrl, rootPath }) - - // adapted PUT base cases from https://www.w3.org/DesignIssues/HTTPFilenameMapping.html - - itMapsUrl(mapper, 'a URL with an extension that matches the content type', - { - url: 'http://localhost/space/foo.html', - contentType: 'text/html', - createIfNotExists: true - }, - { - path: `${rootPath}space/foo.html`, - contentType: 'text/html' - }) - - // Additional PUT cases - - itMapsUrl(mapper, 'a URL without content type', - { - url: 'http://localhost/space/foo.html', - createIfNotExists: true - }, - { - path: `${rootPath}space/foo.html`, - contentType: 'text/html' - }) - - itMapsUrl(mapper, 'a URL with an alternative extension that matches the content type', - { - url: 'http://localhost/space/foo.jpeg', - contentType: 'image/jpeg', - createIfNotExists: true - }, - { - path: `${rootPath}space/foo.jpeg`, - contentType: 'image/jpeg' - }) - - itMapsUrl(mapper, 'a URL with an uppercase extension that matches the content type', - { - url: 'http://localhost/space/foo.JPG', - contentType: 'image/jpeg', - createIfNotExists: true - }, - { - path: `${rootPath}space/foo.JPG`, - contentType: 'image/jpeg' - }) - - itMapsUrl(mapper, 'a URL with a mixed-case extension that matches the content type', - { - url: 'http://localhost/space/foo.jPeG', - contentType: 'image/jpeg', - createIfNotExists: true - }, - { - path: `${rootPath}space/foo.jPeG`, - contentType: 'image/jpeg' - }) - - // GET/HEAD/POST/DELETE/PATCH base cases - - itMapsUrl(mapper, 'a URL of an existing file with extension', - { - url: 'http://localhost/space/foo.html' - }, - { - path: `${rootPath}space/foo.html`, - contentType: 'text/html' - }) - - itMapsUrl(mapper, 'an extensionless URL of an existing file', - { - url: 'http://localhost/space/foo' - }, - { - path: `${rootPath}space/foo`, - contentType: 'text/turtle' - }) - - itMapsUrl(mapper, 'a URL of an existing file with encoded characters', - { - url: 'http://localhost/space/foo%20bar%20bar.html' - }, - { - path: `${rootPath}space/foo bar bar.html`, - contentType: 'text/html' - }) - - itMapsUrl(mapper, 'a URL of a new file with encoded characters', - { - url: 'http://localhost/space%2Ffoo%20bar%20bar.html', - contentType: 'text/html', - createIfNotExists: true - }, - { - path: `${rootPath}space/foo bar bar.html`, - contentType: 'text/html' - }) - - // Security cases - - itMapsUrl(mapper, 'a URL with a /.. path segment', - { - url: 'http://localhost/space/../bar' - }, - new Error('Disallowed /.. segment in URL')) - - itMapsUrl(mapper, 'a URL with an encoded /.. path segment', - { - url: 'http://localhost/space%2F..%2Fbar' - }, - new Error('Disallowed /.. segment in URL')) - - // File to URL mapping - - itMapsFile(mapper, 'an HTML file', - { path: `${rootPath}space/foo.html` }, - { - url: 'http://localhost/space/foo.html', - contentType: 'text/html' - }) - - itMapsFile(mapper, 'a Turtle file', - { path: `${rootPath}space/foo.ttl` }, - { - url: 'http://localhost/space/foo.ttl', - contentType: 'text/turtle' - }) - - itMapsFile(mapper, 'a file with an uppercase extension', - { path: `${rootPath}space/foo.HTML` }, - { - url: 'http://localhost/space/foo.HTML', - contentType: 'text/html' - }) - - itMapsFile(mapper, 'a file with a mixed-case extension', - { path: `${rootPath}space/foo.HtMl` }, - { - url: 'http://localhost/space/foo.HtMl', - contentType: 'text/html' - }) - - itMapsFile(mapper, 'a file with disallowed IRI characters', - { path: `${rootPath}space/foo bar bar.html` }, - { - url: 'http://localhost/space/foo%20bar%20bar.html', - contentType: 'text/html' - }) - }) - - describe('A LegacyResourceMapper instance for a multi-host setup', () => { - const mapper = new LegacyResourceMapper({ rootUrl, rootPath, includeHost: true }) - - itMapsUrl(mapper, 'a URL with a host', - { - url: 'http://example.org/space/foo.html', - contentType: 'text/html', - createIfNotExists: true - }, - { - path: `${rootPath}example.org/space/foo.html`, - contentType: 'text/html' - }) - - itMapsUrl(mapper, 'a URL with a host with a port', - { - url: 'http://example.org:3000/space/foo.html', - contentType: 'text/html', - createIfNotExists: true - }, - { - path: `${rootPath}example.org/space/foo.html`, - contentType: 'text/html' - }) - - itMapsFile(mapper, 'a file on a host', - { - path: `${rootPath}space/foo.html`, - hostname: 'example.org' - }, - { - url: 'http://example.org/space/foo.html', - contentType: 'text/html' - }) - }) - - describe('A LegacyResourceMapper instance for a multi-host setup with a subfolder root URL', () => { - const rootUrl = 'http://localhost/foo/bar/' - const mapper = new LegacyResourceMapper({ rootUrl, rootPath, includeHost: true }) - - itMapsFile(mapper, 'a file on a host', - { - path: `${rootPath}space/foo.html`, - hostname: 'example.org' - }, - { - url: 'http://example.org/foo/bar/space/foo.html', - contentType: 'text/html' - }) - }) -}) - -function asserter (assert) { - const f = (...args) => assert(it, ...args) - f.skip = (...args) => assert(it.skip, ...args) - f.only = (...args) => assert(it.only, ...args) - return f -} - -function mapsUrl (it, mapper, label, options, expected) { - // Set up positive test - if (!(expected instanceof Error)) { - it(`maps ${label}`, async () => { - const actual = await mapper.mapUrlToFile(options) - expect(actual).to.deep.equal(expected) - }) - // Set up error test - } else { - it(`does not map ${label}`, async () => { - const actual = mapper.mapUrlToFile(options) - await expect(actual).to.be.rejectedWith(expected.message) - }) - } -} - -function mapsFile (it, mapper, label, options, expected) { - it(`maps ${label}`, async () => { - const actual = await mapper.mapFileToUrl(options) - expect(actual).to.deep.equal(expected) - }) -} diff --git a/test/unit/resource-mapper-test.js b/test/unit/resource-mapper-test.js index c120c7bdc..027dfdb1c 100644 --- a/test/unit/resource-mapper-test.js +++ b/test/unit/resource-mapper-test.js @@ -14,8 +14,7 @@ describe('ResourceMapper', () => { const mapper = new ResourceMapper({ rootUrl, rootPath, - includeHost: false, - defaultContentType: 'application/octet-stream' + includeHost: false }) // PUT base cases from https://www.w3.org/DesignIssues/HTTPFilenameMapping.html @@ -98,6 +97,28 @@ describe('ResourceMapper', () => { contentType: 'image/jpeg' }) + itMapsUrl(mapper, 'a URL with an overridden extension that matches the content type', + { + url: 'http://localhost/space/foo.acl', + contentType: 'text/turtle', + createIfNotExists: true + }, + { + path: `${rootPath}space/foo.acl`, + contentType: 'text/turtle' + }) + + itMapsUrl(mapper, 'a URL with an alternative overridden extension that matches the content type', + { + url: 'http://localhost/space/foo.acl', + contentType: 'text/n3', + createIfNotExists: true + }, + { + path: `${rootPath}space/foo.acl$.n3`, + contentType: 'text/n3' + }) + // GET/HEAD/POST/DELETE/PATCH base cases itMapsUrl(mapper, 'a URL of a non-existing file', @@ -192,6 +213,87 @@ describe('ResourceMapper', () => { contentType: 'text/html' }) + itMapsUrl(mapper, 'a URL of an existing .acl file', + { + url: 'http://localhost/space/.acl' + }, + [ + `${rootPath}space/.acl` + ], + { + path: `${rootPath}space/.acl`, + contentType: 'text/turtle' + }) + + itMapsUrl(mapper, 'a URL of an existing .acl file with a different content type', + { + url: 'http://localhost/space/.acl' + }, + [ + `${rootPath}space/.acl$.n3` + ], + { + path: `${rootPath}space/.acl$.n3`, + contentType: 'text/n3' + }) + + itMapsUrl(mapper, 'a URL ending with a slash to an index file when index.html is available', + { + url: 'http://localhost/space/' + }, + [ + `${rootPath}space/index.html`, + `${rootPath}space/index$.ttl` + ], + { + path: `${rootPath}space/index.html`, + contentType: 'text/html' + }) + + itMapsUrl(mapper, 'a URL ending with a slash to an index file when index$.html is available', + { + url: 'http://localhost/space/' + }, + [ + `${rootPath}space/index$.html`, + `${rootPath}space/index$.ttl` + ], + { + path: `${rootPath}space/index$.html`, + contentType: 'text/html' + }) + + itMapsUrl(mapper, 'a URL ending with a slash to a folder when no index is available', + { + url: 'http://localhost/space/' + }, + { + path: `${rootPath}space/`, + contentType: 'application/octet-stream' + }) + + itMapsUrl(mapper, 'a URL ending with a slash to an index file for text/html when index.html not is available', + { + url: 'http://localhost/space/', + contentType: 'text/html', + createIfNotExists: true + }, + { + path: `${rootPath}space/index.html`, + contentType: 'text/html' + }) + + itMapsUrl(mapper, 'a URL ending with a slash to an index file for text/turtle when index.ttl not is available', + { + url: 'http://localhost/space/', + contentType: 'text/turtle', + createIfNotExists: true + }, + { + path: `${rootPath}space/index.ttl`, + contentType: 'text/turtle' + }) + // Security cases itMapsUrl(mapper, 'a URL with an unknown content type', @@ -233,6 +335,13 @@ describe('ResourceMapper', () => { contentType: 'text/turtle' }) + itMapsFile(mapper, 'an ACL file', + { path: `${rootPath}space/.acl` }, + { + url: 'http://localhost/space/.acl', + contentType: 'text/turtle' + }) + itMapsFile(mapper, 'an unknown file type', { path: `${rootPath}space/foo.bar` }, { @@ -448,7 +557,7 @@ function mapsUrl (it, mapper, label, options, files, expected) { // Mock filesystem function mockReaddir () { mapper._readdir = async (path) => { - expect(path).to.equal(`${rootPath}space/`) + expect(path.startsWith(`${rootPath}space/`)).to.equal(true) return files.map(f => f.replace(/.*\//, '')) } } diff --git a/test/unit/user-accounts-api-test.js b/test/unit/user-accounts-api-test.js index 01f7be0f3..32c909ed1 100644 --- a/test/unit/user-accounts-api-test.js +++ b/test/unit/user-accounts-api-test.js @@ -13,7 +13,7 @@ const LDP = require('../../lib/ldp') const SolidHost = require('../../lib/models/solid-host') const AccountManager = require('../../lib/models/account-manager') const testAccountsDir = path.join(__dirname, '..', 'resources', 'accounts') -var LegacyResourceMapper = require('../../lib/legacy-resource-mapper') +var ResourceMapper = require('../../lib/resource-mapper') const api = require('../../lib/api/accounts/user-accounts') @@ -27,11 +27,10 @@ describe('api/accounts/user-accounts', () => { describe('newCertificate()', () => { describe('in multi user mode', () => { let multiuser = true - let resourceMapper = new LegacyResourceMapper({ + let resourceMapper = new ResourceMapper({ rootUrl: 'https://localhost:8443/', includeHost: multiuser, - rootPath: testAccountsDir, - defaultContentType: 'text/turtle' + rootPath: testAccountsDir }) let store = new LDP({ multiuser, resourceMapper }) diff --git a/test/unit/utils-test.js b/test/unit/utils-test.js index 3d7213bf0..21129296a 100644 --- a/test/unit/utils-test.js +++ b/test/unit/utils-test.js @@ -70,4 +70,37 @@ describe('Utility functions', function () { assert.equal(utils.fullUrlForReq(req), 'https://example.com/resource1?sort=desc') }) }) + + describe('getContentType()', () => { + describe('for Express headers', () => { + it('should default to text/plain', () => { + assert.equal(utils.getContentType({}), 'text/plain') + }) + + it('should get a basic content type', () => { + assert.equal(utils.getContentType({'content-type': 'text/html'}), 'text/html') + }) + + it('should get a content type without its charset', () => { + assert.equal(utils.getContentType({'content-type': 'text/html; charset=us-ascii'}), 'text/html') + }) + }) + + describe('for Fetch API headers', () => { + it('should default to text/plain', () => { + // eslint-disable-next-line no-undef + assert.equal(utils.getContentType(new Headers({})), 'text/plain') + }) + + it('should get a basic content type', () => { + // eslint-disable-next-line no-undef + assert.equal(utils.getContentType(new Headers({'content-type': 'text/html'})), 'text/html') + }) + + it('should get a content type without its charset', () => { + // eslint-disable-next-line no-undef + assert.equal(utils.getContentType(new Headers({'content-type': 'text/html; charset=us-ascii'})), 'text/html') + }) + }) + }) })