From 05dbcb67c7ef51f895cfa83814f82d7615bdb87c Mon Sep 17 00:00:00 2001 From: Shaun Colley <80714407+swcolley@users.noreply.github.com> Date: Wed, 25 Jan 2023 14:48:07 -0600 Subject: [PATCH] feat(IAM Policy Management): add support for v2/policies (#180) * feat(IAM Policy Management): add support for v2/policies Signed-off-by: Shaun Colley * fix(IAM Policy Management): update time-based condition example and pattern, update property names based on API definition changes, and add support for tags Signed-off-by: Shaun Colley --- examples/iam-policy-management.v1.test.js | 276 +++- iam-policy-management/v1.ts | 1289 ++++++++++++++--- .../iam-policy-management.v1.test.js | 240 ++- test/unit/iam-policy-management.v1.test.js | 702 ++++++++- 4 files changed, 2232 insertions(+), 275 deletions(-) diff --git a/examples/iam-policy-management.v1.test.js b/examples/iam-policy-management.v1.test.js index f9b50a9d..f0d2071b 100644 --- a/examples/iam-policy-management.v1.test.js +++ b/examples/iam-policy-management.v1.test.js @@ -57,6 +57,7 @@ describe('IamPolicyManagementV1', () => { let examplePolicyETag; let exampleCustomRoleId; let exampleCustomRoleEtag; + const exampleCustomRoleDipslayName = 'IAM Groups read access'; const exampleUserId = 'IBMid-user1'; const exampleServiceName = 'iam-groups'; @@ -169,7 +170,7 @@ describe('IamPolicyManagementV1', () => { // end-get_policy }); - test('updatePolicy request example', async () => { + test('replacePolicy request example', async () => { expect(exampleAccountId).not.toBeNull(); expect(examplePolicyId).toBeDefined(); expect(examplePolicyETag).toBeDefined(); @@ -183,7 +184,7 @@ describe('IamPolicyManagementV1', () => { expect(true).toBeFalsy(); }); - originalLog('updatePolicy() result:'); + originalLog('replacePolicy() result:'); // begin-update_policy const policySubjects = [ @@ -232,7 +233,7 @@ describe('IamPolicyManagementV1', () => { }; try { - const res = await iamPolicyManagementService.updatePolicy(params); + const res = await iamPolicyManagementService.replacePolicy(params); examplePolicyETag = res.headers.etag; console.log(JSON.stringify(res.result, null, 2)); } catch (err) { @@ -241,7 +242,7 @@ describe('IamPolicyManagementV1', () => { // end-update_policy }); - test('patchPolicy request example', async () => { + test('updatePolicyState request example', async () => { expect(examplePolicyId).toBeDefined(); expect(examplePolicyETag).toBeDefined(); @@ -254,7 +255,7 @@ describe('IamPolicyManagementV1', () => { expect(true).toBeFalsy(); }); - originalLog('patchPolicy() result:'); + originalLog('updatePolicyState() result:'); // begin-patch_policy const params = { @@ -264,7 +265,7 @@ describe('IamPolicyManagementV1', () => { }; try { - const res = await iamPolicyManagementService.patchPolicy(params); + const res = await iamPolicyManagementService.updatePolicyState(params); console.log(JSON.stringify(res.result, null, 2)); } catch (err) { console.warn(err) @@ -327,6 +328,260 @@ describe('IamPolicyManagementV1', () => { // end-delete_policy }); + test('createV2Policy request example', async () => { + expect(exampleAccountId).not.toBeNull(); + + consoleLogMock.mockImplementation(output => { + originalLog(output); + }); + consoleWarnMock.mockImplementation(output => { + originalWarn(output); + expect(true).toBeFalsy(); + }); + + originalLog('createV2Policy() result:'); + // begin-create_v2_policy + + const policySubject = { + attributes: [ + { + key: 'iam_id', + operator: 'stringEquals', + value: exampleUserId, + }, + ], + }; + const policyResourceAccountAttribute = { + key: 'accountId', + value: exampleAccountId, + operator: 'stringEquals', + }; + const policyResourceServiceAttribute = { + key: 'serviceType', + operator: 'stringEquals', + value: 'service', + }; + const policyResource = { + attributes: [policyResourceAccountAttribute, policyResourceServiceAttribute] + }; + const policyControl = { + grant: { + roles: [{ + role_id: 'crn:v1:bluemix:public:iam::::role:Viewer', + }], + } + }; + const policyRule = { + operator: 'and', + conditions: [ + { + key: '{{environment.attributes.day_of_week}}', + operator: 'dayOfWeekAnyOf', + value: ['1+00:00', '2+00:00', '3+00:00', '4+00:00', '5+00:00'], + }, + { + key: '{{environment.attributes.current_time}}', + operator: 'timeGreaterThanOrEquals', + value: '09:00:00+00:00', + }, + { + key: '{{environment.attributes.current_time}}', + operator: 'timeLessThanOrEquals', + value: '17:00:00+00:00', + }, + ], + } + const policyPattern = 'time-based-conditions:weekly:custom-hours' + const params = { + type: 'access', + subject: policySubject, + control: policyControl, + resource: policyResource, + rule: policyRule, + pattern: policyPattern, + }; + + try { + const res = await iamPolicyManagementService.createV2Policy(params); + examplePolicyId = res.result.id; + console.log(JSON.stringify(res.result, null, 2)); + } catch (err) { + console.warn(err) + } + + // end-create_v2_policy + }); + test('getV2Policy request example', async () => { + expect(examplePolicyId).toBeDefined(); + + consoleLogMock.mockImplementation(output => { + originalLog(output); + }); + consoleWarnMock.mockImplementation(output => { + originalWarn(output); + // when the test fails we need to print out the error message and stop execution right after it + expect(true).toBeFalsy(); + }); + + originalLog('getV2Policy() result:'); + // begin-get_v2_policy + + const params = { + id: examplePolicyId, + }; + + try { + const res = await iamPolicyManagementService.getV2Policy(params); + examplePolicyETag = res.headers.etag; + console.log(JSON.stringify(res.result, null, 2)); + } catch (err) { + console.warn(err) + } + + // end-get_v2_policy + }); + test('replaceV2Policy request example', async () => { + expect(exampleAccountId).not.toBeNull(); + expect(examplePolicyId).toBeDefined(); + expect(examplePolicyETag).toBeDefined(); + + consoleLogMock.mockImplementation(output => { + originalLog(output); + }); + consoleWarnMock.mockImplementation(output => { + originalWarn(output); + // when the test fails we need to print out the error message and stop execution right after it + expect(true).toBeFalsy(); + }); + + originalLog('replaceV2Policy() result:'); + // begin-replace_v2_policy + + const policySubject = { + attributes: [ + { + key: 'iam_id', + operator: 'stringEquals', + value: exampleUserId, + }, + ], + }; + const policyResourceAccountAttribute = { + key: 'accountId', + value: exampleAccountId, + operator: 'stringEquals', + }; + const policyResourceServiceAttribute = { + key: 'serviceType', + operator: 'stringEquals', + value: 'service', + }; + const policyResource = { + attributes: [policyResourceAccountAttribute, policyResourceServiceAttribute] + }; + const updatedPolicyControl = { + grant: { + roles: [{ + role_id: 'crn:v1:bluemix:public:iam::::role:Editor', + }], + } + }; + const policyRule = { + operator: 'and', + conditions: [ + { + key: '{{environment.attributes.day_of_week}}', + operator: 'dayOfWeekAnyOf', + value: ['1+00:00', '2+00:00', '3+00:00', '4+00:00', '5+00:00'], + }, + { + key: '{{environment.attributes.current_time}}', + operator: 'timeGreaterThanOrEquals', + value: '09:00:00+00:00', + }, + { + key: '{{environment.attributes.current_time}}', + operator: 'timeLessThanOrEquals', + value: '17:00:00+00:00', + }, + ], + } + const policyPattern = 'time-based-conditions:weekly:custom-hours' + const params = { + type: 'access', + id: examplePolicyId, + ifMatch: examplePolicyETag, + subject: policySubject, + control: updatedPolicyControl, + resource: policyResource, + rule: policyRule, + pattern: policyPattern, + }; + + try { + const res = await iamPolicyManagementService.replaceV2Policy(params); + console.log(JSON.stringify(res.result, null, 2)); + } catch (err) { + console.warn(err) + } + + // end-replace_v2_policy + }); + test('listV2Policies request example', async () => { + expect(exampleAccountId).not.toBeNull(); + + consoleLogMock.mockImplementation(output => { + originalLog(output); + }); + consoleWarnMock.mockImplementation(output => { + originalWarn(output); + // when the test fails we need to print out the error message and stop execution right after it + expect(true).toBeFalsy(); + }); + + originalLog('listV2Policies() result:'); + // begin-list_v2_policy + + const params = { + accountId: exampleAccountId, + iamId: exampleUserId, + format: 'include_last_permit', + }; + + try { + const res = await iamPolicyManagementService.listV2Policies(params); + console.log(JSON.stringify(res.result, null, 2)); + } catch (err) { + console.warn(err); + } + + // end-list_v2_policy + }); + test('deleteV2Policy request example', async () => { + + consoleLogMock.mockImplementation(output => { + originalLog(output); + }); + consoleWarnMock.mockImplementation(output => { + originalWarn(output); + // when the test fails we need to print out the error message and stop execution right after it + expect(true).toBeFalsy(); + }); + + // begin-delete_v2_policy + + const params = { + id: examplePolicyId, + }; + + try { + await iamPolicyManagementService.deleteV2Policy(params); + } catch (err) { + console.warn(err); + } + + // end-delete_v2_policy + }); test('createRole request example', async () => { expect(exampleAccountId).not.toBeNull(); @@ -343,7 +598,7 @@ describe('IamPolicyManagementV1', () => { // begin-create_role const params = { - displayName: 'IAM Groups read access', + displayName: exampleCustomRoleDipslayName, actions: ['iam-groups.groups.read'], name: 'ExampleRoleIAMGroups', accountId: exampleAccountId, @@ -389,7 +644,7 @@ describe('IamPolicyManagementV1', () => { // end-get_role }); - test('updateRole request example', async () => { + test('replaceRole request example', async () => { expect(exampleCustomRoleId).toBeDefined(); expect(exampleCustomRoleEtag).toBeDefined(); @@ -402,18 +657,19 @@ describe('IamPolicyManagementV1', () => { expect(true).toBeFalsy(); }); - originalLog('updateRole() result:'); + originalLog('replaceRole() result:'); // begin-update_role const updatedRoleActions = ['iam-groups.groups.read', 'iam-groups.groups.list']; const params = { roleId: exampleCustomRoleId, ifMatch: exampleCustomRoleEtag, + displayName: exampleCustomRoleDipslayName, actions: updatedRoleActions, }; try { - const res = await iamPolicyManagementService.updateRole(params); + const res = await iamPolicyManagementService.replaceRole(params); console.log(JSON.stringify(res.result, null, 2)); } catch (err) { console.warn(err); diff --git a/iam-policy-management/v1.ts b/iam-policy-management/v1.ts index 59e22716..05c3b286 100644 --- a/iam-policy-management/v1.ts +++ b/iam-policy-management/v1.ts @@ -1,5 +1,5 @@ /** - * (C) Copyright IBM Corp. 2022. + * (C) Copyright IBM Corp. 2023. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ */ /** - * IBM OpenAPI SDK Code Generator Version: 3.62.0-a2a22f95-20221115-162524 + * IBM OpenAPI SDK Code Generator Version: 3.64.0-959a5845-20230112-195144 */ import * as extend from 'extend'; @@ -103,7 +103,9 @@ class IamPolicyManagementV1 extends BaseService { * and filter by attribute values. This can be done through query parameters. Currently, only the following attributes * are supported: account_id, iam_id, access_group_id, type, service_type, sort, format and state. account_id is a * required query parameter. Only policies that have the specified attributes and that the caller has read access to - * are returned. If the caller does not have read access to any policies an empty array is returned. + * are returned. If the caller does not have read access to any policies an empty array is returned. If a policy was + * created using the new beta v2/policies API, then the caller will see placeholder information, e.g., "unsupported + * version" for iam_id, and a valid v2/policies href. The caller should use this href to view the policy. * * @param {Object} params - The parameters to send to the service. * @param {string} params.accountId - The account GUID in which the policies belong to. @@ -375,8 +377,8 @@ class IamPolicyManagementV1 extends BaseService { * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers * @returns {Promise>} */ - public updatePolicy( - params: IamPolicyManagementV1.UpdatePolicyParams + public replacePolicy( + params: IamPolicyManagementV1.ReplacePolicyParams ): Promise> { const _params = { ...params }; const _requiredParams = ['policyId', 'ifMatch', 'type', 'subjects', 'roles', 'resources']; @@ -410,7 +412,7 @@ class IamPolicyManagementV1 extends BaseService { const sdkHeaders = getSdkHeaders( IamPolicyManagementV1.DEFAULT_SERVICE_NAME, 'v1', - 'updatePolicy' + 'replacePolicy' ); const parameters = { @@ -546,8 +548,8 @@ class IamPolicyManagementV1 extends BaseService { * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers * @returns {Promise>} */ - public patchPolicy( - params: IamPolicyManagementV1.PatchPolicyParams + public updatePolicyState( + params: IamPolicyManagementV1.UpdatePolicyStateParams ): Promise> { const _params = { ...params }; const _requiredParams = ['policyId', 'ifMatch']; @@ -568,7 +570,7 @@ class IamPolicyManagementV1 extends BaseService { const sdkHeaders = getSdkHeaders( IamPolicyManagementV1.DEFAULT_SERVICE_NAME, 'v1', - 'patchPolicy' + 'updatePolicyState' ); const parameters = { @@ -776,19 +778,19 @@ class IamPolicyManagementV1 extends BaseService { * @param {string} params.ifMatch - The revision number for updating a role and must match the ETag value of the * existing role. The Etag can be retrieved using the GET /v2/roles/{role_id} API and looking at the ETag response * header. - * @param {string} [params.displayName] - The display name of the role that is shown in the console. - * @param {string} [params.description] - The description of the role. - * @param {string[]} [params.actions] - The actions of the role. Please refer to [IAM roles and + * @param {string} params.displayName - The display name of the role that is shown in the console. + * @param {string[]} params.actions - The actions of the role. Please refer to [IAM roles and * actions](https://cloud.ibm.com/docs/account?topic=account-iam-service-roles-actions). + * @param {string} [params.description] - The description of the role. * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers * @returns {Promise>} */ - public updateRole( - params: IamPolicyManagementV1.UpdateRoleParams + public replaceRole( + params: IamPolicyManagementV1.ReplaceRoleParams ): Promise> { const _params = { ...params }; - const _requiredParams = ['roleId', 'ifMatch']; - const _validParams = ['roleId', 'ifMatch', 'displayName', 'description', 'actions', 'headers']; + const _requiredParams = ['roleId', 'ifMatch', 'displayName', 'actions']; + const _validParams = ['roleId', 'ifMatch', 'displayName', 'actions', 'description', 'headers']; const _validationErrors = validateParams(_params, _requiredParams, _validParams); if (_validationErrors) { return Promise.reject(_validationErrors); @@ -796,8 +798,8 @@ class IamPolicyManagementV1 extends BaseService { const body = { 'display_name': _params.displayName, - 'description': _params.description, 'actions': _params.actions, + 'description': _params.description, }; const path = { @@ -807,7 +809,7 @@ class IamPolicyManagementV1 extends BaseService { const sdkHeaders = getSdkHeaders( IamPolicyManagementV1.DEFAULT_SERVICE_NAME, 'v1', - 'updateRole' + 'replaceRole' ); const parameters = { @@ -926,195 +928,697 @@ class IamPolicyManagementV1 extends BaseService { return this.createRequest(parameters); } -} - -/************************* - * interfaces - ************************/ - -namespace IamPolicyManagementV1 { - /** An operation response. */ - export interface Response { - result: T; - status: number; - statusText: string; - headers: IncomingHttpHeaders; - } - - /** The callback for a service request. */ - export type Callback = (error: any, response?: Response) => void; - - /** The body of a service request that returns no response data. */ - export interface EmptyObject {} - - /** A standard JS object, defined to avoid the limitations of `Object` and `object` */ - export interface JsonObject { - [key: string]: any; - } - /************************* - * request interfaces + * v2Policies ************************/ - /** Parameters for the `listPolicies` operation. */ - export interface ListPoliciesParams { - /** The account GUID in which the policies belong to. */ - accountId: string; - /** Language code for translations - * * `default` - English - * * `de` - German (Standard) - * * `en` - English - * * `es` - Spanish (Spain) - * * `fr` - French (Standard) - * * `it` - Italian (Standard) - * * `ja` - Japanese - * * `ko` - Korean - * * `pt-br` - Portuguese (Brazil) - * * `zh-cn` - Chinese (Simplified, PRC) - * * `zh-tw` - (Chinese, Taiwan). - */ - acceptLanguage?: string; - /** Optional IAM ID used to identify the subject. */ - iamId?: string; - /** Optional access group id. */ - accessGroupId?: string; - /** Optional type of policy. */ - type?: ListPoliciesConstants.Type | string; - /** Optional type of service. */ - serviceType?: ListPoliciesConstants.ServiceType | string; - /** Optional name of the access management tag in the policy. */ - tagName?: string; - /** Optional value of the access management tag in the policy. */ - tagValue?: string; - /** Optional top level policy field to sort results. Ascending sort is default. Descending sort available by - * prepending '-' to field. Example '-last_modified_at'. - */ - sort?: ListPoliciesConstants.Sort | string; - /** Include additional data per policy returned - * * `include_last_permit` - returns details of when the policy last granted a permit decision and the number of - * times it has done so - * * `display` - returns the list of all actions included in each of the policy roles. - */ - format?: ListPoliciesConstants.Format | string; - /** The state of the policy. * `active` - returns active policies * `deleted` - returns non-active policies. */ - state?: ListPoliciesConstants.State | string; - headers?: OutgoingHttpHeaders; - } - - /** Constants for the `listPolicies` operation. */ - export namespace ListPoliciesConstants { - /** Optional type of policy. */ - export enum Type { - ACCESS = 'access', - AUTHORIZATION = 'authorization', - } - /** Optional type of service. */ - export enum ServiceType { - SERVICE = 'service', - PLATFORM_SERVICE = 'platform_service', - } - /** Optional top level policy field to sort results. Ascending sort is default. Descending sort available by prepending '-' to field. Example '-last_modified_at'. */ - export enum Sort { - ID = 'id', - TYPE = 'type', - HREF = 'href', - CREATED_AT = 'created_at', - CREATED_BY_ID = 'created_by_id', - LAST_MODIFIED_AT = 'last_modified_at', - LAST_MODIFIED_BY_ID = 'last_modified_by_id', - STATE = 'state', - } - /** Include additional data per policy returned * `include_last_permit` - returns details of when the policy last granted a permit decision and the number of times it has done so * `display` - returns the list of all actions included in each of the policy roles. */ - export enum Format { - INCLUDE_LAST_PERMIT = 'include_last_permit', - DISPLAY = 'display', - } - /** The state of the policy. * `active` - returns active policies * `deleted` - returns non-active policies. */ - export enum State { - ACTIVE = 'active', - DELETED = 'deleted', + /** + * Get policies by attributes. + * + * Get policies and filter by attributes. While managing policies, you may want to retrieve policies in the account + * and filter by attribute values. This can be done through query parameters. Currently, only the following attributes + * are supported: account_id, iam_id, access_group_id, type, service_type, sort, format and state. account_id is a + * required query parameter. Only policies that have the specified attributes and that the caller has read access to + * are returned. If the caller does not have read access to any policies an empty array is returned. + * + * @param {Object} params - The parameters to send to the service. + * @param {string} params.accountId - The account GUID in which the policies belong to. + * @param {string} [params.acceptLanguage] - Language code for translations + * * `default` - English + * * `de` - German (Standard) + * * `en` - English + * * `es` - Spanish (Spain) + * * `fr` - French (Standard) + * * `it` - Italian (Standard) + * * `ja` - Japanese + * * `ko` - Korean + * * `pt-br` - Portuguese (Brazil) + * * `zh-cn` - Chinese (Simplified, PRC) + * * `zh-tw` - (Chinese, Taiwan). + * @param {string} [params.iamId] - Optional IAM ID used to identify the subject. + * @param {string} [params.accessGroupId] - Optional access group id. + * @param {string} [params.type] - Optional type of policy. + * @param {string} [params.serviceType] - Optional type of service. + * @param {string} [params.serviceName] - Optional name of service. + * @param {string} [params.serviceGroupId] - Optional ID of service group. + * @param {string} [params.format] - Include additional data per policy returned + * * `include_last_permit` - returns details of when the policy last granted a permit decision and the number of times + * it has done so + * * `display` - returns the list of all actions included in each of the policy roles and translations for all + * relevant fields. + * @param {string} [params.state] - The state of the policy. + * * `active` - returns active policies + * * `deleted` - returns non-active policies. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public listV2Policies( + params: IamPolicyManagementV1.ListV2PoliciesParams + ): Promise> { + const _params = { ...params }; + const _requiredParams = ['accountId']; + const _validParams = [ + 'accountId', + 'acceptLanguage', + 'iamId', + 'accessGroupId', + 'type', + 'serviceType', + 'serviceName', + 'serviceGroupId', + 'format', + 'state', + 'headers', + ]; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); } - } - /** Parameters for the `createPolicy` operation. */ - export interface CreatePolicyParams { - /** The policy type; either 'access' or 'authorization'. */ - type: string; - /** The subjects associated with a policy. */ - subjects: PolicySubject[]; - /** A set of role cloud resource names (CRNs) granted by the policy. */ - roles: PolicyRole[]; - /** The resources associated with a policy. */ - resources: PolicyResource[]; - /** Customer-defined description. */ - description?: string; - /** Language code for translations - * * `default` - English - * * `de` - German (Standard) - * * `en` - English - * * `es` - Spanish (Spain) - * * `fr` - French (Standard) - * * `it` - Italian (Standard) - * * `ja` - Japanese - * * `ko` - Korean - * * `pt-br` - Portuguese (Brazil) - * * `zh-cn` - Chinese (Simplified, PRC) - * * `zh-tw` - (Chinese, Taiwan). - */ - acceptLanguage?: string; - headers?: OutgoingHttpHeaders; - } + const query = { + 'account_id': _params.accountId, + 'iam_id': _params.iamId, + 'access_group_id': _params.accessGroupId, + 'type': _params.type, + 'service_type': _params.serviceType, + 'service_name': _params.serviceName, + 'service_group_id': _params.serviceGroupId, + 'format': _params.format, + 'state': _params.state, + }; - /** Parameters for the `updatePolicy` operation. */ - export interface UpdatePolicyParams { - /** The policy ID. */ - policyId: string; - /** The revision number for updating a policy and must match the ETag value of the existing policy. The Etag can - * be retrieved using the GET /v1/policies/{policy_id} API and looking at the ETag response header. - */ - ifMatch: string; - /** The policy type; either 'access' or 'authorization'. */ - type: string; - /** The subjects associated with a policy. */ - subjects: PolicySubject[]; - /** A set of role cloud resource names (CRNs) granted by the policy. */ - roles: PolicyRole[]; - /** The resources associated with a policy. */ - resources: PolicyResource[]; - /** Customer-defined description. */ - description?: string; - headers?: OutgoingHttpHeaders; - } + const sdkHeaders = getSdkHeaders( + IamPolicyManagementV1.DEFAULT_SERVICE_NAME, + 'v1', + 'listV2Policies' + ); - /** Parameters for the `getPolicy` operation. */ - export interface GetPolicyParams { - /** The policy ID. */ - policyId: string; - headers?: OutgoingHttpHeaders; - } + const parameters = { + options: { + url: '/v2/policies', + method: 'GET', + qs: query, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + { + 'Accept': 'application/json', + 'Accept-Language': _params.acceptLanguage, + }, + _params.headers + ), + }), + }; - /** Parameters for the `deletePolicy` operation. */ - export interface DeletePolicyParams { - /** The policy ID. */ - policyId: string; - headers?: OutgoingHttpHeaders; + return this.createRequest(parameters); } - /** Parameters for the `patchPolicy` operation. */ - export interface PatchPolicyParams { - /** The policy ID. */ - policyId: string; - /** The revision number for updating a policy and must match the ETag value of the existing policy. The Etag can + /** + * Create a policy. + * + * Creates a policy to grant access between a subject and a resource. Currently, there is one type of a v2/policy: + * **access**. A policy administrator might want to create an access policy which grants access to a user, service-id, + * or an access group. + * + * ### Access + * + * To create an access policy, use **`"type": "access"`** in the body. The possible subject attributes are + * **`iam_id`** and **`access_group_id`**. Use the **`iam_id`** subject attribute for assigning access for a user or + * service-id. Use the **`access_group_id`** subject attribute for assigning access for an access group. The roles + * must be a subset of a service's or the platform's supported roles. For more information, see [IAM roles and + * actions](https://cloud.ibm.com/docs/account?topic=account-iam-service-roles-actions). The resource attributes must + * be a subset of a service's or the platform's supported attributes. Caller should check with service, e.g., + * [VPC](https://cloud.ibm.com/docs/vpc?topic=vpc-resource-attributes), to view supported attributes. The policy + * resource must include either the **`serviceType`**, **`serviceName`**, **`resourceGroupId`** or + * **`service_group_id`** attribute and the **`accountId`** attribute.` The rule field can either specify single + * **`key`**, **`value`**, and **`operator`** or be set of **`conditions`** with a combination **`operator`**. The + * possible combination operator are **`and`** and **`or`**. The operator for a rule can be used to specify a + * time-based condition (e.g., access only during business hours, during the Monday-Friday work week). For example, a + * policy can grant access Monday-Friday, 9:00am-5:00pm using the following rule: + * ```json + * "rule": { + * "operator": "and", + * "conditions": [{ + * "key": "{{environment.attributes.day_of_week}}", + * "operator": "dayOfWeekAnyOf", + * "value": ["1+00:00", "2+00:00", "3+00:00", "4+00:00", "5+00:00"] + * }, + * "key": "{{environment.attributes.current_time}}", + * "operator": "timeGreaterThanOrEquals", + * "value": "09:00:00+00:00" + * }, + * "key": "{{environment.attributes.current_time}}", + * "operator": "timeLessThanOrEquals", + * "value": "17:00:00+00:00" + * }] + * } + * ``` Rules and conditions allow the following operators with **`key`**, **`value`** : + * ``` + * 'timeLessThan', 'timeLessThanOrEquals', 'timeGreaterThan', 'timeGreaterThanOrEquals', + * 'dateTimeLessThan', 'dateTimeLessThanOrEquals', 'dateTimeGreaterThan', 'dateTimeGreaterThanOrEquals', + * 'dayOfWeekEquals', 'dayOfWeekAnyOf', + * ``` + * + * The pattern field that matches the rule is required when rule is provided. For the business hour rule example + * above, the **`pattern`** is **`"time-based-conditions:weekly"`**. For more information, see [Time-based conditions + * operators](https://cloud.ibm.com/docs/account?topic=account-iam-condition-properties&interface=ui#policy-condition-properties) + * and + * [Limiting access with time-based + * conditions](https://cloud.ibm.com/docs/account?topic=account-iam-time-based&interface=ui). The IAM Services group + * (`IAM`) is a subset of account management services that includes the IAM platform services IAM Identity, IAM Access + * Management, IAM Users Management, IAM Groups, and future IAM services. If the subject is a locked service-id, the + * request will fail. + * + * ### Attribute Operators + * + * Currently, only the `stringEquals`, `stringMatch`, and `stringEquals` operators are available. For more + * information, see [how to assign access by using wildcards + * policies](https://cloud.ibm.com/docs/account?topic=account-wildcard). + * + * ### Attribute Validations + * + * Policy attribute values must be between 1 and 1,000 characters in length. If location related attributes like + * geography, country, metro, region, satellite, and locationvalues are supported by the service, they are validated + * against Global Catalog locations. + * + * @param {Object} params - The parameters to send to the service. + * @param {Control} params.control - Specifies the type of access granted by the policy. + * @param {string} params.type - The policy type; either 'access' or 'authorization'. + * @param {string} [params.description] - Allows the customer to use their own words to record the purpose/context + * related to a policy. + * @param {V2PolicySubject} [params.subject] - The subject attributes for whom the policy grants access. + * @param {V2PolicyResource} [params.resource] - The resource attributes to which the policy grants access. + * @param {string} [params.pattern] - Indicates pattern of rule, either 'time-based-conditions:once', + * 'time-based-conditions:weekly:all-day', or 'time-based-conditions:weekly:custom-hours'. + * @param {V2PolicyRule} [params.rule] - Additional access conditions associated with the policy. + * @param {string} [params.acceptLanguage] - Language code for translations + * * `default` - English + * * `de` - German (Standard) + * * `en` - English + * * `es` - Spanish (Spain) + * * `fr` - French (Standard) + * * `it` - Italian (Standard) + * * `ja` - Japanese + * * `ko` - Korean + * * `pt-br` - Portuguese (Brazil) + * * `zh-cn` - Chinese (Simplified, PRC) + * * `zh-tw` - (Chinese, Taiwan). + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public createV2Policy( + params: IamPolicyManagementV1.CreateV2PolicyParams + ): Promise> { + const _params = { ...params }; + const _requiredParams = ['control', 'type']; + const _validParams = [ + 'control', + 'type', + 'description', + 'subject', + 'resource', + 'pattern', + 'rule', + 'acceptLanguage', + 'headers', + ]; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); + } + + const body = { + 'control': _params.control, + 'type': _params.type, + 'description': _params.description, + 'subject': _params.subject, + 'resource': _params.resource, + 'pattern': _params.pattern, + 'rule': _params.rule, + }; + + const sdkHeaders = getSdkHeaders( + IamPolicyManagementV1.DEFAULT_SERVICE_NAME, + 'v1', + 'createV2Policy' + ); + + const parameters = { + options: { + url: '/v2/policies', + method: 'POST', + body, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + 'Accept-Language': _params.acceptLanguage, + }, + _params.headers + ), + }), + }; + + return this.createRequest(parameters); + } + + /** + * Update a policy. + * + * Update a policy to grant access between a subject and a resource. A policy administrator might want to update an + * existing policy. + * + * ### Access + * + * To update an access policy, use **`"type": "access"`** in the body. The possible subject attributes are + * **`iam_id`** and **`access_group_id`**. Use the **`iam_id`** subject attribute for assigning access for a user or + * service-id. Use the **`access_group_id`** subject attribute for assigning access for an access group. The roles + * must be a subset of a service's or the platform's supported roles. For more information, see [IAM roles and + * actions](https://cloud.ibm.com/docs/account?topic=account-iam-service-roles-actions). The resource attributes must + * be a subset of a service's or the platform's supported attributes. Caller should check with service, e.g., + * [VPC](https://cloud.ibm.com/docs/vpc?topic=vpc-resource-attributes), to view supported attributes. The policy + * resource must include either the **`serviceType`**, **`serviceName`**, or **`resourceGroupId`** attribute and the + * **`accountId`** attribute.` The rule field can either specify single **`key`**, **`value`**, and **`operator`** or + * be set of **`conditions`** with a combination **`operator`**. The possible combination operator are **`and`** and + * **`or`**. The operator for a rule can be used to specify a time-based condition (e.g., access only during business + * hours, during the Monday-Friday work week). For example, a policy can grant access Monday-Friday, 9:00am-5:00pm + * using the following rule: + * ```json + * "rule": { + * "operator": "and", + * "conditions": [{ + * "key": "{{environment.attributes.day_of_week}}", + * "operator": "dayOfWeekAnyOf", + * "value": ["1+00:00", "2+00:00", "3+00:00", "4+00:00", "5+00:00"] + * }, + * "key": "{{environment.attributes.current_time}}", + * "operator": "timeGreaterThanOrEquals", + * "value": "09:00:00+00:00" + * }, + * "key": "{{environment.attributes.current_time}}", + * "operator": "timeLessThanOrEquals", + * "value": "17:00:00+00:00" + * }] + * } + * ``` Rules and conditions allow the following operators with **`key`**, **`value`** : + * ``` + * 'timeLessThan', 'timeLessThanOrEquals', 'timeGreaterThan', 'timeGreaterThanOrEquals', + * 'dateTimeLessThan', 'dateTimeLessThanOrEquals', 'dateTimeGreaterThan', 'dateTimeGreaterThanOrEquals', + * 'dayOfWeekEquals', 'dayOfWeekAnyOf', + * ``` The pattern field that matches the rule is required when rule is provided. For the business hour rule example + * above, the **`pattern`** is **`"time-based-conditions:weekly"`**. For more information, see [Time-based conditions + * operators](https://cloud.ibm.com/docs/account?topic=account-iam-condition-properties&interface=ui#policy-condition-properties) + * and + * [Limiting access with time-based + * conditions](https://cloud.ibm.com/docs/account?topic=account-iam-time-based&interface=ui). + * + * ### Attribute Operators + * + * Currently, only the `stringEquals`, `stringMatch`, and `stringEquals` operators are available. For more + * information, see [how to assign access by using wildcards + * policies](https://cloud.ibm.com/docs/account?topic=account-wildcard). + * + * ### Attribute Validations + * + * Policy attribute values must be between 1 and 1,000 characters in length. If location related attributes like + * geography, country, metro, region, satellite, and locationvalues are supported by the service, they are validated + * against Global Catalog locations. + * + * @param {Object} params - The parameters to send to the service. + * @param {string} params.id - The policy ID. + * @param {string} params.ifMatch - The revision number for updating a policy and must match the ETag value of the + * existing policy. The Etag can be retrieved using the GET /v2/policies/{id} API and looking at the ETag response + * header. + * @param {Control} params.control - Specifies the type of access granted by the policy. + * @param {string} params.type - The policy type; either 'access' or 'authorization'. + * @param {string} [params.description] - Allows the customer to use their own words to record the purpose/context + * related to a policy. + * @param {V2PolicySubject} [params.subject] - The subject attributes for whom the policy grants access. + * @param {V2PolicyResource} [params.resource] - The resource attributes to which the policy grants access. + * @param {string} [params.pattern] - Indicates pattern of rule, either 'time-based-conditions:once', + * 'time-based-conditions:weekly:all-day', or 'time-based-conditions:weekly:custom-hours'. + * @param {V2PolicyRule} [params.rule] - Additional access conditions associated with the policy. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public replaceV2Policy( + params: IamPolicyManagementV1.ReplaceV2PolicyParams + ): Promise> { + const _params = { ...params }; + const _requiredParams = ['id', 'ifMatch', 'control', 'type']; + const _validParams = [ + 'id', + 'ifMatch', + 'control', + 'type', + 'description', + 'subject', + 'resource', + 'pattern', + 'rule', + 'headers', + ]; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); + } + + const body = { + 'control': _params.control, + 'type': _params.type, + 'description': _params.description, + 'subject': _params.subject, + 'resource': _params.resource, + 'pattern': _params.pattern, + 'rule': _params.rule, + }; + + const path = { + 'id': _params.id, + }; + + const sdkHeaders = getSdkHeaders( + IamPolicyManagementV1.DEFAULT_SERVICE_NAME, + 'v1', + 'replaceV2Policy' + ); + + const parameters = { + options: { + url: '/v2/policies/{id}', + method: 'PUT', + body, + path, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + 'If-Match': _params.ifMatch, + }, + _params.headers + ), + }), + }; + + return this.createRequest(parameters); + } + + /** + * Retrieve a policy by ID. + * + * Retrieve a policy by providing a policy ID. + * + * @param {Object} params - The parameters to send to the service. + * @param {string} params.id - The policy ID. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public getV2Policy( + params: IamPolicyManagementV1.GetV2PolicyParams + ): Promise> { + const _params = { ...params }; + const _requiredParams = ['id']; + const _validParams = ['id', 'headers']; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); + } + + const path = { + 'id': _params.id, + }; + + const sdkHeaders = getSdkHeaders( + IamPolicyManagementV1.DEFAULT_SERVICE_NAME, + 'v1', + 'getV2Policy' + ); + + const parameters = { + options: { + url: '/v2/policies/{id}', + method: 'GET', + path, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend( + true, + sdkHeaders, + { + 'Accept': 'application/json', + }, + _params.headers + ), + }), + }; + + return this.createRequest(parameters); + } + + /** + * Delete a policy by ID. + * + * Delete a policy by providing a policy ID. A policy cannot be deleted if the subject ID contains a locked service + * ID. If the subject of the policy is a locked service-id, the request will fail. + * + * @param {Object} params - The parameters to send to the service. + * @param {string} params.id - The policy ID. + * @param {OutgoingHttpHeaders} [params.headers] - Custom request headers + * @returns {Promise>} + */ + public deleteV2Policy( + params: IamPolicyManagementV1.DeleteV2PolicyParams + ): Promise> { + const _params = { ...params }; + const _requiredParams = ['id']; + const _validParams = ['id', 'headers']; + const _validationErrors = validateParams(_params, _requiredParams, _validParams); + if (_validationErrors) { + return Promise.reject(_validationErrors); + } + + const path = { + 'id': _params.id, + }; + + const sdkHeaders = getSdkHeaders( + IamPolicyManagementV1.DEFAULT_SERVICE_NAME, + 'v1', + 'deleteV2Policy' + ); + + const parameters = { + options: { + url: '/v2/policies/{id}', + method: 'DELETE', + path, + }, + defaultOptions: extend(true, {}, this.baseOptions, { + headers: extend(true, sdkHeaders, {}, _params.headers), + }), + }; + + return this.createRequest(parameters); + } +} + +/************************* + * interfaces + ************************/ + +namespace IamPolicyManagementV1 { + /** An operation response. */ + export interface Response { + result: T; + status: number; + statusText: string; + headers: IncomingHttpHeaders; + } + + /** The callback for a service request. */ + export type Callback = (error: any, response?: Response) => void; + + /** The body of a service request that returns no response data. */ + export interface EmptyObject {} + + /** A standard JS object, defined to avoid the limitations of `Object` and `object` */ + export interface JsonObject { + [key: string]: any; + } + + /************************* + * request interfaces + ************************/ + + /** Parameters for the `listPolicies` operation. */ + export interface ListPoliciesParams { + /** The account GUID in which the policies belong to. */ + accountId: string; + /** Language code for translations + * * `default` - English + * * `de` - German (Standard) + * * `en` - English + * * `es` - Spanish (Spain) + * * `fr` - French (Standard) + * * `it` - Italian (Standard) + * * `ja` - Japanese + * * `ko` - Korean + * * `pt-br` - Portuguese (Brazil) + * * `zh-cn` - Chinese (Simplified, PRC) + * * `zh-tw` - (Chinese, Taiwan). + */ + acceptLanguage?: string; + /** Optional IAM ID used to identify the subject. */ + iamId?: string; + /** Optional access group id. */ + accessGroupId?: string; + /** Optional type of policy. */ + type?: ListPoliciesConstants.Type | string; + /** Optional type of service. */ + serviceType?: ListPoliciesConstants.ServiceType | string; + /** Optional name of the access management tag in the policy. */ + tagName?: string; + /** Optional value of the access management tag in the policy. */ + tagValue?: string; + /** Optional top level policy field to sort results. Ascending sort is default. Descending sort available by + * prepending '-' to field. Example '-last_modified_at'. + */ + sort?: ListPoliciesConstants.Sort | string; + /** Include additional data per policy returned + * * `include_last_permit` - returns details of when the policy last granted a permit decision and the number of + * times it has done so + * * `display` - returns the list of all actions included in each of the policy roles. + */ + format?: ListPoliciesConstants.Format | string; + /** The state of the policy. * `active` - returns active policies * `deleted` - returns non-active policies. */ + state?: ListPoliciesConstants.State | string; + headers?: OutgoingHttpHeaders; + } + + /** Constants for the `listPolicies` operation. */ + export namespace ListPoliciesConstants { + /** Optional type of policy. */ + export enum Type { + ACCESS = 'access', + AUTHORIZATION = 'authorization', + } + /** Optional type of service. */ + export enum ServiceType { + SERVICE = 'service', + PLATFORM_SERVICE = 'platform_service', + } + /** Optional top level policy field to sort results. Ascending sort is default. Descending sort available by prepending '-' to field. Example '-last_modified_at'. */ + export enum Sort { + ID = 'id', + TYPE = 'type', + HREF = 'href', + CREATED_AT = 'created_at', + CREATED_BY_ID = 'created_by_id', + LAST_MODIFIED_AT = 'last_modified_at', + LAST_MODIFIED_BY_ID = 'last_modified_by_id', + STATE = 'state', + } + /** Include additional data per policy returned * `include_last_permit` - returns details of when the policy last granted a permit decision and the number of times it has done so * `display` - returns the list of all actions included in each of the policy roles. */ + export enum Format { + INCLUDE_LAST_PERMIT = 'include_last_permit', + DISPLAY = 'display', + } + /** The state of the policy. * `active` - returns active policies * `deleted` - returns non-active policies. */ + export enum State { + ACTIVE = 'active', + DELETED = 'deleted', + } + } + + /** Parameters for the `createPolicy` operation. */ + export interface CreatePolicyParams { + /** The policy type; either 'access' or 'authorization'. */ + type: string; + /** The subjects associated with a policy. */ + subjects: PolicySubject[]; + /** A set of role cloud resource names (CRNs) granted by the policy. */ + roles: PolicyRole[]; + /** The resources associated with a policy. */ + resources: PolicyResource[]; + /** Customer-defined description. */ + description?: string; + /** Language code for translations + * * `default` - English + * * `de` - German (Standard) + * * `en` - English + * * `es` - Spanish (Spain) + * * `fr` - French (Standard) + * * `it` - Italian (Standard) + * * `ja` - Japanese + * * `ko` - Korean + * * `pt-br` - Portuguese (Brazil) + * * `zh-cn` - Chinese (Simplified, PRC) + * * `zh-tw` - (Chinese, Taiwan). + */ + acceptLanguage?: string; + headers?: OutgoingHttpHeaders; + } + + /** Parameters for the `replacePolicy` operation. */ + export interface ReplacePolicyParams { + /** The policy ID. */ + policyId: string; + /** The revision number for updating a policy and must match the ETag value of the existing policy. The Etag can + * be retrieved using the GET /v1/policies/{policy_id} API and looking at the ETag response header. + */ + ifMatch: string; + /** The policy type; either 'access' or 'authorization'. */ + type: string; + /** The subjects associated with a policy. */ + subjects: PolicySubject[]; + /** A set of role cloud resource names (CRNs) granted by the policy. */ + roles: PolicyRole[]; + /** The resources associated with a policy. */ + resources: PolicyResource[]; + /** Customer-defined description. */ + description?: string; + headers?: OutgoingHttpHeaders; + } + + /** Parameters for the `getPolicy` operation. */ + export interface GetPolicyParams { + /** The policy ID. */ + policyId: string; + headers?: OutgoingHttpHeaders; + } + + /** Parameters for the `deletePolicy` operation. */ + export interface DeletePolicyParams { + /** The policy ID. */ + policyId: string; + headers?: OutgoingHttpHeaders; + } + + /** Parameters for the `updatePolicyState` operation. */ + export interface UpdatePolicyStateParams { + /** The policy ID. */ + policyId: string; + /** The revision number for updating a policy and must match the ETag value of the existing policy. The Etag can * be retrieved using the GET /v1/policies/{policy_id} API and looking at the ETag response header. */ ifMatch: string; /** The policy state. */ - state?: PatchPolicyConstants.State | string; + state?: UpdatePolicyStateConstants.State | string; headers?: OutgoingHttpHeaders; } - /** Constants for the `patchPolicy` operation. */ - export namespace PatchPolicyConstants { + /** Constants for the `updatePolicyState` operation. */ + export namespace UpdatePolicyStateConstants { /** The policy state. */ export enum State { ACTIVE = 'active', @@ -1182,8 +1686,8 @@ namespace IamPolicyManagementV1 { headers?: OutgoingHttpHeaders; } - /** Parameters for the `updateRole` operation. */ - export interface UpdateRoleParams { + /** Parameters for the `replaceRole` operation. */ + export interface ReplaceRoleParams { /** The role ID. */ roleId: string; /** The revision number for updating a role and must match the ETag value of the existing role. The Etag can be @@ -1191,13 +1695,13 @@ namespace IamPolicyManagementV1 { */ ifMatch: string; /** The display name of the role that is shown in the console. */ - displayName?: string; - /** The description of the role. */ - description?: string; + displayName: string; /** The actions of the role. Please refer to [IAM roles and * actions](https://cloud.ibm.com/docs/account?topic=account-iam-service-roles-actions). */ - actions?: string[]; + actions: string[]; + /** The description of the role. */ + description?: string; headers?: OutgoingHttpHeaders; } @@ -1215,32 +1719,357 @@ namespace IamPolicyManagementV1 { headers?: OutgoingHttpHeaders; } + /** Parameters for the `listV2Policies` operation. */ + export interface ListV2PoliciesParams { + /** The account GUID in which the policies belong to. */ + accountId: string; + /** Language code for translations + * * `default` - English + * * `de` - German (Standard) + * * `en` - English + * * `es` - Spanish (Spain) + * * `fr` - French (Standard) + * * `it` - Italian (Standard) + * * `ja` - Japanese + * * `ko` - Korean + * * `pt-br` - Portuguese (Brazil) + * * `zh-cn` - Chinese (Simplified, PRC) + * * `zh-tw` - (Chinese, Taiwan). + */ + acceptLanguage?: string; + /** Optional IAM ID used to identify the subject. */ + iamId?: string; + /** Optional access group id. */ + accessGroupId?: string; + /** Optional type of policy. */ + type?: ListV2PoliciesConstants.Type | string; + /** Optional type of service. */ + serviceType?: ListV2PoliciesConstants.ServiceType | string; + /** Optional name of service. */ + serviceName?: string; + /** Optional ID of service group. */ + serviceGroupId?: string; + /** Include additional data per policy returned + * * `include_last_permit` - returns details of when the policy last granted a permit decision and the number of + * times it has done so + * * `display` - returns the list of all actions included in each of the policy roles and translations for all + * relevant fields. + */ + format?: ListV2PoliciesConstants.Format | string; + /** The state of the policy. * `active` - returns active policies * `deleted` - returns non-active policies. */ + state?: ListV2PoliciesConstants.State | string; + headers?: OutgoingHttpHeaders; + } + + /** Constants for the `listV2Policies` operation. */ + export namespace ListV2PoliciesConstants { + /** Optional type of policy. */ + export enum Type { + ACCESS = 'access', + AUTHORIZATION = 'authorization', + } + /** Optional type of service. */ + export enum ServiceType { + SERVICE = 'service', + PLATFORM_SERVICE = 'platform_service', + } + /** Include additional data per policy returned * `include_last_permit` - returns details of when the policy last granted a permit decision and the number of times it has done so * `display` - returns the list of all actions included in each of the policy roles and translations for all relevant fields. */ + export enum Format { + INCLUDE_LAST_PERMIT = 'include_last_permit', + DISPLAY = 'display', + } + /** The state of the policy. * `active` - returns active policies * `deleted` - returns non-active policies. */ + export enum State { + ACTIVE = 'active', + DELETED = 'deleted', + } + } + + /** Parameters for the `createV2Policy` operation. */ + export interface CreateV2PolicyParams { + /** Specifies the type of access granted by the policy. */ + control: Control; + /** The policy type; either 'access' or 'authorization'. */ + type: CreateV2PolicyConstants.Type | string; + /** Allows the customer to use their own words to record the purpose/context related to a policy. */ + description?: string; + /** The subject attributes for whom the policy grants access. */ + subject?: V2PolicySubject; + /** The resource attributes to which the policy grants access. */ + resource?: V2PolicyResource; + /** Indicates pattern of rule, either 'time-based-conditions:once', 'time-based-conditions:weekly:all-day', or + * 'time-based-conditions:weekly:custom-hours'. + */ + pattern?: string; + /** Additional access conditions associated with the policy. */ + rule?: V2PolicyRule; + /** Language code for translations + * * `default` - English + * * `de` - German (Standard) + * * `en` - English + * * `es` - Spanish (Spain) + * * `fr` - French (Standard) + * * `it` - Italian (Standard) + * * `ja` - Japanese + * * `ko` - Korean + * * `pt-br` - Portuguese (Brazil) + * * `zh-cn` - Chinese (Simplified, PRC) + * * `zh-tw` - (Chinese, Taiwan). + */ + acceptLanguage?: string; + headers?: OutgoingHttpHeaders; + } + + /** Constants for the `createV2Policy` operation. */ + export namespace CreateV2PolicyConstants { + /** The policy type; either 'access' or 'authorization'. */ + export enum Type { + ACCESS = 'access', + AUTHORIZATION = 'authorization', + } + } + + /** Parameters for the `replaceV2Policy` operation. */ + export interface ReplaceV2PolicyParams { + /** The policy ID. */ + id: string; + /** The revision number for updating a policy and must match the ETag value of the existing policy. The Etag can + * be retrieved using the GET /v2/policies/{id} API and looking at the ETag response header. + */ + ifMatch: string; + /** Specifies the type of access granted by the policy. */ + control: Control; + /** The policy type; either 'access' or 'authorization'. */ + type: ReplaceV2PolicyConstants.Type | string; + /** Allows the customer to use their own words to record the purpose/context related to a policy. */ + description?: string; + /** The subject attributes for whom the policy grants access. */ + subject?: V2PolicySubject; + /** The resource attributes to which the policy grants access. */ + resource?: V2PolicyResource; + /** Indicates pattern of rule, either 'time-based-conditions:once', 'time-based-conditions:weekly:all-day', or + * 'time-based-conditions:weekly:custom-hours'. + */ + pattern?: string; + /** Additional access conditions associated with the policy. */ + rule?: V2PolicyRule; + headers?: OutgoingHttpHeaders; + } + + /** Constants for the `replaceV2Policy` operation. */ + export namespace ReplaceV2PolicyConstants { + /** The policy type; either 'access' or 'authorization'. */ + export enum Type { + ACCESS = 'access', + AUTHORIZATION = 'authorization', + } + } + + /** Parameters for the `getV2Policy` operation. */ + export interface GetV2PolicyParams { + /** The policy ID. */ + id: string; + headers?: OutgoingHttpHeaders; + } + + /** Parameters for the `deleteV2Policy` operation. */ + export interface DeleteV2PolicyParams { + /** The policy ID. */ + id: string; + headers?: OutgoingHttpHeaders; + } + /************************* * model interfaces ************************/ + /** Specifies the type of access granted by the policy. */ + export interface Control { + /** Permission granted by the policy. */ + grant: V2PolicyGrant; + } + + /** ControlResponse. */ + export interface ControlResponse {} + + /** Permission granted by the policy with translated roles and additional role information. */ + export interface GrantWithTranslatedRoles { + /** A set of roles granted by the policy. */ + roles: RoleInDisplayFormat[]; + } + + /** A role associated with a policy. */ + export interface PolicyRole { + /** The role Cloud Resource Name (CRN) granted by the policy. Example CRN: + * 'crn:v1:bluemix:public:iam::::role:Editor'. + */ + role_id: string; + /** The display name of the role. */ + display_name?: string; + /** The description of the role. */ + description?: string; + } + + /** An action that can be performed by the policy subject when assigned role. */ + export interface RoleAction { + /** Unique identifier for action with structure service.resource.action e.g., cbr.rule.read. */ + id: string; + /** Service defined display name for action. */ + display_name: string; + /** Service defined description for action. */ + description: string; + } + + /** A role associated with a policy with additional information (display_name, description, actions) when `format=display`. */ + export interface RoleInDisplayFormat { + /** The role Cloud Resource Name (CRN) granted by the policy. Example CRN: + * 'crn:v1:bluemix:public:iam::::role:Editor'. + */ + role_id: string; + /** The service defined (or user defined if a custom role) display name of the role. */ + display_name?: string; + /** The service defined (or user defined if a custom role) description of the role. */ + description?: string; + /** The actions of the role. Please refer to [IAM roles and + * actions](https://cloud.ibm.com/docs/account?topic=account-iam-service-roles-actions). + */ + actions: RoleAction[]; + } + + /** Rule that specifies additional access granted (e.g., time-based condition). */ + export interface RuleAttribute { + /** The name of an attribute. */ + key: string; + /** The operator of an attribute. */ + operator: string; + /** The value of an rule or resource attribute; can be boolean or string for resource attribute. Can be a string + * or an array of strings (e.g., array of days to permit access) for rule attribute. + */ + value: any; + } + + /** The core set of properties associated with the policy. */ + export interface V2Policy { + /** The policy type; either 'access' or 'authorization'. */ + type: string; + /** Allows the customer to use their own words to record the purpose/context related to a policy. */ + description?: string; + /** The subject attributes for whom the policy grants access. */ + subject?: V2PolicySubject; + /** The resource attributes to which the policy grants access. */ + resource?: V2PolicyResource; + /** Indicates pattern of rule, either 'time-based-conditions:once', 'time-based-conditions:weekly:all-day', or + * 'time-based-conditions:weekly:custom-hours'. + */ + pattern?: string; + /** Additional access conditions associated with the policy. */ + rule?: V2PolicyRule; + /** The policy ID. */ + id?: string; + /** The href URL that links to the policies API by policy ID. */ + href?: string; + control: ControlResponse; + /** The UTC timestamp when the policy was created. */ + created_at?: string; + /** The iam ID of the entity that created the policy. */ + created_by_id?: string; + /** The UTC timestamp when the policy was last modified. */ + last_modified_at?: string; + /** The iam ID of the entity that last modified the policy. */ + last_modified_by_id?: string; + /** The policy state, either 'deleted' or 'active'. */ + state: string; + /** The optional last permit time of policy, when passing query parameter format=include_last_permit. */ + last_permit_at?: string; + /** The optional count of times that policy has provided a permit, when passing query parameter + * format=include_last_permit. + */ + last_permit_frequency?: number; + } + + /** A collection of policies. */ + export interface V2PolicyCollection { + /** List of policies. */ + policies?: V2Policy[]; + } + + /** Permission granted by the policy. */ + export interface V2PolicyGrant { + /** A set of role cloud resource names (CRNs) granted by the policy. */ + roles: PolicyRole[]; + } + + /** The resource attributes to which the policy grants access. */ + export interface V2PolicyResource { + /** List of resource attributes to which the policy grants access. */ + attributes: V2PolicyResourceAttribute[]; + /** Optional list of resource tags to which the policy grants access. */ + tags?: V2PolicyResourceTag[]; + } + + /** Resource attribute to which the policy grants access. */ + export interface V2PolicyResourceAttribute { + /** The name of a resource attribute. */ + key: string; + /** The operator of an attribute. */ + operator: string; + /** The value of an rule or resource attribute; can be boolean or string for resource attribute. Can be a string + * or an array of strings (e.g., array of days to permit access) for rule attribute. + */ + value: any; + } + + /** A tag associated with a resource. */ + export interface V2PolicyResourceTag { + /** The name of an access management tag. */ + key: string; + /** The value of an access management tag. */ + value: string; + /** The operator of an access management tag. */ + operator: string; + } + + /** Additional access conditions associated with the policy. */ + export interface V2PolicyRule {} + + /** The subject attributes for whom the policy grants access. */ + export interface V2PolicySubject { + /** List of subject attributes associated with policy/. */ + attributes: V2PolicySubjectAttribute[]; + } + + /** Subject attribute for whom the policy grants access. */ + export interface V2PolicySubjectAttribute { + /** The name of a subject attribute, e.g., iam_id, access_group_id. */ + key: string; + /** The operator of an attribute. */ + operator: string; + /** The value of the ID of the subject, e.g., service ID, access group ID, IAM ID. */ + value: string; + } + /** An additional set of properties associated with a role. */ export interface CustomRole { /** The role ID. Composed of hexadecimal characters. */ id?: string; /** The display name of the role that is shown in the console. */ - display_name?: string; + display_name: string; /** The description of the role. */ description?: string; /** The actions of the role. Please refer to [IAM roles and * actions](https://cloud.ibm.com/docs/account?topic=account-iam-service-roles-actions). */ - actions?: string[]; + actions: string[]; /** The role Cloud Resource Name (CRN). Example CRN: * 'crn:v1:ibmcloud:public:iam-access-management::a/exampleAccountId::customRole:ExampleRoleName'. */ crn?: string; /** The name of the role that is used in the CRN. Can only be alphanumeric and has to be capitalized. */ - name?: string; + name: string; /** The account GUID. */ - account_id?: string; + account_id: string; /** The service name. */ - service_name?: string; + service_name: string; /** The UTC timestamp when the role was created. */ created_at?: string; /** The iam ID of the entity that created the role. */ @@ -1258,15 +2087,15 @@ namespace IamPolicyManagementV1 { /** The policy ID. */ id?: string; /** The policy type; either 'access' or 'authorization'. */ - type?: string; + type: string; /** Customer-defined description. */ description?: string; /** The subjects associated with a policy. */ - subjects?: PolicySubject[]; + subjects: PolicySubject[]; /** A set of role cloud resource names (CRNs) granted by the policy. */ - roles?: PolicyRole[]; + roles: PolicyRole[]; /** The resources associated with a policy. */ - resources?: PolicyResource[]; + resources: PolicyResource[]; /** The href link back to the policy. */ href?: string; /** The UTC timestamp when the policy was created. */ @@ -1295,18 +2124,6 @@ namespace IamPolicyManagementV1 { tags?: ResourceTag[]; } - /** A role associated with a policy. */ - export interface PolicyRole { - /** The role Cloud Resource Name (CRN) granted by the policy. Example CRN: - * 'crn:v1:bluemix:public:iam::::role:Editor'. - */ - role_id: string; - /** The display name of the role. */ - display_name?: string; - /** The description of the role. */ - description?: string; - } - /** The subject attribute values that must match in order for this policy to apply in a permission decision. */ export interface PolicySubject { /** List of subject attributes. */ @@ -1336,13 +2153,13 @@ namespace IamPolicyManagementV1 { /** A role resource. */ export interface Role { /** The display name of the role that is shown in the console. */ - display_name?: string; + display_name: string; /** The description of the role. */ description?: string; /** The actions of the role. Please refer to [IAM roles and * actions](https://cloud.ibm.com/docs/account?topic=account-iam-service-roles-actions). */ - actions?: string[]; + actions: string[]; /** The role Cloud Resource Name (CRN). Example CRN: * 'crn:v1:ibmcloud:public:iam-access-management::a/exampleAccountId::customRole:ExampleRoleName'. */ @@ -1366,6 +2183,40 @@ namespace IamPolicyManagementV1 { /** The value of an attribute. */ value: string; } + + /** Specifies the type of access granted by the policy. */ + export interface ControlResponseControl extends ControlResponse { + /** Permission granted by the policy. */ + grant: V2PolicyGrant; + } + + /** Specifies the type of access granted by the policy with additional role information. */ + export interface ControlResponseControlWithTranslatedRoles extends ControlResponse { + /** Permission granted by the policy with translated roles and additional role information. */ + grant: GrantWithTranslatedRoles; + } + + /** Rule that specifies additional access granted (e.g., time-based condition). */ + export interface V2PolicyRuleRuleAttribute extends V2PolicyRule { + /** The name of an attribute. */ + key: string; + /** The operator of an attribute. */ + operator: string; + /** The value of an rule or resource attribute; can be boolean or string for resource attribute. Can be a string + * or an array of strings (e.g., array of days to permit access) for rule attribute. + */ + value: any; + } + + /** Rule that specifies additional access granted (e.g., time-based condition) accross multiple conditions. */ + export interface V2PolicyRuleRuleWithConditions extends V2PolicyRule { + /** Operator to evalute conditions. */ + operator: string; + /** List of conditions associated with a policy, e.g., time-based-conditions that grant access over a certain + * time period. + */ + conditions: RuleAttribute[]; + } } export = IamPolicyManagementV1; diff --git a/test/integration/iam-policy-management.v1.test.js b/test/integration/iam-policy-management.v1.test.js index 62975f30..0c58fdb3 100644 --- a/test/integration/iam-policy-management.v1.test.js +++ b/test/integration/iam-policy-management.v1.test.js @@ -36,6 +36,8 @@ describe('IamPolicyManagementV1_integration', () => { let testAccountId; let testPolicyETag; let testPolicyId; + let testV2PolicyETag; + let testV2PolicyId; const testUniqueId = Math.floor(Math.random() * 100000); const testUserId = `IBMid-SDKNode${testUniqueId}`; const testViewerRoleCrn = 'crn:v1:bluemix:public:iam::::role:Viewer'; @@ -79,6 +81,55 @@ describe('IamPolicyManagementV1_integration', () => { }, ]; + const v2PolicySubject = { + attributes: [ + { + key: 'iam_id', + operator: 'stringEquals', + value: testUserId, + }, + ], + }; + const v2PolicyResourceAccountAttribute = { + key: 'accountId', + value: testAccountId, + operator: 'stringEquals', + }; + const v2PolicyResourceServiceAttribute = { + key: 'serviceType', + operator: 'stringEquals', + value: 'service', + }; + const v2PolicyResource = { + attributes: [v2PolicyResourceAccountAttribute, v2PolicyResourceServiceAttribute], + }; + const control = { + grant: { + roles: policyRoles, + }, + }; + const rule = { + operator: 'and', + conditions: [ + { + key: '{{environment.attributes.day_of_week}}', + operator: 'dayOfWeekAnyOf', + value: ['1+00:00', '2+00:00', '3+00:00', '4+00:00', '5+00:00'], + }, + { + key: '{{environment.attributes.current_time}}', + operator: 'timeGreaterThanOrEquals', + value: '09:00:00+00:00', + }, + { + key: '{{environment.attributes.current_time}}', + operator: 'timeLessThanOrEquals', + value: '17:00:00+00:00', + }, + ], + }; + const pattern = 'time-based-conditions:weekly:custom-hours'; + let testCustomRoleId; let testCustomRoleEtag; const testCustomRoleName = `TestNodeRole${testUniqueId}`; @@ -181,7 +232,7 @@ describe('IamPolicyManagementV1_integration', () => { let response; try { - response = await service.updatePolicy(params); + response = await service.replacePolicy(params); } catch (err) { console.warn(err); } @@ -211,7 +262,7 @@ describe('IamPolicyManagementV1_integration', () => { let response; try { - response = await service.patchPolicy(params); + response = await service.updatePolicyState(params); } catch (err) { console.warn(err); } @@ -305,6 +356,187 @@ describe('IamPolicyManagementV1_integration', () => { }); }); + describe('V2 Access policy tests', () => { + test('Create a v2 access policy', async () => { + const params = { + type: 'access', + subject: v2PolicySubject, + control, + resource: v2PolicyResource, + rule, + pattern, + }; + + // ensure resource account value is defined + v2PolicyResource.attributes[0].value = testAccountId; + + let response; + try { + response = await service.createV2Policy(params); + } catch (err) { + console.warn(err); + } + + expect(response).toBeDefined(); + expect(response.status).toEqual(201); + const { result } = response || {}; + expect(result).toBeDefined(); + expect(result.type).toEqual(policyType); + expect(result.subject).toEqual(v2PolicySubject); + expect(result.control).toEqual(control); + expect(result.resource).toEqual(v2PolicyResource); + + testV2PolicyId = result.id; + }); + + test('Get a v2 access policy', async () => { + expect(testPolicyId).toBeDefined(); + + const params = { + id: testV2PolicyId, + }; + + let response; + try { + response = await service.getV2Policy(params); + } catch (err) { + console.warn(err); + } + + expect(response).toBeDefined(); + expect(response.status).toEqual(200); + const { result } = response || {}; + expect(result).toBeDefined(); + expect(result.id).toEqual(testV2PolicyId); + expect(result.type).toEqual(policyType); + expect(result.subject).toEqual(v2PolicySubject); + expect(result.control).toEqual(control); + expect(result.resource).toEqual(v2PolicyResource); + + testV2PolicyETag = response.headers.etag; + }); + + test('Update a v2 access policy', async () => { + expect(testV2PolicyId).toBeDefined(); + expect(testV2PolicyETag).toBeDefined(); + + const updatedControl = { + grant: { + roles: [ + { + role_id: testEditorRoleCrn, + }, + ], + }, + }; + + const params = { + id: testV2PolicyId, + ifMatch: testV2PolicyETag, + type: 'access', + subject: v2PolicySubject, + control: updatedControl, + resource: v2PolicyResource, + rule, + pattern, + }; + + let response; + try { + response = await service.replaceV2Policy(params); + } catch (err) { + console.warn(err); + } + + expect(response).toBeDefined(); + expect(response.status).toEqual(200); + const { result } = response || {}; + expect(result).toBeDefined(); + expect(result.id).toEqual(testV2PolicyId); + expect(result.type).toEqual(policyType); + expect(result.subject).toEqual(v2PolicySubject); + expect(result.control).toEqual(updatedControl); + expect(result.resource).toEqual(v2PolicyResource); + }); + + test('List v2 access policies', async () => { + expect(testPolicyId).toBeDefined(); + + const params = { + accountId: testAccountId, + iamId: testUserId, + }; + + let response; + try { + response = await service.listV2Policies(params); + } catch (err) { + console.warn(err); + } + + expect(response).toBeDefined(); + expect(response.status).toEqual(200); + const { result } = response || {}; + expect(result).toBeDefined(); + + // Confirm the test policy is present + let foundTestPolicy = false; + let policy; + for (policy of result.policies) { + if (policy.id === testV2PolicyId) { + foundTestPolicy = true; + break; + } + } + expect(foundTestPolicy).toBeTruthy(); + }); + + test('Clean up all v2 test policies', async () => { + // List all policies for the test user in the account + const params = { + accountId: testAccountId, + iamId: testUserId, + }; + + let response; + try { + response = await service.listV2Policies(params); + } catch (err) { + console.warn(err); + } + + expect(response).toBeDefined(); + expect(response.status).toEqual(200); + const { result } = response || {}; + expect(result).toBeDefined(); + + // Iterate across the policies + let policy; + for (policy of result.policies) { + // Delete the test policy (or any test policies older than 5 minutes) + const createdAt = Date.parse(policy.created_at); + const FIVE_MINUTES = 5 * 60 * 1000; + const fiveMinutesAgo = Date.now() - FIVE_MINUTES; + + if (policy.id === testV2PolicyId || createdAt < fiveMinutesAgo) { + const params = { + id: policy.id, + }; + + let response; + try { + response = await service.deleteV2Policy(params); + } catch (err) { + console.warn(err); + } + + expect(response).toBeDefined(); + expect(response.status).toEqual(204); + } + } + }); + }); + describe('Custom roles tests', () => { test('Create a custom role', async () => { const params = { @@ -376,12 +608,14 @@ describe('IamPolicyManagementV1_integration', () => { roleId: testCustomRoleId, ifMatch: testCustomRoleEtag, description: updCustomRoleDescription, + displayName: testCustomRoleDisplayName, + actions: testCustomRoleActions, headers: { 'transaction-Id': `SDKNode-${testUniqueId}` }, }; let response; try { - response = await service.updateRole(params); + response = await service.replaceRole(params); } catch (err) { console.warn(err); } diff --git a/test/unit/iam-policy-management.v1.test.js b/test/unit/iam-policy-management.v1.test.js index eb585322..3b59535e 100644 --- a/test/unit/iam-policy-management.v1.test.js +++ b/test/unit/iam-policy-management.v1.test.js @@ -1,5 +1,5 @@ /** - * (C) Copyright IBM Corp. 2022. + * (C) Copyright IBM Corp. 2023. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -370,7 +370,7 @@ describe('IamPolicyManagementV1', () => { }); }); - describe('updatePolicy', () => { + describe('replacePolicy', () => { describe('positive tests', () => { // Request models needed by this operation. @@ -410,8 +410,8 @@ describe('IamPolicyManagementV1', () => { tags: [resourceTagModel], }; - function __updatePolicyTest() { - // Construct the params object for operation updatePolicy + function __replacePolicyTest() { + // Construct the params object for operation replacePolicy const policyId = 'testString'; const ifMatch = 'testString'; const type = 'testString'; @@ -419,7 +419,7 @@ describe('IamPolicyManagementV1', () => { const roles = [policyRoleModel]; const resources = [policyResourceModel]; const description = 'testString'; - const updatePolicyParams = { + const replacePolicyParams = { policyId, ifMatch, type, @@ -429,10 +429,10 @@ describe('IamPolicyManagementV1', () => { description, }; - const updatePolicyResult = iamPolicyManagementService.updatePolicy(updatePolicyParams); + const replacePolicyResult = iamPolicyManagementService.replacePolicy(replacePolicyParams); // all methods should return a Promise - expectToBePromise(updatePolicyResult); + expectToBePromise(replacePolicyResult); // assert that create request was called expect(createRequestMock).toHaveBeenCalledTimes(1); @@ -454,17 +454,17 @@ describe('IamPolicyManagementV1', () => { test('should pass the right params to createRequest with enable and disable retries', () => { // baseline test - __updatePolicyTest(); + __replacePolicyTest(); // enable retries and test again createRequestMock.mockClear(); iamPolicyManagementService.enableRetries(); - __updatePolicyTest(); + __replacePolicyTest(); // disable retries and test again createRequestMock.mockClear(); iamPolicyManagementService.disableRetries(); - __updatePolicyTest(); + __replacePolicyTest(); }); test('should prioritize user-given headers', () => { @@ -477,7 +477,7 @@ describe('IamPolicyManagementV1', () => { const resources = [policyResourceModel]; const userAccept = 'fake/accept'; const userContentType = 'fake/contentType'; - const updatePolicyParams = { + const replacePolicyParams = { policyId, ifMatch, type, @@ -490,7 +490,7 @@ describe('IamPolicyManagementV1', () => { }, }; - iamPolicyManagementService.updatePolicy(updatePolicyParams); + iamPolicyManagementService.replacePolicy(replacePolicyParams); checkMediaHeaders(createRequestMock, userAccept, userContentType); }); }); @@ -499,7 +499,7 @@ describe('IamPolicyManagementV1', () => { test('should enforce required parameters', async () => { let err; try { - await iamPolicyManagementService.updatePolicy({}); + await iamPolicyManagementService.replacePolicy({}); } catch (e) { err = e; } @@ -510,7 +510,7 @@ describe('IamPolicyManagementV1', () => { test('should reject promise when required params are not given', async () => { let err; try { - await iamPolicyManagementService.updatePolicy(); + await iamPolicyManagementService.replacePolicy(); } catch (e) { err = e; } @@ -688,23 +688,23 @@ describe('IamPolicyManagementV1', () => { }); }); - describe('patchPolicy', () => { + describe('updatePolicyState', () => { describe('positive tests', () => { - function __patchPolicyTest() { - // Construct the params object for operation patchPolicy + function __updatePolicyStateTest() { + // Construct the params object for operation updatePolicyState const policyId = 'testString'; const ifMatch = 'testString'; const state = 'active'; - const patchPolicyParams = { + const updatePolicyStateParams = { policyId, ifMatch, state, }; - const patchPolicyResult = iamPolicyManagementService.patchPolicy(patchPolicyParams); + const updatePolicyStateResult = iamPolicyManagementService.updatePolicyState(updatePolicyStateParams); // all methods should return a Promise - expectToBePromise(patchPolicyResult); + expectToBePromise(updatePolicyStateResult); // assert that create request was called expect(createRequestMock).toHaveBeenCalledTimes(1); @@ -722,17 +722,17 @@ describe('IamPolicyManagementV1', () => { test('should pass the right params to createRequest with enable and disable retries', () => { // baseline test - __patchPolicyTest(); + __updatePolicyStateTest(); // enable retries and test again createRequestMock.mockClear(); iamPolicyManagementService.enableRetries(); - __patchPolicyTest(); + __updatePolicyStateTest(); // disable retries and test again createRequestMock.mockClear(); iamPolicyManagementService.disableRetries(); - __patchPolicyTest(); + __updatePolicyStateTest(); }); test('should prioritize user-given headers', () => { @@ -741,7 +741,7 @@ describe('IamPolicyManagementV1', () => { const ifMatch = 'testString'; const userAccept = 'fake/accept'; const userContentType = 'fake/contentType'; - const patchPolicyParams = { + const updatePolicyStateParams = { policyId, ifMatch, headers: { @@ -750,7 +750,7 @@ describe('IamPolicyManagementV1', () => { }, }; - iamPolicyManagementService.patchPolicy(patchPolicyParams); + iamPolicyManagementService.updatePolicyState(updatePolicyStateParams); checkMediaHeaders(createRequestMock, userAccept, userContentType); }); }); @@ -759,7 +759,7 @@ describe('IamPolicyManagementV1', () => { test('should enforce required parameters', async () => { let err; try { - await iamPolicyManagementService.patchPolicy({}); + await iamPolicyManagementService.updatePolicyState({}); } catch (e) { err = e; } @@ -770,7 +770,7 @@ describe('IamPolicyManagementV1', () => { test('should reject promise when required params are not given', async () => { let err; try { - await iamPolicyManagementService.patchPolicy(); + await iamPolicyManagementService.updatePolicyState(); } catch (e) { err = e; } @@ -966,27 +966,27 @@ describe('IamPolicyManagementV1', () => { }); }); - describe('updateRole', () => { + describe('replaceRole', () => { describe('positive tests', () => { - function __updateRoleTest() { - // Construct the params object for operation updateRole + function __replaceRoleTest() { + // Construct the params object for operation replaceRole const roleId = 'testString'; const ifMatch = 'testString'; const displayName = 'testString'; - const description = 'testString'; const actions = ['testString']; - const updateRoleParams = { + const description = 'testString'; + const replaceRoleParams = { roleId, ifMatch, displayName, - description, actions, + description, }; - const updateRoleResult = iamPolicyManagementService.updateRole(updateRoleParams); + const replaceRoleResult = iamPolicyManagementService.replaceRole(replaceRoleParams); // all methods should return a Promise - expectToBePromise(updateRoleResult); + expectToBePromise(replaceRoleResult); // assert that create request was called expect(createRequestMock).toHaveBeenCalledTimes(1); @@ -999,42 +999,46 @@ describe('IamPolicyManagementV1', () => { checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); checkUserHeader(createRequestMock, 'If-Match', ifMatch); expect(mockRequestOptions.body.display_name).toEqual(displayName); - expect(mockRequestOptions.body.description).toEqual(description); expect(mockRequestOptions.body.actions).toEqual(actions); + expect(mockRequestOptions.body.description).toEqual(description); expect(mockRequestOptions.path.role_id).toEqual(roleId); } test('should pass the right params to createRequest with enable and disable retries', () => { // baseline test - __updateRoleTest(); + __replaceRoleTest(); // enable retries and test again createRequestMock.mockClear(); iamPolicyManagementService.enableRetries(); - __updateRoleTest(); + __replaceRoleTest(); // disable retries and test again createRequestMock.mockClear(); iamPolicyManagementService.disableRetries(); - __updateRoleTest(); + __replaceRoleTest(); }); test('should prioritize user-given headers', () => { // parameters const roleId = 'testString'; const ifMatch = 'testString'; + const displayName = 'testString'; + const actions = ['testString']; const userAccept = 'fake/accept'; const userContentType = 'fake/contentType'; - const updateRoleParams = { + const replaceRoleParams = { roleId, ifMatch, + displayName, + actions, headers: { Accept: userAccept, 'Content-Type': userContentType, }, }; - iamPolicyManagementService.updateRole(updateRoleParams); + iamPolicyManagementService.replaceRole(replaceRoleParams); checkMediaHeaders(createRequestMock, userAccept, userContentType); }); }); @@ -1043,7 +1047,7 @@ describe('IamPolicyManagementV1', () => { test('should enforce required parameters', async () => { let err; try { - await iamPolicyManagementService.updateRole({}); + await iamPolicyManagementService.replaceRole({}); } catch (e) { err = e; } @@ -1054,7 +1058,7 @@ describe('IamPolicyManagementV1', () => { test('should reject promise when required params are not given', async () => { let err; try { - await iamPolicyManagementService.updateRole(); + await iamPolicyManagementService.replaceRole(); } catch (e) { err = e; } @@ -1231,4 +1235,616 @@ describe('IamPolicyManagementV1', () => { }); }); }); + + describe('listV2Policies', () => { + describe('positive tests', () => { + function __listV2PoliciesTest() { + // Construct the params object for operation listV2Policies + const accountId = 'testString'; + const acceptLanguage = 'default'; + const iamId = 'testString'; + const accessGroupId = 'testString'; + const type = 'access'; + const serviceType = 'service'; + const serviceName = 'testString'; + const serviceGroupId = 'testString'; + const format = 'include_last_permit'; + const state = 'active'; + const listV2PoliciesParams = { + accountId, + acceptLanguage, + iamId, + accessGroupId, + type, + serviceType, + serviceName, + serviceGroupId, + format, + state, + }; + + const listV2PoliciesResult = iamPolicyManagementService.listV2Policies(listV2PoliciesParams); + + // all methods should return a Promise + expectToBePromise(listV2PoliciesResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v2/policies', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + checkUserHeader(createRequestMock, 'Accept-Language', acceptLanguage); + expect(mockRequestOptions.qs.account_id).toEqual(accountId); + expect(mockRequestOptions.qs.iam_id).toEqual(iamId); + expect(mockRequestOptions.qs.access_group_id).toEqual(accessGroupId); + expect(mockRequestOptions.qs.type).toEqual(type); + expect(mockRequestOptions.qs.service_type).toEqual(serviceType); + expect(mockRequestOptions.qs.service_name).toEqual(serviceName); + expect(mockRequestOptions.qs.service_group_id).toEqual(serviceGroupId); + expect(mockRequestOptions.qs.format).toEqual(format); + expect(mockRequestOptions.qs.state).toEqual(state); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __listV2PoliciesTest(); + + // enable retries and test again + createRequestMock.mockClear(); + iamPolicyManagementService.enableRetries(); + __listV2PoliciesTest(); + + // disable retries and test again + createRequestMock.mockClear(); + iamPolicyManagementService.disableRetries(); + __listV2PoliciesTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const accountId = 'testString'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const listV2PoliciesParams = { + accountId, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + iamPolicyManagementService.listV2Policies(listV2PoliciesParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await iamPolicyManagementService.listV2Policies({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await iamPolicyManagementService.listV2Policies(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('createV2Policy', () => { + describe('positive tests', () => { + // Request models needed by this operation. + + // PolicyRole + const policyRoleModel = { + role_id: 'testString', + }; + + // V2PolicyGrant + const v2PolicyGrantModel = { + roles: [policyRoleModel], + }; + + // Control + const controlModel = { + grant: v2PolicyGrantModel, + }; + + // V2PolicySubjectAttribute + const v2PolicySubjectAttributeModel = { + key: 'testString', + operator: 'stringEquals', + value: 'testString', + }; + + // V2PolicySubject + const v2PolicySubjectModel = { + attributes: [v2PolicySubjectAttributeModel], + }; + + // V2PolicyResourceAttribute + const v2PolicyResourceAttributeModel = { + key: 'testString', + operator: 'stringEquals', + value: 'testString', + }; + + // V2PolicyResourceTag + const v2PolicyResourceTagModel = { + key: 'testString', + value: 'testString', + operator: 'stringEquals', + }; + + // V2PolicyResource + const v2PolicyResourceModel = { + attributes: [v2PolicyResourceAttributeModel], + tags: [v2PolicyResourceTagModel], + }; + + // V2PolicyRuleRuleAttribute + const v2PolicyRuleModel = { + key: 'testString', + operator: 'timeLessThan', + value: 'testString', + }; + + function __createV2PolicyTest() { + // Construct the params object for operation createV2Policy + const control = controlModel; + const type = 'access'; + const description = 'testString'; + const subject = v2PolicySubjectModel; + const resource = v2PolicyResourceModel; + const pattern = 'testString'; + const rule = v2PolicyRuleModel; + const acceptLanguage = 'default'; + const createV2PolicyParams = { + control, + type, + description, + subject, + resource, + pattern, + rule, + acceptLanguage, + }; + + const createV2PolicyResult = iamPolicyManagementService.createV2Policy(createV2PolicyParams); + + // all methods should return a Promise + expectToBePromise(createV2PolicyResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v2/policies', 'POST'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + checkUserHeader(createRequestMock, 'Accept-Language', acceptLanguage); + expect(mockRequestOptions.body.control).toEqual(control); + expect(mockRequestOptions.body.type).toEqual(type); + expect(mockRequestOptions.body.description).toEqual(description); + expect(mockRequestOptions.body.subject).toEqual(subject); + expect(mockRequestOptions.body.resource).toEqual(resource); + expect(mockRequestOptions.body.pattern).toEqual(pattern); + expect(mockRequestOptions.body.rule).toEqual(rule); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __createV2PolicyTest(); + + // enable retries and test again + createRequestMock.mockClear(); + iamPolicyManagementService.enableRetries(); + __createV2PolicyTest(); + + // disable retries and test again + createRequestMock.mockClear(); + iamPolicyManagementService.disableRetries(); + __createV2PolicyTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const control = controlModel; + const type = 'access'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const createV2PolicyParams = { + control, + type, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + iamPolicyManagementService.createV2Policy(createV2PolicyParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await iamPolicyManagementService.createV2Policy({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await iamPolicyManagementService.createV2Policy(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('replaceV2Policy', () => { + describe('positive tests', () => { + // Request models needed by this operation. + + // PolicyRole + const policyRoleModel = { + role_id: 'testString', + }; + + // V2PolicyGrant + const v2PolicyGrantModel = { + roles: [policyRoleModel], + }; + + // Control + const controlModel = { + grant: v2PolicyGrantModel, + }; + + // V2PolicySubjectAttribute + const v2PolicySubjectAttributeModel = { + key: 'testString', + operator: 'stringEquals', + value: 'testString', + }; + + // V2PolicySubject + const v2PolicySubjectModel = { + attributes: [v2PolicySubjectAttributeModel], + }; + + // V2PolicyResourceAttribute + const v2PolicyResourceAttributeModel = { + key: 'testString', + operator: 'stringEquals', + value: 'testString', + }; + + // V2PolicyResourceTag + const v2PolicyResourceTagModel = { + key: 'testString', + value: 'testString', + operator: 'stringEquals', + }; + + // V2PolicyResource + const v2PolicyResourceModel = { + attributes: [v2PolicyResourceAttributeModel], + tags: [v2PolicyResourceTagModel], + }; + + // V2PolicyRuleRuleAttribute + const v2PolicyRuleModel = { + key: 'testString', + operator: 'timeLessThan', + value: 'testString', + }; + + function __replaceV2PolicyTest() { + // Construct the params object for operation replaceV2Policy + const id = 'testString'; + const ifMatch = 'testString'; + const control = controlModel; + const type = 'access'; + const description = 'testString'; + const subject = v2PolicySubjectModel; + const resource = v2PolicyResourceModel; + const pattern = 'testString'; + const rule = v2PolicyRuleModel; + const replaceV2PolicyParams = { + id, + ifMatch, + control, + type, + description, + subject, + resource, + pattern, + rule, + }; + + const replaceV2PolicyResult = iamPolicyManagementService.replaceV2Policy(replaceV2PolicyParams); + + // all methods should return a Promise + expectToBePromise(replaceV2PolicyResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v2/policies/{id}', 'PUT'); + const expectedAccept = 'application/json'; + const expectedContentType = 'application/json'; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + checkUserHeader(createRequestMock, 'If-Match', ifMatch); + expect(mockRequestOptions.body.control).toEqual(control); + expect(mockRequestOptions.body.type).toEqual(type); + expect(mockRequestOptions.body.description).toEqual(description); + expect(mockRequestOptions.body.subject).toEqual(subject); + expect(mockRequestOptions.body.resource).toEqual(resource); + expect(mockRequestOptions.body.pattern).toEqual(pattern); + expect(mockRequestOptions.body.rule).toEqual(rule); + expect(mockRequestOptions.path.id).toEqual(id); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __replaceV2PolicyTest(); + + // enable retries and test again + createRequestMock.mockClear(); + iamPolicyManagementService.enableRetries(); + __replaceV2PolicyTest(); + + // disable retries and test again + createRequestMock.mockClear(); + iamPolicyManagementService.disableRetries(); + __replaceV2PolicyTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const id = 'testString'; + const ifMatch = 'testString'; + const control = controlModel; + const type = 'access'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const replaceV2PolicyParams = { + id, + ifMatch, + control, + type, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + iamPolicyManagementService.replaceV2Policy(replaceV2PolicyParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await iamPolicyManagementService.replaceV2Policy({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await iamPolicyManagementService.replaceV2Policy(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('getV2Policy', () => { + describe('positive tests', () => { + function __getV2PolicyTest() { + // Construct the params object for operation getV2Policy + const id = 'testString'; + const getV2PolicyParams = { + id, + }; + + const getV2PolicyResult = iamPolicyManagementService.getV2Policy(getV2PolicyParams); + + // all methods should return a Promise + expectToBePromise(getV2PolicyResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v2/policies/{id}', 'GET'); + const expectedAccept = 'application/json'; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.path.id).toEqual(id); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __getV2PolicyTest(); + + // enable retries and test again + createRequestMock.mockClear(); + iamPolicyManagementService.enableRetries(); + __getV2PolicyTest(); + + // disable retries and test again + createRequestMock.mockClear(); + iamPolicyManagementService.disableRetries(); + __getV2PolicyTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const id = 'testString'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const getV2PolicyParams = { + id, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + iamPolicyManagementService.getV2Policy(getV2PolicyParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await iamPolicyManagementService.getV2Policy({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await iamPolicyManagementService.getV2Policy(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); + + describe('deleteV2Policy', () => { + describe('positive tests', () => { + function __deleteV2PolicyTest() { + // Construct the params object for operation deleteV2Policy + const id = 'testString'; + const deleteV2PolicyParams = { + id, + }; + + const deleteV2PolicyResult = iamPolicyManagementService.deleteV2Policy(deleteV2PolicyParams); + + // all methods should return a Promise + expectToBePromise(deleteV2PolicyResult); + + // assert that create request was called + expect(createRequestMock).toHaveBeenCalledTimes(1); + + const mockRequestOptions = getOptions(createRequestMock); + + checkUrlAndMethod(mockRequestOptions, '/v2/policies/{id}', 'DELETE'); + const expectedAccept = undefined; + const expectedContentType = undefined; + checkMediaHeaders(createRequestMock, expectedAccept, expectedContentType); + expect(mockRequestOptions.path.id).toEqual(id); + } + + test('should pass the right params to createRequest with enable and disable retries', () => { + // baseline test + __deleteV2PolicyTest(); + + // enable retries and test again + createRequestMock.mockClear(); + iamPolicyManagementService.enableRetries(); + __deleteV2PolicyTest(); + + // disable retries and test again + createRequestMock.mockClear(); + iamPolicyManagementService.disableRetries(); + __deleteV2PolicyTest(); + }); + + test('should prioritize user-given headers', () => { + // parameters + const id = 'testString'; + const userAccept = 'fake/accept'; + const userContentType = 'fake/contentType'; + const deleteV2PolicyParams = { + id, + headers: { + Accept: userAccept, + 'Content-Type': userContentType, + }, + }; + + iamPolicyManagementService.deleteV2Policy(deleteV2PolicyParams); + checkMediaHeaders(createRequestMock, userAccept, userContentType); + }); + }); + + describe('negative tests', () => { + test('should enforce required parameters', async () => { + let err; + try { + await iamPolicyManagementService.deleteV2Policy({}); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + + test('should reject promise when required params are not given', async () => { + let err; + try { + await iamPolicyManagementService.deleteV2Policy(); + } catch (e) { + err = e; + } + + expect(err.message).toMatch(/Missing required parameters/); + }); + }); + }); });