From 037447efd3272693bf3a834c6342eb2de3cf2565 Mon Sep 17 00:00:00 2001 From: Daniel Deloff <44780793+rv-ddeloff@users.noreply.github.com> Date: Mon, 11 Oct 2021 15:04:59 -0400 Subject: [PATCH] adds atlassian auth provider Signed-off-by: Daniel Deloff <44780793+rv-ddeloff@users.noreply.github.com> --- packages/app/src/identityProviders.ts | 7 + .../auth/atlassian/AtlassianAuth.ts | 44 +++ .../implementations/auth/atlassian/index.ts | 17 ++ .../src/apis/implementations/auth/index.ts | 1 + packages/core-app-api/src/app/defaultApis.ts | 17 ++ .../src/apis/definitions/auth.ts | 12 + .../src/providers/atlassian/index.ts | 18 ++ .../src/providers/atlassian/provider.test.ts | 96 +++++++ .../src/providers/atlassian/provider.ts | 271 ++++++++++++++++++ .../src/providers/atlassian/strategy.ts | 111 +++++++ .../auth-backend/src/providers/factories.ts | 2 + plugins/auth-backend/src/providers/index.ts | 1 + .../AuthProviders/DefaultProviderSettings.tsx | 9 + 13 files changed, 606 insertions(+) create mode 100644 packages/core-app-api/src/apis/implementations/auth/atlassian/AtlassianAuth.ts create mode 100644 packages/core-app-api/src/apis/implementations/auth/atlassian/index.ts create mode 100644 plugins/auth-backend/src/providers/atlassian/index.ts create mode 100644 plugins/auth-backend/src/providers/atlassian/provider.test.ts create mode 100644 plugins/auth-backend/src/providers/atlassian/provider.ts create mode 100644 plugins/auth-backend/src/providers/atlassian/strategy.ts diff --git a/packages/app/src/identityProviders.ts b/packages/app/src/identityProviders.ts index 49204d2b5e..70630a3d0a 100644 --- a/packages/app/src/identityProviders.ts +++ b/packages/app/src/identityProviders.ts @@ -25,6 +25,7 @@ import { oauth2ApiRef, oidcAuthApiRef, bitbucketAuthApiRef, + atlassianAuthApiRef, } from '@backstage/core-plugin-api'; export const providers = [ @@ -88,4 +89,10 @@ export const providers = [ message: 'Sign In using Bitbucket', apiRef: bitbucketAuthApiRef, }, + { + id: 'atlassian-auth-provider', + title: 'Atlassian', + message: 'Sign In using Atlassian', + apiRef: atlassianAuthApiRef, + }, ]; diff --git a/packages/core-app-api/src/apis/implementations/auth/atlassian/AtlassianAuth.ts b/packages/core-app-api/src/apis/implementations/auth/atlassian/AtlassianAuth.ts new file mode 100644 index 0000000000..423c45bc6c --- /dev/null +++ b/packages/core-app-api/src/apis/implementations/auth/atlassian/AtlassianAuth.ts @@ -0,0 +1,44 @@ +/* + * 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. + */ + +import AtlassianIcon from '@material-ui/icons/AcUnit'; +import { atlassianAuthApiRef } from '@backstage/core-plugin-api'; +import { OAuth2 } from '../oauth2'; +import { OAuthApiCreateOptions } from '../types'; + +const DEFAULT_PROVIDER = { + id: 'atlassian', + title: 'Atlassian', + icon: AtlassianIcon, +}; + +class AtlassianAuth { + static create({ + discoveryApi, + environment = 'development', + provider = DEFAULT_PROVIDER, + oauthRequestApi, + }: OAuthApiCreateOptions): typeof atlassianAuthApiRef.T { + return OAuth2.create({ + discoveryApi, + oauthRequestApi, + provider, + environment, + }); + } +} + +export default AtlassianAuth; diff --git a/packages/core-app-api/src/apis/implementations/auth/atlassian/index.ts b/packages/core-app-api/src/apis/implementations/auth/atlassian/index.ts new file mode 100644 index 0000000000..fb787be1ce --- /dev/null +++ b/packages/core-app-api/src/apis/implementations/auth/atlassian/index.ts @@ -0,0 +1,17 @@ +/* + * 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 { default as AtlassianAuth } from './AtlassianAuth'; diff --git a/packages/core-app-api/src/apis/implementations/auth/index.ts b/packages/core-app-api/src/apis/implementations/auth/index.ts index b622b90b8c..bbc9d23ccc 100644 --- a/packages/core-app-api/src/apis/implementations/auth/index.ts +++ b/packages/core-app-api/src/apis/implementations/auth/index.ts @@ -24,3 +24,4 @@ export * from './auth0'; export * from './microsoft'; export * from './onelogin'; export * from './bitbucket'; +export * from './atlassian'; diff --git a/packages/core-app-api/src/app/defaultApis.ts b/packages/core-app-api/src/app/defaultApis.ts index 5e850f4cce..fb02274cf0 100644 --- a/packages/core-app-api/src/app/defaultApis.ts +++ b/packages/core-app-api/src/app/defaultApis.ts @@ -33,6 +33,7 @@ import { SamlAuth, OneLoginAuth, UnhandledErrorForwarder, + AtlassianAuth, } from '../apis'; import { @@ -55,6 +56,7 @@ import { oneloginAuthApiRef, oidcAuthApiRef, bitbucketAuthApiRef, + atlassianAuthApiRef, } from '@backstage/core-plugin-api'; import OAuth2Icon from '@material-ui/icons/AcUnit'; @@ -244,4 +246,19 @@ export const defaultApis = [ environment: configApi.getOptionalString('auth.environment'), }), }), + createApiFactory({ + api: atlassianAuthApiRef, + deps: { + discoveryApi: discoveryApiRef, + oauthRequestApi: oauthRequestApiRef, + configApi: configApiRef, + }, + factory: ({ discoveryApi, oauthRequestApi, configApi }) => { + return AtlassianAuth.create({ + discoveryApi, + oauthRequestApi, + environment: configApi.getOptionalString('auth.environment'), + }); + }, + }), ]; diff --git a/packages/core-plugin-api/src/apis/definitions/auth.ts b/packages/core-plugin-api/src/apis/definitions/auth.ts index a78414048c..f67614b758 100644 --- a/packages/core-plugin-api/src/apis/definitions/auth.ts +++ b/packages/core-plugin-api/src/apis/definitions/auth.ts @@ -352,3 +352,15 @@ export const bitbucketAuthApiRef: ApiRef< > = createApiRef({ id: 'core.auth.bitbucket', }); + +/** + * Provides authentication towards Atlassian APIs. + * + * See https://developer.atlassian.com/cloud/jira/platform/scopes-for-connect-and-oauth-2-3LO-apps/ + * for a full list of supported scopes. + */ +export const atlassianAuthApiRef: ApiRef< + OAuthApi & ProfileInfoApi & BackstageIdentityApi & SessionApi +> = createApiRef({ + id: 'core.auth.atlassian', +}); diff --git a/plugins/auth-backend/src/providers/atlassian/index.ts b/plugins/auth-backend/src/providers/atlassian/index.ts new file mode 100644 index 0000000000..b99b63d7bc --- /dev/null +++ b/plugins/auth-backend/src/providers/atlassian/index.ts @@ -0,0 +1,18 @@ +/* + * 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 { createAtlassianProvider } from './provider'; +export type { AtlassianAuthProvider } from './provider'; diff --git a/plugins/auth-backend/src/providers/atlassian/provider.test.ts b/plugins/auth-backend/src/providers/atlassian/provider.test.ts new file mode 100644 index 0000000000..e561c2e037 --- /dev/null +++ b/plugins/auth-backend/src/providers/atlassian/provider.test.ts @@ -0,0 +1,96 @@ +/* + * 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. + */ + +import { AtlassianAuthProvider } from './provider'; +import * as helpers from '../../lib/passport/PassportStrategyHelper'; +import { getVoidLogger } from '@backstage/backend-common'; +import { TokenIssuer } from '../../identity'; +import { CatalogIdentityClient } from '../../lib/catalog'; +import { OAuthResult } from '../../lib/oauth'; + +const mockFrameHandler = jest.spyOn( + helpers, + 'executeFrameHandlerStrategy', +) as unknown as jest.MockedFunction<() => Promise<{ result: OAuthResult }>>; + +describe('createAtlassianProvider', () => { + it('should auth', async () => { + const tokenIssuer = { + issueToken: jest.fn(), + listPublicKeys: jest.fn(), + }; + const catalogIdentityClient = { + findUser: jest.fn(), + }; + + const provider = new AtlassianAuthProvider({ + logger: getVoidLogger(), + catalogIdentityClient: + catalogIdentityClient as unknown as CatalogIdentityClient, + tokenIssuer: tokenIssuer as unknown as TokenIssuer, + authHandler: async ({ fullProfile }) => ({ + profile: { + email: fullProfile.emails![0]!.value, + displayName: fullProfile.displayName, + picture: 'http://google.com/lols', + }, + }), + clientId: 'mock', + clientSecret: 'mock', + callbackUrl: 'mock', + scopes: [], + }); + + mockFrameHandler.mockResolvedValueOnce({ + result: { + fullProfile: { + photos: [ + { + value: + 'https://a1cf74336522e87f135f-2f21ace9a6cf0052456644b80fa06d4f.ssl.cf2.rackcdn.com/images/characters_opt/p-mystic-river-sean-penn.jpg', + }, + ], + emails: [{ value: 'conrad@example.com' }], + displayName: 'Conrad', + id: 'conrad', + provider: 'google', + }, + params: { + id_token: 'idToken', + scope: 'scope', + expires_in: 123, + }, + accessToken: 'accessToken', + refreshToken: 'wacka', + }, + }); + const { response } = await provider.handler({} as any); + expect(response).toEqual({ + providerInfo: { + accessToken: 'accessToken', + expiresInSeconds: 123, + idToken: 'idToken', + scope: 'scope', + refreshToken: 'wacka', + }, + profile: { + email: 'conrad@example.com', + displayName: 'Conrad', + picture: 'http://google.com/lols', + }, + }); + }); +}); diff --git a/plugins/auth-backend/src/providers/atlassian/provider.ts b/plugins/auth-backend/src/providers/atlassian/provider.ts new file mode 100644 index 0000000000..a4ab5600e1 --- /dev/null +++ b/plugins/auth-backend/src/providers/atlassian/provider.ts @@ -0,0 +1,271 @@ +/* + * 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. + */ + +import AtlassianStrategy from './strategy'; +import { + encodeState, + OAuthAdapter, + OAuthEnvironmentHandler, + OAuthHandlers, + OAuthProviderOptions, + OAuthRefreshRequest, + OAuthResponse, + OAuthResult, + OAuthStartRequest, +} from '../../lib/oauth'; +import passport from 'passport'; +import { + executeFetchUserProfileStrategy, + executeFrameHandlerStrategy, + executeRedirectStrategy, + executeRefreshTokenStrategy, + makeProfileInfo, + PassportDoneCallback, +} from '../../lib/passport'; +import { + AuthHandler, + AuthProviderFactory, + RedirectInfo, + SignInResolver, +} from '../types'; +import express from 'express'; +import { TokenIssuer } from '../../identity'; +import { CatalogIdentityClient } from '../../lib/catalog'; +import { Logger } from 'winston'; + +export type AtlassianAuthProviderOptions = OAuthProviderOptions & { + scopes: string[]; + signInResolver?: SignInResolver; + authHandler: AuthHandler; + tokenIssuer: TokenIssuer; + catalogIdentityClient: CatalogIdentityClient; + logger: Logger; +}; + +export const atlassianDefaultSignInResolver: SignInResolver = + async (info, ctx) => { + const { profile, result } = info; + + let id = result.fullProfile.id; + + if (profile.email) { + id = profile.email.split('@')[0]; + } + + const token = await ctx.tokenIssuer.issueToken({ + claims: { sub: id, ent: [`user:default/${id}`] }, + }); + + return { id, token }; + }; + +export const atlassianDefaultAuthHandler: AuthHandler = async ({ + fullProfile, + params, +}) => ({ + profile: makeProfileInfo(fullProfile, params.id_token), +}); + +export class AtlassianAuthProvider implements OAuthHandlers { + private readonly _strategy: AtlassianStrategy; + private readonly signInResolver?: SignInResolver; + private readonly authHandler: AuthHandler; + private readonly tokenIssuer: TokenIssuer; + private readonly catalogIdentityClient: CatalogIdentityClient; + private readonly logger: Logger; + + constructor(options: AtlassianAuthProviderOptions) { + this.catalogIdentityClient = options.catalogIdentityClient; + this.logger = options.logger; + this.tokenIssuer = options.tokenIssuer; + this.authHandler = options.authHandler; + this.signInResolver = options.signInResolver; + + this._strategy = new AtlassianStrategy( + { + clientID: options.clientId, + clientSecret: options.clientSecret, + callbackURL: options.callbackUrl, + scope: options.scopes, + }, + ( + accessToken: any, + refreshToken: any, + params: any, + fullProfile: passport.Profile, + done: PassportDoneCallback, + ) => { + done(undefined, { + fullProfile, + accessToken, + refreshToken, + params, + }); + }, + ); + } + + async start(req: OAuthStartRequest): Promise { + return await executeRedirectStrategy(req, this._strategy, { + state: encodeState(req.state), + }); + } + + async handler( + req: express.Request, + ): Promise<{ response: OAuthResponse; refreshToken: string }> { + const { result } = await executeFrameHandlerStrategy( + req, + this._strategy, + ); + + return { + response: await this.handleResult(result), + refreshToken: result.refreshToken ?? '', + }; + } + + private async handleResult(result: OAuthResult): Promise { + const { profile } = await this.authHandler(result); + + const response: OAuthResponse = { + providerInfo: { + idToken: result.params.id_token, + accessToken: result.accessToken, + refreshToken: result.refreshToken, // GitLab expires the old refresh token when used + scope: result.params.scope, + expiresInSeconds: result.params.expires_in, + }, + profile, + }; + + if (this.signInResolver) { + response.backstageIdentity = await this.signInResolver( + { + result, + profile, + }, + { + tokenIssuer: this.tokenIssuer, + catalogIdentityClient: this.catalogIdentityClient, + logger: this.logger, + }, + ); + } + + return response; + } + + async refresh(req: OAuthRefreshRequest): Promise { + const { + accessToken, + params, + refreshToken: newRefreshToken, + } = await executeRefreshTokenStrategy( + this._strategy, + req.refreshToken, + req.scope, + ); + + const fullProfile = await executeFetchUserProfileStrategy( + this._strategy, + accessToken, + ); + + return this.handleResult({ + fullProfile, + params, + accessToken, + refreshToken: newRefreshToken, + }); + } +} + +export type AtlassianProviderOptions = { + /** + * The profile transformation function used to verify and convert the auth response + * into the profile that will be presented to the user. + */ + authHandler?: AuthHandler; + + /** + * Configure sign-in for this provider, without it the provider can not be used to sign users in. + */ + /** + * Maps an auth result to a Backstage identity for the user. + * + * Set to `'email'` to use the default email-based sign in resolver, which will search + * the catalog for a single user entity that has a matching `microsoft.com/email` annotation. + */ + signIn?: { + resolver?: SignInResolver; + }; +}; + +export const createAtlassianProvider = ( + options?: AtlassianProviderOptions, +): AuthProviderFactory => { + return ({ + providerId, + globalConfig, + config, + tokenIssuer, + catalogApi, + logger, + }) => + OAuthEnvironmentHandler.mapConfig(config, envConfig => { + const clientId = envConfig.getString('clientId'); + const clientSecret = envConfig.getString('clientSecret'); + const scopes = envConfig.getStringArray('scopes'); + const callbackUrl = `${globalConfig.baseUrl}/${providerId}/handler/frame`; + + const catalogIdentityClient = new CatalogIdentityClient({ + catalogApi, + tokenIssuer, + }); + + const authHandler: AuthHandler = + options?.authHandler ?? atlassianDefaultAuthHandler; + + const signInResolverFn = + options?.signIn?.resolver ?? atlassianDefaultSignInResolver; + + const signInResolver: SignInResolver = info => + signInResolverFn(info, { + catalogIdentityClient, + tokenIssuer, + logger, + }); + + const provider = new AtlassianAuthProvider({ + clientId, + clientSecret, + scopes, + callbackUrl, + authHandler, + signInResolver, + catalogIdentityClient, + logger, + tokenIssuer, + }); + + return OAuthAdapter.fromConfig(globalConfig, provider, { + disableRefresh: true, + providerId, + tokenIssuer, + }); + }); +}; diff --git a/plugins/auth-backend/src/providers/atlassian/strategy.ts b/plugins/auth-backend/src/providers/atlassian/strategy.ts new file mode 100644 index 0000000000..630348b16d --- /dev/null +++ b/plugins/auth-backend/src/providers/atlassian/strategy.ts @@ -0,0 +1,111 @@ +/* + * 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. + */ + +import OAuth2Strategy, { InternalOAuthError } from 'passport-oauth2'; +import { Profile } from 'passport'; + +interface ProfileResponse { + account_id: string; + email: string; + name: string; + picture: string; + nickname: string; +} + +interface AtlassianStrategyOptions { + clientID: string; + clientSecret: string; + callbackURL: string; + scope: string[]; +} + +const defaultScopes = ['offline_access', 'read:me']; + +export default class AtlassianStrategy extends OAuth2Strategy { + private readonly profileURL: string; + + constructor( + options: AtlassianStrategyOptions, + verify: OAuth2Strategy.VerifyFunction, + ) { + if (!options.scope) { + throw new TypeError('Atlassian requires a scope option'); + } + + const optionsWithURLs = { + ...options, + authorizationURL: `https://auth.atlassian.com/authorize`, + tokenURL: `https://auth.atlassian.com/oauth/token`, + scope: Array.from(new Set([...defaultScopes, ...options.scope])), + }; + + super(optionsWithURLs, verify); + this.profileURL = 'https://api.atlassian.com/me'; + this.name = 'atlassian'; + + this._oauth2.useAuthorizationHeaderforGET(true); + } + + authorizationParams() { + return { + audience: 'api.atlassian.com', + prompt: 'consent', + }; + } + + userProfile( + accessToken: string, + done: (err?: Error | null, profile?: any) => void, + ): void { + this._oauth2.get(this.profileURL, accessToken, (err, body) => { + if (err) { + return done( + new InternalOAuthError( + 'Failed to fetch user profile', + err.statusCode, + ), + ); + } + + if (!body) { + return done( + new Error('Failed to fetch user profile, body cannot be empty'), + ); + } + + try { + const json = typeof body !== 'string' ? body.toString() : body; + const profile = AtlassianStrategy.parse(json); + return done(null, profile); + } catch (e) { + return done(new Error('Failed to parse user profile')); + } + }); + } + + static parse(json: string): Profile { + const resp = JSON.parse(json) as ProfileResponse; + + return { + id: resp.account_id, + provider: 'atlassian', + username: resp.nickname, + displayName: resp.name, + emails: [{ value: resp.email }], + photos: [{ value: resp.picture }], + }; + } +} diff --git a/plugins/auth-backend/src/providers/factories.ts b/plugins/auth-backend/src/providers/factories.ts index c4894f2757..42d3569815 100644 --- a/plugins/auth-backend/src/providers/factories.ts +++ b/plugins/auth-backend/src/providers/factories.ts @@ -27,6 +27,7 @@ import { createOneLoginProvider } from './onelogin'; import { AuthProviderFactory } from './types'; import { createAwsAlbProvider } from './aws-alb'; import { createBitbucketProvider } from './bitbucket'; +import { createAtlassianProvider } from './atlassian'; export const factories: { [providerId: string]: AuthProviderFactory } = { google: createGoogleProvider(), @@ -41,4 +42,5 @@ export const factories: { [providerId: string]: AuthProviderFactory } = { onelogin: createOneLoginProvider(), awsalb: createAwsAlbProvider(), bitbucket: createBitbucketProvider(), + atlassian: createAtlassianProvider(), }; diff --git a/plugins/auth-backend/src/providers/index.ts b/plugins/auth-backend/src/providers/index.ts index 90466a8094..8c5f05fefd 100644 --- a/plugins/auth-backend/src/providers/index.ts +++ b/plugins/auth-backend/src/providers/index.ts @@ -21,6 +21,7 @@ export * from './microsoft'; export * from './oauth2'; export * from './okta'; export * from './bitbucket'; +export * from './atlassian'; export { factories as defaultAuthProviderFactories } from './factories'; diff --git a/plugins/user-settings/src/components/AuthProviders/DefaultProviderSettings.tsx b/plugins/user-settings/src/components/AuthProviders/DefaultProviderSettings.tsx index 4b9cf9c783..8cfb3a7257 100644 --- a/plugins/user-settings/src/components/AuthProviders/DefaultProviderSettings.tsx +++ b/plugins/user-settings/src/components/AuthProviders/DefaultProviderSettings.tsx @@ -25,6 +25,7 @@ import { oktaAuthApiRef, microsoftAuthApiRef, bitbucketAuthApiRef, + atlassianAuthApiRef, } from '@backstage/core-plugin-api'; type Props = { @@ -89,6 +90,14 @@ export const DefaultProviderSettings = ({ configuredProviders }: Props) => ( icon={Star} /> )} + {configuredProviders.includes('atlassian') && ( + + )} {configuredProviders.includes('oauth2') && (