Example #1
0
    def Run(self, args):
        messages = org_policies.OrgPoliciesMessages()
        service = org_policies_base.OrgPoliciesService(args)

        policy = service.GetOrgPolicy(
            org_policies_base.GetOrgPolicyRequest(args))

        if policy.booleanPolicy or (policy.listPolicy
                                    and policy.listPolicy.allowedValues):
            raise exceptions.ResourceManagerError(
                'Cannot add values to a non-denied_values list policy.')

        if policy.listPolicy and policy.listPolicy.allValues:
            raise exceptions.ResourceManagerError(
                'Cannot add values if all_values is already specified.')

        if policy.listPolicy and policy.listPolicy.deniedValues:
            for value in args.denied_value:
                policy.listPolicy.deniedValues.append(six.text_type(value))
        else:
            policy.listPolicy = messages.ListPolicy(
                deniedValues=args.denied_value)

        return service.SetOrgPolicy(
            org_policies_base.SetOrgPolicyRequest(args, policy))
Example #2
0
  def SetUp(self):
    self.SelectApi('beta')
    self.track = calliope_base.ReleaseTrack.BETA

    list_json_patcher = mock.patch(
        'googlecloudsdk.api_lib.compute.request_helper.ListJson', autospec=True)
    self.addCleanup(list_json_patcher.stop)
    self.list_json = list_json_patcher.start()

    self.list_json.side_effect = [
        resource_projector.MakeSerializable(test_resources.IMAGES +
                                            test_resources.CENTOS_IMAGES)
    ]
    self.all_project_requests = [
        (self.compute.images, 'List',
         self.messages.ComputeImagesListRequest(
             project='centos-cloud')),
        (self.compute.images, 'List',
         self.messages.ComputeImagesListRequest(
             project='cos-cloud')),
        (self.compute.images, 'List',
         self.messages.ComputeImagesListRequest(
             project='debian-cloud')),
        (self.compute.images, 'List',
         self.messages.ComputeImagesListRequest(
             project='fedora-coreos-cloud')),
        (self.compute.images, 'List',
         self.messages.ComputeImagesListRequest(
             project='my-project')),
        (self.compute.images, 'List',
         self.messages.ComputeImagesListRequest(
             project='rhel-cloud')),
        (self.compute.images, 'List',
         self.messages.ComputeImagesListRequest(
             project='rhel-sap-cloud')),
        (self.compute.images, 'List',
         self.messages.ComputeImagesListRequest(
             project='suse-cloud')),
        (self.compute.images, 'List',
         self.messages.ComputeImagesListRequest(
             project='suse-sap-cloud')),
        (self.compute.images, 'List',
         self.messages.ComputeImagesListRequest(
             project='ubuntu-os-cloud')),
        (self.compute.images, 'List',
         self.messages.ComputeImagesListRequest(
             project='windows-cloud')),
        (self.compute.images, 'List',
         self.messages.ComputeImagesListRequest(
             project='windows-sql-cloud')),
    ]

    self.mocked_org_policies_client = apitools_mock.Client(
        apis.GetClientClass('cloudresourcemanager',
                            org_policies.ORG_POLICIES_API_VERSION))
    self.mocked_org_policies_client.Mock()
    self.addCleanup(self.mocked_org_policies_client.Unmock)

    self.org_policies_messages = org_policies.OrgPoliciesMessages()
    def Run(self, args):
        service = org_policies_base.OrgPoliciesService(args)
        messages = org_policies.OrgPoliciesMessages()

        return service.SetOrgPolicy(
            org_policies_base.SetOrgPolicyRequest(
                args,
                org_policies.GetFileAsMessage(args.policy_file,
                                              messages.OrgPolicy)))
    def Run(self, args):
        service = org_policies_base.OrgPoliciesService(args)
        messages = org_policies.OrgPoliciesMessages()

        return service.SetOrgPolicy(
            org_policies_base.SetOrgPolicyRequest(
                args,
                messages.OrgPolicy(
                    constraint=org_policies.FormatConstraint(args.id),
                    booleanPolicy=messages.BooleanPolicy(enforced=True))))
Example #5
0
 def ListOrgPoliciesRequest(args):
     messages = org_policies.OrgPoliciesMessages()
     resource_id = org_policies_base.GetResource(args)
     request = messages.ListOrgPoliciesRequest()
     if args.project:
         return messages.CloudresourcemanagerProjectsListOrgPoliciesRequest(
             projectsId=resource_id, listOrgPoliciesRequest=request)
     elif args.organization:
         return messages.CloudresourcemanagerOrganizationsListOrgPoliciesRequest(
             organizationsId=resource_id, listOrgPoliciesRequest=request)
     return None
Example #6
0
  def ClearOrgPolicyRequest(args):
    messages = org_policies.OrgPoliciesMessages()
    resource_id = org_policies_base.GetResource(args)
    request = messages.ClearOrgPolicyRequest(
        constraint=org_policies.FormatConstraint(args.id))

    if args.project:
      return messages.CloudresourcemanagerProjectsClearOrgPolicyRequest(
          projectsId=resource_id, clearOrgPolicyRequest=request)
    elif args.organization:
      return messages.CloudresourcemanagerOrganizationsClearOrgPolicyRequest(
          organizationsId=resource_id, clearOrgPolicyRequest=request)
    return None
Example #7
0
def _GetPolicy(project_id):
    """Get effective org policy of given project."""
    messages = org_policies.OrgPoliciesMessages()
    request = messages.CloudresourcemanagerProjectsGetEffectiveOrgPolicyRequest(
        projectsId=project_id,
        getEffectiveOrgPolicyRequest=messages.GetEffectiveOrgPolicyRequest(
            constraint=org_policies.FormatConstraint(
                'compute.trustedImageProjects')))
    client = org_policies.OrgPoliciesClient()
    response = client.projects.GetEffectiveOrgPolicy(request)
    # There are several possible policy types; the only policy type that applies
    # to 'compute.trustedImageProjects' is listPolicy, so we can assume that's
    # what the caller is interested in.
    return response.listPolicy
  def GetEffectiveOrgPolicyRequest(args):
    m = org_policies.OrgPoliciesMessages()
    resource_id = org_policies_base.GetResource(args)
    request = m.GetEffectiveOrgPolicyRequest(
        constraint=org_policies.FormatConstraint(args.id))

    if args.project:
      return m.CloudresourcemanagerProjectsGetEffectiveOrgPolicyRequest(
          projectsId=resource_id, getEffectiveOrgPolicyRequest=request)
    elif args.organization:
      return m.CloudresourcemanagerOrganizationsGetEffectiveOrgPolicyRequest(
          organizationsId=resource_id, getEffectiveOrgPolicyRequest=request)
    elif args.folder:
      return m.CloudresourcemanagerFoldersGetEffectiveOrgPolicyRequest(
          foldersId=resource_id, getEffectiveOrgPolicyRequest=request)
    return None
Example #9
0
    def ListAvailableOrgPolicyConstraintsRequest(args):
        messages = org_policies.OrgPoliciesMessages()
        resource_id = org_policies_base.GetResource(args)
        request = messages.ListAvailableOrgPolicyConstraintsRequest()

        if args.project:
            # pylint: disable=line-too-long
            return messages.CloudresourcemanagerProjectsListAvailableOrgPolicyConstraintsRequest(
                projectsId=resource_id,
                listAvailableOrgPolicyConstraintsRequest=request)
        elif args.organization:
            # pylint: disable=line-too-long
            return messages.CloudresourcemanagerOrganizationsListAvailableOrgPolicyConstraintsRequest(
                organizationsId=resource_id,
                listAvailableOrgPolicyConstraintsRequest=request)
        return None
Example #10
0
  def Run(self, args):
    flags.CheckResourceFlags(args)
    service = org_policies_base.OrgPoliciesService(args)

    response = service.ListOrgPolicies(self.ListOrgPoliciesRequest(args))

    if args.show_unset:
      constraints = service.ListAvailableOrgPolicyConstraints(
          self.ListAvailableOrgPolicyConstraintsRequest(args))
      existing_policies = [policy.constraint for policy in response.policies]
      messages = org_policies.OrgPoliciesMessages()
      for constraint in constraints.constraints:
        if constraint.name not in existing_policies:
          response.policies.append(
              messages.OrgPolicy(constraint=constraint.name))

    return response.policies
Example #11
0
def GetOrgPolicyRequest(args):
    """Constructs a resource-dependent GetOrgPolicyRequest.

  Args:
    args: Command line arguments.

  Returns:
    Resource-dependent GetOrgPolicyRequest.
  """
    messages = org_policies.OrgPoliciesMessages()
    request = messages.GetOrgPolicyRequest(
        constraint=org_policies.FormatConstraint(args.id))
    resource_id = GetResource(args)
    if args.project:
        return messages.CloudresourcemanagerProjectsGetOrgPolicyRequest(
            projectsId=resource_id, getOrgPolicyRequest=request)
    elif args.organization:
        return messages.CloudresourcemanagerOrganizationsGetOrgPolicyRequest(
            organizationsId=resource_id, getOrgPolicyRequest=request)
    return None
Example #12
0
  def Run(self, args):
    flags.CheckResourceFlags(args)
    messages = org_policies.OrgPoliciesMessages()
    service = org_policies_base.OrgPoliciesService(args)

    policy = service.GetOrgPolicy(org_policies_base.GetOrgPolicyRequest(args))

    if policy.booleanPolicy or (
        policy.listPolicy and
        (policy.listPolicy.deniedValues or policy.listPolicy.allValues)):
      raise exceptions.ResourceManagerError(
          'Cannot add values to a non-allowed_values list policy.')

    if policy.listPolicy and policy.listPolicy.allowedValues:
      for value in args.allowed_value:
        policy.listPolicy.allowedValues.append(unicode(value))
    else:
      policy.listPolicy = messages.ListPolicy(allowedValues=args.allowed_value)

    return service.SetOrgPolicy(
        org_policies_base.SetOrgPolicyRequest(args, policy))
Example #13
0
def SetOrgPolicyRequest(args, policy):
    """Constructs a resource-dependent SetOrgPolicyRequest.

  Args:
    args: Command line arguments.
    policy: OrgPolicy for resource-dependent SetOrgPolicyRequest.

  Returns:
    Resource-dependent SetOrgPolicyRequest.
  """
    messages = org_policies.OrgPoliciesMessages()
    resource_id = GetResource(args)
    request = messages.SetOrgPolicyRequest(policy=policy)

    if args.project:
        return messages.CloudresourcemanagerProjectsSetOrgPolicyRequest(
            projectsId=resource_id, setOrgPolicyRequest=request)
    elif args.organization:
        return messages.CloudresourcemanagerOrganizationsSetOrgPolicyRequest(
            organizationsId=resource_id, setOrgPolicyRequest=request)
    return None
Example #14
0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

from googlecloudsdk.api_lib.resource_manager import org_policies
from googlecloudsdk.core import properties
from tests.lib import e2e_base
from tests.lib import test_case

messages = org_policies.OrgPoliciesMessages()

TEST_ORGANIZATION_ID = '1054311078602'
TEST_CONSTRAINT = 'constraints/compute.disableSerialPortAccess'


class OrgPoliciesIntegrationTest(e2e_base.WithServiceAuth):
    def SetUp(self):
        properties.VALUES.core.user_output_enabled.Set(False)

    def GetIntegrationTestOrgPolicy(self):
        return messages.OrgPolicy(
            constraint=TEST_CONSTRAINT,
            booleanPolicy=messages.BooleanPolicy(enforced=True))

    def AssertOrgPoliciesEqual(self, expected, policy):
Example #15
0
class OrgPoliciesUnitTestBase(cli_test_base.CliTestBase,
                              sdk_test_base.WithFakeAuth):
  """Base class for all Org Policies unit tests with fake auth and mocks."""

  PROJECT_ARG = ['--project', 'test-project']
  ORG_ARG = ['--organization', 'test-org']
  FOLDER_ARG = ['--folder', 'test-folder']
  WRONG_ARG = ['--No-SuCh-FlAg', 'no-such-flag']

  messages = org_policies.OrgPoliciesMessages()

  VALUE_ZERO = 'valueZero'
  VALUE_A = 'valueA'
  VALUE_B = 'valueB'
  ORIGINAL_VALUES = [VALUE_ZERO]
  NEW_VALUES = [VALUE_ZERO, VALUE_A, VALUE_B]
  WHITELIST_CONSTRAINT = 'constraints/goodService.betterWhitelist'
  BLACKLIST_CONSTRAINT = 'constraints/goodService.betterBlacklist'
  TEST_CONSTRAINT = 'constraints/goodService.betterFeatureOne'

  def SetUp(self):
    mock_client = self._SetUpMockCrmClient(
        org_policies.ORG_POLICIES_API_VERSION)
    self.mock_projects = mock_client.projects
    self.mock_organizations = mock_client.organizations
    self.mock_folders = mock_client.folders

  def _SetUpMockCrmClient(self, version):
    client = mock.Client(
        apis.GetClientClass('cloudresourcemanager', version),
        real_client=apis.GetClientInstance(
            'cloudresourcemanager', version, no_http=True))
    client.Mock()
    self.addCleanup(client.Unmock)
    return client

  def RunOrgPolicies(self, *command):
    return self.Run(['beta', 'resource-manager', 'org-policies'] +
                    list(command))

  def ExpectedSetRequest(self, arg, policy):
    msg = self.messages
    if arg == self.PROJECT_ARG:
      return msg.CloudresourcemanagerProjectsSetOrgPolicyRequest(
          projectsId=self.PROJECT_ARG[1],
          setOrgPolicyRequest=msg.SetOrgPolicyRequest(policy=policy))
    elif arg == self.ORG_ARG:
      return msg.CloudresourcemanagerOrganizationsSetOrgPolicyRequest(
          organizationsId=self.ORG_ARG[1],
          setOrgPolicyRequest=msg.SetOrgPolicyRequest(policy=policy))
    elif arg == self.FOLDER_ARG:
      return msg.CloudresourcemanagerFoldersSetOrgPolicyRequest(
          foldersId=self.FOLDER_ARG[1],
          setOrgPolicyRequest=msg.SetOrgPolicyRequest(policy=policy))

  def ExpectedGetRequest(self, arg, constraint):
    msg = self.messages
    if arg == self.PROJECT_ARG:
      return msg.CloudresourcemanagerProjectsGetOrgPolicyRequest(
          projectsId=self.PROJECT_ARG[1],
          getOrgPolicyRequest=msg.GetOrgPolicyRequest(constraint=constraint))
    elif arg == self.ORG_ARG:
      return msg.CloudresourcemanagerOrganizationsGetOrgPolicyRequest(
          organizationsId=self.ORG_ARG[1],
          getOrgPolicyRequest=msg.GetOrgPolicyRequest(constraint=constraint))
    elif arg == self.FOLDER_ARG:
      return msg.CloudresourcemanagerFoldersGetOrgPolicyRequest(
          foldersId=self.FOLDER_ARG[1],
          getOrgPolicyRequest=msg.GetOrgPolicyRequest(constraint=constraint))

  def TestPolicy(self):
    return self.messages.OrgPolicy(
        constraint=self.TEST_CONSTRAINT,
        booleanPolicy=self.messages.BooleanPolicy(enforced=True))

  def WhitelistPolicy(self, allowed_values):
    return self.messages.OrgPolicy(
        constraint=self.WHITELIST_CONSTRAINT,
        listPolicy=self.messages.ListPolicy(allowedValues=allowed_values))

  def AllowAllPolicy(self):
    return self.messages.OrgPolicy(
        constraint=self.WHITELIST_CONSTRAINT,
        listPolicy=self.messages.ListPolicy(
            allValues=self.messages.ListPolicy.AllValuesValueValuesEnum.ALLOW))

  def BlacklistPolicy(self, denied_values):
    return self.messages.OrgPolicy(
        constraint=self.BLACKLIST_CONSTRAINT,
        listPolicy=self.messages.ListPolicy(deniedValues=denied_values))

  def DenyAllPolicy(self):
    return self.messages.OrgPolicy(
        constraint=self.BLACKLIST_CONSTRAINT,
        listPolicy=self.messages.ListPolicy(
            allValues=self.messages.ListPolicy.AllValuesValueValuesEnum.DENY))