Skip to content

feat(auth): implement OIDC auth for frontend #7

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

Closed
wants to merge 17 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
7 changes: 4 additions & 3 deletions cypress.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
const { defineConfig } = require('cypress')
const { defineConfig } = require('cypress');

module.exports = defineConfig({
e2e: {
baseUrl: process.env.CYPRESS_BASE_URL ||'http://localhost:3000',
baseUrl: process.env.CYPRESS_BASE_URL || 'http://localhost:3000',
chromeWebSecurity: false, // Required for OIDC testing
},
})
});
50 changes: 32 additions & 18 deletions cypress/e2e/login.cy.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,33 @@
describe("Display finos UI",()=>{

beforeEach(() =>{
cy.visit('/login')
})
it('shoud find git proxy logo',() =>{
cy.get('[data-test="git-proxy-logo"]').should('exist')
})
it('shoud find username',() =>{
cy.get('[data-test="username"]').should('exist')
})
describe('Login page', () => {
beforeEach(() => {
cy.visit('/login');
});

it('shoud find passsword',() =>{
cy.get('[data-test="password"]').should('exist')
})
it('shoud find login button',() =>{
cy.get('[data-test="login"]').should('exist')
})
})
it('should have git proxy logo', () => {
cy.get('[data-test="git-proxy-logo"]').should('exist');
});

it('should have username input', () => {
cy.get('[data-test="username"]').should('exist');
});

it('should have passsword input', () => {
cy.get('[data-test="password"]').should('exist');
});

it('should have login button', () => {
cy.get('[data-test="login"]').should('exist');
});

describe('OIDC login button', () => {
it('should exist', () => {
cy.get('[data-test="oidc-login"]').should('exist');
});

// Validates that OIDC is configured correctly
it('should redirect to /oidc', () => {
cy.get('[data-test="oidc-login"]').click();
cy.url().should('include', '/oidc');
});
});
});
36 changes: 34 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@finos/git-proxy",
"version": "1.8.0",
"version": "1.8.1",
"description": "Deploy custom push protections and policies on top of Git.",
"scripts": {
"cli": "node ./packages/git-proxy-cli/index.js",
Expand Down Expand Up @@ -59,6 +59,7 @@
"moment": "^2.29.4",
"mongodb": "^5.0.0",
"nodemailer": "^6.6.1",
"openid-client": "^6.2.0",
"parse-diff": "^0.11.1",
"passport": "^0.7.0",
"passport-activedirectory": "^1.0.4",
Expand Down
1 change: 1 addition & 0 deletions src/db/file/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ module.exports.canUserCancelPush = pushes.canUserCancelPush;
module.exports.canUserApproveRejectPush = pushes.canUserApproveRejectPush;

module.exports.findUser = users.findUser;
module.exports.findUserByOIDC = users.findUserByOIDC;
module.exports.getUsers = users.getUsers;
module.exports.createUser = users.createUser;
module.exports.deleteUser = users.deleteUser;
Expand Down
16 changes: 16 additions & 0 deletions src/db/file/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,22 @@ exports.findUser = function (username) {
});
};

exports.findUserByOIDC = function (oidcId) {
return new Promise((resolve, reject) => {
db.findOne({ oidcId: oidcId }, (err, doc) => {
if (err) {
reject(err);
} else {
if (!doc) {
resolve(null);
} else {
resolve(doc);
}
}
});
});
};

exports.createUser = function (data) {
return new Promise((resolve, reject) => {
db.insert(data, (err) => {
Expand Down
16 changes: 13 additions & 3 deletions src/db/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,30 @@ if (config.getDatabase().type === 'mongo') {
sink = require('../db/file');
}

module.exports.createUser = async (username, password, email, gitAccount, admin = false) => {
module.exports.createUser = async (
username,
password,
email,
gitAccount,
admin = false,
oidcId = null,
) => {
console.log(
`creating user
user=${username},
gitAccount=${gitAccount}
email=${email},
admin=${admin}`,
admin=${admin}
oidcId=${oidcId}`,
);

const data = {
username: username,
password: await bcrypt.hash(password, 10),
password: oidcId ? null : await bcrypt.hash(password, 10),
gitAccount: gitAccount,
email: email,
admin: admin,
oidcId: oidcId,
};

if (username === undefined || username === null || username === '') {
Expand Down Expand Up @@ -56,6 +65,7 @@ module.exports.getPushes = sink.getPushes;
module.exports.writeAudit = sink.writeAudit;
module.exports.getPush = sink.getPush;
module.exports.findUser = sink.findUser;
module.exports.findUserByOIDC = sink.findUserByOIDC;
module.exports.getUsers = sink.getUsers;
module.exports.deleteUser = sink.deleteUser;
module.exports.updateUser = sink.updateUser;
Expand Down
8 changes: 7 additions & 1 deletion src/service/passport/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const local = require('./local');
const activeDirectory = require('./activeDirectory');
const oidc = require('./oidc');
const config = require('../../config');
const authenticationConfig = config.getAuthentication();
let _passport;
Expand All @@ -14,10 +15,15 @@ const configure = async () => {
case 'local':
_passport = await local.configure();
break;
case 'openidconnect':
_passport = await oidc.configure();
break;
default:
throw Error(`uknown authentication type ${type}`);
}
_passport.type = authenticationConfig.type;
if (!_passport.type) {
_passport.type = type;
}
return _passport;
};

Expand Down
2 changes: 1 addition & 1 deletion src/service/passport/local.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ const configure = async () => {
const admin = await db.findUser('admin');

if (!admin) {
await db.createUser('admin', 'admin', '[email protected]', 'none', true, true, true, true);
await db.createUser('admin', 'admin', '[email protected]', 'none', true);
}

passport.type = 'local';
Expand Down
114 changes: 114 additions & 0 deletions src/service/passport/oidc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
const passport = require('passport');
const db = require('../../db');

const configure = async () => {
// Temp fix for ERR_REQUIRE_ESM, will be changed when we refactor to ESM
const { discovery, fetchUserInfo } = await import('openid-client');
const { Strategy } = await import('openid-client/passport');
const config = require('../../config').getAuthentication();
const { oidcConfig } = config;
const { issuer, clientID, clientSecret, callbackURL, scope } = oidcConfig;

if (!oidcConfig || !oidcConfig.issuer) {
throw new Error('Missing OIDC issuer in configuration')
}

const server = new URL(issuer);

try {
const config = await discovery(server, clientID, clientSecret);

const strategy = new Strategy({ callbackURL, config, scope }, async (tokenSet, done) => {
// Validate token sub for added security
const idTokenClaims = tokenSet.claims();
const expectedSub = idTokenClaims.sub;
const userInfo = await fetchUserInfo(config, tokenSet.access_token, expectedSub);
handleUserAuthentication(userInfo, done);
});

// currentUrl must be overridden to match the callback URL
strategy.currentUrl = function (request) {
const callbackUrl = new URL(callbackURL);
const currentUrl = Strategy.prototype.currentUrl.call(this, request);
currentUrl.host = callbackUrl.host;
currentUrl.protocol = callbackUrl.protocol;
return currentUrl;
};

passport.use(strategy);

passport.serializeUser((user, done) => {
done(null, user.oidcId || user.username);
})

passport.deserializeUser(async (id, done) => {
try {
const user = await db.findUserByOIDC(id);
done(null, user);
} catch (err) {
done(err);
}
})
passport.type = server.host;

return passport;
} catch (error) {
console.error('OIDC configuration failed:', error);
throw error;
}
}


module.exports.configure = configure;

/**
* Handles user authentication with OIDC.
* @param {Object} userInfo the OIDC user info object
* @param {Function} done the callback function
* @return {Promise} a promise with the authenticated user or an error
*/
const handleUserAuthentication = async (userInfo, done) => {
try {
const user = await db.findUserByOIDC(userInfo.sub);

if (!user) {
const email = safelyExtractEmail(userInfo);
if (!email) return done(new Error('No email found in OIDC profile'));

const newUser = {
username: getUsername(email),
email,
oidcId: userInfo.sub,
};

await db.createUser(newUser.username, null, newUser.email, 'Edit me', false, newUser.oidcId);
return done(null, newUser);
}

return done(null, user);
} catch (err) {
return done(err);
}
};

/**
* Extracts email from OIDC profile.
* This function is necessary because OIDC providers have different ways of storing emails.
* @param {object} profile the profile object from OIDC provider
* @return {string | null} the email address
*/
const safelyExtractEmail = (profile) => {
return profile.email || (profile.emails && profile.emails.length > 0 ? profile.emails[0].value : null);
};

/**
* Generates a username from email address.
* This helps differentiate users within the specific OIDC provider.
* Note: This is incompatible with multiple providers. Ideally, users are identified by
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also if there is a local user with the same username

* OIDC ID (requires refactoring the database).
* @param {string} email the email address
* @return {string} the username
*/
const getUsername = (email) => {
return email ? email.split('@')[0] : '';
};
Loading
Loading