Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: authenticate with openid connect #555

Merged
merged 12 commits into from
Nov 24, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"lodash": "4.17.19",
"moment": "2.24.0",
"moment-timezone": "0.5.26",
"openid-client": "4.2.0",
"otplib": "11.0.1",
"require-all": "3.0.0",
"semver": "6.3.0",
Expand All @@ -67,6 +68,7 @@
"@semantic-release/changelog": "5.0.1",
"@semantic-release/git": "9.0.0",
"@types/jest": "26.0.13",
"@types/jsonwebtoken": "8.5.0",
"babel-eslint": "10.0.3",
"eslint": "6.8.0",
"eslint-config-airbnb-base": "14.0.0",
Expand Down
2 changes: 1 addition & 1 deletion src/context/application-context.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class ApplicationContext {

/**
* @param {*} Class
* @param {boolean?} overrides
* @param {boolean} [overrides]
* @returns {this}
*/
addClass(Class, overrides) {
Expand Down
62 changes: 57 additions & 5 deletions src/context/init.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const fs = require('fs');
const superagentRequest = require('superagent');
const path = require('path');
const openIdClient = require('openid-client');
const jsonwebtoken = require('jsonwebtoken');

const errorMessages = require('../utils/error-messages');
const errorUtils = require('../utils/error');
Expand All @@ -18,12 +20,34 @@ const SchemaFileUpdater = require('../services/schema-file-updater');
const schemasGenerator = require('../generators/schemas');
const ConfigStore = require('../services/config-store');
const ModelsManager = require('../services/models-manager');
const AuthenticationService = require('../services/authentication');
const TokenService = require('../services/token');
const OidcConfigurationRetrieverService = require('../services/oidc-configuration-retriever');
const OidcClientManagerService = require('../services/oidc-client-manager');

function initValue(context) {
context.addValue('forestUrl', process.env.FOREST_URL || 'https://api.forestadmin.com');
}

/**
* @typedef {{
* NODE_ENV: 'production' | 'development';
* FOREST_DISABLE_AUTO_SCHEMA_APPLY: boolean;
* FOREST_2FA_SECRET_SALT?: boolean;
* CORS_ORIGINS?: string;
* JWT_ALGORITHM: string;
* FOREST_PERMISSIONS_EXPIRATION_IN_SECONDS: number;
* FOREST_OIDC_CONFIG_EXPIRATION_IN_SECONDS: number;
* FOREST_URL: string;
* APPLICATION_URL: string;
* FOREST_AUTH_SECRET: string;
* FOREST_ENV_SECRET: string;
* }} Env
*
* @typedef {{
* env: Env
* }} EnvPart
*
* @typedef {{
* errorMessages: import('../utils/error-messages');
* stringUtils: import('../utils/string');
Expand All @@ -40,17 +64,38 @@ function initValue(context) {
* schemaFileUpdater: import('../services/schema-file-updater');
* apimapSender: import('../services/apimap-sender');
* schemasGenerator: import('../generators/schemas');
* authenticationService: import('../services/authentication');
* tokenService: import('../services/token');
* oidcConfigurationRetrieverService: import('../services/oidc-configuration-retriever');
* oidcClientManagerService: import('../services/oidc-client-manager')
* }} Services
*
* @typedef {{
* superagentRequest: import('superagent');
* openIdClient: import('openid-client');
* jsonwebtoken: import('jsonwebtoken');
* }} Externals
*
* @typedef {Utils & Services & Externals} Context
* @typedef {EnvPart & Utils & Services & Externals} Context
*/

/**
* @param {ApplicationContext} context
* @param {import('./application-context')} context
*/
function initEnv(context) {
context.addInstance('env', {
...process.env,
FOREST_URL: process.env.FOREST_URL || 'https://api.forestadmin.com',
JWT_ALGORITHM: process.env.JWT_ALGORITHM || 'HS256',
NODE_ENV: ['dev', 'development'].includes(process.env.NODE_ENV)
? 'development'
: 'production',
APPLICATION_URL: process.env.APPLICATION_URL || `http://localhost:${process.env.APPLICATION_PORT || 3310}`,
});
}

/**
* @param {import('./application-context')} context
*/
function initUtils(context) {
context.addInstance('errorMessages', errorMessages);
Expand All @@ -59,7 +104,7 @@ function initUtils(context) {
}

/**
* @param {ApplicationContext} context
* @param {import('./application-context')} context
*/
function initServices(context) {
context.addInstance('logger', logger);
Expand All @@ -75,23 +120,30 @@ function initServices(context) {
context.addClass(SchemaFileUpdater);
context.addClass(ConfigStore);
context.addClass(ModelsManager);
context.addClass(TokenService);
context.addClass(OidcConfigurationRetrieverService);
context.addClass(OidcClientManagerService);
context.addClass(AuthenticationService);
}

/**
* @param {ApplicationContext} context
* @param {import('./application-context')} context
*/
function initExternals(context) {
context.addInstance('superagentRequest', superagentRequest);
context.addInstance('fs', fs);
context.addInstance('path', path);
context.addInstance('openIdClient', openIdClient);
context.addInstance('jsonwebtoken', jsonwebtoken);
}

/**
* @returns {ApplicationContext<Context>}
* @param {import('./application-context')<Context>} context
*/
function initContext(context) {
initExternals(context);
initValue(context);
initEnv(context);
initUtils(context);
initServices(context);
}
Expand Down
41 changes: 38 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const jwt = require('express-jwt');
const url = require('url');
const requireAll = require('require-all');
const context = require('./context');
const initContext = require('./context/init');
Expand All @@ -24,6 +25,7 @@ const Integrator = require('./integrations');
const ProjectDirectoryUtils = require('./utils/project-directory');
const { is2FASaltValid } = require('./utils/token-checker');
const { getJWTConfiguration } = require('./config/jwt');
const initAuthenticationRoutes = require('./routes/authentication');

const {
logger,
Expand All @@ -38,6 +40,14 @@ const {
fs,
} = context.inject();

const PUBLIC_ROUTES = [
'/',
'/healthcheck',
'/sessions',
'/sessions-google',
...initAuthenticationRoutes.PUBLIC_ROUTES,
];

const pathProjectAbsolute = new ProjectDirectoryUtils().getAbsolutePath();

const ENVIRONMENT_DEVELOPMENT = !process.env.NODE_ENV
Expand Down Expand Up @@ -88,7 +98,20 @@ exports.Schemas = Schemas;
exports.logger = logger;
exports.ResourcesRoute = {};

/**
* @param {import('express').Request} request
* @param {import('express').Response} response
* @param {import('express').NextFunction} next
*/
exports.ensureAuthenticated = (request, response, next) => {
const parsedUrl = url.parse(request.originalUrl);
const forestPublicRoutes = PUBLIC_ROUTES.map((route) => `/forest${route}`);

if (forestPublicRoutes.includes(parsedUrl.pathname)) {
next();
return;
}

auth.authenticate(request, response, next, jwtAuthenticator);
};

Expand Down Expand Up @@ -194,17 +217,28 @@ exports.init = async (Implementation) => {

// CORS
let allowedOrigins = ['localhost:4200', /\.forestadmin\.com$/];
const oneDayInSeconds = 86400;

if (process.env.CORS_ORIGINS) {
allowedOrigins = allowedOrigins.concat(process.env.CORS_ORIGINS.split(','));
}

app.use(pathMounted, cors({
const corsOptions = {
origin: allowedOrigins,
maxAge: 86400, // NOTICE: 1 day
maxAge: oneDayInSeconds,
credentials: true,
preflightContinue: true,
};

app.use(pathService.generate(initAuthenticationRoutes.CALLBACK_ROUTE, opts), cors({
...corsOptions,
// this route needs to be called after a redirection
// in this situation, the origin sent by the browser is "null"
origin: ['null', ...corsOptions.origin],
}));

app.use(pathMounted, cors(corsOptions));

// Mime type
app.use(pathMounted, bodyParser.json());

Expand Down Expand Up @@ -238,6 +272,7 @@ exports.init = async (Implementation) => {

new HealthCheckRoute(app, configStore.lianaOptions).perform();
new SessionRoute(app, configStore.lianaOptions).perform();
initAuthenticationRoutes(app, configStore.lianaOptions, context.inject());

// Init
try {
Expand Down Expand Up @@ -361,4 +396,4 @@ exports.PermissionMiddlewareCreator = require('./middlewares/permissions');

exports.errorHandler = errorHandler;

exports.PUBLIC_ROUTES = ['/', '/healthcheck', '/sessions', '/sessions-google'];
exports.PUBLIC_ROUTES = PUBLIC_ROUTES;
Loading