feat: Support content negotiation for IDP requests

This commit is contained in:
Joachim Van Herwegen
2021-08-10 15:55:49 +02:00
parent 7b42c72142
commit 80ebd02cc4
20 changed files with 483 additions and 209 deletions

View File

@@ -10,14 +10,20 @@ import type { RequestParser } from '../../../src/ldp/http/RequestParser';
import type { ResponseWriter } from '../../../src/ldp/http/ResponseWriter';
import type { Operation } from '../../../src/ldp/operations/Operation';
import { BasicRepresentation } from '../../../src/ldp/representation/BasicRepresentation';
import type { Representation } from '../../../src/ldp/representation/Representation';
import type { HttpRequest } from '../../../src/server/HttpRequest';
import type { HttpResponse } from '../../../src/server/HttpResponse';
import type { TemplateHandler } from '../../../src/server/util/TemplateHandler';
import type {
RepresentationConverter,
RepresentationConverterArgs,
} from '../../../src/storage/conversion/RepresentationConverter';
import { BadRequestHttpError } from '../../../src/util/errors/BadRequestHttpError';
import { InternalServerError } from '../../../src/util/errors/InternalServerError';
import { SOLID_HTTP } from '../../../src/util/Vocabularies';
import { readableToString } from '../../../src/util/StreamUtil';
import { SOLID_HTTP, SOLID_META } from '../../../src/util/Vocabularies';
describe('An IdentityProviderHttpHandler', (): void => {
const apiVersion = '0.1';
const baseUrl = 'http://test.com/';
const idpPath = '/idp';
let request: HttpRequest;
@@ -26,7 +32,7 @@ describe('An IdentityProviderHttpHandler', (): void => {
let providerFactory: jest.Mocked<ProviderFactory>;
let routes: { response: InteractionRoute; complete: InteractionRoute };
let interactionCompleter: jest.Mocked<InteractionCompleter>;
let templateHandler: jest.Mocked<TemplateHandler>;
let converter: jest.Mocked<RepresentationConverter>;
let errorHandler: jest.Mocked<ErrorHandler>;
let responseWriter: jest.Mocked<ResponseWriter>;
let provider: jest.Mocked<Provider>;
@@ -59,11 +65,20 @@ describe('An IdentityProviderHttpHandler', (): void => {
];
routes = {
response: new InteractionRoute('/routeResponse', '/view1', handlers[0], 'default', '/response1'),
complete: new InteractionRoute('/routeComplete', '/view2', handlers[1], 'other', '/response2'),
response: new InteractionRoute('/routeResponse',
{ 'text/html': '/view1' },
handlers[0],
'default',
{ 'text/html': '/response1' }),
complete: new InteractionRoute('/routeComplete',
{ 'text/html': '/view2' },
handlers[1],
'other'),
};
templateHandler = { handleSafe: jest.fn() } as any;
converter = {
handleSafe: jest.fn((input: RepresentationConverterArgs): Representation => input.representation),
} as any;
interactionCompleter = { handleSafe: jest.fn().mockResolvedValue('http://test.com/idp/auth') } as any;
@@ -77,7 +92,7 @@ describe('An IdentityProviderHttpHandler', (): void => {
requestParser,
providerFactory,
Object.values(routes),
templateHandler,
converter,
interactionCompleter,
errorHandler,
responseWriter,
@@ -91,26 +106,35 @@ describe('An IdentityProviderHttpHandler', (): void => {
expect(provider.callback).toHaveBeenLastCalledWith(request, response);
});
it('calls the templateHandler for matching GET requests.', async(): Promise<void> => {
it('creates default Representations for GET requests.', async(): Promise<void> => {
request.url = '/idp/routeResponse';
await expect(handler.handle({ request, response })).resolves.toBeUndefined();
expect(templateHandler.handleSafe).toHaveBeenCalledTimes(1);
expect(templateHandler.handleSafe).toHaveBeenLastCalledWith({ response,
templateFile: routes.response.viewTemplate,
contents: { errorMessage: '', prefilled: {}, authenticating: false }});
expect(responseWriter.handleSafe).toHaveBeenCalledTimes(1);
const { response: mockResponse, result } = responseWriter.handleSafe.mock.calls[0][0];
expect(mockResponse).toBe(response);
expect(JSON.parse(await readableToString(result.data!)))
.toEqual({ apiVersion, errorMessage: '', prefilled: {}, authenticating: false });
expect(result.statusCode).toBe(200);
expect(result.metadata?.contentType).toBe('application/json');
expect(result.metadata?.get(SOLID_META.template)?.value).toBe(routes.response.viewTemplates['text/html']);
});
it('calls the templateHandler for InteractionResponseResults.', async(): Promise<void> => {
it('creates Representations for InteractionResponseResults.', async(): Promise<void> => {
request.url = '/idp/routeResponse';
request.method = 'POST';
await expect(handler.handle({ request, response })).resolves.toBeUndefined();
const operation = await requestParser.handleSafe.mock.results[0].value;
expect(routes.response.handler.handleSafe).toHaveBeenCalledTimes(1);
expect(routes.response.handler.handleSafe).toHaveBeenLastCalledWith({ operation });
expect(templateHandler.handleSafe).toHaveBeenCalledTimes(1);
expect(templateHandler.handleSafe).toHaveBeenLastCalledWith(
{ response, templateFile: routes.response.responseTemplate, contents: { key: 'val', authenticating: false }},
);
expect(responseWriter.handleSafe).toHaveBeenCalledTimes(1);
const { response: mockResponse, result } = responseWriter.handleSafe.mock.calls[0][0];
expect(mockResponse).toBe(response);
expect(JSON.parse(await readableToString(result.data!))).toEqual({ apiVersion, key: 'val', authenticating: false });
expect(result.statusCode).toBe(200);
expect(result.metadata?.contentType).toBe('application/json');
expect(result.metadata?.get(SOLID_META.template)?.value).toBe(routes.response.responseTemplates['text/html']);
});
it('indicates to the templates if the request is part of an auth flow.', async(): Promise<void> => {
@@ -120,13 +144,10 @@ describe('An IdentityProviderHttpHandler', (): void => {
provider.interactionDetails.mockResolvedValueOnce(oidcInteraction);
(routes.response.handler as jest.Mocked<InteractionHandler>).handleSafe.mockResolvedValueOnce({ type: 'response' });
await expect(handler.handle({ request, response })).resolves.toBeUndefined();
const operation = await requestParser.handleSafe.mock.results[0].value;
expect(routes.response.handler.handleSafe).toHaveBeenCalledTimes(1);
expect(routes.response.handler.handleSafe).toHaveBeenLastCalledWith({ operation, oidcInteraction });
expect(templateHandler.handleSafe).toHaveBeenCalledTimes(1);
expect(templateHandler.handleSafe).toHaveBeenLastCalledWith(
{ response, templateFile: routes.response.responseTemplate, contents: { authenticating: true }},
);
expect(responseWriter.handleSafe).toHaveBeenCalledTimes(1);
const { result } = responseWriter.handleSafe.mock.calls[0][0];
expect(JSON.parse(await readableToString(result.data!))).toEqual({ apiVersion, authenticating: true });
});
it('errors for InteractionCompleteResults if no oidcInteraction is defined.', async(): Promise<void> => {
@@ -191,19 +212,21 @@ describe('An IdentityProviderHttpHandler', (): void => {
expect(routes.complete.handler.handleSafe).toHaveBeenCalledTimes(0);
});
it('displays the viewTemplate again in case of POST errors.', async(): Promise<void> => {
it('displays a viewTemplate again in case of POST errors.', async(): Promise<void> => {
request.url = '/idp/routeResponse';
request.method = 'POST';
(routes.response.handler.handleSafe as any)
.mockRejectedValueOnce(new IdpInteractionError(500, 'handle error', { name: 'name' }));
await expect(handler.handle({ request, response })).resolves.toBeUndefined();
expect(templateHandler.handleSafe).toHaveBeenCalledTimes(1);
expect(templateHandler.handleSafe).toHaveBeenLastCalledWith({
response,
templateFile: routes.response.viewTemplate,
contents: { errorMessage: 'handle error', prefilled: { name: 'name' }, authenticating: false },
});
expect(responseWriter.handleSafe).toHaveBeenCalledTimes(1);
const { response: mockResponse, result } = responseWriter.handleSafe.mock.calls[0][0];
expect(mockResponse).toBe(response);
expect(JSON.parse(await readableToString(result.data!)))
.toEqual({ apiVersion, errorMessage: 'handle error', prefilled: { name: 'name' }, authenticating: false });
expect(result.statusCode).toBe(200);
expect(result.metadata?.contentType).toBe('application/json');
expect(result.metadata?.get(SOLID_META.template)?.value).toBe(routes.response.viewTemplates['text/html']);
});
it('defaults to an empty prefilled object in case of POST errors.', async(): Promise<void> => {
@@ -211,19 +234,19 @@ describe('An IdentityProviderHttpHandler', (): void => {
request.method = 'POST';
(routes.response.handler.handleSafe as any).mockRejectedValueOnce(new Error('handle error'));
await expect(handler.handle({ request, response })).resolves.toBeUndefined();
expect(templateHandler.handleSafe).toHaveBeenCalledTimes(1);
expect(templateHandler.handleSafe).toHaveBeenLastCalledWith({
response,
templateFile: routes.response.viewTemplate,
contents: { errorMessage: 'handle error', prefilled: {}, authenticating: false },
});
expect(responseWriter.handleSafe).toHaveBeenCalledTimes(1);
const { response: mockResponse, result } = responseWriter.handleSafe.mock.calls[0][0];
expect(mockResponse).toBe(response);
expect(JSON.parse(await readableToString(result.data!)))
.toEqual({ apiVersion, errorMessage: 'handle error', prefilled: {}, authenticating: false });
});
it('calls the errorHandler if there is a problem resolving the request.', async(): Promise<void> => {
request.url = '/idp/routeResponse';
request.method = 'GET';
const error = new Error('bad template');
templateHandler.handleSafe.mockRejectedValueOnce(error);
converter.handleSafe.mockRejectedValueOnce(error);
errorHandler.handleSafe.mockResolvedValueOnce({ statusCode: 500 });
await expect(handler.handle({ request, response })).resolves.toBeUndefined();
expect(errorHandler.handleSafe).toHaveBeenCalledTimes(1);
@@ -244,19 +267,6 @@ describe('An IdentityProviderHttpHandler', (): void => {
expect(responseWriter.handleSafe).toHaveBeenLastCalledWith({ response, result: { statusCode: 500 }});
});
it('can only resolve InteractionResponseResult responses if a responseTemplate is set.', async(): Promise<void> => {
request.url = '/idp/routeResponse';
request.method = 'POST';
(routes.response as any).responseTemplate = undefined;
const error = new BadRequestHttpError('Unsupported request: POST http://test.com/idp/routeResponse');
errorHandler.handleSafe.mockResolvedValueOnce({ statusCode: 500 });
await expect(handler.handle({ request, response })).resolves.toBeUndefined();
expect(errorHandler.handleSafe).toHaveBeenCalledTimes(1);
expect(errorHandler.handleSafe).toHaveBeenLastCalledWith({ error, preferences: { type: { 'text/html': 1 }}});
expect(responseWriter.handleSafe).toHaveBeenCalledTimes(1);
expect(responseWriter.handleSafe).toHaveBeenLastCalledWith({ response, result: { statusCode: 500 }});
});
it('errors if no route is configured for the default prompt.', async(): Promise<void> => {
handler = new IdentityProviderHttpHandler(
baseUrl,
@@ -264,7 +274,7 @@ describe('An IdentityProviderHttpHandler', (): void => {
requestParser,
providerFactory,
[],
templateHandler,
converter,
interactionCompleter,
errorHandler,
responseWriter,

View File

@@ -1,39 +0,0 @@
import { readableToString } from '../../../../src';
import type { ResponseDescription, ResponseWriter, HttpResponse } from '../../../../src';
import { TemplateHandler } from '../../../../src/server/util/TemplateHandler';
import type { TemplateEngine } from '../../../../src/util/templates/TemplateEngine';
describe('A TemplateHandler', (): void => {
const contents = { contents: 'contents' };
const templateFile = '/templates/main.html.ejs';
let responseWriter: jest.Mocked<ResponseWriter>;
let templateEngine: jest.Mocked<TemplateEngine>;
const response: HttpResponse = {} as any;
beforeEach((): void => {
responseWriter = {
handleSafe: jest.fn(),
} as any;
templateEngine = {
render: jest.fn().mockResolvedValue('rendered'),
};
});
it('renders the template in the response.', async(): Promise<void> => {
const handler = new TemplateHandler(responseWriter, templateEngine);
await handler.handle({ response, contents, templateFile });
expect(templateEngine.render).toHaveBeenCalledTimes(1);
expect(templateEngine.render).toHaveBeenCalledWith(contents, { templateFile });
expect(responseWriter.handleSafe).toHaveBeenCalledTimes(1);
const input: { response: HttpResponse; result: ResponseDescription } = responseWriter.handleSafe.mock.calls[0][0];
expect(input.response).toBe(response);
expect(input.result.statusCode).toBe(200);
expect(input.result.metadata?.contentType).toBe('text/html');
await expect(readableToString(input.result.data!)).resolves.toBe('rendered');
});
});

View File

@@ -0,0 +1,67 @@
import { DataFactory } from 'n3';
import { BasicRepresentation } from '../../../../src/ldp/representation/BasicRepresentation';
import type { Representation } from '../../../../src/ldp/representation/Representation';
import type { RepresentationPreferences } from '../../../../src/ldp/representation/RepresentationPreferences';
import { DynamicJsonToTemplateConverter } from '../../../../src/storage/conversion/DynamicJsonToTemplateConverter';
import type { RepresentationConverterArgs } from '../../../../src/storage/conversion/RepresentationConverter';
import { readableToString } from '../../../../src/util/StreamUtil';
import type { TemplateEngine } from '../../../../src/util/templates/TemplateEngine';
import { CONTENT_TYPE_TERM, SOLID_META } from '../../../../src/util/Vocabularies';
import namedNode = DataFactory.namedNode;
describe('A DynamicJsonToTemplateConverter', (): void => {
const templateFile = '/path/to/template.html.ejs';
const identifier = { path: 'http://test.com/foo' };
let representation: Representation;
let preferences: RepresentationPreferences;
let input: RepresentationConverterArgs;
let templateEngine: jest.Mocked<TemplateEngine>;
let converter: DynamicJsonToTemplateConverter;
beforeEach(async(): Promise<void> => {
representation = new BasicRepresentation('{ "json": true }', identifier, 'application/json');
// Create dummy template metadata
const templateNode = namedNode(templateFile);
representation.metadata.add(SOLID_META.terms.template, templateNode);
representation.metadata.addQuad(templateNode, CONTENT_TYPE_TERM, 'text/html');
preferences = { type: { 'text/html': 1 }};
input = { identifier, representation, preferences };
templateEngine = {
render: jest.fn().mockReturnValue(Promise.resolve('<html>')),
};
converter = new DynamicJsonToTemplateConverter(templateEngine);
});
it('can only handle JSON data.', async(): Promise<void> => {
representation.metadata.contentType = 'text/plain';
await expect(converter.canHandle(input)).rejects.toThrow('Only JSON data is supported');
});
it('can only handle preferences matching the templates found.', async(): Promise<void> => {
input.preferences = { type: { 'text/plain': 1 }};
await expect(converter.canHandle(input)).rejects.toThrow('No templates found matching text/plain, only text/html');
});
it('can handle JSON input with templates matching the preferences.', async(): Promise<void> => {
await expect(converter.canHandle(input)).resolves.toBeUndefined();
});
it('uses the input JSON as parameters for the matching template.', async(): Promise<void> => {
const result = await converter.handle(input);
await expect(readableToString(result.data)).resolves.toBe('<html>');
expect(result.binary).toBe(true);
expect(result.metadata.contentType).toBe('text/html');
expect(templateEngine.render).toHaveBeenCalledTimes(1);
expect(templateEngine.render).toHaveBeenLastCalledWith({ json: true }, { templateFile });
});
it('supports missing type preferences.', async(): Promise<void> => {
input.preferences = {};
const result = await converter.handle(input);
await expect(readableToString(result.data)).resolves.toBe('<html>');
});
});

View File

@@ -1,10 +1,10 @@
import 'jest-rdf';
import type { Literal } from 'n3';
import type { NamedNode, Literal } from 'n3';
import { BasicRepresentation } from '../../../src/ldp/representation/BasicRepresentation';
import type { Representation } from '../../../src/ldp/representation/Representation';
import { RepresentationMetadata } from '../../../src/ldp/representation/RepresentationMetadata';
import { cloneRepresentation, updateModifiedDate } from '../../../src/util/ResourceUtil';
import { DC, XSD } from '../../../src/util/Vocabularies';
import { addTemplateMetadata, cloneRepresentation, updateModifiedDate } from '../../../src/util/ResourceUtil';
import { CONTENT_TYPE_TERM, DC, SOLID_META, XSD } from '../../../src/util/Vocabularies';
describe('ResourceUtil', (): void => {
let representation: Representation;
@@ -30,6 +30,21 @@ describe('ResourceUtil', (): void => {
});
});
describe('#addTemplateMetadata', (): void => {
const filePath = '/templates/template.html.ejs';
const contentType = 'text/html';
it('stores the template metadata.', (): void => {
const metadata = new RepresentationMetadata();
addTemplateMetadata(metadata, filePath, contentType);
const templateNode = metadata.get(SOLID_META.terms.template);
expect(templateNode?.value).toBe(filePath);
const quads = metadata.quads(templateNode as NamedNode, CONTENT_TYPE_TERM);
expect(quads).toHaveLength(1);
expect(quads[0].object.value).toBe(contentType);
});
});
describe('#cloneRepresentation', (): void => {
it('returns a clone of the passed representation.', async(): Promise<void> => {
const res = await cloneRepresentation(representation);