fix: Let Representations always have a body

This is relevant when the request has a content-type
but no data.
This commit is contained in:
Joachim Van Herwegen 2021-10-11 15:21:40 +02:00
parent f1ef2ced03
commit 5613ff9e71
36 changed files with 95 additions and 63 deletions

View File

@ -11,9 +11,6 @@ export class SparqlPatchModesExtractor extends ModesExtractor {
if (method !== 'PATCH') { if (method !== 'PATCH') {
throw new NotImplementedHttpError(`Cannot determine permissions of ${method}, only PATCH.`); throw new NotImplementedHttpError(`Cannot determine permissions of ${method}, only PATCH.`);
} }
if (!body) {
throw new NotImplementedHttpError('Cannot determine permissions of PATCH operations without a body.');
}
if (!this.isSparql(body)) { if (!this.isSparql(body)) {
throw new NotImplementedHttpError('Cannot determine permissions of non-SPARQL patches.'); throw new NotImplementedHttpError('Cannot determine permissions of non-SPARQL patches.');
} }

View File

@ -29,7 +29,7 @@ export interface Operation {
*/ */
permissionSet?: PermissionSet; permissionSet?: PermissionSet;
/** /**
* Optional representation of the body. * Representation of the body and metadata headers.
*/ */
body?: Representation; body: Representation;
} }

View File

@ -19,4 +19,4 @@ export interface BodyParserArgs {
* Parses the body of an incoming {@link HttpRequest} and converts it to a {@link Representation}. * Parses the body of an incoming {@link HttpRequest} and converts it to a {@link Representation}.
*/ */
export abstract class BodyParser extends export abstract class BodyParser extends
AsyncHandler<BodyParserArgs, Representation | undefined> {} AsyncHandler<BodyParserArgs, Representation> {}

View File

@ -13,7 +13,7 @@ export class RawBodyParser extends BodyParser {
// Note that the only reason this is a union is in case the body is empty. // Note that the only reason this is a union is in case the body is empty.
// If this check gets moved away from the BodyParsers this union could be removed // If this check gets moved away from the BodyParsers this union could be removed
public async handle({ request, metadata }: BodyParserArgs): Promise<Representation | undefined> { public async handle({ request, metadata }: BodyParserArgs): Promise<Representation> {
const { const {
'content-type': contentType, 'content-type': contentType,
'content-length': contentLength, 'content-length': contentLength,
@ -26,7 +26,7 @@ export class RawBodyParser extends BodyParser {
// some still provide a Content-Length of 0 (but without Content-Type). // some still provide a Content-Length of 0 (but without Content-Type).
if ((!contentLength || (/^0+$/u.test(contentLength) && !contentType)) && !transferEncoding) { if ((!contentLength || (/^0+$/u.test(contentLength) && !contentType)) && !transferEncoding) {
this.logger.debug('HTTP request does not have a body, or its empty body is missing a Content-Type header'); this.logger.debug('HTTP request does not have a body, or its empty body is missing a Content-Type header');
return; return new BasicRepresentation([], metadata);
} }
// While RFC7231 allows treating a body without content type as an octet stream, // While RFC7231 allows treating a body without content type as an octet stream,

View File

@ -38,6 +38,7 @@ export class SparqlUpdateBodyParser extends BodyParser {
binary: true, binary: true,
data: guardedStreamFrom(sparql), data: guardedStreamFrom(sparql),
metadata, metadata,
isEmpty: false,
}; };
} }
} }

View File

@ -32,9 +32,9 @@ export class PatchOperationHandler extends OperationHandler {
// Solid, §2.1: "A Solid server MUST reject PUT, POST and PATCH requests // Solid, §2.1: "A Solid server MUST reject PUT, POST and PATCH requests
// without the Content-Type header with a status code of 400." // without the Content-Type header with a status code of 400."
// https://solid.github.io/specification/protocol#http-server // https://solid.github.io/specification/protocol#http-server
if (!operation.body?.metadata.contentType) { if (!operation.body.metadata.contentType) {
this.logger.warn('No Content-Type header specified on PATCH request'); this.logger.warn('PATCH requests require the Content-Type header to be set');
throw new BadRequestHttpError('No Content-Type header specified on PATCH request'); throw new BadRequestHttpError('PATCH requests require the Content-Type header to be set');
} }
await this.store.modifyResource(operation.target, operation.body as Patch, operation.conditions); await this.store.modifyResource(operation.target, operation.body as Patch, operation.conditions);
return new ResetResponseDescription(); return new ResetResponseDescription();

View File

@ -31,9 +31,9 @@ export class PostOperationHandler extends OperationHandler {
// Solid, §2.1: "A Solid server MUST reject PUT, POST and PATCH requests // Solid, §2.1: "A Solid server MUST reject PUT, POST and PATCH requests
// without the Content-Type header with a status code of 400." // without the Content-Type header with a status code of 400."
// https://solid.github.io/specification/protocol#http-server // https://solid.github.io/specification/protocol#http-server
if (!operation.body?.metadata.contentType) { if (!operation.body.metadata.contentType) {
this.logger.warn('No Content-Type header specified on POST request'); this.logger.warn('POST requests require the Content-Type header to be set');
throw new BadRequestHttpError('No Content-Type header specified on POST request'); throw new BadRequestHttpError('POST requests require the Content-Type header to be set');
} }
const identifier = await this.store.addResource(operation.target, operation.body, operation.conditions); const identifier = await this.store.addResource(operation.target, operation.body, operation.conditions);
return new CreatedResponseDescription(identifier); return new CreatedResponseDescription(identifier);

View File

@ -31,9 +31,9 @@ export class PutOperationHandler extends OperationHandler {
// Solid, §2.1: "A Solid server MUST reject PUT, POST and PATCH requests // Solid, §2.1: "A Solid server MUST reject PUT, POST and PATCH requests
// without the Content-Type header with a status code of 400." // without the Content-Type header with a status code of 400."
// https://solid.github.io/specification/protocol#http-server // https://solid.github.io/specification/protocol#http-server
if (!operation.body?.metadata.contentType) { if (!operation.body.metadata.contentType) {
this.logger.warn('No Content-Type header specified on PUT request'); this.logger.warn('PUT requests require the Content-Type header to be set');
throw new BadRequestHttpError('No Content-Type header specified on PUT request'); throw new BadRequestHttpError('PUT requests require the Content-Type header to be set');
} }
await this.store.setRepresentation(operation.target, operation.body, operation.conditions); await this.store.setRepresentation(operation.target, operation.body, operation.conditions);
return new ResetResponseDescription(); return new ResetResponseDescription();

View File

@ -24,6 +24,11 @@ export class BasicRepresentation implements Representation {
public readonly metadata: RepresentationMetadata; public readonly metadata: RepresentationMetadata;
public readonly binary: boolean; public readonly binary: boolean;
/**
* An empty Representation
*/
public constructor();
/** /**
* @param data - The representation data * @param data - The representation data
* @param metadata - The representation metadata * @param metadata - The representation metadata
@ -86,13 +91,15 @@ export class BasicRepresentation implements Representation {
); );
public constructor( public constructor(
data: Readable | any[] | string, data?: Readable | any[] | string,
metadata: RepresentationMetadata | MetadataRecord | MetadataIdentifier | string, metadata?: RepresentationMetadata | MetadataRecord | MetadataIdentifier | string,
metadataRest?: MetadataRecord | string | boolean, metadataRest?: MetadataRecord | string | boolean,
binary?: boolean, binary?: boolean,
) { ) {
if (typeof data === 'string' || Array.isArray(data)) { if (typeof data === 'string' || Array.isArray(data)) {
data = guardedStreamFrom(data); data = guardedStreamFrom(data);
} else if (!data) {
data = guardedStreamFrom([]);
} }
this.data = guardStream(data); this.data = guardStream(data);
@ -110,4 +117,11 @@ export class BasicRepresentation implements Representation {
} }
this.binary = binary; this.binary = binary;
} }
/**
* Data should only be interpreted if there is a content type.
*/
public get isEmpty(): boolean {
return !this.metadata.contentType;
}
} }

View File

@ -19,4 +19,10 @@ export interface Representation {
* (as opposed to complex objects). * (as opposed to complex objects).
*/ */
binary: boolean; binary: boolean;
/**
* Whether the data stream is empty.
* This being true does not imply that the data stream has a length of more than 0,
* only that it is a possibility and should be read to be sure.
*/
isEmpty: boolean;
} }

View File

@ -3,7 +3,6 @@ import type { ErrorHandler } from '../http/output/error/ErrorHandler';
import { RedirectResponseDescription } from '../http/output/response/RedirectResponseDescription'; import { RedirectResponseDescription } from '../http/output/response/RedirectResponseDescription';
import { ResponseDescription } from '../http/output/response/ResponseDescription'; import { ResponseDescription } from '../http/output/response/ResponseDescription';
import { BasicRepresentation } from '../http/representation/BasicRepresentation'; import { BasicRepresentation } from '../http/representation/BasicRepresentation';
import type { Representation } from '../http/representation/Representation';
import { getLoggerFor } from '../logging/LogUtil'; import { getLoggerFor } from '../logging/LogUtil';
import type { HttpRequest } from '../server/HttpRequest'; import type { HttpRequest } from '../server/HttpRequest';
import type { OperationHttpHandlerInput } from '../server/OperationHttpHandler'; import type { OperationHttpHandlerInput } from '../server/OperationHttpHandler';
@ -124,10 +123,10 @@ export class IdentityProviderHttpHandler extends OperationHttpHandler {
} }
// Cloning input data so it can be sent back in case of errors // Cloning input data so it can be sent back in case of errors
let clone: Representation | undefined; let clone = operation.body;
// IDP handlers expect JSON data // IDP handlers expect JSON data
if (operation.body) { if (!operation.body.isEmpty) {
const args = { const args = {
representation: operation.body, representation: operation.body,
preferences: { type: { [APPLICATION_JSON]: 1 }}, preferences: { type: { [APPLICATION_JSON]: 1 }},
@ -187,7 +186,7 @@ export class IdentityProviderHttpHandler extends OperationHttpHandler {
const details = await readJsonStream(response.data!); const details = await readJsonStream(response.data!);
// Add the input data to the JSON response; // Add the input data to the JSON response;
if (operation.body) { if (!operation.body.isEmpty) {
details.prefilled = await readJsonStream(operation.body.data); details.prefilled = await readJsonStream(operation.body.data);
// Don't send passwords back // Don't send passwords back

View File

@ -12,7 +12,7 @@ export class SessionHttpHandler extends InteractionHandler {
throw new NotImplementedHttpError('Only interactions with a valid session are supported.'); throw new NotImplementedHttpError('Only interactions with a valid session are supported.');
} }
const { remember } = await readJsonStream(operation.body!.data); const { remember } = await readJsonStream(operation.body.data);
return { return {
type: 'complete', type: 'complete',
details: { webId: oidcInteraction.session.accountId, shouldRemember: Boolean(remember) }, details: { webId: oidcInteraction.session.accountId, shouldRemember: Boolean(remember) },

View File

@ -39,7 +39,7 @@ export class ForgotPasswordHandler extends InteractionHandler {
public async handle({ operation }: InteractionHandlerInput): Promise<InteractionResponseResult<{ email: string }>> { public async handle({ operation }: InteractionHandlerInput): Promise<InteractionResponseResult<{ email: string }>> {
// Validate incoming data // Validate incoming data
const { email } = await readJsonStream(operation.body!.data); const { email } = await readJsonStream(operation.body.data);
assert(typeof email === 'string' && email.length > 0, 'Email required'); assert(typeof email === 'string' && email.length > 0, 'Email required');
await this.resetPassword(email); await this.resetPassword(email);

View File

@ -43,7 +43,7 @@ export class LoginHandler extends InteractionHandler {
*/ */
private async parseInput(operation: Operation): Promise<{ email: string; password: string; remember: boolean }> { private async parseInput(operation: Operation): Promise<{ email: string; password: string; remember: boolean }> {
const prefilled: Record<string, string> = {}; const prefilled: Record<string, string> = {};
const { email, password, remember } = await readJsonStream(operation.body!.data); const { email, password, remember } = await readJsonStream(operation.body.data);
assert(typeof email === 'string' && email.length > 0, 'Email required'); assert(typeof email === 'string' && email.length > 0, 'Email required');
prefilled.email = email; prefilled.email = email;
assert(typeof password === 'string' && password.length > 0, 'Password required'); assert(typeof password === 'string' && password.length > 0, 'Password required');

View File

@ -19,7 +19,7 @@ export class RegistrationHandler extends InteractionHandler {
public async handle({ operation }: InteractionHandlerInput): public async handle({ operation }: InteractionHandlerInput):
Promise<InteractionResponseResult<RegistrationResponse>> { Promise<InteractionResponseResult<RegistrationResponse>> {
const data = await readJsonStream(operation.body!.data); const data = await readJsonStream(operation.body.data);
const validated = this.registrationManager.validateInput(data, false); const validated = this.registrationManager.validateInput(data, false);
const details = await this.registrationManager.register(validated, false); const details = await this.registrationManager.register(validated, false);
return { type: 'response', details }; return { type: 'response', details };

View File

@ -24,7 +24,7 @@ export class ResetPasswordHandler extends InteractionHandler {
// Extract record ID from request URL // Extract record ID from request URL
const recordId = /\/([^/]+)$/u.exec(operation.target.path)?.[1]; const recordId = /\/([^/]+)$/u.exec(operation.target.path)?.[1];
// Validate input data // Validate input data
const { password, confirmPassword } = await readJsonStream(operation.body!.data); const { password, confirmPassword } = await readJsonStream(operation.body.data);
assert( assert(
typeof recordId === 'string' && recordId.length > 0, typeof recordId === 'string' && recordId.length > 0,
'Invalid request. Open the link from your email again', 'Invalid request. Open the link from your email again',

View File

@ -159,7 +159,7 @@ export class SetupHttpHandler extends OperationHttpHandler {
// Registration manager expects JSON data // Registration manager expects JSON data
let json: SetupInput = {}; let json: SetupInput = {};
if (operation.body) { if (!operation.body.isEmpty) {
const args = { const args = {
representation: operation.body, representation: operation.body,
preferences: { type: { [APPLICATION_JSON]: 1 }}, preferences: { type: { [APPLICATION_JSON]: 1 }},

View File

@ -37,7 +37,7 @@ class DummyConverter extends TypedRepresentationConverter {
const data = guardedStreamFrom([ 'dummy' ]); const data = guardedStreamFrom([ 'dummy' ]);
const metadata = new RepresentationMetadata(representation.metadata, 'x/x'); const metadata = new RepresentationMetadata(representation.metadata, 'x/x');
return { binary: true, data, metadata }; return { binary: true, data, metadata, isEmpty: false };
} }
} }

View File

@ -55,7 +55,7 @@ describe('A BasicRequestParser with simple input parsers', (): void => {
}); });
expect(result.body?.metadata.contentType).toEqual('text/turtle'); expect(result.body?.metadata.contentType).toEqual('text/turtle');
await expect(arrayifyStream(result.body!.data)).resolves.toEqual( await expect(arrayifyStream(result.body.data)).resolves.toEqual(
[ '<http://test.com/s> <http://test.com/p> <http://test.com/o>.' ], [ '<http://test.com/s> <http://test.com/p> <http://test.com/o>.' ],
); );
}); });

View File

@ -19,10 +19,6 @@ describe('A SparqlPatchModesExtractor', (): void => {
await expect(result).rejects.toThrow(NotImplementedHttpError); await expect(result).rejects.toThrow(NotImplementedHttpError);
await expect(result).rejects.toThrow('Cannot determine permissions of GET, only PATCH.'); await expect(result).rejects.toThrow('Cannot determine permissions of GET, only PATCH.');
result = extractor.canHandle({ ...operation, body: undefined });
await expect(result).rejects.toThrow(NotImplementedHttpError);
await expect(result).rejects.toThrow('Cannot determine permissions of PATCH operations without a body.');
result = extractor.canHandle({ ...operation, body: {} as SparqlUpdatePatch }); result = extractor.canHandle({ ...operation, body: {} as SparqlUpdatePatch });
await expect(result).rejects.toThrow(NotImplementedHttpError); await expect(result).rejects.toThrow(NotImplementedHttpError);
await expect(result).rejects.toThrow('Cannot determine permissions of non-SPARQL patches.'); await expect(result).rejects.toThrow('Cannot determine permissions of non-SPARQL patches.');

View File

@ -19,16 +19,18 @@ describe('A RawBodyparser', (): void => {
}); });
it('returns empty output if there is no content length or transfer encoding.', async(): Promise<void> => { it('returns empty output if there is no content length or transfer encoding.', async(): Promise<void> => {
input.request = guardedStreamFrom([ '' ]) as HttpRequest; input.request = guardedStreamFrom([ 'data' ]) as HttpRequest;
input.request.headers = {}; input.request.headers = {};
await expect(bodyParser.handle(input)).resolves.toBeUndefined(); const result = await bodyParser.handle(input);
await expect(arrayifyStream(result.data)).resolves.toEqual([]);
}); });
// https://github.com/solid/community-server/issues/498 // https://github.com/solid/community-server/issues/498
it('returns empty output if the content length is 0 and there is no content type.', async(): Promise<void> => { it('returns empty output if the content length is 0 and there is no content type.', async(): Promise<void> => {
input.request = guardedStreamFrom([ '' ]) as HttpRequest; input.request = guardedStreamFrom([ 'data' ]) as HttpRequest;
input.request.headers = { 'content-length': '0' }; input.request.headers = { 'content-length': '0' };
await expect(bodyParser.handle(input)).resolves.toBeUndefined(); const result = await bodyParser.handle(input);
await expect(arrayifyStream(result.data)).resolves.toEqual([]);
}); });
it('errors when a content length is specified without content type.', async(): Promise<void> => { it('errors when a content length is specified without content type.', async(): Promise<void> => {
@ -48,7 +50,7 @@ describe('A RawBodyparser', (): void => {
it('returns a Representation if there is empty data.', async(): Promise<void> => { it('returns a Representation if there is empty data.', async(): Promise<void> => {
input.request = guardedStreamFrom([]) as HttpRequest; input.request = guardedStreamFrom([]) as HttpRequest;
input.request.headers = { 'content-length': '0', 'content-type': 'text/turtle' }; input.request.headers = { 'content-length': '0', 'content-type': 'text/turtle' };
const result = (await bodyParser.handle(input))!; const result = await bodyParser.handle(input);
expect(result).toEqual({ expect(result).toEqual({
binary: true, binary: true,
data: input.request, data: input.request,
@ -60,7 +62,7 @@ describe('A RawBodyparser', (): void => {
it('returns a Representation if there is non-empty data.', async(): Promise<void> => { it('returns a Representation if there is non-empty data.', async(): Promise<void> => {
input.request = guardedStreamFrom([ '<http://test.com/s> <http://test.com/p> <http://test.com/o>.' ]) as HttpRequest; input.request = guardedStreamFrom([ '<http://test.com/s> <http://test.com/p> <http://test.com/o>.' ]) as HttpRequest;
input.request.headers = { 'transfer-encoding': 'chunked', 'content-type': 'text/turtle' }; input.request.headers = { 'transfer-encoding': 'chunked', 'content-type': 'text/turtle' };
const result = (await bodyParser.handle(input))!; const result = await bodyParser.handle(input);
expect(result).toEqual({ expect(result).toEqual({
binary: true, binary: true,
data: input.request, data: input.request,

View File

@ -1,5 +1,6 @@
import { DeleteOperationHandler } from '../../../../src/http/ldp/DeleteOperationHandler'; import { DeleteOperationHandler } from '../../../../src/http/ldp/DeleteOperationHandler';
import type { Operation } from '../../../../src/http/Operation'; import type { Operation } from '../../../../src/http/Operation';
import { BasicRepresentation } from '../../../../src/http/representation/BasicRepresentation';
import { BasicConditions } from '../../../../src/storage/BasicConditions'; import { BasicConditions } from '../../../../src/storage/BasicConditions';
import type { ResourceStore } from '../../../../src/storage/ResourceStore'; import type { ResourceStore } from '../../../../src/storage/ResourceStore';
import { NotImplementedHttpError } from '../../../../src/util/errors/NotImplementedHttpError'; import { NotImplementedHttpError } from '../../../../src/util/errors/NotImplementedHttpError';
@ -7,10 +8,11 @@ import { NotImplementedHttpError } from '../../../../src/util/errors/NotImplemen
describe('A DeleteOperationHandler', (): void => { describe('A DeleteOperationHandler', (): void => {
let operation: Operation; let operation: Operation;
const conditions = new BasicConditions({}); const conditions = new BasicConditions({});
const body = new BasicRepresentation();
const store = {} as unknown as ResourceStore; const store = {} as unknown as ResourceStore;
const handler = new DeleteOperationHandler(store); const handler = new DeleteOperationHandler(store);
beforeEach(async(): Promise<void> => { beforeEach(async(): Promise<void> => {
operation = { method: 'DELETE', target: { path: 'http://test.com/foo' }, preferences: {}, conditions }; operation = { method: 'DELETE', target: { path: 'http://test.com/foo' }, preferences: {}, conditions, body };
store.deleteResource = jest.fn(async(): Promise<any> => undefined); store.deleteResource = jest.fn(async(): Promise<any> => undefined);
}); });

View File

@ -1,5 +1,6 @@
import { GetOperationHandler } from '../../../../src/http/ldp/GetOperationHandler'; import { GetOperationHandler } from '../../../../src/http/ldp/GetOperationHandler';
import type { Operation } from '../../../../src/http/Operation'; import type { Operation } from '../../../../src/http/Operation';
import { BasicRepresentation } from '../../../../src/http/representation/BasicRepresentation';
import type { Representation } from '../../../../src/http/representation/Representation'; import type { Representation } from '../../../../src/http/representation/Representation';
import { BasicConditions } from '../../../../src/storage/BasicConditions'; import { BasicConditions } from '../../../../src/storage/BasicConditions';
import type { ResourceStore } from '../../../../src/storage/ResourceStore'; import type { ResourceStore } from '../../../../src/storage/ResourceStore';
@ -9,11 +10,12 @@ describe('A GetOperationHandler', (): void => {
let operation: Operation; let operation: Operation;
const conditions = new BasicConditions({}); const conditions = new BasicConditions({});
const preferences = {}; const preferences = {};
const body = new BasicRepresentation();
let store: ResourceStore; let store: ResourceStore;
let handler: GetOperationHandler; let handler: GetOperationHandler;
beforeEach(async(): Promise<void> => { beforeEach(async(): Promise<void> => {
operation = { method: 'GET', target: { path: 'http://test.com/foo' }, preferences, conditions }; operation = { method: 'GET', target: { path: 'http://test.com/foo' }, preferences, conditions, body };
store = { store = {
getRepresentation: jest.fn(async(): Promise<Representation> => getRepresentation: jest.fn(async(): Promise<Representation> =>
({ binary: false, data: 'data', metadata: 'metadata' } as any)), ({ binary: false, data: 'data', metadata: 'metadata' } as any)),

View File

@ -1,6 +1,7 @@
import type { Readable } from 'stream'; import type { Readable } from 'stream';
import { HeadOperationHandler } from '../../../../src/http/ldp/HeadOperationHandler'; import { HeadOperationHandler } from '../../../../src/http/ldp/HeadOperationHandler';
import type { Operation } from '../../../../src/http/Operation'; import type { Operation } from '../../../../src/http/Operation';
import { BasicRepresentation } from '../../../../src/http/representation/BasicRepresentation';
import type { Representation } from '../../../../src/http/representation/Representation'; import type { Representation } from '../../../../src/http/representation/Representation';
import { BasicConditions } from '../../../../src/storage/BasicConditions'; import { BasicConditions } from '../../../../src/storage/BasicConditions';
import type { ResourceStore } from '../../../../src/storage/ResourceStore'; import type { ResourceStore } from '../../../../src/storage/ResourceStore';
@ -10,12 +11,13 @@ describe('A HeadOperationHandler', (): void => {
let operation: Operation; let operation: Operation;
const conditions = new BasicConditions({}); const conditions = new BasicConditions({});
const preferences = {}; const preferences = {};
const body = new BasicRepresentation();
let store: ResourceStore; let store: ResourceStore;
let handler: HeadOperationHandler; let handler: HeadOperationHandler;
let data: Readable; let data: Readable;
beforeEach(async(): Promise<void> => { beforeEach(async(): Promise<void> => {
operation = { method: 'HEAD', target: { path: 'http://test.com/foo' }, preferences, conditions }; operation = { method: 'HEAD', target: { path: 'http://test.com/foo' }, preferences, conditions, body };
data = { destroy: jest.fn() } as any; data = { destroy: jest.fn() } as any;
store = { store = {
getRepresentation: jest.fn(async(): Promise<Representation> => getRepresentation: jest.fn(async(): Promise<Representation> =>

View File

@ -25,10 +25,8 @@ describe('A PatchOperationHandler', (): void => {
await expect(handler.canHandle({ operation })).rejects.toThrow(NotImplementedHttpError); await expect(handler.canHandle({ operation })).rejects.toThrow(NotImplementedHttpError);
}); });
it('errors if there is no body or content-type.', async(): Promise<void> => { it('errors if there is no content-type.', async(): Promise<void> => {
operation.body!.metadata.contentType = undefined; operation.body.metadata.contentType = undefined;
await expect(handler.handle({ operation })).rejects.toThrow(BadRequestHttpError);
delete operation.body;
await expect(handler.handle({ operation })).rejects.toThrow(BadRequestHttpError); await expect(handler.handle({ operation })).rejects.toThrow(BadRequestHttpError);
}); });

View File

@ -32,10 +32,8 @@ describe('A PostOperationHandler', (): void => {
await expect(handler.canHandle({ operation })).rejects.toThrow(NotImplementedHttpError); await expect(handler.canHandle({ operation })).rejects.toThrow(NotImplementedHttpError);
}); });
it('errors if there is no body or content-type.', async(): Promise<void> => { it('errors if there is no content-type.', async(): Promise<void> => {
operation.body!.metadata.contentType = undefined; operation.body.metadata.contentType = undefined;
await expect(handler.handle({ operation })).rejects.toThrow(BadRequestHttpError);
delete operation.body;
await expect(handler.handle({ operation })).rejects.toThrow(BadRequestHttpError); await expect(handler.handle({ operation })).rejects.toThrow(BadRequestHttpError);
}); });

View File

@ -26,10 +26,8 @@ describe('A PutOperationHandler', (): void => {
await expect(handler.canHandle({ operation })).rejects.toThrow(NotImplementedHttpError); await expect(handler.canHandle({ operation })).rejects.toThrow(NotImplementedHttpError);
}); });
it('errors if there is no body or content-type.', async(): Promise<void> => { it('errors if there is no content-type.', async(): Promise<void> => {
operation.body!.metadata.contentType = undefined; operation.body.metadata.contentType = undefined;
await expect(handler.handle({ operation })).rejects.toThrow(BadRequestHttpError);
delete operation.body;
await expect(handler.handle({ operation })).rejects.toThrow(BadRequestHttpError); await expect(handler.handle({ operation })).rejects.toThrow(BadRequestHttpError);
}); });

View File

@ -3,6 +3,7 @@ import { CredentialGroup } from '../../../../../src/authentication/Credentials';
import type { AclPermission } from '../../../../../src/authorization/permissions/AclPermission'; import type { AclPermission } from '../../../../../src/authorization/permissions/AclPermission';
import { WebAclMetadataCollector } from '../../../../../src/http/ldp/metadata/WebAclMetadataCollector'; import { WebAclMetadataCollector } from '../../../../../src/http/ldp/metadata/WebAclMetadataCollector';
import type { Operation } from '../../../../../src/http/Operation'; import type { Operation } from '../../../../../src/http/Operation';
import { BasicRepresentation } from '../../../../../src/http/representation/BasicRepresentation';
import { RepresentationMetadata } from '../../../../../src/http/representation/RepresentationMetadata'; import { RepresentationMetadata } from '../../../../../src/http/representation/RepresentationMetadata';
import { ACL, AUTH } from '../../../../../src/util/Vocabularies'; import { ACL, AUTH } from '../../../../../src/util/Vocabularies';
@ -16,6 +17,7 @@ describe('A WebAclMetadataCollector', (): void => {
method: 'GET', method: 'GET',
target: { path: 'http://test.com/foo' }, target: { path: 'http://test.com/foo' },
preferences: {}, preferences: {},
body: new BasicRepresentation(),
}; };
metadata = new RepresentationMetadata(); metadata = new RepresentationMetadata();

View File

@ -38,7 +38,12 @@ describe('An IdentityProviderHttpHandler', (): void => {
let handler: IdentityProviderHttpHandler; let handler: IdentityProviderHttpHandler;
beforeEach(async(): Promise<void> => { beforeEach(async(): Promise<void> => {
operation = { method: 'GET', target: { path: 'http://test.com/idp' }, preferences: { type: { 'text/html': 1 }}}; operation = {
method: 'GET',
target: { path: 'http://test.com/idp' },
preferences: { type: { 'text/html': 1 }},
body: new BasicRepresentation(),
};
provider = { provider = {
callback: jest.fn(), callback: jest.fn(),

View File

@ -43,6 +43,7 @@ describe('A SetupHttpHandler', (): void => {
method: 'GET', method: 'GET',
target: { path: 'http://test.com/setup' }, target: { path: 'http://test.com/setup' },
preferences: { type: { 'text/html': 1 }}, preferences: { type: { 'text/html': 1 }},
body: new BasicRepresentation(),
}; };
errorHandler = { handleSafe: jest.fn(({ error }: ErrorHandlerArgs): ResponseDescription => ({ errorHandler = { handleSafe: jest.fn(({ error }: ErrorHandlerArgs): ResponseDescription => ({

View File

@ -5,6 +5,7 @@ import type { PermissionReader } from '../../../src/authorization/PermissionRead
import type { ModesExtractor } from '../../../src/authorization/permissions/ModesExtractor'; import type { ModesExtractor } from '../../../src/authorization/permissions/ModesExtractor';
import { AccessMode } from '../../../src/authorization/permissions/Permissions'; import { AccessMode } from '../../../src/authorization/permissions/Permissions';
import type { Operation } from '../../../src/http/Operation'; import type { Operation } from '../../../src/http/Operation';
import { BasicRepresentation } from '../../../src/http/representation/BasicRepresentation';
import { AuthorizingHttpHandler } from '../../../src/server/AuthorizingHttpHandler'; import { AuthorizingHttpHandler } from '../../../src/server/AuthorizingHttpHandler';
import type { HttpRequest } from '../../../src/server/HttpRequest'; import type { HttpRequest } from '../../../src/server/HttpRequest';
import type { HttpResponse } from '../../../src/server/HttpResponse'; import type { HttpResponse } from '../../../src/server/HttpResponse';
@ -30,6 +31,7 @@ describe('An AuthorizingHttpHandler', (): void => {
target: { path: 'http://test.com/foo' }, target: { path: 'http://test.com/foo' },
method: 'GET', method: 'GET',
preferences: {}, preferences: {},
body: new BasicRepresentation(),
}; };
credentialsExtractor = { credentialsExtractor = {

View File

@ -5,6 +5,7 @@ import type { ErrorHandler } from '../../../src/http/output/error/ErrorHandler';
import { OkResponseDescription } from '../../../src/http/output/response/OkResponseDescription'; import { OkResponseDescription } from '../../../src/http/output/response/OkResponseDescription';
import { ResponseDescription } from '../../../src/http/output/response/ResponseDescription'; import { ResponseDescription } from '../../../src/http/output/response/ResponseDescription';
import type { ResponseWriter } from '../../../src/http/output/ResponseWriter'; import type { ResponseWriter } from '../../../src/http/output/ResponseWriter';
import { BasicRepresentation } from '../../../src/http/representation/BasicRepresentation';
import { RepresentationMetadata } from '../../../src/http/representation/RepresentationMetadata'; import { RepresentationMetadata } from '../../../src/http/representation/RepresentationMetadata';
import type { HttpRequest } from '../../../src/server/HttpRequest'; import type { HttpRequest } from '../../../src/server/HttpRequest';
import type { HttpResponse } from '../../../src/server/HttpResponse'; import type { HttpResponse } from '../../../src/server/HttpResponse';
@ -15,7 +16,8 @@ describe('A ParsingHttpHandler', (): void => {
const request: HttpRequest = {} as any; const request: HttpRequest = {} as any;
const response: HttpResponse = {} as any; const response: HttpResponse = {} as any;
const preferences = { type: { 'text/html': 1 }}; const preferences = { type: { 'text/html': 1 }};
const operation: Operation = { method: 'GET', target: { path: 'http://test.com/foo' }, preferences }; const body = new BasicRepresentation();
const operation: Operation = { method: 'GET', target: { path: 'http://test.com/foo' }, preferences, body };
const errorResponse = new ResponseDescription(400); const errorResponse = new ResponseDescription(400);
let requestParser: jest.Mocked<RequestParser>; let requestParser: jest.Mocked<RequestParser>;
let metadataCollector: jest.Mocked<OperationMetadataCollector>; let metadataCollector: jest.Mocked<OperationMetadataCollector>;

View File

@ -164,6 +164,7 @@ describe('A DataAccessorBasedStore', (): void => {
metadata: new RepresentationMetadata( metadata: new RepresentationMetadata(
{ [CONTENT_TYPE]: 'text/plain', [RDF.type]: DataFactory.namedNode(LDP.Resource) }, { [CONTENT_TYPE]: 'text/plain', [RDF.type]: DataFactory.namedNode(LDP.Resource) },
), ),
isEmpty: false,
}; };
}); });

View File

@ -4,6 +4,7 @@ import arrayifyStream from 'arrayify-stream';
import { SparqlEndpointFetcher } from 'fetch-sparql-endpoint'; import { SparqlEndpointFetcher } from 'fetch-sparql-endpoint';
import { DataFactory } from 'n3'; import { DataFactory } from 'n3';
import type { Quad } from 'rdf-js'; import type { Quad } from 'rdf-js';
import { BasicRepresentation } from '../../../../src/http/representation/BasicRepresentation';
import { RepresentationMetadata } from '../../../../src/http/representation/RepresentationMetadata'; import { RepresentationMetadata } from '../../../../src/http/representation/RepresentationMetadata';
import { SparqlDataAccessor } from '../../../../src/storage/accessors/SparqlDataAccessor'; import { SparqlDataAccessor } from '../../../../src/storage/accessors/SparqlDataAccessor';
import { INTERNAL_QUADS } from '../../../../src/util/ContentTypes'; import { INTERNAL_QUADS } from '../../../../src/util/ContentTypes';
@ -69,11 +70,13 @@ describe('A SparqlDataAccessor', (): void => {
}); });
it('can only handle quad data.', async(): Promise<void> => { it('can only handle quad data.', async(): Promise<void> => {
await expect(accessor.canHandle({ binary: true, data, metadata })).rejects.toThrow(UnsupportedMediaTypeHttpError); let representation = new BasicRepresentation(data, metadata, true);
metadata.contentType = 'newInternalType'; await expect(accessor.canHandle(representation)).rejects.toThrow(UnsupportedMediaTypeHttpError);
await expect(accessor.canHandle({ binary: false, data, metadata })).rejects.toThrow(UnsupportedMediaTypeHttpError); representation = new BasicRepresentation(data, 'newInternalType', false);
await expect(accessor.canHandle(representation)).rejects.toThrow(UnsupportedMediaTypeHttpError);
representation = new BasicRepresentation(data, INTERNAL_QUADS, false);
metadata.contentType = INTERNAL_QUADS; metadata.contentType = INTERNAL_QUADS;
await expect(accessor.canHandle({ binary: false, data, metadata })).resolves.toBeUndefined(); await expect(accessor.canHandle(representation)).resolves.toBeUndefined();
}); });
it('returns the corresponding quads when data is requested.', async(): Promise<void> => { it('returns the corresponding quads when data is requested.', async(): Promise<void> => {

View File

@ -19,6 +19,7 @@ function getPatch(query: string): SparqlUpdatePatch {
data: guardedStreamFrom(prefixedQuery), data: guardedStreamFrom(prefixedQuery),
metadata: new RepresentationMetadata(), metadata: new RepresentationMetadata(),
binary: true, binary: true,
isEmpty: false,
}; };
} }

View File

@ -26,7 +26,7 @@ describe('A ConvertingRouterRule', (): void => {
rule = new ConvertingRouterRule({ store: store1, supportChecker: checker1 }, defaultStore); rule = new ConvertingRouterRule({ store: store1, supportChecker: checker1 }, defaultStore);
metadata = new RepresentationMetadata(); metadata = new RepresentationMetadata();
representation = { binary: true, data: 'data!' as any, metadata }; representation = { binary: true, data: 'data!' as any, metadata, isEmpty: false };
}); });
it('returns the corresponding store if it supports the input.', async(): Promise<void> => { it('returns the corresponding store if it supports the input.', async(): Promise<void> => {