CommunitySolidServer/test/unit/init/AppRunner.test.ts
jaxoncreed 1d65143e89
feat: Add identity provider (#455)
* Add identity provider handler as a dependency

* Temp Identity

* Figured out how to get koa to work

* Hooked up idp to networking

* Feat/idp architecture refactor (#430)

* Logs in with solid oidc

* Refactored Provider

* Attempt to hook up dependencies

* Partial wiring of oidc provider components

* IdP networking now works with architecture

* Interaction Handlers Set Up

* fix: Rename & adapt to CSS

* Included Login Interaction

* Refactored architecture to bind Interaction Policy to HttpHandlers

Co-authored-by: Matthieu Bosquet <matthieubosquet@gmail.com>

* fix: Rebase on master

* fix: DI after rebase

* Reimplemented Routing

* Renamed modules and removed ProviderFactory (#450)

* refactor: Solid IdP DI

* refactor: IdP interaction handler DI

* refactor: IdP interaction waterfall

* refactor: Remove unnecessary legacy URL parse

* fix: Add legacy parse back in

* feat: adapter & fix: handlers

* Removed adapter factory

* fix: refactor IdP

* fix: refactor IdP

* fix: refactor IdP

* feat: Add IdP to file storage config

* fix: Unintended commit

* fix: Components ignore

* feat: Basic resource store adapter

* Partially complete idp routing

* Set up initial routing injection graph

* Clean up ResourceStorageAdapter

* Refactored configuration architecture

* Hooked up Login UIs (#518)

* feat: Use template path & run fileserver

* feat: Use util function to read resource

* Fixed DI JSON-LD context

* fixed rendering

* WebId validator

* Set up persistent storage for loing and register

* Fixed ejs template routing

* Refactored StorageAdapters

* NSS login successful

* Forgot password infrastructure

* Can send email (#557)

* Can send email

* fix: IdP crashes if interaction ID doesn't exist (#587)

* feat: Require an issuer registration token

* fix: Issuer registration token typo in error

* fix: Remove dummy IdP storage adapter

* fix: Remove unused library lodash

* fix: Remove unused library lru-cache

* Production ready keystore

* Ruben comments before clownface removal

* Removed clownface

* Change key value store

* Completed Ruben's comments

* Added comments to each class

* Fixed errors on login

* Ruben feedback

* Refactored out getPostRenderHandler

* Identity provider tests (#622)

* corrected tests lacking <void> on promises

* Added files for all idp tests

* Added unfinished tests for all added files

* ErrorHandlingWaterfallHandler

* RenderEjsHandler and RouterHandler tests

* GetPostRouterHandler and BasicOnErrorHandler tests

* Corrected tests for updates to Idp

* fix: missing export

* fix: audience claim

* Client Id Support (#630)

* Added client_id for the auth challenge

* Update src/identity/storage/ClientWebIdFetchingStorageAdapterFactory.ts

Co-authored-by: Matthieu Bosquet <matthieubosquet@gmail.com>

Co-authored-by: Matthieu Bosquet <matthieubosquet@gmail.com>

* fix: Rebase fixes

* Several minor Idp changes/refactors (#656)

* fix: Minor changes

* refactor: Split EmailPasswordInteractionPolicy

* refactor: Remove ErrorHandlingWaterfallHandler

* refactor: Clean up dependencies

* fix: Add dummy IdentityProviderHandler to fix integration tests

* Replace KeyValueStore with KeyValueStorage (#663)

* feat: Create WrappedExpiringStorage

* refactor: Update ResourceStoreEmailPasswordStore to use KeyValueStorage

* refactor: Update KeyGeneratingIdpConfigurationGenerator to use KeyValueStorage

* refactor: Update ResourceStoreStorageAdapterFactory to use ExpiringStorage

* refactor: Removed KeyValueStore

* refactor: Simplify EmailPassword handlers (#664)

* refactor: Order index.ts

* test: Add EmailPasswordForgotPasswordHandler unit tests

* test: Add EmailPasswordGetResetPasswordHandler unit tests

* test: Add EmailPasswordLoginHandler unit tests

* test: Add EmailPasswordRegistrationHandler unit tests

* test: Add EmailPasswordResetPasswordHandler unit tests

* test: Remove unnecessary test file

* feat: Basic instructions for using the IdP

* fix: IdP instructions and add example WebID

* fix: IdP registration copy

* fix: IdP instruction editorial

* Update README.md

Co-authored-by: Joachim Van Herwegen <joachimvh@gmail.com>

* Update README.md

Co-authored-by: Joachim Van Herwegen <joachimvh@gmail.com>

* test: Add KeyGeneratingIdpConfigurationGenerator unit tests

* test: Add KeyValueEmailPasswordStore unit tests

* test: Create IdP integration test

* test: Add EmailPasswordInteractionPolicy unit tests

* test: Add BasicIssuerReferenceWebIdOwnershipValidator unit tests

* test: Add ChooseInitialInteractionHandler unit tests

Also fixes the config warning.

* test: Add EjsTemplateRenderer unit tests

* test: Add EmailSender unit tests

* test: Add FormDataUtil unit tests

* test: Add IdpRouteController unit tests

* test: Add OidcInteractionCompleter unit tests

* refactor: Simplify ClientWebIdFetchingStorageAdapterFactory

* test: Add ClientWebIdFetchingStorageAdapterFactory unit tests

* refactor: Fix ejs html warnings

* test: Add step to test logging in again

Included are updates to handle cookies more correctly.

* feat: Add IdpConfirmHttpHandler

This way there's a handler for the confirm page.

* test: Add ExpiringStorageAdapterFactory unit tests

* test: Add IdentityProviderFactory unit tests

* test: Add IdentityProviderHttpHandler unit tests

* refactor: Minor refactors

* refactor: Use jose instead of node-jose

* refactor: Use jose instead of node-jose

Reduces the number of dependencies since other libraries
also depend on jose.

* Update src/identity/configuration/KeyGeneratingIdpConfigurationGenerator.ts

Co-authored-by: Matthieu Bosquet <matthieubosquet@gmail.com>

* refactor: Use interfaces instead of abstract classes

* refactor: Make WebIdOwnershipValidator an AsyncHandler

* refactor: Make TemplateRenderer an AsyncHandler

* fix: Fix typing issue

* fix: Convert JWK to plain object for node 15

* feat: Update CI configuration

--ignore-scripts was removed because it also stopped dependency scripts,
which was a requirement for bcrypt.
15.0 was removed since that version doesn't run the required scripts after install.
14.0 was removed since the somehow it caused the solid-authn client to do the wrong calls.

* test: Run integration tests on Node 14.2

This is the lowest 14.x version where the IdP integration tests succeed.

* feat: Use ErrorResponseWriter for handling oidc errors

* test: Mock Date in OidcInteractionCompleter tests

* fix: Correctly generate new identifiers

Previously there could be double slashes if the base URL ended in slash.

* fix: Correctly handle storagePathName in ExpiringStorageAdapterFactory

* fix: Fix issue with new CliRunner test in rebase

* fix: Handle unknown errors more consistently

* feat: Make idp parameter dynamic

* feat: Add more logging

* refactor: Link css instead of injecting

* fix: Fix redis integration tests with idp

* refactor: Shorten idp class names

* refactor: Remove e-mail configuration from default config

* feat: Store JsonResourceStorage data in a single container

* feat: Make sure expired data gets removed at some point

* feat: Only accept strings as keys in KeyValueStorage

* fix: Various minor fixes based on review

Co-authored-by: Matthieu Bosquet <matthieubosquet@gmail.com>
Co-authored-by: Joachim Van Herwegen <joachimvh@gmail.com>
2021-05-04 13:17:43 +02:00

364 lines
14 KiB
TypeScript

import { ComponentsManager } from 'componentsjs';
import { AppRunner } from '../../../src/init/AppRunner';
import type { Initializer } from '../../../src/init/Initializer';
import { joinFilePath } from '../../../src/util/PathUtil';
const initializer: jest.Mocked<Initializer> = {
handleSafe: jest.fn(),
} as any;
const manager: jest.Mocked<ComponentsManager<Initializer>> = {
instantiate: jest.fn(async(): Promise<Initializer> => initializer),
configRegistry: {
register: jest.fn(),
},
} as any;
jest.mock('componentsjs', (): any => ({
// eslint-disable-next-line @typescript-eslint/naming-convention
ComponentsManager: {
build: jest.fn(async(): Promise<ComponentsManager<Initializer>> => manager),
},
}));
jest.spyOn(process, 'cwd').mockReturnValue('/var/cwd');
const error = jest.spyOn(console, 'error').mockImplementation(jest.fn());
const write = jest.spyOn(process.stderr, 'write').mockImplementation(jest.fn());
const exit = jest.spyOn(process, 'exit').mockImplementation(jest.fn() as any);
describe('AppRunner', (): void => {
afterEach((): void => {
jest.clearAllMocks();
});
describe('run', (): void => {
it('starts the server with default settings.', async(): Promise<void> => {
await new AppRunner().run(
{
mainModulePath: joinFilePath(__dirname, '../../../'),
dumpErrorState: true,
logLevel: 'info',
},
joinFilePath(__dirname, '../../../config/config-default.json'),
{
port: 3000,
loggingLevel: 'info',
rootFilePath: '/var/cwd/',
podConfigJson: '/var/cwd/pod-config.json',
},
);
expect(ComponentsManager.build).toHaveBeenCalledTimes(1);
expect(ComponentsManager.build).toHaveBeenCalledWith({
dumpErrorState: true,
logLevel: 'info',
mainModulePath: joinFilePath(__dirname, '../../../'),
});
expect(manager.configRegistry.register).toHaveBeenCalledTimes(1);
expect(manager.configRegistry.register)
.toHaveBeenCalledWith(joinFilePath(__dirname, '/../../../config/config-default.json'));
expect(manager.instantiate).toHaveBeenCalledTimes(1);
expect(manager.instantiate).toHaveBeenCalledWith(
'urn:solid-server:default:Initializer',
{
variables: {
'urn:solid-server:default:variable:port': 3000,
'urn:solid-server:default:variable:baseUrl': 'http://localhost:3000/',
'urn:solid-server:default:variable:rootFilePath': '/var/cwd/',
'urn:solid-server:default:variable:sparqlEndpoint': undefined,
'urn:solid-server:default:variable:loggingLevel': 'info',
'urn:solid-server:default:variable:podConfigJson': '/var/cwd/pod-config.json',
'urn:solid-server:default:variable:idpTemplateFolder': joinFilePath(__dirname, '../../../templates/idp'),
},
},
);
expect(initializer.handleSafe).toHaveBeenCalledTimes(1);
expect(initializer.handleSafe).toHaveBeenCalledWith();
});
});
describe('runCli', (): void => {
it('starts the server with default settings.', async(): Promise<void> => {
new AppRunner().runCli({
argv: [ 'node', 'script' ],
});
// Wait until initializer has been called, because we can't await AppRunner.run.
await new Promise((resolve): void => {
setImmediate(resolve);
});
expect(ComponentsManager.build).toHaveBeenCalledTimes(1);
expect(ComponentsManager.build).toHaveBeenCalledWith({
dumpErrorState: true,
logLevel: 'info',
mainModulePath: joinFilePath(__dirname, '../../../'),
});
expect(manager.configRegistry.register).toHaveBeenCalledTimes(1);
expect(manager.configRegistry.register)
.toHaveBeenCalledWith(joinFilePath(__dirname, '/../../../config/config-default.json'));
expect(manager.instantiate).toHaveBeenCalledTimes(1);
expect(manager.instantiate).toHaveBeenCalledWith(
'urn:solid-server:default:Initializer',
{
variables: {
'urn:solid-server:default:variable:port': 3000,
'urn:solid-server:default:variable:baseUrl': 'http://localhost:3000/',
'urn:solid-server:default:variable:rootFilePath': '/var/cwd/',
'urn:solid-server:default:variable:sparqlEndpoint': undefined,
'urn:solid-server:default:variable:loggingLevel': 'info',
'urn:solid-server:default:variable:podConfigJson': '/var/cwd/pod-config.json',
'urn:solid-server:default:variable:idpTemplateFolder': joinFilePath(__dirname, '../../../templates/idp'),
},
},
);
expect(initializer.handleSafe).toHaveBeenCalledTimes(1);
expect(initializer.handleSafe).toHaveBeenCalledWith();
});
it('accepts abbreviated flags.', async(): Promise<void> => {
new AppRunner().runCli({
argv: [
'node', 'script',
'-b', 'http://pod.example/',
'-c', 'myconfig.json',
'-f', '/root',
'-l', 'debug',
'-m', 'module/path',
'-p', '4000',
'-s', 'http://localhost:5000/sparql',
'--podConfigJson', '/different-path.json',
'--idpTemplateFolder', 'templates/idp',
],
});
// Wait until initializer has been called, because we can't await AppRunner.run.
await new Promise((resolve): void => {
setImmediate(resolve);
});
expect(ComponentsManager.build).toHaveBeenCalledTimes(1);
expect(ComponentsManager.build).toHaveBeenCalledWith({
dumpErrorState: true,
logLevel: 'debug',
mainModulePath: '/var/cwd/module/path',
});
expect(manager.configRegistry.register).toHaveBeenCalledTimes(1);
expect(manager.configRegistry.register).toHaveBeenCalledWith('/var/cwd/myconfig.json');
expect(manager.instantiate).toHaveBeenCalledWith(
'urn:solid-server:default:Initializer',
{
variables: {
'urn:solid-server:default:variable:baseUrl': 'http://pod.example/',
'urn:solid-server:default:variable:loggingLevel': 'debug',
'urn:solid-server:default:variable:port': 4000,
'urn:solid-server:default:variable:rootFilePath': '/root',
'urn:solid-server:default:variable:sparqlEndpoint': 'http://localhost:5000/sparql',
'urn:solid-server:default:variable:podConfigJson': '/different-path.json',
'urn:solid-server:default:variable:idpTemplateFolder': '/var/cwd/templates/idp',
},
},
);
});
it('accepts full flags.', async(): Promise<void> => {
new AppRunner().runCli({
argv: [
'node', 'script',
'--baseUrl', 'http://pod.example/',
'--config', 'myconfig.json',
'--loggingLevel', 'debug',
'--mainModulePath', 'module/path',
'--port', '4000',
'--rootFilePath', 'root',
'--sparqlEndpoint', 'http://localhost:5000/sparql',
'--podConfigJson', '/different-path.json',
'--idpTemplateFolder', 'templates/idp',
],
});
// Wait until initializer has been called, because we can't await AppRunner.run.
await new Promise((resolve): void => {
setImmediate(resolve);
});
expect(ComponentsManager.build).toHaveBeenCalledTimes(1);
expect(ComponentsManager.build).toHaveBeenCalledWith({
dumpErrorState: true,
logLevel: 'debug',
mainModulePath: '/var/cwd/module/path',
});
expect(manager.configRegistry.register).toHaveBeenCalledTimes(1);
expect(manager.configRegistry.register).toHaveBeenCalledWith('/var/cwd/myconfig.json');
expect(manager.instantiate).toHaveBeenCalledWith(
'urn:solid-server:default:Initializer',
{
variables: {
'urn:solid-server:default:variable:baseUrl': 'http://pod.example/',
'urn:solid-server:default:variable:loggingLevel': 'debug',
'urn:solid-server:default:variable:port': 4000,
'urn:solid-server:default:variable:rootFilePath': '/var/cwd/root',
'urn:solid-server:default:variable:sparqlEndpoint': 'http://localhost:5000/sparql',
'urn:solid-server:default:variable:podConfigJson': '/different-path.json',
'urn:solid-server:default:variable:idpTemplateFolder': '/var/cwd/templates/idp',
},
},
);
});
it('uses the default process.argv in case none are provided.', async(): Promise<void> => {
const { argv } = process;
process.argv = [
'node', 'script',
'-b', 'http://pod.example/',
'-c', 'myconfig.json',
'-f', '/root',
'-l', 'debug',
'-m', 'module/path',
'-p', '4000',
'-s', 'http://localhost:5000/sparql',
'--podConfigJson', '/different-path.json',
'--idpTemplateFolder', 'templates/idp',
];
new AppRunner().runCli();
// Wait until initializer has been called, because we can't await AppRunner.run.
await new Promise((resolve): void => {
setImmediate(resolve);
});
expect(ComponentsManager.build).toHaveBeenCalledTimes(1);
expect(ComponentsManager.build).toHaveBeenCalledWith({
dumpErrorState: true,
logLevel: 'debug',
mainModulePath: '/var/cwd/module/path',
});
expect(manager.configRegistry.register).toHaveBeenCalledTimes(1);
expect(manager.configRegistry.register).toHaveBeenCalledWith('/var/cwd/myconfig.json');
expect(manager.instantiate).toHaveBeenCalledWith(
'urn:solid-server:default:Initializer',
{
variables: {
'urn:solid-server:default:variable:baseUrl': 'http://pod.example/',
'urn:solid-server:default:variable:loggingLevel': 'debug',
'urn:solid-server:default:variable:port': 4000,
'urn:solid-server:default:variable:rootFilePath': '/root',
'urn:solid-server:default:variable:sparqlEndpoint': 'http://localhost:5000/sparql',
'urn:solid-server:default:variable:podConfigJson': '/different-path.json',
'urn:solid-server:default:variable:idpTemplateFolder': '/var/cwd/templates/idp',
},
},
);
process.argv = argv;
});
it('exits with output to stderr when instantiation fails.', async(): Promise<void> => {
manager.instantiate.mockRejectedValueOnce(new Error('Fatal'));
new AppRunner().runCli({
argv: [ 'node', 'script' ],
});
// Wait until initializer has been called, because we can't await AppRunner.run.
await new Promise((resolve): void => {
setImmediate(resolve);
});
expect(write).toHaveBeenCalledTimes(2);
expect(write).toHaveBeenNthCalledWith(1,
expect.stringMatching(/^Error: could not instantiate server from .*config-default\.json/u));
expect(write).toHaveBeenNthCalledWith(2,
expect.stringMatching(/^Error: Fatal/u));
expect(exit).toHaveBeenCalledTimes(1);
expect(exit).toHaveBeenCalledWith(1);
});
it('exits without output to stderr when initialization fails.', async(): Promise<void> => {
initializer.handleSafe.mockRejectedValueOnce(new Error('Fatal'));
new AppRunner().runCli({
argv: [ 'node', 'script' ],
});
// Wait until initializer has been called, because we can't await AppRunner.run.
await new Promise((resolve): void => {
setImmediate(resolve);
});
expect(write).toHaveBeenCalledTimes(0);
expect(exit).toHaveBeenCalledWith(1);
});
it('exits when unknown options are passed to the main executable.', async(): Promise<void> => {
new AppRunner().runCli({
argv: [
'node', 'script', '--foo',
],
});
// Wait until initializer has been called, because we can't await AppRunner.run.
await new Promise((resolve): void => {
setImmediate(resolve);
});
expect(error).toHaveBeenCalledWith('Unknown option: "foo"');
expect(exit).toHaveBeenCalledTimes(1);
expect(exit).toHaveBeenCalledWith(1);
});
it('exits when no value is passed to the main executable for an argument.', async(): Promise<void> => {
new AppRunner().runCli({
argv: [
'node', 'script', '-s',
],
});
// Wait until initializer has been called, because we can't await AppRunner.run.
await new Promise((resolve): void => {
setImmediate(resolve);
});
expect(error).toHaveBeenCalledWith('Missing value for argument "s"');
expect(exit).toHaveBeenCalledTimes(1);
expect(exit).toHaveBeenCalledWith(1);
});
it('exits when unknown parameters are passed to the main executable.', async(): Promise<void> => {
new AppRunner().runCli({
argv: [
'node', 'script', 'foo', 'bar', 'foo.txt', 'bar.txt',
],
});
// Wait until initializer has been called, because we can't await AppRunner.run.
await new Promise((resolve): void => {
setImmediate(resolve);
});
// There seems to be an issue with yargs where the first and last `"` are missing.
expect(error).toHaveBeenCalledWith('Unsupported arguments: foo", "bar", "foo.txt", "bar.txt');
expect(exit).toHaveBeenCalledTimes(1);
expect(exit).toHaveBeenCalledWith(1);
});
it('exits when multiple values for a parameter are passed.', async(): Promise<void> => {
new AppRunner().runCli({
argv: [
'node', 'script', '-ll',
],
});
// Wait until initializer has been called, because we can't await AppRunner.run.
await new Promise((resolve): void => {
setImmediate(resolve);
});
expect(error).toHaveBeenCalledWith('Multiple values were provided for: "l", [info,info]');
expect(exit).toHaveBeenCalledTimes(1);
expect(exit).toHaveBeenCalledWith(1);
});
});
});