CommunitySolidServer/test/integration/IdentityTestState.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

150 lines
5.5 KiB
TypeScript

import { stringify } from 'querystring';
import { URL } from 'url';
import { Session } from '@inrupt/solid-client-authn-node';
import { load } from 'cheerio';
import type { Response } from 'cross-fetch';
import { fetch } from 'cross-fetch';
import type { Cookie } from 'set-cookie-parser';
import { parse, splitCookiesString } from 'set-cookie-parser';
import { APPLICATION_X_WWW_FORM_URLENCODED } from '../../src/util/ContentTypes';
/* eslint-disable jest/no-standalone-expect */
/**
* Helper class to track the state while going through an IDP procedure
* and generalizes several common calls and checks.
*/
export class IdentityTestState {
private readonly baseUrl: string;
private readonly redirectUrl: string;
private readonly oidcIssuer: string;
public readonly session: Session;
private readonly cookies: Map<string, Cookie>;
private cookie?: string;
public constructor(baseUrl: string, redirectUrl: string, oidcIssuer: string) {
this.baseUrl = baseUrl;
this.redirectUrl = redirectUrl;
this.oidcIssuer = oidcIssuer;
this.session = new Session();
this.cookies = new Map();
}
/**
* Performs a fetch call while keeping track of the stored cookies and preventing redirects.
* @param url - URL to call.
* @param method - Method to use.
* @param body - Body to send along.
* @param contentType - Content-Type of the body.
*/
// eslint-disable-next-line default-param-last
public async fetchIdp(url: string, method = 'GET', body?: string, contentType?: string): Promise<Response> {
const options = { method, headers: { cookie: this.cookie }, body, redirect: 'manual' } as any;
if (contentType) {
options.headers['content-type'] = contentType;
}
const res = await fetch(url, options);
// Parse the cookies that need to be set and convert them to the corresponding header value
// Make sure we don't overwrite cookies that were already present
if (res.headers.get('set-cookie')) {
const newCookies = parse(splitCookiesString(res.headers.get('set-cookie')!));
for (const cookie of newCookies) {
this.cookies.set(cookie.name, cookie);
}
// eslint-disable-next-line unicorn/prefer-spread
this.cookie = Array.from(this.cookies, ([ , nom ]): string => `${nom.name}=${nom.value}`).join('; ');
}
return res;
}
/**
* Uses the given jquery command to find a node in the given html body.
* The value from the given attribute field then gets extracted and combined with the base url.
* @param html - Body to parse.
* @param jquery - Query to run on the body.
* @param attr - Attribute to extract.
*/
public extractUrl(html: string, jquery: string, attr: string): string {
const url = load(html)(jquery).attr(attr);
expect(typeof url).toBe('string');
return new URL(url!, this.baseUrl).href;
}
/**
* Initializes an authentication session and stores the relevant cookies for later re-use.
* All te relevant links from the login page get extracted.
*/
public async startSession(): Promise<string> {
let nextUrl = '';
await this.session.login({
redirectUrl: this.redirectUrl,
oidcIssuer: this.oidcIssuer,
handleRedirect(data): void {
nextUrl = data;
},
});
expect(nextUrl.length > 0).toBeTruthy();
expect(nextUrl.startsWith(this.oidcIssuer)).toBeTruthy();
// Need to catch the redirect so we can copy the cookies
const res = await this.fetchIdp(nextUrl);
expect(res.status).toBe(302);
nextUrl = res.headers.get('location')!;
return nextUrl;
}
public async parseLoginPage(url: string): Promise<{ register: string; login: string; forgotPassword: string }> {
const res = await this.fetchIdp(url);
expect(res.status).toBe(200);
const text = await res.text();
const register = this.extractUrl(text, 'a:contains("Register")', 'href');
const login = this.extractUrl(text, 'form', 'action');
const forgotPassword = this.extractUrl(text, 'a:contains("Forgot Password")', 'href');
return { register, login, forgotPassword };
}
/**
* Logs in by sending the corresponding email and password to the given form action.
* The URL should be extracted from the login page.
*/
public async login(url: string, email: string, password: string): Promise<void> {
const formData = stringify({ email, password });
const res = await this.fetchIdp(url, 'POST', formData, APPLICATION_X_WWW_FORM_URLENCODED);
expect(res.status).toBe(302);
const nextUrl = res.headers.get('location')!;
return this.handleLoginRedirect(nextUrl);
}
/**
* Calls the given URL and extracts the action URL from a form contained within the resulting body.
* Also returns the resulting body in case further parsing is needed.
*/
public async extractFormUrl(url: string): Promise<{ url: string; body: string }> {
const res = await this.fetchIdp(url);
expect(res.status).toBe(200);
const text = await res.text();
const formUrl = this.extractUrl(text, 'form', 'action');
return {
url: new URL(formUrl, this.baseUrl).href,
body: text,
};
}
/**
* Handles the redirect that happens after logging in.
*/
public async handleLoginRedirect(url: string): Promise<void> {
const res = await this.fetchIdp(url);
expect(res.status).toBe(302);
const mockUrl = res.headers.get('location')!;
expect(mockUrl.startsWith(this.redirectUrl)).toBeTruthy();
const info = await this.session.handleIncomingRedirect(mockUrl);
expect(info?.isLoggedIn).toBe(true);
}
}