Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { frodo } from '@rockcarver/frodo-lib';
import { Option } from 'commander';

import { configManagerImportSecrets } from '../../../configManagerOps/FrConfigSecretOps';
import { getTokens } from '../../../ops/AuthenticateOps';
import { printMessage, verboseMessage } from '../../../utils/Console';
import { FrodoCommand } from '../../FrodoCommand';

const { CLOUD_DEPLOYMENT_TYPE_KEY, FORGEOPS_DEPLOYMENT_TYPE_KEY } =
frodo.utils.constants;

const deploymentTypes = [
CLOUD_DEPLOYMENT_TYPE_KEY,
FORGEOPS_DEPLOYMENT_TYPE_KEY,
];

export default function setup() {
const program = new FrodoCommand(
'frodo config-manager push secrets',
[],
deploymentTypes
);

program
.description('Import secrets.')
.addOption(
new Option(
'-n, --name <name>',
'Secret name; import only the specified secret'
)
)
.addOption(
new Option(
'-e, --env <values>',
'Value to set for the secret. Will override .env files and environment variables.'
)
)

.action(async (host, realm, user, password, options, command) => {
command.handleDefaultArgsAndOpts(
host,
realm,
user,
password,
options,
command
);

if (await getTokens(false, true, deploymentTypes)) {
verboseMessage('Importing secrets');
const outcome = await configManagerImportSecrets(
options.name,
options.env
);
if (!outcome) process.exitCode = 1;
}
// unrecognized combination of options or no options
else {
printMessage(
'Unrecognized combination of options or no options...',
'error'
);
program.help();
process.exitCode = 1;
}
});

return program;
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import OrgPrivileges from './config-manager-push-org-privileges';
import PasswordPolicy from './config-manager-push-password-policy';
import Schedules from './config-manager-push-schedules';
import ServiceObjects from './config-manager-push-service-objects';
import Secrets from './config-manager-push-secrets';
import TermsAndConditions from './config-manager-push-terms-and-conditions';
import Themes from './config-manager-push-themes';
import UiConfig from './config-manager-push-ui-config';
Expand Down Expand Up @@ -43,6 +44,6 @@ export default function setup() {
program.addCommand(UiConfig().name('ui-config'));
program.addCommand(Authentication().name('authentication'));
program.addCommand(ConnectorDefinitions().name('connector-definitions'));

program.addCommand(Secrets().name('secrets'));
return program;
}
133 changes: 130 additions & 3 deletions src/configManagerOps/FrConfigSecretOps.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { frodo } from '@rockcarver/frodo-lib';
import { frodo, FrodoError } from '@rockcarver/frodo-lib';
import { SecretSkeleton } from '@rockcarver/frodo-lib/types/api/cloud/SecretsApi';
import { SecretsExportInterface } from '@rockcarver/frodo-lib/types/ops/cloud/SecretsOps';
import fs from 'fs';

import {
createProgressIndicator,
Expand All @@ -9,8 +10,14 @@ import {
updateProgressIndicator,
} from '../utils/Console';

const { getFilePath, saveJsonToFile } = frodo.utils;
const { readSecrets, exportSecret } = frodo.cloud.secret;
const { getFilePath, saveJsonToFile, readToJson, loadEnvFile } = frodo.utils;
const {
readSecrets,
exportSecret,
createSecret,
createVersionOfSecret,
readSecret,
} = frodo.cloud.secret;

/**
* Export all secrets to individual files in fr-config-manager format
Expand Down Expand Up @@ -87,3 +94,123 @@ export async function configManagerExportSecrets(
}
return false;
}

export function resolvePlaceholder(
placeholder: string,
envFile: Record<string, string> = {}
): string {
const match = placeholder.match(/^\$\{(BASE64:)?(.+)\}$/);
if (!match) {
throw new FrodoError(`Invalid placeholder format: ${placeholder}`);
}
const isBase64 = !!match[1];
const name = match[2];

let value: string;
if (name in envFile) {
value = envFile[name];
} else if (name in process.env) {
value = process.env[name];
} else {
throw new FrodoError(`No value found for ${name}`);
}
return isBase64 ? value : Buffer.from(value).toString('base64');
}

export async function configManagerImportSecrets(
secretName?: string,
value?: string
): Promise<boolean> {
const errors = [];
const spinnerId = createProgressIndicator(
'indeterminate',
0,
`Reading secrets...`
);
let indicatorId: string;
try {
const secretsDir = getFilePath(`esvs/secrets/`);
if (!fs.existsSync(secretsDir)) {
stopProgressIndicator(spinnerId, `No secrets found`, 'fail');
return true;
}

const fileNames = fs
.readdirSync(secretsDir)
.filter((name) => name.toLowerCase().endsWith('.json'))
.filter((name) => !secretName || name === secretName);

if (fileNames.length === 0) {
stopProgressIndicator(
spinnerId,
secretName
? `No matching secret found for ${secretName}`
: 'No secrets found to import',
'fail'
);
return true;
}

stopProgressIndicator(
spinnerId,
`Successfully read ${fileNames.length} secrets.`,
'success'
);

const envFile = loadEnvFile();

indicatorId = createProgressIndicator(
'determinate',
fileNames.length,
'Importing secrets'
);

for (const fileName of fileNames) {
try {
const importData = readToJson(`${secretsDir}/${fileName}`, {overrideValue: value, envFile, base64Encode: false})
const secretValue = importData.valueBase64

if (!secretValue){
throw new FrodoError(
`No value provided for secret ${importData._id}`
)
}

let exists = true;
try {
await readSecret(importData._id);
} catch {
exists = false;
}

if (exists) {
await createVersionOfSecret(importData._id, secretValue);
} else {
await createSecret(
importData._id,
secretValue,
importData.description,
importData.encoding,
importData.useInPlaceholders
);
}
updateProgressIndicator(
indicatorId,
`Imported secret ${importData._id}`
);
} catch (error) {
errors.push(error);
}
}

if (errors.length > 0) {
throw new FrodoError(`Error importing secrets`, errors);
}
stopProgressIndicator(indicatorId, `${fileNames.length} secrets imported.`);
return true;
} catch (error) {
stopProgressIndicator(indicatorId, `Error importing secrets`, 'fail');
printError(error);
return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`CLI help interface for 'config-manager push secrets' should be expected english 1`] = `
"Usage: frodo config-manager push secrets [options] [host] [realm] [username] [password]

[Experimental] Import secrets.

Arguments:
host AM base URL, e.g.: https://cdk.iam.example.com/am. To use
a connection profile, just specify a unique substring or
alias.
realm Realm. Specify realm as '/' for the root realm or 'realm'
or '/parent/child' otherwise. (default: "alpha" for
Identity Cloud tenants, "/" otherwise.)
username Username to login with. Must be an admin user with
appropriate rights to manage authentication
journeys/trees.
password Password.

Options:
-e, --env <values> Value to set for the secret. Will override .env files and
environment variables.
-n, --name <name> Secret name; import only the specified secret
-h, --help Help
-hh, --help-more Help with all options.
-hhh, --help-all Help with all options, environment variables, and usage
examples.
"
`;
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ Commands:
org-privileges [Experimental] Import organization privileges config.
password-policy [Experimental] Import password-policy objects.
schedules [Experimental] Import schedules.
secrets [Experimental] Import secrets.
service-objects [Experimental] Import service objects.
terms-and-conditions [Experimental] Import terms and conditions.
themes [Experimental] Import themes.
Expand Down
10 changes: 10 additions & 0 deletions test/client_cli/en/config-manager-push-secrets.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import cp from 'child_process';
import { promisify } from 'util';

const exec = promisify(cp.exec);
const CMD = 'frodo config-manager push secrets --help';
const { stdout } = await exec(CMD);

test("CLI help interface for 'config-manager push secrets' should be expected english", async () => {
expect(stdout).toMatchSnapshot();
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`frodo config-manager push secrets "frodo config-manager push secrets -D test/e2e/exports/fr-config-manager/cloud ": should import the secrets into cloud" 1`] = `""`;

exports[`frodo config-manager push secrets "frodo config-manager push secrets -n esv-fr-test-secret -e my-test-value test/e2e/exports/fr-config-manager/cloud": should import the specified secret into cloud 1`] = `""`;
86 changes: 86 additions & 0 deletions test/e2e/config-manager-push-secrets.e2e.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/**
* Follow this process to write e2e tests for the CLI project:
*
* 1. Test if all the necessary mocks for your tests already exist.
* In mock mode, run the command you want to test with the same arguments
* and parameters exactly as you want to test it, for example:
*
* $ FRODO_MOCK=1 frodo conn save https://openam-frodo-dev.forgeblocks.com/am volker.scheuber@forgerock.com Sup3rS3cr3t!
*
* If your command completes without errors and with the expected results,
* all the required mocks already exist and you are good to write your
* test and skip to step #4.
*
* If, however, your command fails and you see errors like the one below,
* you know you need to record the mock responses first:
*
* [Polly] [adapter:node-http] Recording for the following request is not found and `recordIfMissing` is `false`.
*
* 2. Record mock responses for your exact command.
* In mock record mode, run the command you want to test with the same arguments
* and parameters exactly as you want to test it, for example:
*
* $ FRODO_MOCK=record frodo conn save https://openam-frodo-dev.forgeblocks.com/am volker.scheuber@forgerock.com Sup3rS3cr3t!
*
* Wait until you see all the Polly instances (mock recording adapters) have
* shutdown before you try to run step #1 again.
* Messages like these indicate mock recording adapters shutting down:
*
* Polly instance 'conn/4' stopping in 3s...
* Polly instance 'conn/4' stopping in 2s...
* Polly instance 'conn/save/3' stopping in 3s...
* Polly instance 'conn/4' stopping in 1s...
* Polly instance 'conn/save/3' stopping in 2s...
* Polly instance 'conn/4' stopped.
* Polly instance 'conn/save/3' stopping in 1s...
* Polly instance 'conn/save/3' stopped.
*
* 3. Validate your freshly recorded mock responses are complete and working.
* Re-run the exact command you want to test in mock mode (see step #1).
*
* 4. Write your test.
* Make sure to use the exact command including number of arguments and params.
*
* 5. Commit both your test and your new recordings to the repository.
* Your tests are likely going to reside outside the frodo-lib project but
* the recordings must be committed to the frodo-lib project.
*/

/*
// ForgeOps
FRODO_MOCK=record FRODO_NO_CACHE=1 FRODO_HOST=https://nightly.gcp.forgeops.com/am frodo config-manager push secrets -D test/e2e/exports/fr-config-manager/cloud
FRODO_MOCK=record FRODO_NO_CACHE=1 FRODO_HOST=https://nightly.gcp.forgeops.com/am frodo config-manager push secrets -n esv-fr-test-secret -e my-test-value -D test/e2e/exports/fr-config-manager/cloud


*/

import cp from 'child_process';
import { promisify } from 'util';
import { getEnv, removeAnsiEscapeCodes } from './utils/TestUtils';
import { connection as c } from './utils/TestConfig';

const exec = promisify(cp.exec);

process.env['FRODO_MOCK'] = '1';
const cloudEnv = getEnv(c);

const allDirectory = "test/e2e/exports/fr-config-manager/cloud";

describe('frodo config-manager push secrets', () => {
test(`"frodo config-manager push secrets -D ${allDirectory} ": should import the secrets into cloud"`, async () => {
const CMD = `frodo config-manager push secrets -D ${allDirectory} `;
const { stdout, stderr } = await exec(CMD, {
env: {
...cloudEnv.env,
ESV_FR_TEST_SECRET: "my-fr-test-secret-value",
ESV_TEST_SECRET: "my-test-secret-value"
}
});
expect(removeAnsiEscapeCodes(stdout)).toMatchSnapshot();
});
test(`"frodo config-manager push secrets -n esv-fr-test-secret -e my-test-value ${allDirectory}": should import the specified secret into cloud`, async () => {
const CMD = `frodo config-manager push secrets -n esv-fr-test-secret -e my-test-value -D ${allDirectory}`;
const { stdout } = await exec(CMD, cloudEnv);
expect(removeAnsiEscapeCodes(stdout)).toMatchSnapshot();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"_id": "esv-fr-test-secret",
"description": "this is a fr-config manager test secret",
"encoding": "generic",
"useInPlaceholders": true,
"valueBase64": "${ESV_FR_TEST_SECRET}"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"_id": "esv-test-secret",
"description": "This is a frodo test",
"encoding": "generic",
"useInPlaceholders": true,
"valueBase64": "${ESV_TEST_SECRET}"
}
Loading