Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(ocm)!: add basic permissions to ocm backend plugin #1528

Merged
merged 5 commits into from
May 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion plugins/ocm-backend/dev/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,24 @@ export async function startStandaloneServer(
},
},
});

const createEnv = makeCreateEnv(config);
const catalogEnv = useHotMemoize(module, () => createEnv('catalog'));
const discovery = HostDiscovery.fromConfig(config);
const tokenManager = ServerTokenManager.fromConfig(config, {
logger,
});
const permissions = ServerPermissionClient.fromConfig(config, {
discovery,
tokenManager,
});

const ocmRouterOptions: RouterOptions = { logger, config };
const ocmRouterOptions: RouterOptions = {
logger,
config,
permissions,
discovery,
};
const service = createServiceBuilder(module)
.setPort(options.port)
.enableCors({
Expand Down
7 changes: 4 additions & 3 deletions plugins/ocm-backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,18 @@
"configSchema": "config.d.ts",
"dependencies": {
"@backstage/backend-common": "^0.21.6",
"@backstage/backend-dynamic-feature-service": "^0.2.8",
"@backstage/backend-plugin-api": "^0.6.16",
"@backstage/backend-tasks": "^0.5.21",
"@backstage/catalog-client": "^1.6.3",
"@backstage/catalog-model": "^1.4.5",
"@backstage/config": "^1.2.0",
"@backstage/errors": "^1.2.4",
"@backstage/plugin-catalog-node": "^1.11.0",
"@backstage/plugin-kubernetes-common": "^0.7.5",
"@backstage/plugin-permission-common": "0.7.13",
"@backstage/plugin-permission-node": "0.7.27",
"@janus-idp/backstage-plugin-ocm-common": "2.3.0",
"@backstage/backend-dynamic-feature-service": "^0.2.8",
"@kubernetes/client-node": "^0.20.0",
"express": "^4.18.2",
"express-promise-router": "^4.1.1",
Expand All @@ -62,8 +65,6 @@
"@janus-idp/cli": "1.8.1",
"@backstage/plugin-auth-node": "0.4.11",
"@backstage/plugin-catalog-backend": "1.21.0",
"@backstage/plugin-permission-common": "0.7.13",
"@backstage/plugin-permission-node": "0.7.27",
"@types/express": "4.17.20",
"@types/supertest": "2.0.16",
"msw": "1.3.2",
Expand Down
57 changes: 56 additions & 1 deletion plugins/ocm-backend/src/service/router.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ConfigReader } from '@backstage/config';
import { AuthorizeResult } from '@backstage/plugin-permission-common';

import express from 'express';
import { setupServer } from 'msw/node';
Expand Down Expand Up @@ -26,11 +27,33 @@ const logger = createLogger({
transports: [new transports.Console({ silent: true })],
});

const mockedAuthorize = jest.fn().mockImplementation(async () => [
{
result: AuthorizeResult.ALLOW,
},
]);

const mockedAuthorizeConditional = jest.fn().mockImplementation(async () => [
{
result: AuthorizeResult.ALLOW,
},
]);

const mockPermissionEvaluator = {
authorize: mockedAuthorize,
authorizeConditional: mockedAuthorizeConditional,
};

const mockDiscovery = {
getBaseUrl: jest.fn(),
getExternalBaseUrl: jest.fn(),
};

describe('createRouter', () => {
let app: express.Express;

beforeAll(async () => {
jest.resetAllMocks();
jest.clearAllMocks();
const router = await createRouter({
logger: logger,
config: new ConfigReader({
Expand All @@ -46,11 +69,28 @@ describe('createRouter', () => {
},
},
}),
permissions: mockPermissionEvaluator,
discovery: mockDiscovery,
});
app = express().use(router);
});

describe('GET /status', () => {
it('should deny access when getting all clusters', async () => {
mockedAuthorize.mockImplementationOnce(async () => [
{ result: AuthorizeResult.DENY },
]);

const result = await request(app).get('/status');

expect(mockedAuthorize).toHaveBeenCalled();

expect(result.statusCode).toBe(403);
expect(result.body.error).toEqual({
name: 'NotAllowedError',
message: 'Unauthorized',
});
});
it('should get all clusters', async () => {
const result = await request(app).get('/status');

Expand Down Expand Up @@ -177,6 +217,21 @@ describe('createRouter', () => {
});

describe('GET /status/:hubName/:clusterName', () => {
it('should deny access when getting all clusters', async () => {
mockedAuthorize.mockImplementationOnce(async () => [
{ result: AuthorizeResult.DENY },
]);

const result = await request(app).get('/status/foo/cluster1');

expect(mockedAuthorize).toHaveBeenCalled();

expect(result.statusCode).toBe(403);
expect(result.body.error).toEqual({
name: 'NotAllowedError',
message: 'Unauthorized',
});
});
it('should correctly parse a cluster', async () => {
const result = await request(app).get('/status/foo/cluster1');

Expand Down
145 changes: 104 additions & 41 deletions plugins/ocm-backend/src/service/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,37 @@
* limitations under the License.
*/

import { errorHandler, loggerToWinstonLogger } from '@backstage/backend-common';
import {
createLegacyAuthAdapters,
errorHandler,
loggerToWinstonLogger,
PluginEndpointDiscovery,
} from '@backstage/backend-common';
import {
coreServices,
createBackendPlugin,
HttpAuthService,
PermissionsService,
} from '@backstage/backend-plugin-api';
import { Config } from '@backstage/config';
import { NotAllowedError } from '@backstage/errors';
import {
AuthorizeResult,
BasicPermission,
} from '@backstage/plugin-permission-common';
import { createPermissionIntegrationRouter } from '@backstage/plugin-permission-node';

import express from 'express';
import Router from 'express-promise-router';
import { Request } from 'express-serve-static-core';
import { Logger } from 'winston';

import {
Cluster,
ClusterOverview,
ocmClusterReadPermission,
ocmEntityPermissions,
ocmEntityReadPermission,
} from '@janus-idp/backstage-plugin-ocm-common';

import { readOcmConfigs } from '../helpers/config';
Expand All @@ -52,11 +69,25 @@ import { ManagedClusterInfo } from '../types';
export interface RouterOptions {
logger: Logger;
config: Config;
discovery: PluginEndpointDiscovery;
permissions: PermissionsService;
httpAuth?: HttpAuthService;
}

const buildRouter = (config: Config, logger: Logger) => {
const buildRouter = (
config: Config,
logger: Logger,
httpAuth: HttpAuthService,
permissions: PermissionsService,
) => {
const router = Router();

const permissionsIntegrationRouter = createPermissionIntegrationRouter({
permissions: ocmEntityPermissions,
});

router.use(express.json());
router.use(permissionsIntegrationRouter);

const clients = Object.fromEntries(
readOcmConfigs(config).map(provider => [
Expand All @@ -68,43 +99,63 @@ const buildRouter = (config: Config, logger: Logger) => {
]),
);

router.get(
'/status/:providerId/:clusterName',
async ({ params: { clusterName, providerId } }, response) => {
logger.debug(
`Incoming status request for ${clusterName} cluster on ${providerId} hub`,
);

if (!clients.hasOwnProperty(providerId)) {
throw Object.assign(new Error('Hub not found'), {
statusCode: 404,
name: 'HubNotFound',
});
}

const normalizedClusterName = translateResourceToOCM(
clusterName,
clients[providerId].hubResourceName,
);

const mc = await getManagedCluster(
clients[providerId].client,
normalizedClusterName,
);
const mci = await getManagedClusterInfo(
clients[providerId].client,
normalizedClusterName,
);

response.send({
name: clusterName,
...parseManagedCluster(mc),
...parseUpdateInfo(mci),
} as Cluster);
},
);
const authorize = async (request: Request, permission: BasicPermission) => {
const decision = (
await permissions.authorize([{ permission: permission }], {
credentials: await httpAuth.credentials(request),
})
)[0];

return decision;
};

router.get('/status/:providerId/:clusterName', async (request, response) => {
const decision = await authorize(request, ocmEntityReadPermission);

if (decision.result === AuthorizeResult.DENY) {
throw new NotAllowedError('Unauthorized');
}

const { clusterName, providerId } = request.params;
logger.debug(
`Incoming status request for ${clusterName} cluster on ${providerId} hub`,
);

if (!clients.hasOwnProperty(providerId)) {
throw Object.assign(new Error('Hub not found'), {
statusCode: 404,
name: 'HubNotFound',
});
}

const normalizedClusterName = translateResourceToOCM(
clusterName,
clients[providerId].hubResourceName,
);

const mc = await getManagedCluster(
clients[providerId].client,
normalizedClusterName,
);
const mci = await getManagedClusterInfo(
clients[providerId].client,
normalizedClusterName,
);

response.send({
name: clusterName,
...parseManagedCluster(mc),
...parseUpdateInfo(mci),
} as Cluster);
});

router.get('/status', async (request, response) => {
const decision = await authorize(request, ocmClusterReadPermission);

if (decision.result === AuthorizeResult.DENY) {
throw new NotAllowedError('Unauthorized');
}

router.get('/status', async (_, response) => {
logger.debug(`Incoming status request for all clusters`);

const allClusters = await Promise.all(
Expand Down Expand Up @@ -144,8 +195,11 @@ export async function createRouter(
): Promise<express.Router> {
const { logger } = options;
const { config } = options;
const { permissions } = options;

const { httpAuth } = createLegacyAuthAdapters(options);

return buildRouter(config, logger);
return buildRouter(config, logger, httpAuth, permissions);
}

export const ocmPlugin = createBackendPlugin({
Expand All @@ -156,9 +210,18 @@ export const ocmPlugin = createBackendPlugin({
logger: coreServices.logger,
config: coreServices.rootConfig,
http: coreServices.httpRouter,
httpAuth: coreServices.httpAuth,
permissions: coreServices.permissions,
},
async init({ config, logger, http }) {
http.use(buildRouter(config, loggerToWinstonLogger(logger)));
async init({ config, logger, http, httpAuth, permissions }) {
http.use(
buildRouter(
config,
loggerToWinstonLogger(logger),
httpAuth,
permissions,
),
);
},
});
},
Expand Down
5 changes: 4 additions & 1 deletion plugins/ocm-common/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,8 @@
"plugin"
],
"homepage": "https://janus-idp.io/",
"bugs": "https://github.com/janus-idp/backstage-plugins/issues"
"bugs": "https://github.com/janus-idp/backstage-plugins/issues",
"dependencies": {
"@backstage/plugin-permission-common": "^0.7.13"
}
}
Loading
Loading