adds atlassian auth provider

Signed-off-by: Daniel Deloff <44780793+rv-ddeloff@users.noreply.github.com>
This commit is contained in:
Daniel Deloff
2021-10-11 15:04:59 -04:00
parent 89bcf90b66
commit 037447efd3
13 changed files with 606 additions and 0 deletions
+7
View File
@@ -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,
},
];
@@ -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;
@@ -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';
@@ -24,3 +24,4 @@ export * from './auth0';
export * from './microsoft';
export * from './onelogin';
export * from './bitbucket';
export * from './atlassian';
@@ -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'),
});
},
}),
];
@@ -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',
});
@@ -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';
@@ -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',
},
});
});
});
@@ -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<OAuthResult>;
authHandler: AuthHandler<OAuthResult>;
tokenIssuer: TokenIssuer;
catalogIdentityClient: CatalogIdentityClient;
logger: Logger;
};
export const atlassianDefaultSignInResolver: SignInResolver<OAuthResult> =
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<OAuthResult> = async ({
fullProfile,
params,
}) => ({
profile: makeProfileInfo(fullProfile, params.id_token),
});
export class AtlassianAuthProvider implements OAuthHandlers {
private readonly _strategy: AtlassianStrategy;
private readonly signInResolver?: SignInResolver<OAuthResult>;
private readonly authHandler: AuthHandler<OAuthResult>;
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<OAuthResult>,
) => {
done(undefined, {
fullProfile,
accessToken,
refreshToken,
params,
});
},
);
}
async start(req: OAuthStartRequest): Promise<RedirectInfo> {
return await executeRedirectStrategy(req, this._strategy, {
state: encodeState(req.state),
});
}
async handler(
req: express.Request,
): Promise<{ response: OAuthResponse; refreshToken: string }> {
const { result } = await executeFrameHandlerStrategy<OAuthResult>(
req,
this._strategy,
);
return {
response: await this.handleResult(result),
refreshToken: result.refreshToken ?? '',
};
}
private async handleResult(result: OAuthResult): Promise<OAuthResponse> {
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<OAuthResponse> {
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<OAuthResult>;
/**
* 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<OAuthResult>;
};
};
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<OAuthResult> =
options?.authHandler ?? atlassianDefaultAuthHandler;
const signInResolverFn =
options?.signIn?.resolver ?? atlassianDefaultSignInResolver;
const signInResolver: SignInResolver<OAuthResult> = 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,
});
});
};
@@ -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 }],
};
}
}
@@ -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(),
};
@@ -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';
@@ -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') && (
<ProviderSettingsItem
title="Atlassian"
description="Provides authentication towards Atlassian APIs"
apiRef={atlassianAuthApiRef}
icon={Star}
/>
)}
{configuredProviders.includes('oauth2') && (
<ProviderSettingsItem
title="YourOrg"