Merge pull request #24353 from matteosilv/onelogin-provider

New OneLogin auth backend module
This commit is contained in:
Fredrik Adelöw
2024-06-10 16:10:44 +02:00
committed by GitHub
20 changed files with 502 additions and 178 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@backstage/plugin-auth-backend-module-onelogin-provider': minor
---
Separate out the OneLogin provider into its own module
+5
View File
@@ -0,0 +1,5 @@
---
'@backstage/plugin-auth-backend': patch
---
Updated to use the new `@backstage/plugin-auth-backend-module-onelogin-provider` implementation
@@ -268,6 +268,7 @@ Olausson
Oldsberg
onboarding
Onboarding
onelogin
OpenSearch
OpenShift
openssl
@@ -0,0 +1 @@
module.exports = require('@backstage/cli/config/eslint-factory')(__dirname);
@@ -0,0 +1,8 @@
# Auth Module: OneLogin Provider
This module provides an OneLogin auth provider implementation for `@backstage/plugin-auth-backend`.
## Links
- [Repository](https://github.com/backstage/backstage/tree/master/plugins/auth-backend-module-onelogin-provider)
- [Backstage Project Homepage](https://backstage.io)
@@ -0,0 +1,30 @@
## API Report File for "@backstage/plugin-auth-backend-module-onelogin-provider"
> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).
```ts
import { BackendFeature } from '@backstage/backend-plugin-api';
import { OAuthAuthenticator } from '@backstage/plugin-auth-node';
import { OAuthAuthenticatorResult } from '@backstage/plugin-auth-node';
import { PassportOAuthAuthenticatorHelper } from '@backstage/plugin-auth-node';
import { PassportProfile } from '@backstage/plugin-auth-node';
import { SignInResolverFactory } from '@backstage/plugin-auth-node';
// @public (undocumented)
const authModuleOneLoginProvider: () => BackendFeature;
export default authModuleOneLoginProvider;
// @public (undocumented)
export const oneLoginAuthenticator: OAuthAuthenticator<
PassportOAuthAuthenticatorHelper,
PassportProfile
>;
// @public
export namespace oneLoginSignInResolvers {
const usernameMatchingUserEntityName: SignInResolverFactory<
OAuthAuthenticatorResult<PassportProfile>,
unknown
>;
}
```
@@ -0,0 +1,10 @@
apiVersion: backstage.io/v1alpha1
kind: Component
metadata:
name: backstage-plugin-auth-backend-module-onelogin-provider
title: '@backstage/plugin-auth-backend-module-onelogin-provider'
description: The onelogin-provider backend module for the auth plugin.
spec:
lifecycle: experimental
type: backstage-backend-plugin-module
owner: maintainers
@@ -0,0 +1,34 @@
/*
* Copyright 2020 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export interface Config {
auth?: {
providers?: {
/** @visibility frontend */
onelogin?: {
[authEnv: string]: {
clientId: string;
/**
* @visibility secret
*/
clientSecret: string;
issuer: string;
callbackUrl?: string;
};
};
};
};
}
@@ -0,0 +1,24 @@
/*
* Copyright 2023 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { createBackend } from '@backstage/backend-defaults';
const backend = createBackend();
backend.add(import('@backstage/plugin-auth-backend'));
backend.add(import('../src'));
backend.start();
@@ -0,0 +1,19 @@
# Knip report
## Unused dependencies (4)
| Name | Location | Severity |
| :---------------------------- | :----------- | :------- |
| @backstage/backend-plugin-api | package.json | error |
| @backstage/plugin-auth-node | package.json | error |
| passport | package.json | error |
| express | package.json | error |
## Unused devDependencies (3)
| Name | Location | Severity |
| :----------------------------- | :----------- | :------- |
| @backstage/plugin-auth-backend | package.json | error |
| @backstage/backend-test-utils | package.json | error |
| @backstage/backend-defaults | package.json | error |
@@ -0,0 +1,49 @@
{
"name": "@backstage/plugin-auth-backend-module-onelogin-provider",
"version": "0.0.0",
"description": "The onelogin-provider backend module for the auth plugin.",
"backstage": {
"role": "backend-plugin-module"
},
"publishConfig": {
"access": "public",
"main": "dist/index.cjs.js",
"types": "dist/index.d.ts"
},
"repository": {
"type": "git",
"url": "https://github.com/backstage/backstage",
"directory": "plugins/auth-backend-module-onelogin-provider"
},
"license": "Apache-2.0",
"main": "src/index.ts",
"types": "src/index.ts",
"files": [
"dist",
"config.d.ts"
],
"scripts": {
"build": "backstage-cli package build",
"clean": "backstage-cli package clean",
"lint": "backstage-cli package lint",
"prepack": "backstage-cli package prepack",
"postpack": "backstage-cli package postpack",
"start": "backstage-cli package start",
"test": "backstage-cli package test"
},
"dependencies": {
"@backstage/backend-plugin-api": "workspace:^",
"@backstage/plugin-auth-node": "workspace:^",
"express": "^4.18.2",
"passport": "^0.7.0",
"passport-onelogin-oauth": "^0.0.1"
},
"devDependencies": {
"@backstage/backend-defaults": "workspace:^",
"@backstage/backend-test-utils": "workspace:^",
"@backstage/cli": "workspace:^",
"@backstage/plugin-auth-backend": "workspace:^",
"supertest": "^6.3.3"
},
"configSchema": "config.d.ts"
}
@@ -0,0 +1,76 @@
/*
* Copyright 2023 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Strategy as OneLoginStrategy } from 'passport-onelogin-oauth';
import {
createOAuthAuthenticator,
PassportOAuthAuthenticatorHelper,
PassportOAuthDoneCallback,
PassportProfile,
} from '@backstage/plugin-auth-node';
/** @public */
export const oneLoginAuthenticator = createOAuthAuthenticator({
defaultProfileTransform:
PassportOAuthAuthenticatorHelper.defaultProfileTransform,
initialize({ callbackUrl, config }) {
const clientId = config.getString('clientId');
const clientSecret = config.getString('clientSecret');
const issuer = config.getString('issuer');
return PassportOAuthAuthenticatorHelper.from(
new OneLoginStrategy(
{
clientID: clientId,
clientSecret: clientSecret,
callbackURL: callbackUrl,
issuer,
passReqToCallback: false,
},
(
accessToken: string,
refreshToken: string,
params: any,
fullProfile: PassportProfile,
done: PassportOAuthDoneCallback,
) => {
done(
undefined,
{ fullProfile, params, accessToken },
{ refreshToken },
);
},
),
);
},
async start(input, helper) {
input.scope = 'openid';
return helper.start(input, {
accessType: 'offline',
prompt: 'consent',
});
},
async authenticate(input, helper) {
return helper.authenticate(input);
},
async refresh(input, helper) {
input.scope = 'openid';
return helper.refresh(input);
},
});
@@ -0,0 +1,25 @@
/*
* Copyright 2023 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* The onelogin-provider backend module for the auth plugin.
*
* @packageDocumentation
*/
export { oneLoginAuthenticator } from './authenticator';
export { authModuleOneLoginProvider as default } from './module';
export { oneLoginSignInResolvers } from './resolvers';
@@ -0,0 +1,79 @@
/*
* Copyright 2023 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { mockServices, startTestBackend } from '@backstage/backend-test-utils';
import { authModuleOneLoginProvider } from './module';
import request from 'supertest';
import { decodeOAuthState } from '@backstage/plugin-auth-node';
describe('authModuleOneLoginProvider', () => {
it('should start', async () => {
const { server } = await startTestBackend({
features: [
import('@backstage/plugin-auth-backend'),
authModuleOneLoginProvider,
mockServices.rootConfig.factory({
data: {
app: {
baseUrl: 'http://localhost:3000',
},
auth: {
providers: {
onelogin: {
development: {
clientId: 'my-client-id',
clientSecret: 'my-client-secret',
issuer: 'https://my-company.onelogin.com/oidc/2',
},
},
},
},
},
}),
],
});
const agent = request.agent(server);
const res = await agent.get('/api/auth/onelogin/start?env=development');
expect(res.status).toEqual(302);
const nonceCookie = agent.jar.getCookie('onelogin-nonce', {
domain: 'localhost',
path: '/api/auth/onelogin/handler',
script: false,
secure: false,
});
expect(nonceCookie).toBeDefined();
const startUrl = new URL(res.get('location'));
expect(startUrl.origin).toBe('https://my-company.onelogin.com');
expect(startUrl.pathname).toBe('/oidc/2/auth');
expect(Object.fromEntries(startUrl.searchParams)).toEqual({
response_type: 'code',
scope: 'openid',
client_id: 'my-client-id',
redirect_uri: `http://localhost:${server.port()}/api/auth/onelogin/handler/frame`,
state: expect.any(String),
});
expect(decodeOAuthState(startUrl.searchParams.get('state')!)).toEqual({
env: 'development',
nonce: decodeURIComponent(nonceCookie.value),
});
});
});
@@ -0,0 +1,48 @@
/*
* Copyright 2023 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { createBackendModule } from '@backstage/backend-plugin-api';
import {
authProvidersExtensionPoint,
commonSignInResolvers,
createOAuthProviderFactory,
} from '@backstage/plugin-auth-node';
import { oneLoginAuthenticator } from './authenticator';
import { oneLoginSignInResolvers } from './resolvers';
/** @public */
export const authModuleOneLoginProvider = createBackendModule({
pluginId: 'auth',
moduleId: 'onelogin-provider',
register(reg) {
reg.registerInit({
deps: {
providers: authProvidersExtensionPoint,
},
async init({ providers }) {
providers.registerProvider({
providerId: 'onelogin',
factory: createOAuthProviderFactory({
authenticator: oneLoginAuthenticator,
signInResolverFactories: {
...oneLoginSignInResolvers,
...commonSignInResolvers,
},
}),
});
},
});
},
});
@@ -0,0 +1,50 @@
/*
* Copyright 2023 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
createSignInResolverFactory,
OAuthAuthenticatorResult,
PassportProfile,
SignInInfo,
} from '@backstage/plugin-auth-node';
/**
* Available sign-in resolvers for the OneLogin auth provider.
*
* @public
*/
export namespace oneLoginSignInResolvers {
/**
* Looks up the user by matching their OneLogin username to the entity name.
*/
export const usernameMatchingUserEntityName = createSignInResolverFactory({
create() {
return async (
info: SignInInfo<OAuthAuthenticatorResult<PassportProfile>>,
ctx,
) => {
const { result } = info;
const id = result.fullProfile.username;
if (!id) {
throw new Error(`OneLogin user profile does not contain a username`);
}
return ctx.signInWithCatalogUser({ entityRef: { name: id } });
};
},
});
}
@@ -13,8 +13,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
declare module 'passport-onelogin-oauth' {
import { Request } from 'express';
import { StrategyCreated } from 'passport';
export class Strategy {
constructor(options: any, verify: any);
authenticate(this: StrategyCreated<this>, req: Request, options?: any): any;
}
}
+1
View File
@@ -57,6 +57,7 @@
"@backstage/plugin-auth-backend-module-oauth2-proxy-provider": "workspace:^",
"@backstage/plugin-auth-backend-module-oidc-provider": "workspace:^",
"@backstage/plugin-auth-backend-module-okta-provider": "workspace:^",
"@backstage/plugin-auth-backend-module-onelogin-provider": "workspace:^",
"@backstage/plugin-auth-node": "workspace:^",
"@backstage/plugin-catalog-node": "workspace:^",
"@backstage/types": "workspace:^",
@@ -14,156 +14,18 @@
* limitations under the License.
*/
import { Strategy as OneLoginStrategy } from 'passport-onelogin-oauth';
import express from 'express';
import { oneLoginAuthenticator } from '@backstage/plugin-auth-backend-module-onelogin-provider';
import {
OAuthAdapter,
OAuthProviderOptions,
OAuthHandlers,
OAuthResponse,
OAuthEnvironmentHandler,
OAuthStartRequest,
encodeState,
OAuthRefreshRequest,
OAuthResult,
} from '../../lib/oauth';
import passport from 'passport';
import {
executeFrameHandlerStrategy,
executeRedirectStrategy,
executeRefreshTokenStrategy,
makeProfileInfo,
executeFetchUserProfileStrategy,
PassportDoneCallback,
} from '../../lib/passport';
import { OAuthStartResponse, AuthHandler } from '../types';
import { createAuthProviderIntegration } from '../createAuthProviderIntegration';
import {
AuthResolverContext,
SignInResolver,
createOAuthProviderFactory,
} from '@backstage/plugin-auth-node';
type PrivateInfo = {
refreshToken: string;
};
export type Options = OAuthProviderOptions & {
issuer: string;
signInResolver?: SignInResolver<OAuthResult>;
authHandler: AuthHandler<OAuthResult>;
resolverContext: AuthResolverContext;
};
export class OneLoginProvider implements OAuthHandlers {
private readonly _strategy: any;
private readonly signInResolver?: SignInResolver<OAuthResult>;
private readonly authHandler: AuthHandler<OAuthResult>;
private readonly resolverContext: AuthResolverContext;
constructor(options: Options) {
this.signInResolver = options.signInResolver;
this.authHandler = options.authHandler;
this.resolverContext = options.resolverContext;
this._strategy = new OneLoginStrategy(
{
issuer: options.issuer,
clientID: options.clientId,
clientSecret: options.clientSecret,
callbackURL: options.callbackUrl,
passReqToCallback: false,
},
(
accessToken: any,
refreshToken: any,
params: any,
fullProfile: passport.Profile,
done: PassportDoneCallback<OAuthResult, PrivateInfo>,
) => {
done(
undefined,
{
accessToken,
refreshToken,
params,
fullProfile,
},
{
refreshToken,
},
);
},
);
}
async start(req: OAuthStartRequest): Promise<OAuthStartResponse> {
return await executeRedirectStrategy(req, this._strategy, {
accessType: 'offline',
prompt: 'consent',
scope: 'openid',
state: encodeState(req.state),
});
}
async handler(req: express.Request) {
const { result, privateInfo } = await executeFrameHandlerStrategy<
OAuthResult,
PrivateInfo
>(req, this._strategy);
return {
response: await this.handleResult(result),
refreshToken: privateInfo.refreshToken,
};
}
async refresh(req: OAuthRefreshRequest) {
const { accessToken, refreshToken, params } =
await executeRefreshTokenStrategy(
this._strategy,
req.refreshToken,
'openid',
);
const fullProfile = await executeFetchUserProfileStrategy(
this._strategy,
accessToken,
);
return {
response: await this.handleResult({
fullProfile,
params,
accessToken,
}),
refreshToken,
};
}
private async handleResult(result: OAuthResult) {
const { profile } = await this.authHandler(result, this.resolverContext);
const response: OAuthResponse = {
providerInfo: {
idToken: result.params.id_token,
accessToken: result.accessToken,
scope: result.params.scope,
expiresInSeconds: result.params.expires_in,
},
profile,
};
if (this.signInResolver) {
response.backstageIdentity = await this.signInResolver(
{
result,
profile,
},
this.resolverContext,
);
}
return response;
}
}
import {
adaptLegacyOAuthHandler,
adaptLegacyOAuthSignInResolver,
} from '../../lib/legacy';
import { OAuthResult } from '../../lib/oauth';
import { createAuthProviderIntegration } from '../createAuthProviderIntegration';
import { AuthHandler } from '../types';
/**
* Auth provider integration for OneLogin auth
@@ -188,36 +50,10 @@ export const onelogin = createAuthProviderIntegration({
resolver: SignInResolver<OAuthResult>;
};
}) {
return ({ providerId, globalConfig, config, resolverContext }) =>
OAuthEnvironmentHandler.mapConfig(config, envConfig => {
const clientId = envConfig.getString('clientId');
const clientSecret = envConfig.getString('clientSecret');
const issuer = envConfig.getString('issuer');
const customCallbackUrl = envConfig.getOptionalString('callbackUrl');
const callbackUrl =
customCallbackUrl ||
`${globalConfig.baseUrl}/${providerId}/handler/frame`;
const authHandler: AuthHandler<OAuthResult> = options?.authHandler
? options.authHandler
: async ({ fullProfile, params }) => ({
profile: makeProfileInfo(fullProfile, params.id_token),
});
const provider = new OneLoginProvider({
clientId,
clientSecret,
callbackUrl,
issuer,
authHandler,
signInResolver: options?.signIn?.resolver,
resolverContext,
});
return OAuthAdapter.fromConfig(globalConfig, provider, {
providerId,
callbackUrl,
});
});
return createOAuthProviderFactory({
authenticator: oneLoginAuthenticator,
profileTransform: adaptLegacyOAuthHandler(options?.authHandler),
signInResolver: adaptLegacyOAuthSignInResolver(options?.signIn?.resolver),
});
},
});
+18
View File
@@ -4987,6 +4987,23 @@ __metadata:
languageName: unknown
linkType: soft
"@backstage/plugin-auth-backend-module-onelogin-provider@workspace:^, @backstage/plugin-auth-backend-module-onelogin-provider@workspace:plugins/auth-backend-module-onelogin-provider":
version: 0.0.0-use.local
resolution: "@backstage/plugin-auth-backend-module-onelogin-provider@workspace:plugins/auth-backend-module-onelogin-provider"
dependencies:
"@backstage/backend-defaults": "workspace:^"
"@backstage/backend-plugin-api": "workspace:^"
"@backstage/backend-test-utils": "workspace:^"
"@backstage/cli": "workspace:^"
"@backstage/plugin-auth-backend": "workspace:^"
"@backstage/plugin-auth-node": "workspace:^"
express: ^4.18.2
passport: ^0.7.0
passport-onelogin-oauth: ^0.0.1
supertest: ^6.3.3
languageName: unknown
linkType: soft
"@backstage/plugin-auth-backend-module-pinniped-provider@workspace:plugins/auth-backend-module-pinniped-provider":
version: 0.0.0-use.local
resolution: "@backstage/plugin-auth-backend-module-pinniped-provider@workspace:plugins/auth-backend-module-pinniped-provider"
@@ -5058,6 +5075,7 @@ __metadata:
"@backstage/plugin-auth-backend-module-oauth2-proxy-provider": "workspace:^"
"@backstage/plugin-auth-backend-module-oidc-provider": "workspace:^"
"@backstage/plugin-auth-backend-module-okta-provider": "workspace:^"
"@backstage/plugin-auth-backend-module-onelogin-provider": "workspace:^"
"@backstage/plugin-auth-node": "workspace:^"
"@backstage/plugin-catalog-node": "workspace:^"
"@backstage/types": "workspace:^"