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

N8n 4058 spike single sign on #3814

Closed
wants to merge 8 commits into from
Closed
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
62,304 changes: 735 additions & 61,569 deletions package-lock.json

Large diffs are not rendered by default.

69 changes: 68 additions & 1 deletion packages/cli/config/schema.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/* eslint-disable no-restricted-syntax */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */

import path from 'path';
import * as core from 'n8n-core';
import path from 'path';

export const schema = {
database: {
Expand Down Expand Up @@ -503,6 +503,73 @@ export const schema = {
doc: 'JWT tenant to allow (optional)',
},
},
oidc: {
enabled: {
doc: 'OpenID Connect enabled.',
format: Boolean,
default: false,
env: 'N8N_OIDC_ENABLED',
},
issuerUrl: {
doc: 'OpenID Issuer URL.',
format: String,
default: '',
env: 'N8N_OIDC_ISSUER_URL',
},
clientId: {
doc: 'OpenID Client ID.',
format: String,
default: '',
env: 'N8N_OIDC_CLIENT_ID',
},
clientSecret: {
doc: 'OpenID Client Secret.',
format: String,
default: '',
env: 'N8N_OIDC_CLIENT_SECRET',
},
responseTypes: {
doc: 'OpenID Response Types.',
format: function check(rawValue: string): void {
try {
const values = JSON.parse(rawValue);
if (!Array.isArray(values)) {
throw new Error();
}

for (const value of values) {
if (typeof value !== 'string') {
throw new Error();
}
}
} catch (error) {
throw new TypeError(`The response types are not a valid Array of strings.`);
}
},
default: '["code"]',
env: 'N8N_OIDC_RESPONSE_TYPES',
},
tokenEndpointAuthMethod: {
doc: 'OpenID Token Endpoint Auth Method.',
format: [
'client_secret_basic',
'client_secret_post',
'client_secret_jwt',
'private_key_jwt',
'tls_client_auth',
'self_signed_tls_client_auth',
'none',
] as const,
default: 'client_secret_post',
env: 'N8N_OIDC_TOKEN_ENDPOINT_AUTH_METHOD',
},
scope: {
doc: 'OpenID Scope.',
format: String,
default: 'openid email profile',
env: 'N8N_OIDC_SCOPE',
},
},
},

endpoints: {
Expand Down
5 changes: 4 additions & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
"@types/cookie-parser": "^1.4.2",
"@types/dotenv": "^8.2.0",
"@types/express": "^4.17.6",
"@types/express-session": "^1.17.5",
"@types/jest": "^27.4.0",
"@types/localtunnel": "^1.9.0",
"@types/lodash.get": "^4.4.6",
Expand Down Expand Up @@ -97,9 +98,9 @@
"typescript": "~4.6.0"
},
"dependencies": {
"@oclif/core": "^1.9.3",
"@apidevtools/swagger-cli": "4.0.0",
"@oclif/command": "^1.5.18",
"@oclif/core": "^1.9.3",
"@oclif/errors": "^1.2.2",
"@rudderstack/rudder-sdk-node": "1.0.6",
"@types/json-diff": "^0.5.1",
Expand Down Expand Up @@ -127,6 +128,7 @@
"dotenv": "^8.0.0",
"express": "^4.16.4",
"express-openapi-validator": "^4.13.6",
"express-session": "^1.17.3",
"fast-glob": "^3.2.5",
"flatted": "^3.2.4",
"google-timezones-json": "^1.0.2",
Expand All @@ -152,6 +154,7 @@
"oauth-1.0a": "^2.2.6",
"open": "^7.0.0",
"openapi-types": "^10.0.0",
"openid-client": "^5.1.8",
"p-cancelable": "^2.0.0",
"passport": "^0.5.0",
"passport-cookie": "^1.0.9",
Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/Db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ export async function init(

collections.Role = linkRepository(entities.Role);
collections.User = linkRepository(entities.User);
collections.FederatedUser = linkRepository(entities.FederatedUser);
collections.SharedCredentials = linkRepository(entities.SharedCredentials);
collections.SharedWorkflow = linkRepository(entities.SharedWorkflow);
collections.Settings = linkRepository(entities.Settings);
Expand Down
20 changes: 11 additions & 9 deletions packages/cli/src/Interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,16 @@ import { Repository } from 'typeorm';
import { ChildProcess } from 'child_process';
import { Url } from 'url';
import { Request } from 'express';
import { WorkflowEntity } from './databases/entities/WorkflowEntity';
import { TagEntity } from './databases/entities/TagEntity';
import { Role } from './databases/entities/Role';
import { User } from './databases/entities/User';
import { SharedCredentials } from './databases/entities/SharedCredentials';
import { SharedWorkflow } from './databases/entities/SharedWorkflow';
import { Settings } from './databases/entities/Settings';
import { InstalledPackages } from './databases/entities/InstalledPackages';
import { InstalledNodes } from './databases/entities/InstalledNodes';
import type { WorkflowEntity } from './databases/entities/WorkflowEntity';
import type { TagEntity } from './databases/entities/TagEntity';
import type { Role } from './databases/entities/Role';
import type { User } from './databases/entities/User';
import type { SharedCredentials } from './databases/entities/SharedCredentials';
import type { SharedWorkflow } from './databases/entities/SharedWorkflow';
import type { Settings } from './databases/entities/Settings';
import type { InstalledPackages } from './databases/entities/InstalledPackages';
import type { InstalledNodes } from './databases/entities/InstalledNodes';
import type { FederatedUser } from './databases/entities/FederatedUser';

export interface IActivationError {
time: number;
Expand Down Expand Up @@ -83,6 +84,7 @@ export interface IDatabaseCollections {
Tag: Repository<TagEntity>;
Role: Repository<Role>;
User: Repository<User>;
FederatedUser: Repository<FederatedUser>;
SharedCredentials: Repository<SharedCredentials>;
SharedWorkflow: Repository<SharedWorkflow>;
Settings: Repository<Settings>;
Expand Down
54 changes: 24 additions & 30 deletions packages/cli/src/Server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,31 +29,28 @@
/* eslint-disable import/no-dynamic-require */
/* eslint-disable no-await-in-loop */

import bodyParser from 'body-parser';
import history from 'connect-history-api-fallback';
import cookieParser from 'cookie-parser';
import express from 'express';
import { readFileSync, promises } from 'fs';
import { promises, readFileSync } from 'fs';
import { readFile } from 'fs/promises';
import _, { cloneDeep } from 'lodash';
import os from 'os';
import { dirname as pathDirname, join as pathJoin, resolve as pathResolve } from 'path';
import {
FindManyOptions,
getConnection,
getConnectionManager,
In,
IsNull,
LessThanOrEqual,
Not,
Raw,
} from 'typeorm';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import history from 'connect-history-api-fallback';
import os from 'os';
// eslint-disable-next-line import/no-extraneous-dependencies
import clientOAuth2 from 'client-oauth2';
import { createHmac } from 'crypto';
import clientOAuth1, { RequestOptions } from 'oauth-1.0a';
import csrf from 'csrf';
import requestPromise, { OptionsWithUrl } from 'request-promise-native';
import { createHmac, randomBytes } from 'crypto';
// IMPORTANT! Do not switch to anther bcrypt library unless really necessary and
// tested with all possible systems like Windows, Alpine on ARM, FreeBSD, ...
import { compare } from 'bcryptjs';
Expand Down Expand Up @@ -87,11 +84,9 @@ import jwks from 'jwks-rsa';
// @ts-ignore
import timezones from 'google-timezones-json';
import parseUrl from 'parseurl';
import querystring from 'querystring';
import promClient, { Registry } from 'prom-client';
import * as Queue from './Queue';
import querystring from 'querystring';
import {
LoadNodesAndCredentials,
ActiveExecutions,
ActiveWorkflowRunner,
CredentialsHelper,
Expand All @@ -101,6 +96,8 @@ import {
Db,
ExternalHooks,
GenericHelpers,
getCredentialForUser,
getCredentialWithoutUser,
ICredentialsDb,
ICredentialsOverwrite,
ICustomRequest,
Expand All @@ -116,6 +113,7 @@ import {
IN8nUISettings,
IPackageVersions,
ITagWithCountDb,
IWorkflowDb,
IWorkflowExecutionDataProcess,
IWorkflowResponse,
NodeTypes,
Expand All @@ -129,48 +127,43 @@ import {
WorkflowExecuteAdditionalData,
WorkflowHelpers,
WorkflowRunner,
getCredentialForUser,
getCredentialWithoutUser,
IWorkflowDb,
} from '.';
import * as Queue from './Queue';

import config from '../config';

import * as TagHelpers from './TagHelpers';

import { InternalHooksManager } from './InternalHooksManager';
import { TagEntity } from './databases/entities/TagEntity';
import { WorkflowEntity } from './databases/entities/WorkflowEntity';
import { getSharedWorkflowIds, isBelowOnboardingThreshold, whereClause } from './WorkflowHelpers';
import { InternalHooksManager } from './InternalHooksManager';
import { getCredentialTranslationPath, getNodeTranslationPath } from './TranslationHelpers';
import { WEBHOOK_METHODS } from './WebhookHelpers';
import { getSharedWorkflowIds, isBelowOnboardingThreshold, whereClause } from './WorkflowHelpers';

import { userManagementRouter } from './UserManagement';
import { resolveJwt } from './UserManagement/auth/jwt';
import { credentialsController } from './api/credentials.api';
import { nodesController } from './api/nodes.api';
import { oauth2CredentialController } from './api/oauth2Credential.api';
import { workflowsController } from './api/workflows.api';
import { AUTH_COOKIE_NAME, RESPONSE_ERROR_MESSAGES } from './constants';
import { ExecutionEntity } from './databases/entities/ExecutionEntity';
import { User } from './databases/entities/User';
import { DEFAULT_EXECUTIONS_GET_ALL_LIMIT, validateEntity } from './GenericHelpers';
import { loadPublicApiVersions } from './PublicApi';
import type {
AuthenticatedRequest,
CredentialRequest,
ExecutionRequest,
NodeParameterOptionsRequest,
OAuthRequest,
TagsRequest,
WorkflowRequest,
} from './requests';
import { DEFAULT_EXECUTIONS_GET_ALL_LIMIT, validateEntity } from './GenericHelpers';
import { ExecutionEntity } from './databases/entities/ExecutionEntity';
import { AUTH_COOKIE_NAME, RESPONSE_ERROR_MESSAGES } from './constants';
import { credentialsController } from './api/credentials.api';
import { workflowsController } from './api/workflows.api';
import { nodesController } from './api/nodes.api';
import { oauth2CredentialController } from './api/oauth2Credential.api';
import { userManagementRouter } from './UserManagement';
import { resolveJwt } from './UserManagement/auth/jwt';
import {
getInstanceBaseUrl,
isEmailSetUp,
isUserManagementEnabled,
} from './UserManagement/UserManagementHelper';
import { loadPublicApiVersions } from './PublicApi';
import { SharedWorkflow } from './databases/entities/SharedWorkflow';

require('body-parser-xml')(bodyParser);

Expand Down Expand Up @@ -665,6 +658,7 @@ class App {
from: new RegExp(
// eslint-disable-next-line no-useless-escape
`^\/(${this.restEndpoint}|healthz|metrics|css|js|${this.endpointWebhook}|${this.endpointWebhookTest})\/?.*$`,
// `^\/(${this.restEndpoint}(?!\/login\/)|healthz|metrics|css|js|${this.endpointWebhook}|${this.endpointWebhookTest})\/?.*$`,
),
to: (context) => {
return context.parsedUrl.pathname!.toString();
Expand Down
32 changes: 27 additions & 5 deletions packages/cli/src/UserManagement/auth/jwt.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion */
/* eslint-disable import/no-cycle */

import jwt from 'jsonwebtoken';
import { Response } from 'express';
import { createHash } from 'crypto';
import type { NextFunction, Request, Response } from 'express';
import jwt from 'jsonwebtoken';
import { Db } from '../..';
import config from '../../../config';
import { AUTH_COOKIE_NAME } from '../../constants';
import { JwtPayload, JwtToken } from '../Interfaces';
import { User } from '../../databases/entities/User';
import * as config from '../../../config';
import { AuthenticatedRequest } from '../../requests';
import { JwtPayload, JwtToken } from '../Interfaces';

export function jwtFromRequest(req: Request): string | null {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
return (req.cookies?.[AUTH_COOKIE_NAME] as string | undefined) ?? null;
}

export function issueJWT(user: User): JwtToken {
const { id, email, password } = user;
Expand Down Expand Up @@ -65,3 +70,20 @@ export async function issueCookie(res: Response, user: User): Promise<void> {
const userData = issueJWT(user);
res.cookie(AUTH_COOKIE_NAME, userData.token, { maxAge: userData.expiresIn, httpOnly: true });
}

// middleware to refresh cookie before it expires
export async function refreshCookie(
req: AuthenticatedRequest,
res: Response,
next: NextFunction,
): Promise<void> {
const cookieAuth = jwtFromRequest(req);
if (cookieAuth && req.user) {
const cookieContents = jwt.decode(cookieAuth) as JwtPayload & { exp: number };
if (cookieContents.exp * 1000 - Date.now() < 259200000) {
// if cookie expires in < 3 days, renew it.
await issueCookie(res, req.user);
}
}
next();
}
Loading