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,78 @@
import { frodo } from '@rockcarver/frodo-lib';
import { Option } from 'commander';

import { configManagerImportAuthzPolicy } from '../../../configManagerOps/FrConfigAuthzPoliciesOps';
import { getTokens } from '../../../ops/AuthenticateOps';
import { printMessage } 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 authz-policies',
deploymentTypes
);

program
.description('Import authorization policies.')
.addOption(
new Option(
'-r, --realm <realm>',
'Specifies the realm to import from. Only policy sets from this realm will be imported.'
)
)
.addOption(
new Option(
'-n, --policy-name <set-name>',
'Policy set name. If specified, only the policy set with the specified name is imported.'
)
)

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

if (options.name && !options.realm) {
printMessage(
'The -n/--policy-name option requires -r/--realm to be specified.',
'error'
);
program.help();
process.exitCode = 1;
return;
}

if (await getTokens(false, true, deploymentTypes)) {
printMessage(
`Importing organization privileges config for authz policies`
);
const outcome = await configManagerImportAuthzPolicy(
options.realm,
options.name
);
if (!outcome) process.exitCode = 1;
} 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 @@ -4,6 +4,7 @@ import Audit from './config-manager-push-audit';
import Authentication from './config-manager-push-authentication';
import ConnectorDefinitions from './config-manager-push-connector-definitions';
import CookieDomains from './config-manager-push-cookie-domain';
import AuthzPolicies from './config-manager-push-authz-policies';
import EmailProvider from './config-manager-push-email-provider';
import EmailTemplates from './config-manager-push-email-templates';
import Endpoints from './config-manager-push-endpoints';
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(AuthzPolicies().name('authz-policies'));
return program;
}
96 changes: 96 additions & 0 deletions src/configManagerOps/FrConfigAuthzPoliciesOps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@ import { frodo, state } from '@rockcarver/frodo-lib';
import { PolicySkeleton } from '@rockcarver/frodo-lib/types/api/PoliciesApi';
import { PolicySetSkeleton } from '@rockcarver/frodo-lib/types/api/PolicySetApi';
import { ResourceTypeSkeleton } from '@rockcarver/frodo-lib/types/api/ResourceTypesApi';
import { PolicySetExportInterface } from '@rockcarver/frodo-lib/types/ops/PolicySetOps';
import fs from 'fs';
import { readFile } from 'fs/promises';

import { printError, verboseMessage } from '../utils/Console';

const { getFilePath, saveJsonToFile } = frodo.utils;
const { policySet, policy, resourceType } = frodo.authz;
const { importPolicySet, importPolicySets } = frodo.authz.policySet;
const { readRealms } = frodo.realm;

type ByName = { policySetName: string };
Expand Down Expand Up @@ -228,3 +231,96 @@ export async function configManagerExportAuthzPoliciesAll(): Promise<boolean> {
return false;
}
}

/**
* Import authz policy sets
* @param realm optional realm to import to
* @param name optional name to import
* @returns {Promise<boolean>} true if all imports were successful
*/
export async function configManagerImportAuthzPolicy(
realm: string,
name: string
): Promise<boolean> {
try {
let realmsToProcess: string[];
if (realm) {
realmsToProcess = [realm];
} else {
const realmsDir = getFilePath('realms/');
realmsToProcess = fs
.readdirSync(realmsDir, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name);
}

for (const realmName of realmsToProcess) {
state.setRealm(realmName);

const realmAuthzDir = `realms/${realmName}/authorization`;

const policySetsDir = getFilePath(`${realmAuthzDir}/policy-sets`);
const psDirs = name
? [name]
: fs.existsSync(policySetsDir)
? fs.readdirSync(policySetsDir)
: [];

const policyset: Record<string, any> = {};
const policyMap: Record<string, any> = {};
const referencedResourceTypeUuids: Set<string> = new Set();

for (const psDir of psDirs) {
const psFilePath = `${policySetsDir}/${psDir}/${psDir}.json`;
const psData = JSON.parse(fs.readFileSync(psFilePath, 'utf8'));
policyset[psData.name] = psData;
psData.resourceTypeUuids?.forEach((id: string) =>
referencedResourceTypeUuids.add(id)
);

const policiesDir = `${policySetsDir}/${psDir}/policies`;
for (const file of fs.readdirSync(policiesDir)) {
if (file.endsWith('.json')) {
const pData = JSON.parse(
fs.readFileSync(`${policiesDir}/${file}`, 'utf8')
);
policyMap[pData.name] = pData;
}
}
}

const resourcetype: Record<string, any> = {};
const resourceTypesDir = getFilePath(`${realmAuthzDir}/resource-types`);
if (fs.existsSync(resourceTypesDir)) {
for (const file of fs.readdirSync(resourceTypesDir)) {
if (file.endsWith('.json')) {
const rtData = JSON.parse(
fs.readFileSync(`${resourceTypesDir}/${file}`, 'utf8')
);
if (!name || referencedResourceTypeUuids.has(rtData.uuid)) {
resourcetype[rtData.uuid] = rtData;
}
}
}
}

const importData: PolicySetExportInterface = {
script: {},
resourcetype,
policy: policyMap,
policyset,
};

if (name) {
await importPolicySet(name, importData);
} else {
await importPolicySets(importData);
}
}

return true;
} catch (error) {
printError(error);
return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

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

[Experimental] Import authorization policies.

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:
-n, --policy-name <set-name> Policy set name. If specified, only the policy
set with the specified name is imported.
-r, --realm <realm> Specifies the realm to import from. Only policy
sets from this realm will be imported.
-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 @@ -16,6 +16,7 @@ Commands:
access-config [Experimental] Import access configuration.
audit [Experimental] Import audit configuration.
authentication [Experimental] Import authentication objects.
authz-policies [Experimental] Import authorization policies.
connector-definitions [Experimental] Import connector definitions.
cookie-domains [Experimental] Import cookie domains.
email-provider [Experimental] Import email provider configuration.
Expand Down
10 changes: 10 additions & 0 deletions test/client_cli/en/config-manager-push-authz-polocies.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 authz-policies --help';
const { stdout } = await exec(CMD);

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

exports[`frodo config-manager push authz-policies "frodo config-manager push authz-policies -D test/e2e/exports/fr-config-manager/forgeops -m forgeops": should import the authz-policies into forgeops" 1`] = `""`;

exports[`frodo config-manager push authz-policies "frodo config-manager push authz-policies -n test_id -r alpha-D test/e2e/exports/fr-config-manager/forgeops -m forgeops": should import a specific auth policy by name into forgeops" 1`] = `""`;

exports[`frodo config-manager push authz-policies "frodo config-manager push authz-policies -r alpha -D test/e2e/exports/fr-config-manager/forgeops -m forgeops": should import a specific authz policy by name into forgeops" 1`] = `""`;
94 changes: 94 additions & 0 deletions test/e2e/config-manager-push-authz-policies.e2e.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/**
* 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 authz-policies -D test/e2e/exports/fr-config-manager/forgeops -m forgeops
FRODO_MOCK=record FRODO_NO_CACHE=1 FRODO_HOST=https://nightly.gcp.forgeops.com/am frodo config-manager push authz-policies -n test_id -r alpha -D test/e2e/exports/fr-config-manager/forgeops -m forgeops
FRODO_MOCK=record FRODO_NO_CACHE=1 FRODO_HOST=https://nightly.gcp.forgeops.com/am frodo config-manager push authz-policies -r alpha -D test/e2e/exports/fr-config-manager/forgeops -m forgeops
*/

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

const exec = promisify(cp.exec);

process.env['FRODO_MOCK'] = '1';
const forgeopsEnv = getEnv(fc);

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

describe('frodo config-manager push authz-policies', () => {
test(`"frodo config-manager push authz-policies -D ${allDirectory} -m forgeops": should import the authz-policies into forgeops"`, async () => {
const CMD = `frodo config-manager push authz-policies -D ${allDirectory} -m forgeops`;
const { stdout } = await exec(CMD, forgeopsEnv);
expect(removeAnsiEscapeCodes(stdout)).toMatchSnapshot();
});
test(`"frodo config-manager push authz-policies -r alpha -D ${allDirectory} -m forgeops": should import a specific authz policy by name into forgeops"`, async () => {
const CMD = `frodo config-manager push authz-policies -r alpha -D ${allDirectory} -m forgeops`;
const { stdout } = await exec(CMD, {
env: {
...forgeopsEnv.env,
FRODO_REALM: 'alpha'
}
});
expect(removeAnsiEscapeCodes(stdout)).toMatchSnapshot();
});
test(`"frodo config-manager push authz-policies -n test_id -r alpha-D ${allDirectory} -m forgeops": should import a specific auth policy by name into forgeops"`, async () => {
const CMD = `frodo config-manager push authz-policies -n test_id -r alpha -D ${allDirectory} -m forgeops`;
const { stdout } = await exec(CMD, {
env: {
...forgeopsEnv.env,
FRODO_REALM: 'alpha'
}
});
expect(removeAnsiEscapeCodes(stdout)).toMatchSnapshot();
});
});
Loading