auth-backend: use the catalog client (#3298)

This commit is contained in:
Fredrik Adelöw
2020-11-18 21:10:04 +01:00
committed by GitHub
parent 4c7be36164
commit 4a25ee5cf5
7 changed files with 99 additions and 61 deletions
@@ -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<CatalogApi> = {
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',
},
});
});
});
@@ -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<string, string>;
@@ -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<UserEntity> {
const conditions = ['kind=user'];
const filter: Record<string, string> = {
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;
}
}
@@ -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, {
+4 -2
View File
@@ -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 = (
+11 -8
View File
@@ -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();
@@ -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;