From 2ae89a1c8b6b572155e83ff9c75d5f27f7b98fa3 Mon Sep 17 00:00:00 2001 From: Patrik Oldsberg Date: Fri, 8 Apr 2022 13:40:54 +0200 Subject: [PATCH] auth-backend: migrate gitlab provider to use resolver context Signed-off-by: Patrik Oldsberg --- .../src/providers/gitlab/provider.test.ts | 31 +++------ .../src/providers/gitlab/provider.ts | 67 +++---------------- 2 files changed, 18 insertions(+), 80 deletions(-) diff --git a/plugins/auth-backend/src/providers/gitlab/provider.test.ts b/plugins/auth-backend/src/providers/gitlab/provider.test.ts index f51ba58365..169930786b 100644 --- a/plugins/auth-backend/src/providers/gitlab/provider.test.ts +++ b/plugins/auth-backend/src/providers/gitlab/provider.test.ts @@ -21,9 +21,7 @@ import { import * as helpers from '../../lib/passport/PassportStrategyHelper'; import { PassportProfile } from '../../lib/passport/types'; import { OAuthResult } from '../../lib/oauth'; -import { getVoidLogger } from '@backstage/backend-common'; -import { TokenIssuer } from '../../identity'; -import { CatalogIdentityClient } from '../../lib/catalog'; +import { AuthResolverContext } from '../types'; const mockFrameHandler = jest.spyOn( helpers, @@ -31,26 +29,16 @@ const mockFrameHandler = jest.spyOn( ) as unknown as jest.MockedFunction<() => Promise<{ result: OAuthResult }>>; describe('GitlabAuthProvider', () => { - const tokenIssuer = { - issueToken: jest.fn(), - listPublicKeys: jest.fn(), - }; - const catalogIdentityClient = { - findUser: jest.fn(), - resolveCatalogMembership: async ({ - entityRefs, - }: { - entityRefs: string[]; - }) => entityRefs, - } as unknown as CatalogIdentityClient; - const provider = new GitlabAuthProvider({ clientId: 'mock', clientSecret: 'mock', callbackUrl: 'mock', baseUrl: 'mock', - catalogIdentityClient, - tokenIssuer: tokenIssuer as unknown as TokenIssuer, + resolverContext: { + signInWithCatalogUser: jest.fn(async ({ entityRef }) => ({ + token: `token-for-user:${entityRef.name}`, + })), + } as unknown as AuthResolverContext, authHandler: async ({ fullProfile }) => ({ profile: { email: fullProfile.emails![0]!.value, @@ -59,7 +47,6 @@ describe('GitlabAuthProvider', () => { }, }), signInResolver: gitlabUsernameEntityNameSignInResolver, - logger: getVoidLogger(), }); it('should transform to type OAuthResponse', async () => { @@ -92,7 +79,7 @@ describe('GitlabAuthProvider', () => { }, expect: { backstageIdentity: { - id: 'jimmymarkum', + token: 'token-for-user:jimmymarkum', }, providerInfo: { accessToken: '19xasczxcm9n7gacn9jdgm19me', @@ -134,7 +121,7 @@ describe('GitlabAuthProvider', () => { }, expect: { backstageIdentity: { - id: 'daveboyle', + token: 'token-for-user:daveboyle', }, providerInfo: { accessToken: @@ -196,7 +183,7 @@ describe('GitlabAuthProvider', () => { expect(result).toEqual({ response: { backstageIdentity: { - id: 'mockuser', + token: 'token-for-user:mockuser', }, profile: { displayName: 'Mocked User', diff --git a/plugins/auth-backend/src/providers/gitlab/provider.ts b/plugins/auth-backend/src/providers/gitlab/provider.ts index a26313fe95..292ed3efa5 100644 --- a/plugins/auth-backend/src/providers/gitlab/provider.ts +++ b/plugins/auth-backend/src/providers/gitlab/provider.ts @@ -14,13 +14,8 @@ * limitations under the License. */ -import { - DEFAULT_NAMESPACE, - stringifyEntityRef, -} from '@backstage/catalog-model'; import express from 'express'; import { Strategy as GitlabStrategy } from 'passport-gitlab2'; -import { Logger } from 'winston'; import { executeRedirectStrategy, executeFrameHandlerStrategy, @@ -34,6 +29,7 @@ import { AuthProviderFactory, SignInResolver, AuthHandler, + AuthResolverContext, } from '../types'; import { OAuthAdapter, @@ -46,8 +42,6 @@ import { encodeState, OAuthResult, } from '../../lib/oauth'; -import { TokenIssuer } from '../../identity'; -import { CatalogIdentityClient } from '../../lib/catalog'; type PrivateInfo = { refreshToken: string; @@ -57,9 +51,7 @@ export type GitlabAuthProviderOptions = OAuthProviderOptions & { baseUrl: string; signInResolver?: SignInResolver; authHandler: AuthHandler; - tokenIssuer: TokenIssuer; - catalogIdentityClient: CatalogIdentityClient; - logger: Logger; + resolverContext: AuthResolverContext; }; export const gitlabUsernameEntityNameSignInResolver: SignInResolver< @@ -72,23 +64,7 @@ export const gitlabUsernameEntityNameSignInResolver: SignInResolver< throw new Error(`GitLab user profile does not contain a username`); } - const entityRef = stringifyEntityRef({ - kind: 'User', - namespace: DEFAULT_NAMESPACE, - name: id, - }); - const ownershipEntityRefs = - await ctx.catalogIdentityClient.resolveCatalogMembership({ - entityRefs: [entityRef], - }); - const token = await ctx.tokenIssuer.issueToken({ - claims: { - sub: entityRef, - ent: ownershipEntityRefs, - }, - }); - - return { id, token }; + return ctx.signInWithCatalogUser({ entityRef: { name: id } }); }; export const gitlabDefaultAuthHandler: AuthHandler = async ({ @@ -102,14 +78,10 @@ export class GitlabAuthProvider implements OAuthHandlers { private readonly _strategy: GitlabStrategy; private readonly signInResolver?: SignInResolver; private readonly authHandler: AuthHandler; - private readonly tokenIssuer: TokenIssuer; - private readonly catalogIdentityClient: CatalogIdentityClient; - private readonly logger: Logger; + private readonly resolverContext: AuthResolverContext; constructor(options: GitlabAuthProviderOptions) { - this.catalogIdentityClient = options.catalogIdentityClient; - this.logger = options.logger; - this.tokenIssuer = options.tokenIssuer; + this.resolverContext = options.resolverContext; this.authHandler = options.authHandler; this.signInResolver = options.signInResolver; @@ -180,12 +152,7 @@ export class GitlabAuthProvider implements OAuthHandlers { } private async handleResult(result: OAuthResult): Promise { - const context = { - logger: this.logger, - catalogIdentityClient: this.catalogIdentityClient, - tokenIssuer: this.tokenIssuer, - }; - const { profile } = await this.authHandler(result, context); + const { profile } = await this.authHandler(result, this.resolverContext); const response: OAuthResponse = { providerInfo: { @@ -203,7 +170,7 @@ export class GitlabAuthProvider implements OAuthHandlers { result, profile, }, - context, + this.resolverContext, ); } @@ -255,15 +222,7 @@ export const createGitlabProvider = (options?: { resolver: SignInResolver; }; }): AuthProviderFactory => { - return ({ - providerId, - globalConfig, - config, - tokenIssuer, - tokenManager, - catalogApi, - logger, - }) => + return ({ providerId, globalConfig, config, resolverContext }) => OAuthEnvironmentHandler.mapConfig(config, envConfig => { const clientId = envConfig.getString('clientId'); const clientSecret = envConfig.getString('clientSecret'); @@ -274,11 +233,6 @@ export const createGitlabProvider = (options?: { customCallbackUrl || `${globalConfig.baseUrl}/${providerId}/handler/frame`; - const catalogIdentityClient = new CatalogIdentityClient({ - catalogApi, - tokenManager, - }); - const authHandler: AuthHandler = options?.authHandler ?? gitlabDefaultAuthHandler; @@ -289,15 +243,12 @@ export const createGitlabProvider = (options?: { baseUrl, authHandler, signInResolver: options?.signIn?.resolver, - catalogIdentityClient, - logger, - tokenIssuer, + resolverContext, }); return OAuthAdapter.fromConfig(globalConfig, provider, { disableRefresh: false, providerId, - tokenIssuer, callbackUrl, }); });