Added tests to plugin vault & vault-backend
Signed-off-by: ivgo <ivgo@spreadgroup.com>
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* Copyright 2022 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 { ConfigReader } from '@backstage/config';
|
||||
import { getVaultConfig } from './config';
|
||||
|
||||
describe('GetVaultConfig', () => {
|
||||
it('fails by missing keys', () => {
|
||||
expect(() => getVaultConfig(new ConfigReader({}))).toThrow();
|
||||
expect(() =>
|
||||
getVaultConfig(
|
||||
new ConfigReader({
|
||||
vault: {},
|
||||
}),
|
||||
),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it('loads default params', () => {
|
||||
const config = new ConfigReader({
|
||||
vault: {
|
||||
sourceUrl: 'http://www.example.com',
|
||||
token: '123',
|
||||
},
|
||||
});
|
||||
|
||||
const vaultConfig = getVaultConfig(config);
|
||||
expect(vaultConfig).toStrictEqual({
|
||||
sourceUrl: 'http://www.example.com',
|
||||
token: '123',
|
||||
kvVersion: 2,
|
||||
secretEngine: 'secrets',
|
||||
});
|
||||
});
|
||||
|
||||
it('loads custom params', () => {
|
||||
const config = new ConfigReader({
|
||||
vault: {
|
||||
sourceUrl: 'http://www.example.com',
|
||||
token: '123',
|
||||
kvVersion: 1,
|
||||
secretEngine: 'test',
|
||||
},
|
||||
});
|
||||
|
||||
const vaultConfig = getVaultConfig(config);
|
||||
expect(vaultConfig).toStrictEqual({
|
||||
sourceUrl: 'http://www.example.com',
|
||||
token: '123',
|
||||
kvVersion: 1,
|
||||
secretEngine: 'test',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright 2022 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 { Config } from '@backstage/config';
|
||||
|
||||
/**
|
||||
* The configuration needed for the vault-backend plugin
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
export interface VaultConfig {
|
||||
/**
|
||||
* The sourceUrl for your Vault instance.
|
||||
*/
|
||||
sourceUrl: string;
|
||||
|
||||
/**
|
||||
* The token used by Backstage to access Vault.
|
||||
*/
|
||||
token: string;
|
||||
|
||||
/**
|
||||
* The secret engine name where in vault. Defaults to `secrets`.
|
||||
*/
|
||||
secretEngine: string;
|
||||
|
||||
/**
|
||||
* The version of the K/V API. Defaults to `2`.
|
||||
*/
|
||||
kvVersion: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the Vault config from a config object
|
||||
*
|
||||
* @public
|
||||
*
|
||||
* @param config - The config object to extract from
|
||||
*/
|
||||
export function getVaultConfig(config: Config): VaultConfig {
|
||||
return {
|
||||
sourceUrl: config.getString('vault.sourceUrl'),
|
||||
token: config.getString('vault.token'),
|
||||
kvVersion: config.getOptionalNumber('vault.kvVersion') ?? 2,
|
||||
secretEngine: config.getOptionalString('vault.secretEngine') ?? 'secrets',
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright 2022 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.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Copyright 2022 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.
|
||||
*/
|
||||
export * from './config';
|
||||
@@ -13,6 +13,7 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { Config } from '@backstage/config';
|
||||
import { Logger } from 'winston';
|
||||
import express, { Router } from 'express';
|
||||
@@ -58,8 +59,6 @@ export class VaultBuilder {
|
||||
|
||||
const router = this.buildRouter(this.vaultClient);
|
||||
|
||||
await this.renewToken(this.vaultClient);
|
||||
|
||||
return {
|
||||
router: router,
|
||||
};
|
||||
@@ -97,6 +96,11 @@ export class VaultBuilder {
|
||||
const router = Router();
|
||||
router.use(express.json());
|
||||
|
||||
router.get('/health', (_, response) => {
|
||||
this.env.logger.info('PONG!');
|
||||
response.send({ status: 'ok' });
|
||||
});
|
||||
|
||||
router.get('/v1/secrets', async (req, res) => {
|
||||
const path = req.query.path;
|
||||
if (typeof path !== 'string') {
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* 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 { getVoidLogger } from '@backstage/backend-common';
|
||||
import { ConfigReader } from '@backstage/config';
|
||||
import express from 'express';
|
||||
import request from 'supertest';
|
||||
|
||||
import { createRouter } from './router';
|
||||
|
||||
describe('createRouter', () => {
|
||||
let app: express.Express;
|
||||
|
||||
beforeAll(async () => {
|
||||
const router = await createRouter({
|
||||
logger: getVoidLogger(),
|
||||
config: new ConfigReader({
|
||||
vault: {
|
||||
sourceUrl: 'https://www.example.com',
|
||||
token: '1234567890',
|
||||
},
|
||||
}),
|
||||
});
|
||||
app = express().use(router);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
});
|
||||
|
||||
describe('GET /health', () => {
|
||||
it('returns ok', async () => {
|
||||
const response = await request(app).get('/health');
|
||||
|
||||
expect(response.status).toEqual(200);
|
||||
expect(response.body).toEqual({ status: 'ok' });
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* 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 { setupRequestMockHandlers } from '@backstage/backend-test-utils';
|
||||
import { rest } from 'msw';
|
||||
import { setupServer } from 'msw/node';
|
||||
import { Secret, VaultClient, VaultSecretList } from './vaultApi';
|
||||
import { ConfigReader } from '@backstage/config';
|
||||
|
||||
describe('VaultApi', () => {
|
||||
const server = setupServer();
|
||||
setupRequestMockHandlers(server);
|
||||
|
||||
const mockBaseUrl = 'https://api-vault.com';
|
||||
const config = new ConfigReader({
|
||||
vault: {
|
||||
sourceUrl: mockBaseUrl,
|
||||
token: '1234567890',
|
||||
},
|
||||
});
|
||||
|
||||
const mockListResult: VaultSecretList = {
|
||||
data: {
|
||||
keys: ['secret::one', 'secret::two'],
|
||||
},
|
||||
};
|
||||
const mockListResultEmpty: VaultSecretList = {
|
||||
data: {
|
||||
keys: [],
|
||||
},
|
||||
};
|
||||
|
||||
const mockSecretsResult: Secret[] = [
|
||||
{
|
||||
name: 'secret::one',
|
||||
editUrl: `${mockBaseUrl}/ui/vault/secrets/secrets/edit/test/success/secret::one`,
|
||||
showUrl: `${mockBaseUrl}/ui/vault/secrets/secrets/show/test/success/secret::one`,
|
||||
},
|
||||
{
|
||||
name: 'secret::two',
|
||||
editUrl: `${mockBaseUrl}/ui/vault/secrets/secrets/edit/test/success/secret::two`,
|
||||
showUrl: `${mockBaseUrl}/ui/vault/secrets/secrets/show/test/success/secret::two`,
|
||||
},
|
||||
];
|
||||
|
||||
const setupHandlers = () => {
|
||||
server.use(
|
||||
rest.get(
|
||||
`${mockBaseUrl}/v1/secrets/metadata/test/success`,
|
||||
(_, res, ctx) => {
|
||||
return res(ctx.json(mockListResult));
|
||||
},
|
||||
),
|
||||
rest.get(
|
||||
`${mockBaseUrl}/v1/secrets/metadata/test/error`,
|
||||
(_, res, ctx) => {
|
||||
return res(ctx.json(mockListResultEmpty));
|
||||
},
|
||||
),
|
||||
rest.post(`${mockBaseUrl}/v1/auth/token/renew-self`, (_, res, ctx) => {
|
||||
return res(ctx.json({ auth: { client_token: '0987654321' } }));
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
it('should return secrets', async () => {
|
||||
setupHandlers();
|
||||
const api = new VaultClient({ config });
|
||||
const secrets = await api.listSecrets('test/success');
|
||||
expect(secrets).toEqual(mockSecretsResult);
|
||||
});
|
||||
|
||||
it('should return empty secret list', async () => {
|
||||
setupHandlers();
|
||||
const api = new VaultClient({ config });
|
||||
const secrets = await api.listSecrets('test/error');
|
||||
expect(secrets).toEqual([]);
|
||||
});
|
||||
|
||||
it('should return success token renew', async () => {
|
||||
setupHandlers();
|
||||
const api = new VaultClient({ config });
|
||||
const apiRenew = await api.renewToken();
|
||||
expect(apiRenew).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should render frontend url', () => {
|
||||
const api = new VaultClient({ config });
|
||||
const url = api.getFrontendSecretsUrl();
|
||||
expect(url).toEqual(`${mockBaseUrl}/ui/vault/secrets/secrets`);
|
||||
});
|
||||
});
|
||||
@@ -16,20 +16,21 @@
|
||||
|
||||
import { Config } from '@backstage/config';
|
||||
import fetch from 'cross-fetch';
|
||||
import { getVaultConfig, VaultConfig } from '../config';
|
||||
|
||||
type VaultSecretList = {
|
||||
export type VaultSecretList = {
|
||||
data: {
|
||||
keys: string[];
|
||||
};
|
||||
};
|
||||
|
||||
type Secret = {
|
||||
export type Secret = {
|
||||
name: string;
|
||||
showUrl: string;
|
||||
editUrl: string;
|
||||
};
|
||||
|
||||
type RenewTokenResponse = {
|
||||
export type RenewTokenResponse = {
|
||||
auth: {
|
||||
client_token: string;
|
||||
};
|
||||
@@ -42,17 +43,10 @@ export interface VaultApi {
|
||||
}
|
||||
|
||||
export class VaultClient implements VaultApi {
|
||||
private readonly vaultUrl: string;
|
||||
private vaultToken: string;
|
||||
private readonly kvVersion: number;
|
||||
private readonly secretEngineName: string;
|
||||
private vaultConfig: VaultConfig;
|
||||
|
||||
constructor({ config }: { config: Config }) {
|
||||
this.vaultUrl = config.getString('vault.sourceUrl');
|
||||
this.vaultToken = config.getString('vault.token');
|
||||
this.kvVersion = config.getOptionalNumber('vault.kvVersion') ?? 2;
|
||||
this.secretEngineName =
|
||||
config.getOptionalString('vault.secretEngine') ?? 'secrets';
|
||||
this.vaultConfig = getVaultConfig(config);
|
||||
}
|
||||
|
||||
private async callApi<T>(
|
||||
@@ -61,12 +55,14 @@ export class VaultClient implements VaultApi {
|
||||
method: string = 'GET',
|
||||
): Promise<T | undefined> {
|
||||
const response = await fetch(
|
||||
`${this.vaultUrl}/${path}?${new URLSearchParams(query).toString()}`,
|
||||
`${this.vaultConfig.sourceUrl}/${path}?${new URLSearchParams(
|
||||
query,
|
||||
).toString()}`,
|
||||
{
|
||||
method,
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'X-Vault-Token': this.vaultToken,
|
||||
'X-Vault-Token': this.vaultConfig.token,
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -82,14 +78,14 @@ export class VaultClient implements VaultApi {
|
||||
}
|
||||
|
||||
getFrontendSecretsUrl(): string {
|
||||
return `${this.vaultUrl}/ui/vault/secrets/${this.secretEngineName}`;
|
||||
return `${this.vaultConfig.sourceUrl}/ui/vault/secrets/${this.vaultConfig.secretEngine}`;
|
||||
}
|
||||
|
||||
async listSecrets(secretPath: string): Promise<Secret[]> {
|
||||
const listUrl =
|
||||
this.kvVersion === 2
|
||||
? `v1/${this.secretEngineName}/metadata/${secretPath}`
|
||||
: `v1/${this.secretEngineName}/${secretPath}`;
|
||||
this.vaultConfig.kvVersion === 2
|
||||
? `v1/${this.vaultConfig.secretEngine}/metadata/${secretPath}`
|
||||
: `v1/${this.vaultConfig.secretEngine}/${secretPath}`;
|
||||
const result = await this.callApi<VaultSecretList>(listUrl, { list: true });
|
||||
if (!result) {
|
||||
return [];
|
||||
@@ -105,8 +101,8 @@ export class VaultClient implements VaultApi {
|
||||
} else {
|
||||
secrets.push({
|
||||
name: secret,
|
||||
editUrl: `${this.vaultUrl}/ui/vault/secrets/${this.secretEngineName}/edit/${secretPath}/${secret}`,
|
||||
showUrl: `${this.vaultUrl}/ui/vault/secrets/${this.secretEngineName}/show/${secretPath}/${secret}`,
|
||||
editUrl: `${this.vaultConfig.sourceUrl}/ui/vault/secrets/${this.vaultConfig.secretEngine}/edit/${secretPath}/${secret}`,
|
||||
showUrl: `${this.vaultConfig.sourceUrl}/ui/vault/secrets/${this.vaultConfig.secretEngine}/show/${secretPath}/${secret}`,
|
||||
});
|
||||
}
|
||||
}),
|
||||
@@ -125,7 +121,7 @@ export class VaultClient implements VaultApi {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.vaultToken = result.auth.client_token;
|
||||
this.vaultConfig.token = result.auth.client_token;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user