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

WIP: SAML support (backend) #311

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
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
5 changes: 5 additions & 0 deletions server/.env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ SECRET_KEY=notsecretkey
# TRUST_PROXY=0
# TOKEN_EXPIRES_IN=365 # In days

# Uncomment for SAML login
#SAML_CONFIG=[{"id": "sso", "name": "My SSO Provider", "idp": {"sso_login_url": "https://idp.example.com/sls", "sso_logout_url": "https://idp.example.com/slo", "certificates": "<PEM idp cert"}, "sp": {"entity_id": "http://localhost:3000/", "assert_endpoint": "http://localhost:1337/api/saml/sso/acs", "certificate": "<sp PEM cert>", "private_key": "<sp PEM key>"}, "bindings": {"username": "username", "full_name": "fullname", "email": "email", "admin": ["groups", "admin"]}}]

DISABLE_LOCAL_AUTH=0

## Do not edit this

TZ=UTC
10 changes: 10 additions & 0 deletions server/api/controllers/access-tokens/create.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ const Errors = {
INVALID_PASSWORD: {
invalidPassword: 'Invalid password',
},
LOCAL_AUTH_DISABLED: {
localAuthDisabled: 'Local authentication is disabled',
},
};

module.exports = {
Expand Down Expand Up @@ -37,9 +40,16 @@ module.exports = {
invalidPassword: {
responseType: 'unauthorized',
},
localAuthDisabled: {
responseType: 'unauthorized',
},
},

async fn(inputs) {
if (!sails.config.custom.localAuth) {
throw Errors.LOCAL_AUTH_DISABLED;
}

const remoteAddress = getRemoteAddress(this.req);

const user = await sails.helpers.users.getOneByEmailOrUsername(inputs.emailOrUsername);
Expand Down
28 changes: 25 additions & 3 deletions server/api/controllers/access-tokens/delete.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,38 @@
module.exports = {
async fn() {
const { accessToken } = this.req;
const { accessToken, currentUser } = this.req;

await Session.updateOne({
const session = await Session.updateOne({
accessToken,
deletedAt: null,
}).set({
deletedAt: new Date().toUTCString(),
});

return {
const result = {
item: accessToken,
};

if (currentUser.ssoId) {
try {
const { sp, idp } = await sails.helpers.saml.getConfig(currentUser.ssoId);

const ssoUrl = await new Promise((resolve, reject) => {
sp.create_logout_request_url(idp, { session_index: session.sso_id }, (err, url) => {
if (err) {
reject();
} else {
resolve(url);
}
});
});

Object.assign(result, { ssoUrl });
} catch (e) {
// not saml or bad config
}
}

return result;
},
};
8 changes: 8 additions & 0 deletions server/api/controllers/authentication/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = {
async fn() {
return {
local: sails.config.custom.localAuth,
saml: sails.config.custom.samlConfig.map((config) => _.pick(config, ['id', 'name'])),
};
},
};
87 changes: 87 additions & 0 deletions server/api/controllers/authentication/saml/acs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
const { getRemoteAddress } = require('../../../../utils/remoteAddress');

const Errors = {
INVALID_ID: {
invalidId: 'Invalid authentication provider ID',
},
BAD_SAML_RESPONSE: {
badSAMLResponse: 'Bad SAML response',
},
};

module.exports = {
inputs: {
id: {
type: 'string',
required: true,
},
SAMLResponse: {
type: 'string',
required: true,
},
},

exits: {
invalidId: {
responseType: 'notFound',
},
badSAMLResponse: {
responseType: 'forbidden',
},
},

async fn(inputs) {
const { sp, idp, bindings } = await sails.helpers.saml.getConfig(inputs.id);

const options = { request_body: { SAMLResponse: inputs.SAMLResponse } };

const response = await new Promise((resolve, reject) => {
sp.post_assert(idp, options, (err, res) => {
if (err !== null) {
reject(Errors.BAD_SAML_RESPONSE);
return;
}
resolve(res);
});
});

let user = await sails.helpers.users.getOne({
ssoId: inputs.id,
ssoName: response.user.name_id,
});

const values = await sails.helpers.saml.parseAttributes(bindings, response.user.attributes);

if (user === undefined) {
Object.assign(values, { ssoId: inputs.id, ssoName: response.user.name_id });
user = await User.create(values);
} else if (!_.isEqual(_.pick(user, Object.keys(values)), values)) {
user = await User.updateOne(_.pick(user, ['id'])).set(values);
}

const accessToken = sails.helpers.utils.createToken(user.id);

await Session.create({
accessToken,
remoteAddress: getRemoteAddress(this.req),
userId: user.id,
userAgent: this.req.headers['user-agent'],
ssoId: response.user.session_index,
});

this.res.cookie('accessToken', accessToken, {
secure: true,
sameSite: 'strict',
maxAge: sails.config.custom.tokenExpiresIn * 86400000,
});
this.res.cookie('accessTokenVersion', 1, {
secure: true,
sameSite: 'strict',
maxAge: sails.config.custom.tokenExpiresIn * 86400000,
});

return this.res.redirect(
sails.config.custom.baseUrl || (env.NODE_ENV === 'prod' ? '/' : 'http://localhost:3000/'),
);
},
};
41 changes: 41 additions & 0 deletions server/api/controllers/authentication/saml/login-request.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const Errors = {
INVALID_ID: {
invalidId: 'Invalid authentication provider ID',
},
BAD_CONFIGURATION: {
badConfiguration: 'Bad SAML configuration',
},
};

module.exports = {
inputs: {
id: {
type: 'string',
required: true,
},
},

exits: {
invalidId: {
responseType: 'notFound',
},
badConfiguration: {
responseType: 'serverError',
},
},

async fn(inputs) {
const { sp, idp } = await sails.helpers.saml.getConfig(inputs.id);

const url = await new Promise((resolve, reject) => {
sp.create_login_request_url(idp, {}, (err, loginUrl) => {
if (err != null) {
reject(Errors.BAD_CONFIGURATION);
}
resolve(loginUrl);
});
});

return { item: url };
},
};
22 changes: 22 additions & 0 deletions server/api/controllers/authentication/saml/metadata.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
module.exports = {
inputs: {
id: {
type: 'string',
required: true,
},
},

exits: {
invalidId: {
responseType: 'notFound',
},
},

async fn(inputs) {
const { sp } = await sails.helpers.saml.getConfig(inputs.id);

this.res.setHeader('Content-Type', 'text/xml');

return sp.create_metadata();
},
};
29 changes: 29 additions & 0 deletions server/api/helpers/saml/get-config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const saml2 = require('saml2-js');

module.exports = {
inputs: {
id: {
type: 'string',
required: true,
},
},

exits: {
invalidId: {},
},

async fn(inputs) {
for (let i = 0, l = sails.config.custom.samlConfig.length; i < l; i += 1) {
const config = sails.config.custom.samlConfig[i];
if (config.id === inputs.id) {
return {
sp: new saml2.ServiceProvider(config.sp),
idp: new saml2.IdentityProvider(config.idp),
bindings: config.bindings,
};
}
}

throw 'invalidId';
},
};
36 changes: 36 additions & 0 deletions server/api/helpers/saml/parse-attributes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
module.exports = {
inputs: {
bindings: {
type: 'ref',
required: true,
},
attributes: {
type: 'ref',
required: true,
},
},

async fn({ bindings, attributes }) {
const values = { password: 'SSO' };

if ('email' in bindings) {
[values.email] = attributes[bindings.email];
}

if ('full_name' in bindings) {
[values.name] = attributes[bindings.full_name];
} else if ('first_name' in bindings && 'last_name' in bindings) {
values.name = `${attributes[bindings.first_name][0]} ${attributes[bindings.last_name][0]}`;
}

if ('username' in bindings) {
[values.username] = attributes[bindings.username];
}

if ('admin' in bindings) {
values.isAdmin = _.includes(attributes[bindings.admin[0]], bindings.admin[1]);
}

return values;
},
};
14 changes: 11 additions & 3 deletions server/api/helpers/users/get-one-by-email-or-username.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,21 @@ module.exports = {
type: 'string',
required: true,
},
includeSSOUsers: {
type: 'boolean',
defaultsTo: true,
},
},

async fn(inputs) {
const fieldName = inputs.emailOrUsername.includes('@') ? 'email' : 'username';

return sails.helpers.users.getOne({
[fieldName]: inputs.emailOrUsername.toLowerCase(),
});
const conditions = { [fieldName]: inputs.emailOrUsername.toLowerCase() };

if (includeSSOUsers) {
conditions[ssoId] = null;
}

return sails.helpers.users.getOne(conditions);
},
};
4 changes: 4 additions & 0 deletions server/api/models/Session.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ module.exports = {
type: 'ref',
columnName: 'deleted_at',
},
ssoId: {
type: 'string',
columnName: 'sso_id',
},

// ╔═╗╔╦╗╔╗ ╔═╗╔╦╗╔═╗
// ║╣ ║║║╠╩╗║╣ ║║╚═╗
Expand Down
12 changes: 11 additions & 1 deletion server/api/models/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,16 @@ module.exports = {
type: 'ref',
columnName: 'password_changed_at',
},
ssoId: {
type: 'string',
columnName: 'sso_id',
allowNull: true,
},
ssoName: {
type: 'string',
columnName: 'sso_name',
allowNull: true,
},

// ╔═╗╔╦╗╔╗ ╔═╗╔╦╗╔═╗
// ║╣ ║║║╠╩╗║╣ ║║╚═╗
Expand Down Expand Up @@ -106,7 +116,7 @@ module.exports = {

customToJSON() {
return {
..._.omit(this, ['password', 'avatarDirname', 'passwordChangedAt']),
..._.omit(this, ['password', 'avatarDirname', 'passwordChangedAt', 'ssoName']),
avatarUrl:
this.avatarDirname &&
`${sails.config.custom.userAvatarsUrl}/${this.avatarDirname}/square-100.jpg`,
Expand Down
Loading