auth-backend: migrate github provider

Signed-off-by: Patrik Oldsberg <poldsberg@gmail.com>
This commit is contained in:
Patrik Oldsberg
2023-08-20 14:50:01 +02:00
parent d852a15972
commit 72f7979fd2
5 changed files with 62 additions and 664 deletions
+2 -2
View File
@@ -478,7 +478,7 @@ export const providers: Readonly<{
authHandler?: AuthHandler<GithubOAuthResult> | undefined;
signIn?:
| {
resolver: SignInResolver<GithubOAuthResult>;
resolver: SignInResolver_2<GithubOAuthResult>;
}
| undefined;
stateEncoder?: StateEncoder | undefined;
@@ -486,7 +486,7 @@ export const providers: Readonly<{
| undefined,
) => AuthProviderFactory_2;
resolvers: Readonly<{
usernameMatchingUserEntityName: () => SignInResolver<GithubOAuthResult>;
usernameMatchingUserEntityName: () => SignInResolver_2<GithubOAuthResult>;
}>;
}>;
gitlab: Readonly<{
+1
View File
@@ -39,6 +39,7 @@
"@backstage/config": "workspace:^",
"@backstage/errors": "workspace:^",
"@backstage/plugin-auth-backend-module-gcp-iap-provider": "workspace:^",
"@backstage/plugin-auth-backend-module-github-provider": "workspace:^",
"@backstage/plugin-auth-backend-module-google-provider": "workspace:^",
"@backstage/plugin-auth-node": "workspace:^",
"@backstage/plugin-catalog-node": "workspace:^",
@@ -1,410 +0,0 @@
/*
* 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 { Profile as PassportProfile } from 'passport';
import { GithubAuthProvider, GithubOAuthResult, github } from './provider';
import * as helpers from '../../lib/passport/PassportStrategyHelper';
import { makeProfileInfo } from '../../lib/passport/PassportStrategyHelper';
import { OAuthStartRequest, encodeState } from '../../lib/oauth';
import { AuthResolverContext } from '../types';
jest.mock('../../lib/passport/PassportStrategyHelper', () => {
return {
...jest.requireActual('../../lib/passport/PassportStrategyHelper'),
executeFrameHandlerStrategy: jest.fn(),
executeRefreshTokenStrategy: jest.fn(),
executeFetchUserProfileStrategy: jest.fn(),
};
});
const mockFrameHandler = jest.spyOn(
helpers,
'executeFrameHandlerStrategy',
) as unknown as jest.MockedFunction<
() => Promise<{
result: GithubOAuthResult;
privateInfo: { refreshToken?: string };
}>
>;
describe('GithubAuthProvider', () => {
const provider = new GithubAuthProvider({
resolverContext: {
signInWithCatalogUser: jest.fn(({ entityRef }) => ({
token: `token-for-user:${entityRef.name}`,
})),
} as unknown as AuthResolverContext,
signInResolver: github.resolvers.usernameMatchingUserEntityName(),
authHandler: async ({ fullProfile }) => ({
profile: makeProfileInfo(fullProfile),
}),
stateEncoder: async (req: OAuthStartRequest) => ({
encodedState: encodeState(req.state),
}),
callbackUrl: 'mock',
clientId: 'mock',
clientSecret: 'mock',
});
describe('should transform to type OAuthResponse', () => {
it('when all fields are present, it should be able to map them', async () => {
const accessToken = '19xasczxcm9n7gacn9jdgm19me';
const fullProfile = {
id: 'uid-123',
username: 'jimmymarkum',
provider: 'github',
displayName: 'Jimmy Markum',
emails: [
{
value: 'jimmymarkum@gmail.com',
},
],
photos: [
{
value:
'https://a1cf74336522e87f135f-2f21ace9a6cf0052456644b80fa06d4f.ssl.cf2.rackcdn.com/images/characters_opt/p-mystic-river-sean-penn.jpg',
},
],
};
const params = {
scope: 'read:scope',
};
const expected = {
backstageIdentity: {
token: 'token-for-user:jimmymarkum',
},
providerInfo: {
accessToken: '19xasczxcm9n7gacn9jdgm19me',
scope: 'read:scope',
expiresInSeconds: 3600,
},
profile: {
email: 'jimmymarkum@gmail.com',
displayName: 'Jimmy Markum',
picture:
'https://a1cf74336522e87f135f-2f21ace9a6cf0052456644b80fa06d4f.ssl.cf2.rackcdn.com/images/characters_opt/p-mystic-river-sean-penn.jpg',
},
};
mockFrameHandler.mockResolvedValueOnce({
result: { fullProfile, accessToken, params },
privateInfo: {},
});
const { response } = await provider.handler({} as any);
expect(response).toEqual(expected);
});
it('when "email" is missing, it should be able to create the profile without it', async () => {
const accessToken = '19xasczxcm9n7gacn9jdgm19me';
const fullProfile = {
id: 'uid-123',
username: 'jimmymarkum',
provider: 'github',
displayName: 'Jimmy Markum',
emails: null,
photos: [
{
value:
'https://a1cf74336522e87f135f-2f21ace9a6cf0052456644b80fa06d4f.ssl.cf2.rackcdn.com/images/characters_opt/p-mystic-river-sean-penn.jpg',
},
],
} as unknown as PassportProfile;
const params = {
scope: 'read:scope',
};
const expected = {
backstageIdentity: {
token: 'token-for-user:jimmymarkum',
},
providerInfo: {
accessToken: '19xasczxcm9n7gacn9jdgm19me',
scope: 'read:scope',
expiresInSeconds: 3600,
},
profile: {
displayName: 'Jimmy Markum',
picture:
'https://a1cf74336522e87f135f-2f21ace9a6cf0052456644b80fa06d4f.ssl.cf2.rackcdn.com/images/characters_opt/p-mystic-river-sean-penn.jpg',
},
};
mockFrameHandler.mockResolvedValueOnce({
result: { fullProfile, accessToken, params },
privateInfo: {},
});
const { response } = await provider.handler({} as any);
expect(response).toEqual(expected);
});
it('when "displayName" is missing, it should be able to create the profile and map "displayName" with "username"', async () => {
const accessToken = '19xasczxcm9n7gacn9jdgm19me';
const fullProfile = {
id: 'uid-123',
username: 'jimmymarkum',
provider: 'github',
displayName: null,
emails: null,
photos: [
{
value:
'https://a1cf74336522e87f135f-2f21ace9a6cf0052456644b80fa06d4f.ssl.cf2.rackcdn.com/images/characters_opt/p-mystic-river-sean-penn.jpg',
},
],
} as unknown as PassportProfile;
const params = {
scope: 'read:scope',
};
const expected = {
backstageIdentity: {
token: 'token-for-user:jimmymarkum',
},
providerInfo: {
accessToken: '19xasczxcm9n7gacn9jdgm19me',
scope: 'read:scope',
expiresInSeconds: 3600,
},
profile: {
displayName: 'jimmymarkum',
picture:
'https://a1cf74336522e87f135f-2f21ace9a6cf0052456644b80fa06d4f.ssl.cf2.rackcdn.com/images/characters_opt/p-mystic-river-sean-penn.jpg',
},
};
mockFrameHandler.mockResolvedValueOnce({
result: { fullProfile, accessToken, params },
privateInfo: {},
});
const { response } = await provider.handler({} as any);
expect(response).toEqual(expected);
});
it('when "photos" is missing, it should be able to create the profile without it', async () => {
const accessToken =
'ajakljsdoiahoawxbrouawucmbawe.awkxjemaneasdxwe.sodijxqeqwexeqwxe';
const fullProfile = {
id: 'ipd12039',
username: 'daveboyle',
provider: 'github',
displayName: 'Dave Boyle',
emails: [
{
value: 'daveboyle@github.org',
},
],
};
const params = {
scope: 'read:user',
};
const expected = {
backstageIdentity: {
token: 'token-for-user:daveboyle',
},
providerInfo: {
accessToken:
'ajakljsdoiahoawxbrouawucmbawe.awkxjemaneasdxwe.sodijxqeqwexeqwxe',
scope: 'read:user',
expiresInSeconds: 3600,
},
profile: {
displayName: 'Dave Boyle',
email: 'daveboyle@github.org',
},
};
mockFrameHandler.mockResolvedValueOnce({
result: { fullProfile, accessToken, params },
privateInfo: {},
});
const { response } = await provider.handler({} as any);
expect(response).toEqual(expected);
});
it('should forward a refresh token', async () => {
mockFrameHandler.mockResolvedValueOnce({
result: {
fullProfile: {
id: 'ipd12039',
username: 'daveboyle',
provider: 'github',
displayName: 'Dave Boyle',
},
accessToken: 'a.b.c',
params: {
scope: 'read:user',
expires_in: '123',
},
},
privateInfo: { refreshToken: 'refresh-me' },
});
const response = await provider.handler({} as any);
expect(response).toEqual({
response: {
backstageIdentity: {
token: 'token-for-user:daveboyle',
},
providerInfo: {
accessToken: 'a.b.c',
scope: 'read:user',
expiresInSeconds: 123,
},
profile: {
displayName: 'Dave Boyle',
},
},
refreshToken: 'refresh-me',
});
});
it('should fail if username is not available', async () => {
mockFrameHandler.mockResolvedValueOnce({
result: {
fullProfile: {
id: 'ipd12039',
provider: 'github',
displayName: 'Dave Boyle',
},
accessToken: 'a.b.c',
params: {
scope: 'read:user',
expires_in: '123',
},
},
privateInfo: { refreshToken: 'refresh-me' },
});
await expect(provider.handler({} as any)).rejects.toThrow(
'GitHub user profile does not contain a username',
);
});
it('should forward a new refresh token on refresh', async () => {
const mockRefreshToken = jest.spyOn(
helpers,
'executeRefreshTokenStrategy',
) as unknown as jest.MockedFunction<() => Promise<{}>>;
mockRefreshToken.mockResolvedValueOnce({
accessToken: 'a.b.c',
refreshToken: 'dont-forget-to-send-refresh',
params: {
id_token: 'my-id',
expires_in: '123',
scope: 'read_user',
},
});
const mockUserProfile = jest.spyOn(
helpers,
'executeFetchUserProfileStrategy',
) as unknown as jest.MockedFunction<() => Promise<PassportProfile>>;
mockUserProfile.mockResolvedValueOnce({
id: 'mockid',
username: 'mockuser',
provider: 'github',
displayName: 'Mocked User',
emails: [
{
value: 'mockuser@gmail.com',
},
],
});
const result = await provider.refresh({ scope: 'actual-scope' } as any);
expect(result).toEqual({
response: {
backstageIdentity: {
token: 'token-for-user:mockuser',
},
profile: {
displayName: 'Mocked User',
email: 'mockuser@gmail.com',
picture: undefined,
},
providerInfo: {
accessToken: 'a.b.c',
expiresInSeconds: 123,
scope: 'actual-scope',
},
},
refreshToken: 'dont-forget-to-send-refresh',
});
mockRefreshToken.mockRestore();
mockUserProfile.mockRestore();
});
it('should use access token as refresh token', async () => {
const mockUserProfile = jest.spyOn(
helpers,
'executeFetchUserProfileStrategy',
) as unknown as jest.MockedFunction<() => Promise<PassportProfile>>;
mockUserProfile.mockResolvedValueOnce({
id: 'mockid',
username: 'mockuser',
provider: 'github',
displayName: 'Mocked User',
emails: [
{
value: 'mockuser@gmail.com',
},
],
});
const result = await provider.refresh({
refreshToken: 'access-token.le-token',
scope: 'the-scope',
} as any);
expect(mockUserProfile).toHaveBeenCalledTimes(1);
expect(mockUserProfile).toHaveBeenCalledWith(
expect.anything(),
'le-token',
);
expect(result).toEqual({
response: {
backstageIdentity: {
token: 'token-for-user:mockuser',
},
profile: {
displayName: 'Mocked User',
email: 'mockuser@gmail.com',
picture: undefined,
},
providerInfo: {
accessToken: 'le-token',
expiresInSeconds: 3600,
scope: 'the-scope',
},
},
refreshToken: 'access-token.le-token',
});
mockUserProfile.mockRestore();
});
});
});
@@ -14,41 +14,16 @@
* limitations under the License.
*/
import express from 'express';
import { Profile as PassportProfile } from 'passport';
import { Strategy as GithubStrategy } from 'passport-github2';
import {
executeFetchUserProfileStrategy,
executeFrameHandlerStrategy,
executeRedirectStrategy,
executeRefreshTokenStrategy,
makeProfileInfo,
PassportDoneCallback,
} from '../../lib/passport';
import {
OAuthStartResponse,
AuthHandler,
SignInResolver,
StateEncoder,
AuthResolverContext,
} from '../types';
import {
OAuthAdapter,
OAuthProviderOptions,
OAuthHandlers,
OAuthEnvironmentHandler,
OAuthStartRequest,
encodeState,
OAuthRefreshRequest,
} from '../../lib/oauth';
import { AuthHandler, StateEncoder } from '../types';
import { createAuthProviderIntegration } from '../createAuthProviderIntegration';
import { BACKSTAGE_SESSION_EXPIRATION } from '../../lib/session';
const ACCESS_TOKEN_PREFIX = 'access-token.';
type PrivateInfo = {
refreshToken?: string;
};
import {
createOAuthProviderFactory,
OAuthAuthenticatorResult,
ProfileTransform,
SignInResolver,
} from '@backstage/plugin-auth-node';
import { githubAuthenticator } from '@backstage/plugin-auth-backend-module-github-provider';
/** @public */
export type GithubOAuthResult = {
@@ -62,170 +37,6 @@ export type GithubOAuthResult = {
refreshToken?: string;
};
export type GithubAuthProviderOptions = OAuthProviderOptions & {
tokenUrl?: string;
userProfileUrl?: string;
authorizationUrl?: string;
signInResolver?: SignInResolver<GithubOAuthResult>;
authHandler: AuthHandler<GithubOAuthResult>;
stateEncoder: StateEncoder;
resolverContext: AuthResolverContext;
};
export class GithubAuthProvider implements OAuthHandlers {
private readonly _strategy: GithubStrategy;
private readonly signInResolver?: SignInResolver<GithubOAuthResult>;
private readonly authHandler: AuthHandler<GithubOAuthResult>;
private readonly resolverContext: AuthResolverContext;
private readonly stateEncoder: StateEncoder;
constructor(options: GithubAuthProviderOptions) {
this.signInResolver = options.signInResolver;
this.authHandler = options.authHandler;
this.stateEncoder = options.stateEncoder;
this.resolverContext = options.resolverContext;
this._strategy = new GithubStrategy(
{
clientID: options.clientId,
clientSecret: options.clientSecret,
callbackURL: options.callbackUrl,
tokenURL: options.tokenUrl,
userProfileURL: options.userProfileUrl,
authorizationURL: options.authorizationUrl,
},
(
accessToken: any,
refreshToken: any,
params: any,
fullProfile: any,
done: PassportDoneCallback<GithubOAuthResult, PrivateInfo>,
) => {
done(undefined, { fullProfile, params, accessToken }, { refreshToken });
},
);
}
async start(req: OAuthStartRequest): Promise<OAuthStartResponse> {
return await executeRedirectStrategy(req, this._strategy, {
scope: req.scope,
state: (await this.stateEncoder(req)).encodedState,
});
}
async handler(req: express.Request) {
const { result, privateInfo } = await executeFrameHandlerStrategy<
GithubOAuthResult,
PrivateInfo
>(req, this._strategy);
let refreshToken = privateInfo.refreshToken;
// If we do not have a real refresh token and we have a non-expiring
// access token, then we use that as our refresh token.
if (!refreshToken && !result.params.expires_in) {
refreshToken = ACCESS_TOKEN_PREFIX + result.accessToken;
}
return {
response: await this.handleResult(result),
refreshToken,
};
}
async refresh(req: OAuthRefreshRequest) {
// We've enable persisting scope in the OAuth provider, so scope here will
// be whatever was stored in the cookie
const { scope, refreshToken } = req;
// This is the OAuth App flow. A non-expiring access token is stored in the
// refresh token cookie. We use that token to fetch the user profile and
// refresh the Backstage session when needed.
if (refreshToken?.startsWith(ACCESS_TOKEN_PREFIX)) {
const accessToken = refreshToken.slice(ACCESS_TOKEN_PREFIX.length);
const fullProfile = await executeFetchUserProfileStrategy(
this._strategy,
accessToken,
).catch(error => {
if (error.oauthError?.statusCode === 401) {
throw new Error('Invalid access token');
}
throw error;
});
return {
response: await this.handleResult({
fullProfile,
params: { scope },
accessToken,
}),
refreshToken,
};
}
// This is the App flow, which is close to a standard OAuth refresh flow. It has a
// pretty long session expiration, and it also ignores the requested scope, instead
// just allowing access to whatever is configured as part of the app installation.
const result = await executeRefreshTokenStrategy(
this._strategy,
refreshToken,
scope,
);
return {
response: await this.handleResult({
fullProfile: await executeFetchUserProfileStrategy(
this._strategy,
result.accessToken,
),
params: { ...result.params, scope },
accessToken: result.accessToken,
}),
refreshToken: result.refreshToken,
};
}
private async handleResult(result: GithubOAuthResult) {
const { profile } = await this.authHandler(result, this.resolverContext);
const expiresInStr = result.params.expires_in;
let expiresInSeconds =
expiresInStr === undefined ? undefined : Number(expiresInStr);
let backstageIdentity = undefined;
if (this.signInResolver) {
backstageIdentity = await this.signInResolver(
{
result,
profile,
},
this.resolverContext,
);
// GitHub sessions last longer than Backstage sessions, so if we're using
// GitHub for sign-in, then we need to expire the sessions earlier
if (expiresInSeconds) {
expiresInSeconds = Math.min(
expiresInSeconds,
BACKSTAGE_SESSION_EXPIRATION,
);
} else {
expiresInSeconds = BACKSTAGE_SESSION_EXPIRATION;
}
}
return {
backstageIdentity,
providerInfo: {
accessToken: result.accessToken,
scope: result.params.scope,
expiresInSeconds,
},
profile,
};
}
}
/**
* Auth provider integration for GitHub auth
*
@@ -267,60 +78,55 @@ export const github = createAuthProviderIntegration({
*/
stateEncoder?: StateEncoder;
}) {
return ({ providerId, globalConfig, config, resolverContext }) =>
OAuthEnvironmentHandler.mapConfig(config, envConfig => {
const clientId = envConfig.getString('clientId');
const clientSecret = envConfig.getString('clientSecret');
const enterpriseInstanceUrl = envConfig
.getOptionalString('enterpriseInstanceUrl')
?.replace(/\/$/, '');
const customCallbackUrl = envConfig.getOptionalString('callbackUrl');
const authorizationUrl = enterpriseInstanceUrl
? `${enterpriseInstanceUrl}/login/oauth/authorize`
: undefined;
const tokenUrl = enterpriseInstanceUrl
? `${enterpriseInstanceUrl}/login/oauth/access_token`
: undefined;
const userProfileUrl = enterpriseInstanceUrl
? `${enterpriseInstanceUrl}/api/v3/user`
: undefined;
const callbackUrl =
customCallbackUrl ||
`${globalConfig.baseUrl}/${providerId}/handler/frame`;
const authHandler: AuthHandler<GithubOAuthResult> = options?.authHandler
? options.authHandler
: async ({ fullProfile }) => ({
profile: makeProfileInfo(fullProfile),
});
const stateEncoder: StateEncoder =
options?.stateEncoder ??
(async (
req: OAuthStartRequest,
): Promise<{ encodedState: string }> => {
return { encodedState: encodeState(req.state) };
});
const provider = new GithubAuthProvider({
clientId,
clientSecret,
callbackUrl,
tokenUrl,
userProfileUrl,
authorizationUrl,
signInResolver: options?.signIn?.resolver,
authHandler,
stateEncoder,
resolverContext,
});
return OAuthAdapter.fromConfig(globalConfig, provider, {
persistScopes: true,
providerId,
callbackUrl,
});
});
const authHandler = options?.authHandler;
const signInResolver = options?.signIn?.resolver;
return createOAuthProviderFactory({
authenticator: githubAuthenticator,
profileTransform:
authHandler &&
((async (result, ctx) =>
authHandler!(
{
fullProfile: result.fullProfile,
accessToken: result.session.accessToken,
params: {
scope: result.session.scope,
expires_in: result.session.expiresInSeconds
? String(result.session.expiresInSeconds)
: '',
refresh_token_expires_in: result.session
.refreshTokenExpiresInSeconds
? String(result.session.refreshTokenExpiresInSeconds)
: '',
},
},
ctx,
)) as ProfileTransform<OAuthAuthenticatorResult<PassportProfile>>),
signInResolver:
signInResolver &&
((async ({ profile, result }, ctx) =>
signInResolver(
{
profile: profile,
result: {
fullProfile: result.fullProfile,
accessToken: result.session.accessToken,
refreshToken: result.session.refreshToken,
params: {
scope: result.session.scope,
expires_in: result.session.expiresInSeconds
? String(result.session.expiresInSeconds)
: '',
refresh_token_expires_in: result.session
.refreshTokenExpiresInSeconds
? String(result.session.refreshTokenExpiresInSeconds)
: '',
},
},
},
ctx,
)) as SignInResolver<OAuthAuthenticatorResult<PassportProfile>>),
});
},
resolvers: {
/**
+2 -1
View File
@@ -4553,7 +4553,7 @@ __metadata:
languageName: unknown
linkType: soft
"@backstage/plugin-auth-backend-module-github-provider@workspace:plugins/auth-backend-module-github-provider":
"@backstage/plugin-auth-backend-module-github-provider@workspace:^, @backstage/plugin-auth-backend-module-github-provider@workspace:plugins/auth-backend-module-github-provider":
version: 0.0.0-use.local
resolution: "@backstage/plugin-auth-backend-module-github-provider@workspace:plugins/auth-backend-module-github-provider"
dependencies:
@@ -4599,6 +4599,7 @@ __metadata:
"@backstage/config": "workspace:^"
"@backstage/errors": "workspace:^"
"@backstage/plugin-auth-backend-module-gcp-iap-provider": "workspace:^"
"@backstage/plugin-auth-backend-module-github-provider": "workspace:^"
"@backstage/plugin-auth-backend-module-google-provider": "workspace:^"
"@backstage/plugin-auth-node": "workspace:^"
"@backstage/plugin-catalog-node": "workspace:^"