diff --git a/plugins/auth-backend/package.json b/plugins/auth-backend/package.json index af3d056b28..28ac51034e 100644 --- a/plugins/auth-backend/package.json +++ b/plugins/auth-backend/package.json @@ -21,6 +21,7 @@ }, "dependencies": { "@backstage/backend-common": "^0.2.1", + "@backstage/catalog-client": "^0.2.0", "@backstage/catalog-model": "^0.2.0", "@backstage/config": "^0.1.1", "@types/express": "^4.17.6", diff --git a/plugins/auth-backend/src/lib/catalog/CatalogIdentityClient.test.ts b/plugins/auth-backend/src/lib/catalog/CatalogIdentityClient.test.ts new file mode 100644 index 0000000000..ec6aa1b6ba --- /dev/null +++ b/plugins/auth-backend/src/lib/catalog/CatalogIdentityClient.test.ts @@ -0,0 +1,48 @@ +/* + * Copyright 2020 Spotify AB + * + * 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 { CatalogApi } from '@backstage/catalog-client'; +import { UserEntity } from '@backstage/catalog-model'; +import { CatalogIdentityClient } from './CatalogIdentityClient'; + +describe('CatalogIdentityClient', () => { + const catalogApi: jest.Mocked = { + getLocationById: jest.fn(), + getEntityByName: jest.fn(), + getEntities: jest.fn(), + addLocation: jest.fn(), + getLocationByEntity: jest.fn(), + removeEntityByUid: jest.fn(), + }; + + afterEach(() => jest.resetAllMocks()); + + it('passes through the correct search params', async () => { + catalogApi.getEntities.mockResolvedValueOnce({ items: [{} as UserEntity] }); + const client = new CatalogIdentityClient({ + catalogApi: catalogApi as CatalogApi, + }); + + client.findUser({ annotations: { key: 'value' } }); + + expect(catalogApi.getEntities).toBeCalledWith({ + filter: { + kind: 'user', + 'metadata.annotations.key': 'value', + }, + }); + }); +}); diff --git a/plugins/auth-backend/src/lib/catalog/CatalogIdentityClient.ts b/plugins/auth-backend/src/lib/catalog/CatalogIdentityClient.ts index e56763f656..5bc4e5de21 100644 --- a/plugins/auth-backend/src/lib/catalog/CatalogIdentityClient.ts +++ b/plugins/auth-backend/src/lib/catalog/CatalogIdentityClient.ts @@ -14,13 +14,9 @@ * limitations under the License. */ -import { - ConflictError, - NotFoundError, - PluginEndpointDiscovery, -} from '@backstage/backend-common'; +import { ConflictError, NotFoundError } from '@backstage/backend-common'; +import { CatalogApi } from '@backstage/catalog-client'; import { UserEntity } from '@backstage/catalog-model'; -import fetch from 'cross-fetch'; type UserQuery = { annotations: Record; @@ -30,10 +26,10 @@ type UserQuery = { * A catalog client tailored for reading out identity data from the catalog. */ export class CatalogIdentityClient { - private readonly discovery: PluginEndpointDiscovery; + private readonly catalogApi: CatalogApi; - constructor(options: { discovery: PluginEndpointDiscovery }) { - this.discovery = options.discovery; + constructor(options: { catalogApi: CatalogApi }) { + this.catalogApi = options.catalogApi; } /** @@ -42,35 +38,23 @@ export class CatalogIdentityClient { * Throws a NotFoundError or ConflictError if 0 or multiple users are found. */ async findUser(query: UserQuery): Promise { - const conditions = ['kind=user']; + const filter: Record = { + kind: 'user', + }; for (const [key, value] of Object.entries(query.annotations)) { - const uk = encodeURIComponent(key); - const uv = encodeURIComponent(value); - conditions.push(`metadata.annotations.${uk}=${uv}`); + filter[`metadata.annotations.${key}`] = value; } - const baseUrl = await this.discovery.getBaseUrl('catalog'); - const response = await fetch( - `${baseUrl}/entities?filter=${conditions.join(',')}`, - ); + const { items } = await this.catalogApi.getEntities({ filter }); - if (!response.ok) { - const text = await response.text(); - throw new Error( - `Request failed with ${response.status} ${response.statusText}, ${text}`, - ); - } - - const users: UserEntity[] = await response.json(); - - if (users.length !== 1) { - if (users.length > 1) { + if (items.length !== 1) { + if (items.length > 1) { throw new ConflictError('User lookup resulted in multiple matches'); } else { throw new NotFoundError('User not found'); } } - return users[0]; + return items[0] as UserEntity; } } diff --git a/plugins/auth-backend/src/providers/google/provider.ts b/plugins/auth-backend/src/providers/google/provider.ts index 80143ca201..dd5b51eb01 100644 --- a/plugins/auth-backend/src/providers/google/provider.ts +++ b/plugins/auth-backend/src/providers/google/provider.ts @@ -15,29 +15,29 @@ */ import express from 'express'; -import { Logger } from 'winston'; +import passport from 'passport'; import { Strategy as GoogleStrategy } from 'passport-google-oauth20'; +import { Logger } from 'winston'; +import { CatalogIdentityClient } from '../../lib/catalog'; import { + encodeState, + OAuthAdapter, + OAuthEnvironmentHandler, + OAuthHandlers, + OAuthProviderOptions, + OAuthRefreshRequest, + OAuthResponse, + OAuthStartRequest, +} from '../../lib/oauth'; +import { + executeFetchUserProfileStrategy, executeFrameHandlerStrategy, executeRedirectStrategy, executeRefreshTokenStrategy, makeProfileInfo, - executeFetchUserProfileStrategy, PassportDoneCallback, } from '../../lib/passport'; -import { RedirectInfo, AuthProviderFactory } from '../types'; -import { - OAuthAdapter, - OAuthHandlers, - OAuthProviderOptions, - OAuthResponse, - OAuthEnvironmentHandler, - OAuthStartRequest, - encodeState, - OAuthRefreshRequest, -} from '../../lib/oauth'; -import passport from 'passport'; -import { CatalogIdentityClient } from '../../lib/catalog'; +import { AuthProviderFactory, RedirectInfo } from '../types'; type PrivateInfo = { refreshToken: string; @@ -179,7 +179,7 @@ export const createGoogleProvider: AuthProviderFactory = ({ config, logger, tokenIssuer, - discovery, + catalogApi, }) => OAuthEnvironmentHandler.mapConfig(config, envConfig => { const providerId = 'google'; @@ -192,7 +192,7 @@ export const createGoogleProvider: AuthProviderFactory = ({ clientSecret, callbackUrl, logger, - identityClient: new CatalogIdentityClient({ discovery }), + identityClient: new CatalogIdentityClient({ catalogApi }), }); return OAuthAdapter.fromConfig(globalConfig, provider, { diff --git a/plugins/auth-backend/src/providers/types.ts b/plugins/auth-backend/src/providers/types.ts index 6776095f99..0e500e027e 100644 --- a/plugins/auth-backend/src/providers/types.ts +++ b/plugins/auth-backend/src/providers/types.ts @@ -14,11 +14,12 @@ * limitations under the License. */ +import { PluginEndpointDiscovery } from '@backstage/backend-common'; +import { CatalogApi } from '@backstage/catalog-client'; +import { Config } from '@backstage/config'; import express from 'express'; import { Logger } from 'winston'; import { TokenIssuer } from '../identity'; -import { Config } from '@backstage/config'; -import { PluginEndpointDiscovery } from '@backstage/backend-common'; export type AuthProviderConfig = { /** @@ -117,6 +118,7 @@ export type AuthProviderFactoryOptions = { logger: Logger; tokenIssuer: TokenIssuer; discovery: PluginEndpointDiscovery; + catalogApi: CatalogApi; }; export type AuthProviderFactory = ( diff --git a/plugins/auth-backend/src/service/router.ts b/plugins/auth-backend/src/service/router.ts index 6bb100de6b..0d19e67fc4 100644 --- a/plugins/auth-backend/src/service/router.ts +++ b/plugins/auth-backend/src/service/router.ts @@ -14,18 +14,19 @@ * limitations under the License. */ -import express from 'express'; -import Router from 'express-promise-router'; -import cookieParser from 'cookie-parser'; -import { Logger } from 'winston'; -import { createAuthProvider } from '../providers'; -import { Config } from '@backstage/config'; -import { DatabaseKeyStore, TokenFactory, createOidcRouter } from '../identity'; import { NotFoundError, - PluginEndpointDiscovery, PluginDatabaseManager, + PluginEndpointDiscovery, } from '@backstage/backend-common'; +import { CatalogClient } from '@backstage/catalog-client'; +import { Config } from '@backstage/config'; +import cookieParser from 'cookie-parser'; +import express from 'express'; +import Router from 'express-promise-router'; +import { Logger } from 'winston'; +import { createOidcRouter, DatabaseKeyStore, TokenFactory } from '../identity'; +import { createAuthProvider } from '../providers'; export interface RouterOptions { logger: Logger; @@ -56,6 +57,7 @@ export async function createRouter({ keyDurationSeconds, logger: logger.child({ component: 'token-factory' }), }); + const catalogApi = new CatalogClient({ discoveryApi: discovery }); router.use(cookieParser()); router.use(express.urlencoded({ extended: false })); @@ -73,6 +75,7 @@ export async function createRouter({ logger, tokenIssuer, discovery, + catalogApi, }); const r = Router(); diff --git a/plugins/auth-backend/src/service/standaloneServer.ts b/plugins/auth-backend/src/service/standaloneServer.ts index a4f2377507..15a3347d5f 100644 --- a/plugins/auth-backend/src/service/standaloneServer.ts +++ b/plugins/auth-backend/src/service/standaloneServer.ts @@ -14,16 +14,16 @@ * limitations under the License. */ -import Knex from 'knex'; -import { Server } from 'http'; -import { Logger } from 'winston'; -import { createRouter } from './router'; import { createServiceBuilder, - useHotMemoize, loadBackendConfig, SingleHostDiscovery, + useHotMemoize, } from '@backstage/backend-common'; +import { Server } from 'http'; +import Knex from 'knex'; +import { Logger } from 'winston'; +import { createRouter } from './router'; export interface ServerOptions { logger: Logger;