feat: Create SetupHttpHandler

This handler allows users to set up servers with a pod
and without having to enable public access first
This commit is contained in:
Joachim Van Herwegen
2021-09-15 16:52:16 +02:00
parent 02df2905de
commit 4e1a2f5981
11 changed files with 1094 additions and 489 deletions

View File

@@ -1,288 +1,54 @@
import {
RegistrationHandler,
} from '../../../../../../src/identity/interaction/email-password/handler/RegistrationHandler';
import type { AccountStore } from '../../../../../../src/identity/interaction/email-password/storage/AccountStore';
import type { OwnershipValidator } from '../../../../../../src/identity/ownership/OwnershipValidator';
import type {
RegistrationManager, RegistrationParams, RegistrationResponse,
} from '../../../../../../src/identity/interaction/email-password/util/RegistrationManager';
import type { Operation } from '../../../../../../src/ldp/operations/Operation';
import type { ResourceIdentifier } from '../../../../../../src/ldp/representation/ResourceIdentifier';
import type { IdentifierGenerator } from '../../../../../../src/pods/generate/IdentifierGenerator';
import type { PodManager } from '../../../../../../src/pods/PodManager';
import type { PodSettings } from '../../../../../../src/pods/settings/PodSettings';
import { joinUrl } from '../../../../../../src/util/PathUtil';
import { createPostJsonOperation } from './Util';
describe('A RegistrationHandler', (): void => {
// "Correct" values for easy object creation
const webId = 'http://alice.test.com/card#me';
const email = 'alice@test.email';
const password = 'superSecretPassword';
const confirmPassword = password;
const podName = 'alice';
const podBaseUrl = 'http://test.com/alice/';
const createWebId = true;
const register = true;
const createPod = true;
let operation: Operation;
const baseUrl = 'http://test.com/';
const webIdSuffix = '/profile/card';
let podSettings: PodSettings;
let identifierGenerator: IdentifierGenerator;
let ownershipValidator: OwnershipValidator;
let accountStore: AccountStore;
let podManager: PodManager;
let validated: RegistrationParams;
let details: RegistrationResponse;
let registrationManager: jest.Mocked<RegistrationManager>;
let handler: RegistrationHandler;
beforeEach(async(): Promise<void> => {
podSettings = { email, webId, podBaseUrl };
identifierGenerator = {
generate: jest.fn((name: string): ResourceIdentifier => ({ path: `${baseUrl}${name}/` })),
validated = {
email: 'alice@test.email',
password: 'superSecret',
createWebId: true,
register: true,
createPod: true,
rootPod: true,
};
details = {
email: 'alice@test.email',
createWebId: true,
register: true,
createPod: true,
};
ownershipValidator = {
handleSafe: jest.fn(),
registrationManager = {
validateInput: jest.fn().mockReturnValue(validated),
register: jest.fn().mockResolvedValue(details),
} as any;
accountStore = {
create: jest.fn(),
verify: jest.fn(),
deleteAccount: jest.fn(),
} as any;
podManager = {
createPod: jest.fn(),
};
handler = new RegistrationHandler({
baseUrl,
webIdSuffix,
identifierGenerator,
accountStore,
ownershipValidator,
podManager,
});
handler = new RegistrationHandler(registrationManager);
});
describe('validating data', (): void => {
it('rejects array inputs.', async(): Promise<void> => {
operation = createPostJsonOperation({ mydata: [ 'a', 'b' ]});
await expect(handler.handle({ operation }))
.rejects.toThrow('Unexpected multiple values for mydata.');
it('converts the stream to json and sends it to the registration manager.', async(): Promise<void> => {
const params = { email: 'alice@test.email', password: 'superSecret' };
operation = createPostJsonOperation(params);
await expect(handler.handle({ operation })).resolves.toEqual({
type: 'response',
details,
});
it('errors on invalid emails.', async(): Promise<void> => {
operation = createPostJsonOperation({ email: undefined });
await expect(handler.handle({ operation }))
.rejects.toThrow('Please enter a valid e-mail address.');
operation = createPostJsonOperation({ email: '' });
await expect(handler.handle({ operation }))
.rejects.toThrow('Please enter a valid e-mail address.');
operation = createPostJsonOperation({ email: 'invalidEmail' });
await expect(handler.handle({ operation }))
.rejects.toThrow('Please enter a valid e-mail address.');
});
it('errors when a required WebID is not valid.', async(): Promise<void> => {
operation = createPostJsonOperation({ email, register, webId: undefined });
await expect(handler.handle({ operation }))
.rejects.toThrow('Please enter a valid WebID.');
operation = createPostJsonOperation({ email, register, webId: '' });
await expect(handler.handle({ operation }))
.rejects.toThrow('Please enter a valid WebID.');
});
it('errors on invalid passwords when registering.', async(): Promise<void> => {
operation = createPostJsonOperation({ email, webId, password, confirmPassword: 'bad', register });
await expect(handler.handle({ operation }))
.rejects.toThrow('Your password and confirmation did not match.');
});
it('errors on invalid pod names when required.', async(): Promise<void> => {
operation = createPostJsonOperation({ email, webId, createPod, podName: undefined });
await expect(handler.handle({ operation }))
.rejects.toThrow('Please specify a Pod name.');
operation = createPostJsonOperation({ email, webId, createPod, podName: ' ' });
await expect(handler.handle({ operation }))
.rejects.toThrow('Please specify a Pod name.');
operation = createPostJsonOperation({ email, webId, createWebId });
await expect(handler.handle({ operation }))
.rejects.toThrow('Please specify a Pod name.');
});
it('errors when trying to create a WebID without registering or creating a pod.', async(): Promise<void> => {
operation = createPostJsonOperation({ email, podName, createWebId });
await expect(handler.handle({ operation }))
.rejects.toThrow('Please enter a password.');
operation = createPostJsonOperation({ email, podName, createWebId, createPod });
await expect(handler.handle({ operation }))
.rejects.toThrow('Please enter a password.');
operation = createPostJsonOperation({ email, podName, createWebId, createPod, register });
await expect(handler.handle({ operation }))
.rejects.toThrow('Please enter a password.');
});
it('errors when no option is chosen.', async(): Promise<void> => {
operation = createPostJsonOperation({ email, webId });
await expect(handler.handle({ operation }))
.rejects.toThrow('Please register for a WebID or create a Pod.');
});
});
describe('handling data', (): void => {
it('can register a user.', async(): Promise<void> => {
operation = createPostJsonOperation({ email, webId, password, confirmPassword, register });
await expect(handler.handle({ operation })).resolves.toEqual({
details: {
email,
webId,
oidcIssuer: baseUrl,
createWebId: false,
register: true,
createPod: false,
},
type: 'response',
});
expect(ownershipValidator.handleSafe).toHaveBeenCalledTimes(1);
expect(ownershipValidator.handleSafe).toHaveBeenLastCalledWith({ webId });
expect(accountStore.create).toHaveBeenCalledTimes(1);
expect(accountStore.create).toHaveBeenLastCalledWith(email, webId, password);
expect(accountStore.verify).toHaveBeenCalledTimes(1);
expect(accountStore.verify).toHaveBeenLastCalledWith(email);
expect(identifierGenerator.generate).toHaveBeenCalledTimes(0);
expect(accountStore.deleteAccount).toHaveBeenCalledTimes(0);
expect(podManager.createPod).toHaveBeenCalledTimes(0);
});
it('can create a pod.', async(): Promise<void> => {
const params = { email, webId, podName, createPod };
operation = createPostJsonOperation(params);
await expect(handler.handle({ operation })).resolves.toEqual({
details: {
email,
webId,
oidcIssuer: baseUrl,
podBaseUrl: `${baseUrl}${podName}/`,
createWebId: false,
register: false,
createPod: true,
},
type: 'response',
});
expect(ownershipValidator.handleSafe).toHaveBeenCalledTimes(1);
expect(ownershipValidator.handleSafe).toHaveBeenLastCalledWith({ webId });
expect(identifierGenerator.generate).toHaveBeenCalledTimes(1);
expect(identifierGenerator.generate).toHaveBeenLastCalledWith(podName);
expect(podManager.createPod).toHaveBeenCalledTimes(1);
expect(podManager.createPod).toHaveBeenLastCalledWith({ path: `${baseUrl}${podName}/` }, podSettings);
expect(accountStore.create).toHaveBeenCalledTimes(0);
expect(accountStore.verify).toHaveBeenCalledTimes(0);
expect(accountStore.deleteAccount).toHaveBeenCalledTimes(0);
});
it('adds an oidcIssuer to the data when doing both IDP registration and pod creation.', async(): Promise<void> => {
const params = { email, webId, password, confirmPassword, podName, register, createPod };
podSettings.oidcIssuer = baseUrl;
operation = createPostJsonOperation(params);
await expect(handler.handle({ operation })).resolves.toEqual({
details: {
email,
webId,
oidcIssuer: baseUrl,
podBaseUrl: `${baseUrl}${podName}/`,
createWebId: false,
register: true,
createPod: true,
},
type: 'response',
});
expect(ownershipValidator.handleSafe).toHaveBeenCalledTimes(1);
expect(ownershipValidator.handleSafe).toHaveBeenLastCalledWith({ webId });
expect(accountStore.create).toHaveBeenCalledTimes(1);
expect(accountStore.create).toHaveBeenLastCalledWith(email, webId, password);
expect(identifierGenerator.generate).toHaveBeenCalledTimes(1);
expect(identifierGenerator.generate).toHaveBeenLastCalledWith(podName);
expect(podManager.createPod).toHaveBeenCalledTimes(1);
expect(podManager.createPod).toHaveBeenLastCalledWith({ path: `${baseUrl}${podName}/` }, podSettings);
expect(accountStore.verify).toHaveBeenCalledTimes(1);
expect(accountStore.verify).toHaveBeenLastCalledWith(email);
expect(accountStore.deleteAccount).toHaveBeenCalledTimes(0);
});
it('deletes the created account if pod generation fails.', async(): Promise<void> => {
const params = { email, webId, password, confirmPassword, podName, register, createPod };
podSettings.oidcIssuer = baseUrl;
operation = createPostJsonOperation(params);
(podManager.createPod as jest.Mock).mockRejectedValueOnce(new Error('pod error'));
await expect(handler.handle({ operation })).rejects.toThrow('pod error');
expect(ownershipValidator.handleSafe).toHaveBeenCalledTimes(1);
expect(ownershipValidator.handleSafe).toHaveBeenLastCalledWith({ webId });
expect(accountStore.create).toHaveBeenCalledTimes(1);
expect(accountStore.create).toHaveBeenLastCalledWith(email, webId, password);
expect(identifierGenerator.generate).toHaveBeenCalledTimes(1);
expect(identifierGenerator.generate).toHaveBeenLastCalledWith(podName);
expect(podManager.createPod).toHaveBeenCalledTimes(1);
expect(podManager.createPod).toHaveBeenLastCalledWith({ path: `${baseUrl}${podName}/` }, podSettings);
expect(accountStore.deleteAccount).toHaveBeenCalledTimes(1);
expect(accountStore.deleteAccount).toHaveBeenLastCalledWith(email);
expect(accountStore.verify).toHaveBeenCalledTimes(0);
});
it('can create a WebID with an account and pod.', async(): Promise<void> => {
const params = { email, password, confirmPassword, podName, createWebId, register, createPod };
const generatedWebID = joinUrl(baseUrl, podName, webIdSuffix);
podSettings.webId = generatedWebID;
podSettings.oidcIssuer = baseUrl;
operation = createPostJsonOperation(params);
await expect(handler.handle({ operation })).resolves.toEqual({
details: {
email,
webId: generatedWebID,
oidcIssuer: baseUrl,
podBaseUrl: `${baseUrl}${podName}/`,
createWebId: true,
register: true,
createPod: true,
},
type: 'response',
});
expect(identifierGenerator.generate).toHaveBeenCalledTimes(1);
expect(identifierGenerator.generate).toHaveBeenLastCalledWith(podName);
expect(accountStore.create).toHaveBeenCalledTimes(1);
expect(accountStore.create).toHaveBeenLastCalledWith(email, generatedWebID, password);
expect(accountStore.verify).toHaveBeenCalledTimes(1);
expect(accountStore.verify).toHaveBeenLastCalledWith(email);
expect(podManager.createPod).toHaveBeenCalledTimes(1);
expect(podManager.createPod).toHaveBeenLastCalledWith({ path: `${baseUrl}${podName}/` }, podSettings);
expect(ownershipValidator.handleSafe).toHaveBeenCalledTimes(0);
expect(accountStore.deleteAccount).toHaveBeenCalledTimes(0);
});
it('throws an error if something goes wrong.', async(): Promise<void> => {
const params = { email, webId, podName, createPod };
operation = createPostJsonOperation(params);
(podManager.createPod as jest.Mock).mockRejectedValueOnce(new Error('pod error'));
const prom = handler.handle({ operation });
await expect(prom).rejects.toThrow('pod error');
});
expect(registrationManager.validateInput).toHaveBeenCalledTimes(1);
expect(registrationManager.validateInput).toHaveBeenLastCalledWith(params, false);
expect(registrationManager.register).toHaveBeenCalledTimes(1);
expect(registrationManager.register).toHaveBeenLastCalledWith(validated, false);
});
});

View File

@@ -0,0 +1,323 @@
import type { AccountStore } from '../../../../../../src/identity/interaction/email-password/storage/AccountStore';
import {
RegistrationManager,
} from '../../../../../../src/identity/interaction/email-password/util/RegistrationManager';
import type { OwnershipValidator } from '../../../../../../src/identity/ownership/OwnershipValidator';
import type { ResourceIdentifier } from '../../../../../../src/ldp/representation/ResourceIdentifier';
import type { IdentifierGenerator } from '../../../../../../src/pods/generate/IdentifierGenerator';
import type { PodManager } from '../../../../../../src/pods/PodManager';
import type { PodSettings } from '../../../../../../src/pods/settings/PodSettings';
import { joinUrl } from '../../../../../../src/util/PathUtil';
describe('A RegistrationManager', (): void => {
// "Correct" values for easy object creation
const webId = 'http://alice.test.com/card#me';
const email = 'alice@test.email';
const password = 'superSecretPassword';
const confirmPassword = password;
const podName = 'alice';
const podBaseUrl = 'http://test.com/alice/';
const createWebId = true;
const register = true;
const createPod = true;
const rootPod = true;
const baseUrl = 'http://test.com/';
const webIdSuffix = '/profile/card';
let podSettings: PodSettings;
let identifierGenerator: IdentifierGenerator;
let ownershipValidator: OwnershipValidator;
let accountStore: AccountStore;
let podManager: PodManager;
let manager: RegistrationManager;
beforeEach(async(): Promise<void> => {
podSettings = { email, webId, podBaseUrl };
identifierGenerator = {
generate: jest.fn((name: string): ResourceIdentifier => ({ path: `${baseUrl}${name}/` })),
};
ownershipValidator = {
handleSafe: jest.fn(),
} as any;
accountStore = {
create: jest.fn(),
verify: jest.fn(),
deleteAccount: jest.fn(),
} as any;
podManager = {
createPod: jest.fn(),
};
manager = new RegistrationManager({
baseUrl,
webIdSuffix,
identifierGenerator,
accountStore,
ownershipValidator,
podManager,
});
});
describe('validating data', (): void => {
it('errors on invalid emails.', async(): Promise<void> => {
let input: any = { email: undefined };
expect((): any => manager.validateInput(input)).toThrow('Please enter a valid e-mail address.');
input = { email: '' };
expect((): any => manager.validateInput(input)).toThrow('Please enter a valid e-mail address.');
input = { email: 'invalidEmail' };
expect((): any => manager.validateInput(input)).toThrow('Please enter a valid e-mail address.');
});
it('errors when setting rootPod to true when not allowed.', async(): Promise<void> => {
const input = { email, createWebId, rootPod };
expect((): any => manager.validateInput(input)).toThrow('Creating a root pod is not supported.');
});
it('errors when a required WebID is not valid.', async(): Promise<void> => {
let input: any = { email, register, webId: undefined };
expect((): any => manager.validateInput(input)).toThrow('Please enter a valid WebID.');
input = { email, register, webId: '' };
expect((): any => manager.validateInput(input)).toThrow('Please enter a valid WebID.');
});
it('errors on invalid passwords when registering.', async(): Promise<void> => {
const input: any = { email, webId, password, confirmPassword: 'bad', register };
expect((): any => manager.validateInput(input)).toThrow('Your password and confirmation did not match.');
});
it('errors on invalid pod names when required.', async(): Promise<void> => {
let input: any = { email, webId, createPod, podName: undefined };
expect((): any => manager.validateInput(input)).toThrow('Please specify a Pod name.');
input = { email, webId, createPod, podName: ' ' };
expect((): any => manager.validateInput(input)).toThrow('Please specify a Pod name.');
input = { email, webId, createWebId };
expect((): any => manager.validateInput(input)).toThrow('Please specify a Pod name.');
});
it('errors when trying to create a WebID without registering or creating a pod.', async(): Promise<void> => {
let input: any = { email, podName, createWebId };
expect((): any => manager.validateInput(input)).toThrow('Please enter a password.');
input = { email, podName, createWebId, createPod };
expect((): any => manager.validateInput(input)).toThrow('Please enter a password.');
input = { email, podName, createWebId, createPod, register };
expect((): any => manager.validateInput(input)).toThrow('Please enter a password.');
});
it('errors when no option is chosen.', async(): Promise<void> => {
const input = { email, webId };
expect((): any => manager.validateInput(input)).toThrow('Please register for a WebID or create a Pod.');
});
it('adds the template parameter if there is one.', async(): Promise<void> => {
const input = { email, webId, podName, template: 'template', createPod };
expect(manager.validateInput(input)).toEqual({
email, webId, podName, template: 'template', createWebId: false, register: false, createPod, rootPod: false,
});
});
it('does not require a pod name when creating a root pod.', async(): Promise<void> => {
const input = { email, webId, createPod, rootPod };
expect(manager.validateInput(input, true)).toEqual({
email, webId, createWebId: false, register: false, createPod, rootPod,
});
});
it('trims input parameters.', async(): Promise<void> => {
let input: any = {
email: ` ${email} `,
password: ` ${password} `,
confirmPassword: ` ${password} `,
podName: ` ${podName} `,
template: ' template ',
createWebId,
register,
createPod,
};
expect(manager.validateInput(input)).toEqual({
email, password, podName, template: 'template', createWebId, register, createPod, rootPod: false,
});
input = { email, webId: ` ${webId} `, password, confirmPassword, register: true };
expect(manager.validateInput(input)).toEqual({
email, webId, password, createWebId: false, register, createPod: false, rootPod: false,
});
});
});
describe('handling data', (): void => {
it('can register a user.', async(): Promise<void> => {
const params: any = { email, webId, password, confirmPassword, register, createPod: false, createWebId: false };
await expect(manager.register(params)).resolves.toEqual({
email,
webId,
oidcIssuer: baseUrl,
createWebId: false,
register: true,
createPod: false,
});
expect(ownershipValidator.handleSafe).toHaveBeenCalledTimes(1);
expect(ownershipValidator.handleSafe).toHaveBeenLastCalledWith({ webId });
expect(accountStore.create).toHaveBeenCalledTimes(1);
expect(accountStore.create).toHaveBeenLastCalledWith(email, webId, password);
expect(accountStore.verify).toHaveBeenCalledTimes(1);
expect(accountStore.verify).toHaveBeenLastCalledWith(email);
expect(identifierGenerator.generate).toHaveBeenCalledTimes(0);
expect(accountStore.deleteAccount).toHaveBeenCalledTimes(0);
expect(podManager.createPod).toHaveBeenCalledTimes(0);
});
it('can create a pod.', async(): Promise<void> => {
const params: any = { email, webId, podName, createPod, createWebId: false, register: false };
await expect(manager.register(params)).resolves.toEqual({
email,
webId,
oidcIssuer: baseUrl,
podBaseUrl: `${baseUrl}${podName}/`,
createWebId: false,
register: false,
createPod: true,
});
expect(ownershipValidator.handleSafe).toHaveBeenCalledTimes(1);
expect(ownershipValidator.handleSafe).toHaveBeenLastCalledWith({ webId });
expect(identifierGenerator.generate).toHaveBeenCalledTimes(1);
expect(identifierGenerator.generate).toHaveBeenLastCalledWith(podName);
expect(podManager.createPod).toHaveBeenCalledTimes(1);
expect(podManager.createPod).toHaveBeenLastCalledWith({ path: `${baseUrl}${podName}/` }, podSettings, false);
expect(accountStore.create).toHaveBeenCalledTimes(0);
expect(accountStore.verify).toHaveBeenCalledTimes(0);
expect(accountStore.deleteAccount).toHaveBeenCalledTimes(0);
});
it('adds an oidcIssuer to the data when doing both IDP registration and pod creation.', async(): Promise<void> => {
const params: any = { email, webId, password, confirmPassword, podName, register, createPod, createWebId: false };
podSettings.oidcIssuer = baseUrl;
await expect(manager.register(params)).resolves.toEqual({
email,
webId,
oidcIssuer: baseUrl,
podBaseUrl: `${baseUrl}${podName}/`,
createWebId: false,
register: true,
createPod: true,
});
expect(ownershipValidator.handleSafe).toHaveBeenCalledTimes(1);
expect(ownershipValidator.handleSafe).toHaveBeenLastCalledWith({ webId });
expect(accountStore.create).toHaveBeenCalledTimes(1);
expect(accountStore.create).toHaveBeenLastCalledWith(email, webId, password);
expect(identifierGenerator.generate).toHaveBeenCalledTimes(1);
expect(identifierGenerator.generate).toHaveBeenLastCalledWith(podName);
expect(podManager.createPod).toHaveBeenCalledTimes(1);
expect(podManager.createPod).toHaveBeenLastCalledWith({ path: `${baseUrl}${podName}/` }, podSettings, false);
expect(accountStore.verify).toHaveBeenCalledTimes(1);
expect(accountStore.verify).toHaveBeenLastCalledWith(email);
expect(accountStore.deleteAccount).toHaveBeenCalledTimes(0);
});
it('deletes the created account if pod generation fails.', async(): Promise<void> => {
const params: any = { email, webId, password, confirmPassword, podName, register, createPod };
podSettings.oidcIssuer = baseUrl;
(podManager.createPod as jest.Mock).mockRejectedValueOnce(new Error('pod error'));
await expect(manager.register(params)).rejects.toThrow('pod error');
expect(ownershipValidator.handleSafe).toHaveBeenCalledTimes(1);
expect(ownershipValidator.handleSafe).toHaveBeenLastCalledWith({ webId });
expect(accountStore.create).toHaveBeenCalledTimes(1);
expect(accountStore.create).toHaveBeenLastCalledWith(email, webId, password);
expect(identifierGenerator.generate).toHaveBeenCalledTimes(1);
expect(identifierGenerator.generate).toHaveBeenLastCalledWith(podName);
expect(podManager.createPod).toHaveBeenCalledTimes(1);
expect(podManager.createPod).toHaveBeenLastCalledWith({ path: `${baseUrl}${podName}/` }, podSettings, false);
expect(accountStore.deleteAccount).toHaveBeenCalledTimes(1);
expect(accountStore.deleteAccount).toHaveBeenLastCalledWith(email);
expect(accountStore.verify).toHaveBeenCalledTimes(0);
});
it('does not try to delete an account on failure if there was no registration.', async(): Promise<void> => {
const params: any = { email, webId, podName, createPod };
(podManager.createPod as jest.Mock).mockRejectedValueOnce(new Error('pod error'));
await expect(manager.register(params)).rejects.toThrow('pod error');
expect(ownershipValidator.handleSafe).toHaveBeenCalledTimes(1);
expect(ownershipValidator.handleSafe).toHaveBeenLastCalledWith({ webId });
expect(identifierGenerator.generate).toHaveBeenCalledTimes(1);
expect(identifierGenerator.generate).toHaveBeenLastCalledWith(podName);
expect(podManager.createPod).toHaveBeenCalledTimes(1);
expect(podManager.createPod).toHaveBeenLastCalledWith({ path: `${baseUrl}${podName}/` }, podSettings, false);
expect(accountStore.create).toHaveBeenCalledTimes(0);
expect(accountStore.deleteAccount).toHaveBeenCalledTimes(0);
expect(accountStore.verify).toHaveBeenCalledTimes(0);
});
it('can create a WebID with an account and pod.', async(): Promise<void> => {
const params: any = { email, password, confirmPassword, podName, createWebId, register, createPod };
const generatedWebID = joinUrl(baseUrl, podName, webIdSuffix);
podSettings.webId = generatedWebID;
podSettings.oidcIssuer = baseUrl;
await expect(manager.register(params)).resolves.toEqual({
email,
webId: generatedWebID,
oidcIssuer: baseUrl,
podBaseUrl: `${baseUrl}${podName}/`,
createWebId: true,
register: true,
createPod: true,
});
expect(identifierGenerator.generate).toHaveBeenCalledTimes(1);
expect(identifierGenerator.generate).toHaveBeenLastCalledWith(podName);
expect(accountStore.create).toHaveBeenCalledTimes(1);
expect(accountStore.create).toHaveBeenLastCalledWith(email, generatedWebID, password);
expect(accountStore.verify).toHaveBeenCalledTimes(1);
expect(accountStore.verify).toHaveBeenLastCalledWith(email);
expect(podManager.createPod).toHaveBeenCalledTimes(1);
expect(podManager.createPod).toHaveBeenLastCalledWith({ path: `${baseUrl}${podName}/` }, podSettings, false);
expect(ownershipValidator.handleSafe).toHaveBeenCalledTimes(0);
expect(accountStore.deleteAccount).toHaveBeenCalledTimes(0);
});
it('can create a root pod.', async(): Promise<void> => {
const params: any = { email, webId, createPod, rootPod, createWebId: false, register: false };
podSettings.podBaseUrl = baseUrl;
await expect(manager.register(params, true)).resolves.toEqual({
email,
webId,
oidcIssuer: baseUrl,
podBaseUrl: baseUrl,
createWebId: false,
register: false,
createPod: true,
});
expect(ownershipValidator.handleSafe).toHaveBeenCalledTimes(1);
expect(ownershipValidator.handleSafe).toHaveBeenLastCalledWith({ webId });
expect(podManager.createPod).toHaveBeenCalledTimes(1);
expect(podManager.createPod).toHaveBeenLastCalledWith({ path: baseUrl }, podSettings, true);
expect(identifierGenerator.generate).toHaveBeenCalledTimes(0);
expect(accountStore.create).toHaveBeenCalledTimes(0);
expect(accountStore.verify).toHaveBeenCalledTimes(0);
expect(accountStore.deleteAccount).toHaveBeenCalledTimes(0);
});
});
});

View File

@@ -0,0 +1,248 @@
import type { RegistrationManager,
RegistrationResponse } from '../../../../src/identity/interaction/email-password/util/RegistrationManager';
import type { Initializer } from '../../../../src/init/Initializer';
import type { SetupInput } from '../../../../src/init/setup/SetupHttpHandler';
import { SetupHttpHandler } from '../../../../src/init/setup/SetupHttpHandler';
import type { ErrorHandlerArgs, ErrorHandler } from '../../../../src/ldp/http/ErrorHandler';
import type { RequestParser } from '../../../../src/ldp/http/RequestParser';
import type { ResponseDescription } from '../../../../src/ldp/http/response/ResponseDescription';
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 { RepresentationMetadata } from '../../../../src/ldp/representation/RepresentationMetadata';
import type { HttpRequest } from '../../../../src/server/HttpRequest';
import type { HttpResponse } from '../../../../src/server/HttpResponse';
import { getBestPreference } from '../../../../src/storage/conversion/ConversionUtil';
import type { RepresentationConverterArgs,
RepresentationConverter } from '../../../../src/storage/conversion/RepresentationConverter';
import type { KeyValueStorage } from '../../../../src/storage/keyvalue/KeyValueStorage';
import { APPLICATION_JSON } from '../../../../src/util/ContentTypes';
import type { HttpError } from '../../../../src/util/errors/HttpError';
import { InternalServerError } from '../../../../src/util/errors/InternalServerError';
import { MethodNotAllowedHttpError } from '../../../../src/util/errors/MethodNotAllowedHttpError';
import { NotImplementedHttpError } from '../../../../src/util/errors/NotImplementedHttpError';
import { joinUrl } from '../../../../src/util/PathUtil';
import { guardedStreamFrom, readableToString } from '../../../../src/util/StreamUtil';
import { CONTENT_TYPE, SOLID_META } from '../../../../src/util/Vocabularies';
describe('A SetupHttpHandler', (): void => {
const baseUrl = 'http://test.com/';
let request: HttpRequest;
let requestBody: SetupInput;
const response: HttpResponse = {} as any;
const viewTemplate = '/templates/view';
const responseTemplate = '/templates/response';
const storageKey = 'completed';
let details: RegistrationResponse;
let requestParser: jest.Mocked<RequestParser>;
let errorHandler: jest.Mocked<ErrorHandler>;
let responseWriter: jest.Mocked<ResponseWriter>;
let registrationManager: jest.Mocked<RegistrationManager>;
let initializer: jest.Mocked<Initializer>;
let converter: jest.Mocked<RepresentationConverter>;
let storage: jest.Mocked<KeyValueStorage<string, any>>;
let handler: SetupHttpHandler;
beforeEach(async(): Promise<void> => {
request = { url: '/setup', method: 'GET', headers: {}} as any;
requestBody = {};
requestParser = {
handleSafe: jest.fn(async(req: HttpRequest): Promise<Operation> => ({
target: { path: joinUrl(baseUrl, req.url!) },
method: req.method!,
body: req.method === 'GET' ?
undefined :
new BasicRepresentation(JSON.stringify(requestBody), req.headers['content-type'] ?? 'text/plain'),
preferences: { type: { 'text/html': 1 }},
})),
} as any;
errorHandler = { handleSafe: jest.fn(({ error }: ErrorHandlerArgs): ResponseDescription => ({
statusCode: 400,
data: guardedStreamFrom(`{ "name": "${error.name}", "message": "${error.message}" }`),
})) } as any;
responseWriter = { handleSafe: jest.fn() } as any;
initializer = {
handleSafe: jest.fn(),
} as any;
details = {
email: 'alice@test.email',
createWebId: true,
register: true,
createPod: true,
};
registrationManager = {
validateInput: jest.fn((input): any => input),
register: jest.fn().mockResolvedValue(details),
} as any;
converter = {
handleSafe: jest.fn((input: RepresentationConverterArgs): Representation => {
// Just find the best match;
const type = getBestPreference(input.preferences.type!, { '*/*': 1 })!;
const metadata = new RepresentationMetadata(input.representation.metadata, { [CONTENT_TYPE]: type.value });
return new BasicRepresentation(input.representation.data, metadata);
}),
} as any;
storage = new Map<string, any>() as any;
handler = new SetupHttpHandler({
requestParser,
errorHandler,
responseWriter,
initializer,
registrationManager,
converter,
storageKey,
storage,
viewTemplate,
responseTemplate,
});
});
// Since all tests check similar things, the test functionality is generalized in here
async function testPost(input: SetupInput, error?: HttpError): Promise<void> {
request.method = 'POST';
const initialize = Boolean(input.initialize);
const registration = Boolean(input.registration);
requestBody = { initialize, registration };
await expect(handler.handle({ request, response })).resolves.toBeUndefined();
expect(initializer.handleSafe).toHaveBeenCalledTimes(!error && initialize ? 1 : 0);
expect(registrationManager.validateInput).toHaveBeenCalledTimes(!error && registration ? 1 : 0);
expect(registrationManager.register).toHaveBeenCalledTimes(!error && registration ? 1 : 0);
expect(responseWriter.handleSafe).toHaveBeenCalledTimes(1);
const { response: mockResponse, result } = responseWriter.handleSafe.mock.calls[0][0];
expect(mockResponse).toBe(response);
let expectedResult: any = { initialize, registration };
if (error) {
expectedResult = { name: error.name, message: error.message };
} else if (registration) {
Object.assign(expectedResult, details);
}
expect(JSON.parse(await readableToString(result.data!))).toEqual(expectedResult);
expect(result.statusCode).toBe(error?.statusCode ?? 200);
expect(result.metadata?.contentType).toBe('text/html');
expect(result.metadata?.get(SOLID_META.template)?.value).toBe(error ? viewTemplate : responseTemplate);
if (!error && registration) {
expect(registrationManager.validateInput).toHaveBeenLastCalledWith(requestBody, true);
expect(registrationManager.register).toHaveBeenLastCalledWith(requestBody, true);
}
}
it('returns the view template on GET requests.', async(): Promise<void> => {
await expect(handler.handle({ request, response })).resolves.toBeUndefined();
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({});
expect(result.statusCode).toBe(200);
expect(result.metadata?.contentType).toBe('text/html');
expect(result.metadata?.get(SOLID_META.template)?.value).toBe(viewTemplate);
// Setup is still enabled since this was a GET request
expect(storage.get(storageKey)).toBeUndefined();
});
it('simply disables the handler if no setup is requested.', async(): Promise<void> => {
await expect(testPost({ initialize: false, registration: false })).resolves.toBeUndefined();
// Handler is now disabled due to successful POST
expect(storage.get(storageKey)).toBe(true);
});
it('defaults to an empty body if there is none.', async(): Promise<void> => {
requestParser.handleSafe.mockResolvedValueOnce({
target: { path: joinUrl(baseUrl, '/randomPath') },
method: 'POST',
preferences: { type: { 'text/html': 1 }},
});
await expect(testPost({})).resolves.toBeUndefined();
});
it('calls the initializer when requested.', async(): Promise<void> => {
await expect(testPost({ initialize: true, registration: false })).resolves.toBeUndefined();
});
it('calls the registrationManager when requested.', async(): Promise<void> => {
await expect(testPost({ initialize: false, registration: true })).resolves.toBeUndefined();
});
it('converts non-HTTP errors to internal errors.', async(): Promise<void> => {
converter.handleSafe.mockRejectedValueOnce(new Error('bad data'));
const error = new InternalServerError('bad data');
await expect(testPost({ initialize: true, registration: false }, error)).resolves.toBeUndefined();
});
it('errors on non-GET/POST requests.', async(): Promise<void> => {
request.method = 'PUT';
requestBody = { initialize: true, registration: true };
const error = new MethodNotAllowedHttpError();
await expect(handler.handle({ request, response })).resolves.toBeUndefined();
expect(initializer.handleSafe).toHaveBeenCalledTimes(0);
expect(registrationManager.register).toHaveBeenCalledTimes(0);
expect(errorHandler.handleSafe).toHaveBeenCalledTimes(1);
expect(errorHandler.handleSafe).toHaveBeenLastCalledWith({ error, preferences: { type: { [APPLICATION_JSON]: 1 }}});
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({ name: error.name, message: error.message });
expect(result.statusCode).toBe(405);
expect(result.metadata?.contentType).toBe('text/html');
expect(result.metadata?.get(SOLID_META.template)?.value).toBe(viewTemplate);
// Setup is not disabled since there was an error
expect(storage.get(storageKey)).toBeUndefined();
});
it('errors when attempting registration when no RegistrationManager is defined.', async(): Promise<void> => {
handler = new SetupHttpHandler({
requestParser,
errorHandler,
responseWriter,
initializer,
converter,
storageKey,
storage,
viewTemplate,
responseTemplate,
});
request.method = 'POST';
requestBody = { initialize: false, registration: true };
const error = new NotImplementedHttpError('This server is not configured to support registration during setup.');
await expect(testPost({ initialize: false, registration: true }, error)).resolves.toBeUndefined();
// Setup is not disabled since there was an error
expect(storage.get(storageKey)).toBeUndefined();
});
it('errors when attempting initialization when no Initializer is defined.', async(): Promise<void> => {
handler = new SetupHttpHandler({
requestParser,
errorHandler,
responseWriter,
registrationManager,
converter,
storageKey,
storage,
viewTemplate,
responseTemplate,
});
request.method = 'POST';
requestBody = { initialize: true, registration: false };
const error = new NotImplementedHttpError('This server is not configured with a setup initializer.');
await expect(testPost({ initialize: true, registration: false }, error)).resolves.toBeUndefined();
// Setup is not disabled since there was an error
expect(storage.get(storageKey)).toBeUndefined();
});
});

View File

@@ -37,13 +37,23 @@ describe('A GeneratedPodManager', (): void => {
it('throws an error if the generate identifier is not available.', async(): Promise<void> => {
store.resourceExists.mockResolvedValueOnce(true);
const result = manager.createPod({ path: `${base}user/` }, settings);
const result = manager.createPod({ path: `${base}user/` }, settings, false);
await expect(result).rejects.toThrow(`There already is a resource at ${base}user/`);
await expect(result).rejects.toThrow(ConflictHttpError);
});
it('generates an identifier and writes containers before writing the resources in them.', async(): Promise<void> => {
await expect(manager.createPod({ path: `${base}${settings.login}/` }, settings)).resolves.toBeUndefined();
await expect(manager.createPod({ path: `${base}${settings.login}/` }, settings, false)).resolves.toBeUndefined();
expect(store.setRepresentation).toHaveBeenCalledTimes(3);
expect(store.setRepresentation).toHaveBeenNthCalledWith(1, { path: '/path/' }, '/');
expect(store.setRepresentation).toHaveBeenNthCalledWith(2, { path: '/path/a/' }, '/a/');
expect(store.setRepresentation).toHaveBeenNthCalledWith(3, { path: '/path/a/b' }, '/a/b');
});
it('allows overwriting when enabled.', async(): Promise<void> => {
store.resourceExists.mockResolvedValueOnce(true);
await expect(manager.createPod({ path: `${base}${settings.login}/` }, settings, true)).resolves.toBeUndefined();
expect(store.setRepresentation).toHaveBeenCalledTimes(3);
expect(store.setRepresentation).toHaveBeenNthCalledWith(1, { path: '/path/' }, '/');