feat: Simplify and merge OIDC configurations

This commit is contained in:
Joachim Van Herwegen
2021-07-08 12:00:46 +02:00
parent d850ad1025
commit fdc52f50e5
18 changed files with 479 additions and 601 deletions

View File

@@ -1,113 +0,0 @@
import type { interactionPolicy, Configuration, KoaContextWithOIDC } from 'oidc-provider';
import type { ConfigurationFactory } from '../../../src/identity/configuration/ConfigurationFactory';
import { IdentityProviderFactory } from '../../../src/identity/IdentityProviderFactory';
import type { InteractionPolicy } from '../../../src/identity/interaction/InteractionPolicy';
import type { ErrorHandler } from '../../../src/ldp/http/ErrorHandler';
import type { ResponseWriter } from '../../../src/ldp/http/ResponseWriter';
import type { HttpResponse } from '../../../src/server/HttpResponse';
jest.mock('oidc-provider', (): any => ({
// eslint-disable-next-line @typescript-eslint/naming-convention
Provider: jest.fn().mockImplementation((issuer: string, config: Configuration): any => ({ issuer, config })),
}));
describe('An IdentityProviderFactory', (): void => {
const issuer = 'http://test.com/';
const idpPolicy: InteractionPolicy = {
policy: [ 'prompt' as unknown as interactionPolicy.Prompt ],
url: (ctx: KoaContextWithOIDC): string => `/idp/interaction/${ctx.oidc.uid}`,
};
const webId = 'http://alice.test.com/card#me';
let configuration: any;
let errorHandler: ErrorHandler;
let responseWriter: ResponseWriter;
let factory: IdentityProviderFactory;
beforeEach(async(): Promise<void> => {
configuration = {};
const configurationFactory: ConfigurationFactory = {
createConfiguration: async(): Promise<any> => configuration,
};
errorHandler = {
handleSafe: jest.fn().mockResolvedValue({ statusCode: 500 }),
} as any;
responseWriter = { handleSafe: jest.fn() } as any;
factory = new IdentityProviderFactory(issuer, configurationFactory, errorHandler, responseWriter);
});
it('has fixed default values.', async(): Promise<void> => {
const result = await factory.createProvider(idpPolicy) as any;
expect(result.issuer).toBe(issuer);
expect(result.config.interactions).toEqual(idpPolicy);
const findResult = await result.config.findAccount({}, webId);
expect(findResult.accountId).toBe(webId);
await expect(findResult.claims()).resolves.toEqual({ sub: webId, webid: webId });
expect(result.config.claims).toEqual({ webid: [ 'webid', 'client_webid' ]});
expect(result.config.conformIdTokenClaims).toBe(false);
expect(result.config.features).toEqual({
registration: { enabled: true },
dPoP: { enabled: true, ack: 'draft-01' },
claimsParameter: { enabled: true },
});
expect(result.config.subjectTypes).toEqual([ 'public', 'pairwise' ]);
expect(result.config.formats).toEqual({
// eslint-disable-next-line @typescript-eslint/naming-convention
AccessToken: 'jwt',
});
expect(result.config.audiences()).toBe('solid');
expect(result.config.extraAccessTokenClaims({}, {})).toEqual({});
expect(result.config.extraAccessTokenClaims({}, { accountId: webId })).toEqual({
webid: webId,
// This will need to change once #718 is fixed
// eslint-disable-next-line @typescript-eslint/naming-convention
client_webid: 'http://localhost:3001/',
aud: 'solid',
});
// Test the renderError function
const response: HttpResponse = { } as any;
await expect(result.config.renderError({ res: response }, null, 'error!')).resolves.toBeUndefined();
expect(errorHandler.handleSafe).toHaveBeenCalledTimes(1);
expect(errorHandler.handleSafe)
.toHaveBeenLastCalledWith({ error: 'error!', preferences: { type: { 'text/plain': 1 }}});
expect(responseWriter.handleSafe).toHaveBeenCalledTimes(1);
expect(responseWriter.handleSafe).toHaveBeenLastCalledWith({ response, result: { statusCode: 500 }});
});
it('overwrites fields from the factory config.', async(): Promise<void> => {
configuration.dummy = 'value!';
configuration.conformIdTokenClaims = true;
const result = await factory.createProvider(idpPolicy) as any;
expect(result.config.dummy).toBe('value!');
expect(result.config.conformIdTokenClaims).toBe(false);
});
it('copies specific object values from the factory config.', async(): Promise<void> => {
configuration.interactions = { dummy: 'interaction!' };
configuration.claims = { dummy: 'claim!' };
configuration.features = { dummy: 'feature!' };
configuration.subjectTypes = [ 'dummy!' ];
configuration.formats = { dummy: 'format!' };
const result = await factory.createProvider({ policy: 'policy!', url: 'url!' } as any) as any;
expect(result.config.interactions).toEqual({ policy: 'policy!', url: 'url!' });
expect(result.config.claims).toEqual({ dummy: 'claim!', webid: [ 'webid', 'client_webid' ]});
expect(result.config.features).toEqual({
dummy: 'feature!',
registration: { enabled: true },
dPoP: { enabled: true, ack: 'draft-01' },
claimsParameter: { enabled: true },
});
expect(result.config.subjectTypes).toEqual([ 'public', 'pairwise' ]);
expect(result.config.formats).toEqual({
// eslint-disable-next-line @typescript-eslint/naming-convention
AccessToken: 'jwt',
});
});
});

View File

@@ -1,8 +1,7 @@
import type { interactionPolicy, KoaContextWithOIDC, Provider } from 'oidc-provider';
import type { IdentityProviderFactory } from '../../../src/identity/IdentityProviderFactory';
import type { Provider } from 'oidc-provider';
import type { ProviderFactory } from '../../../src/identity/configuration/ProviderFactory';
import { IdentityProviderHttpHandler } from '../../../src/identity/IdentityProviderHttpHandler';
import type { InteractionHttpHandler } from '../../../src/identity/interaction/InteractionHttpHandler';
import type { InteractionPolicy } from '../../../src/identity/interaction/InteractionPolicy';
import type { ErrorHandler } from '../../../src/ldp/http/ErrorHandler';
import type { ResponseDescription } from '../../../src/ldp/http/response/ResponseDescription';
import type { ResponseWriter } from '../../../src/ldp/http/ResponseWriter';
@@ -12,15 +11,11 @@ import type { HttpResponse } from '../../../src/server/HttpResponse';
describe('An IdentityProviderHttpHandler', (): void => {
const request: HttpRequest = {} as any;
const response: HttpResponse = {} as any;
let providerFactory: IdentityProviderFactory;
const idpPolicy: InteractionPolicy = {
policy: [ 'prompt' as unknown as interactionPolicy.Prompt ],
url: (ctx: KoaContextWithOIDC): string => `/idp/interaction/${ctx.oidc.uid}`,
};
let interactionHttpHandler: InteractionHttpHandler;
let errorHandler: ErrorHandler;
let responseWriter: ResponseWriter;
let provider: Provider;
let providerFactory: jest.Mocked<ProviderFactory>;
let interactionHttpHandler: jest.Mocked<InteractionHttpHandler>;
let errorHandler: jest.Mocked<ErrorHandler>;
let responseWriter: jest.Mocked<ResponseWriter>;
let provider: jest.Mocked<Provider>;
let handler: IdentityProviderHttpHandler;
beforeEach(async(): Promise<void> => {
@@ -29,8 +24,8 @@ describe('An IdentityProviderHttpHandler', (): void => {
} as any;
providerFactory = {
createProvider: jest.fn().mockResolvedValue(provider),
} as any;
getProvider: jest.fn().mockResolvedValue(provider),
};
interactionHttpHandler = {
canHandle: jest.fn(),
@@ -43,7 +38,6 @@ describe('An IdentityProviderHttpHandler', (): void => {
handler = new IdentityProviderHttpHandler(
providerFactory,
idpPolicy,
interactionHttpHandler,
errorHandler,
responseWriter,
@@ -70,8 +64,8 @@ describe('An IdentityProviderHttpHandler', (): void => {
it('returns an error response if there was an issue with the interaction handler.', async(): Promise<void> => {
const error = new Error('error!');
const errorResponse: ResponseDescription = { statusCode: 500 };
(interactionHttpHandler.handle as jest.Mock).mockRejectedValueOnce(error);
(errorHandler.handleSafe as jest.Mock).mockResolvedValueOnce(errorResponse);
interactionHttpHandler.handle.mockRejectedValueOnce(error);
errorHandler.handleSafe.mockResolvedValueOnce(errorResponse);
await expect(handler.handle({ request, response })).resolves.toBeUndefined();
expect(provider.callback).toHaveBeenCalledTimes(0);
expect(interactionHttpHandler.handle).toHaveBeenCalledTimes(1);
@@ -83,25 +77,16 @@ describe('An IdentityProviderHttpHandler', (): void => {
});
it('re-throws the error if it is not a native Error.', async(): Promise<void> => {
(interactionHttpHandler.handle as jest.Mock).mockRejectedValueOnce('apple!');
interactionHttpHandler.handle.mockRejectedValueOnce('apple!');
await expect(handler.handle({ request, response })).rejects.toEqual('apple!');
});
it('caches the provider after creating it.', async(): Promise<void> => {
expect(providerFactory.createProvider).toHaveBeenCalledTimes(0);
await expect(handler.handle({ request, response })).resolves.toBeUndefined();
expect(providerFactory.createProvider).toHaveBeenCalledTimes(1);
expect(providerFactory.createProvider).toHaveBeenLastCalledWith(idpPolicy);
await expect(handler.handle({ request, response })).resolves.toBeUndefined();
expect(providerFactory.createProvider).toHaveBeenCalledTimes(1);
});
it('errors if there is an issue creating the provider.', async(): Promise<void> => {
const error = new Error('error!');
(providerFactory.createProvider as jest.Mock).mockRejectedValueOnce(error);
providerFactory.getProvider.mockRejectedValueOnce(error);
await expect(handler.handle({ request, response })).rejects.toThrow(error);
(providerFactory.createProvider as jest.Mock).mockRejectedValueOnce('apple');
providerFactory.getProvider.mockRejectedValueOnce('apple');
await expect(handler.handle({ request, response })).rejects.toBe('apple');
});
});

View File

@@ -0,0 +1,161 @@
import type { Configuration } from 'oidc-provider';
import { IdentityProviderFactory } from '../../../../src/identity/configuration/IdentityProviderFactory';
import type { AdapterFactory } from '../../../../src/identity/storage/AdapterFactory';
import type { ErrorHandler } from '../../../../src/ldp/http/ErrorHandler';
import type { ResponseWriter } from '../../../../src/ldp/http/ResponseWriter';
import type { HttpResponse } from '../../../../src/server/HttpResponse';
import type { KeyValueStorage } from '../../../../src/storage/keyvalue/KeyValueStorage';
/* eslint-disable @typescript-eslint/naming-convention */
jest.mock('oidc-provider', (): any => ({
Provider: jest.fn().mockImplementation((issuer: string, config: Configuration): any => ({ issuer, config })),
}));
const routes = {
authorization: '/foo/idp/auth',
check_session: '/foo/idp/session/check',
code_verification: '/foo/idp/device',
device_authorization: '/foo/idp/device/auth',
end_session: '/foo/idp/session/end',
introspection: '/foo/idp/token/introspection',
jwks: '/foo/idp/jwks',
pushed_authorization_request: '/foo/idp/request',
registration: '/foo/idp/reg',
revocation: '/foo/idp/token/revocation',
token: '/foo/idp/token',
userinfo: '/foo/idp/me',
};
describe('An IdentityProviderFactory', (): void => {
let baseConfig: Configuration;
const baseUrl = 'http://test.com/foo/';
const idpPath = '/idp';
const webId = 'http://alice.test.com/card#me';
let adapterFactory: jest.Mocked<AdapterFactory>;
let storage: jest.Mocked<KeyValueStorage<string, any>>;
let errorHandler: jest.Mocked<ErrorHandler>;
let responseWriter: jest.Mocked<ResponseWriter>;
let factory: IdentityProviderFactory;
beforeEach(async(): Promise<void> => {
baseConfig = { claims: { webid: [ 'webid', 'client_webid' ]}};
adapterFactory = {
createStorageAdapter: jest.fn().mockReturnValue('adapter!'),
};
const map = new Map();
storage = {
get: jest.fn((id: string): any => map.get(id)),
set: jest.fn((id: string, value: any): any => map.set(id, value)),
} as any;
errorHandler = {
handleSafe: jest.fn().mockResolvedValue({ statusCode: 500 }),
} as any;
responseWriter = { handleSafe: jest.fn() } as any;
factory = new IdentityProviderFactory(baseConfig, {
adapterFactory,
baseUrl,
idpPath,
storage,
errorHandler,
responseWriter,
});
});
it('errors if the idpPath parameter does not start with a slash.', async(): Promise<void> => {
expect((): any => new IdentityProviderFactory(baseConfig, {
adapterFactory,
baseUrl,
idpPath: 'idp',
storage,
errorHandler,
responseWriter,
})).toThrow('idpPath needs to start with a /');
});
it('creates a correct configuration.', async(): Promise<void> => {
// This is the output of our mock function
const { issuer, config } = await factory.getProvider() as unknown as { issuer: string; config: Configuration };
expect(issuer).toBe(baseUrl);
// Copies the base config
expect(config.claims).toEqual(baseConfig.claims);
(config.adapter as (name: string) => any)('test!');
expect(adapterFactory.createStorageAdapter).toHaveBeenCalledTimes(1);
expect(adapterFactory.createStorageAdapter).toHaveBeenLastCalledWith('test!');
expect(config.cookies?.keys).toEqual([ expect.any(String) ]);
expect(config.jwks).toEqual({ keys: [ expect.objectContaining({ kty: 'RSA' }) ]});
expect(config.routes).toEqual(routes);
expect((config.interactions?.url as any)()).toEqual('/idp/');
expect((config.audiences as any)()).toBe('solid');
const findResult = await config.findAccount?.({} as any, webId);
expect(findResult?.accountId).toBe(webId);
await expect((findResult?.claims as any)()).resolves.toEqual({ sub: webId, webid: webId });
expect((config.extraAccessTokenClaims as any)({}, {})).toEqual({});
expect((config.extraAccessTokenClaims as any)({}, { accountId: webId })).toEqual({
webid: webId,
// This will need to change once #718 is fixed
client_id: 'http://localhost:3001/',
});
// Test the renderError function
const response = { } as HttpResponse;
await expect((config.renderError as any)({ res: response }, null, 'error!')).resolves.toBeUndefined();
expect(errorHandler.handleSafe).toHaveBeenCalledTimes(1);
expect(errorHandler.handleSafe)
.toHaveBeenLastCalledWith({ error: 'error!', preferences: { type: { 'text/plain': 1 }}});
expect(responseWriter.handleSafe).toHaveBeenCalledTimes(1);
expect(responseWriter.handleSafe).toHaveBeenLastCalledWith({ response, result: { statusCode: 500 }});
});
it('copies a field from the input config if values need to be added to it.', async(): Promise<void> => {
baseConfig.cookies = {
long: { signed: true },
};
factory = new IdentityProviderFactory(baseConfig, {
adapterFactory,
baseUrl,
idpPath,
storage,
errorHandler,
responseWriter,
});
const { config } = await factory.getProvider() as unknown as { issuer: string; config: Configuration };
expect(config.cookies?.long?.signed).toBe(true);
});
it('caches the provider.', async(): Promise<void> => {
const result1 = await factory.getProvider() as unknown as { issuer: string; config: Configuration };
const result2 = await factory.getProvider() as unknown as { issuer: string; config: Configuration };
expect(result1).toBe(result2);
});
it('uses cached keys in case they already exist.', async(): Promise<void> => {
const result1 = await factory.getProvider() as unknown as { issuer: string; config: Configuration };
// Create a new factory that is not cached yet
const factory2 = new IdentityProviderFactory(baseConfig, {
adapterFactory,
baseUrl,
idpPath,
storage,
errorHandler,
responseWriter,
});
const result2 = await factory2.getProvider() as unknown as { issuer: string; config: Configuration };
expect(result1.config.cookies).toEqual(result2.config.cookies);
expect(result1.config.jwks).toEqual(result2.config.jwks);
expect(storage.get).toHaveBeenCalledTimes(4);
expect(storage.set).toHaveBeenCalledTimes(2);
expect(storage.set).toHaveBeenCalledWith('/idp/jwks', result1.config.jwks);
expect(storage.set).toHaveBeenCalledWith('/idp/cookie-secret', result1.config.cookies?.keys);
});
});

View File

@@ -1,96 +0,0 @@
import { KeyConfigurationFactory } from '../../../../src/identity/configuration/KeyConfigurationFactory';
import type { AdapterFactory } from '../../../../src/identity/storage/AdapterFactory';
import type { KeyValueStorage } from '../../../../src/storage/keyvalue/KeyValueStorage';
/* eslint-disable @typescript-eslint/naming-convention */
function getExpected(adapter: any, cookieKeys: any, jwks: any): any {
return {
adapter,
cookies: {
long: { signed: true, maxAge: 1 * 24 * 60 * 60 * 1000 },
short: { signed: true },
keys: cookieKeys,
},
conformIdTokenClaims: false,
features: {
devInteractions: { enabled: false },
deviceFlow: { enabled: true },
introspection: { enabled: true },
revocation: { enabled: true },
registration: { enabled: true },
claimsParameter: { enabled: true },
},
jwks,
ttl: {
AccessToken: 1 * 60 * 60,
AuthorizationCode: 10 * 60,
IdToken: 1 * 60 * 60,
DeviceCode: 10 * 60,
RefreshToken: 1 * 24 * 60 * 60,
},
subjectTypes: [ 'public', 'pairwise' ],
routes: {
authorization: '/foo/idp/auth',
check_session: '/foo/idp/session/check',
code_verification: '/foo/idp/device',
device_authorization: '/foo/idp/device/auth',
end_session: '/foo/idp/session/end',
introspection: '/foo/idp/token/introspection',
jwks: '/foo/idp/jwks',
pushed_authorization_request: '/foo/idp/request',
registration: '/foo/idp/reg',
revocation: '/foo/idp/token/revocation',
token: '/foo/idp/token',
userinfo: '/foo/idp/me',
},
discovery: {
solid_oidc_supported: 'https://solidproject.org/TR/solid-oidc',
},
};
}
describe('A KeyConfigurationFactory', (): void => {
let storageAdapterFactory: AdapterFactory;
const baseUrl = 'http://test.com/foo/';
const idpPathName = 'idp';
let storage: KeyValueStorage<string, any>;
let generator: KeyConfigurationFactory;
beforeEach(async(): Promise<void> => {
storageAdapterFactory = {
createStorageAdapter: jest.fn().mockReturnValue('adapter!'),
};
const map = new Map();
storage = {
get: jest.fn((id: string): any => map.get(id)),
set: jest.fn((id: string, value: any): any => map.set(id, value)),
} as any;
generator = new KeyConfigurationFactory(storageAdapterFactory, baseUrl, idpPathName, storage);
});
it('creates a correct configuration.', async(): Promise<void> => {
const result = await generator.createConfiguration();
expect(result).toEqual(getExpected(
expect.any(Function),
[ expect.any(String) ],
{ keys: [ expect.objectContaining({ kty: 'RSA' }) ]},
));
(result.adapter as (name: string) => any)('test!');
expect(storageAdapterFactory.createStorageAdapter).toHaveBeenCalledTimes(1);
expect(storageAdapterFactory.createStorageAdapter).toHaveBeenLastCalledWith('test!');
});
it('stores cookie keys and jwks for re-use.', async(): Promise<void> => {
const result = await generator.createConfiguration();
const result2 = await generator.createConfiguration();
expect(result.cookies).toEqual(result2.cookies);
expect(result.jwks).toEqual(result2.jwks);
expect(storage.get).toHaveBeenCalledTimes(4);
expect(storage.set).toHaveBeenCalledTimes(2);
expect(storage.set).toHaveBeenCalledWith('idp/jwks', result.jwks);
expect(storage.set).toHaveBeenCalledWith('idp/cookie-secret', result.cookies?.keys);
});
});

View File

@@ -1,20 +0,0 @@
import {
AccountInteractionPolicy,
} from '../../../../../src/identity/interaction/email-password/AccountInteractionPolicy';
describe('An AccountInteractionPolicy', (): void => {
const idpPath = '/idp';
const interactionPolicy = new AccountInteractionPolicy(idpPath);
it('errors if the idpPath parameter does not start with a slash.', async(): Promise<void> => {
expect((): any => new AccountInteractionPolicy('idp')).toThrow('idpPath needs to start with a /');
});
it('has a select_account policy at index 0.', async(): Promise<void> => {
expect(interactionPolicy.policy[0].name).toBe('select_account');
});
it('sets the default url to /idp/.', async(): Promise<void> => {
expect(interactionPolicy.url({ oidc: { uid: 'valid-uid' }} as any)).toBe('/idp/');
});
});