Example #1
0
def _AddVpcAccessibleServicesFilter(args, req, version):
    """Add the particular service filter message based on specified args."""
    service_restriction_config = None
    allowed_services = None
    enable_restriction = None
    restriction_modified = False
    service_perimeter_config = req.servicePerimeter.status
    if not service_perimeter_config:
        service_perimeter_config = (util.GetMessages(
            version=version).ServicePerimeterConfig)

    if args.IsSpecified('vpc_allowed_services'):
        allowed_services = getattr(args, 'vpc_allowed_services')
        restriction_modified = True

    if args.IsSpecified('enable_vpc_accessible_services'):
        enable_restriction = getattr(args, 'enable_vpc_accessible_services')
        restriction_modified = True

    if restriction_modified:
        service_restriction_config = getattr(service_perimeter_config,
                                             'vpcAccessibleServices')
        if not service_restriction_config:
            service_restriction_config = (getattr(
                util.GetMessages(version=version), 'VpcAccessibleServices'))
        service_restriction_config.allowedServices = allowed_services
        service_restriction_config.enableRestriction = enable_restriction

    setattr(service_perimeter_config, 'vpcAccessibleServices',
            service_restriction_config)
    req.servicePerimeter.status = service_perimeter_config

    return req
Example #2
0
 def Run(self, args):
     client = zones_api.Client(version=self._API_VERSION)
     messages = util.GetMessages(version=self._API_VERSION)
     perimeter_ref = args.CONCEPTS.perimeter.Parse()
     policies.ValidateAccessPolicyArg(perimeter_ref, args)
     original_perimeter = client.Get(perimeter_ref)
     base_config = _GetBaseConfig(original_perimeter)
     updated_resources = repeated.ParsePrimitiveArgs(
         args, 'resources', lambda: base_config.resources or [])
     updated_restricted_services = repeated.ParsePrimitiveArgs(
         args, 'restricted-services',
         lambda: base_config.restrictedServices or [])
     updated_access_levels = repeated.ParsePrimitiveArgs(
         args, 'access-levels', lambda: base_config.accessLevels or [])
     base_vpc_config = base_config.vpcAccessibleServices
     if base_vpc_config is None:
         base_vpc_config = messages.VpcAccessibleServices()
     updated_vpc_services = repeated.ParsePrimitiveArgs(
         args, 'vpc-allowed-services',
         lambda: base_vpc_config.allowedServices or [])
     if args.IsSpecified('enable_vpc_accessible_services'):
         updated_vpc_enabled = args.enable_vpc_accessible_services
     elif base_config.vpcAccessibleServices is not None:
         updated_vpc_enabled = base_vpc_config.enableRestriction
     else:
         updated_vpc_enabled = None
     return client.PatchDryRunConfig(
         perimeter_ref,
         resources=updated_resources,
         levels=updated_access_levels,
         restricted_services=updated_restricted_services,
         vpc_allowed_services=updated_vpc_services,
         enable_vpc_accessible_services=updated_vpc_enabled)
Example #3
0
    def VersionedParseAccessLevels(path):
        """Parse a YAML representation of a list of Access Levels with basic/custom level conditions.

    Args:
      path: str, path to file containing basic/custom access levels

    Returns:
      list of Access Level objects.

    Raises:
      ParseError: if the file could not be read into the proper object
    """

        data = yaml.load_path(path)
        if not data:
            raise ParseError(path, 'File is empty')

        messages = util.GetMessages(version=api_version)
        message_class = messages.AccessLevel
        try:
            levels = [encoding.DictToMessage(c, message_class) for c in data]
        except Exception as err:
            raise InvalidFormatError(path, six.text_type(err), message_class)

        _ValidateAllLevelFieldsRecognized(path, levels)
        return levels
Example #4
0
def AddImplicitServiceWildcard(ref, args, req):
  """Add an implicit wildcard for services if they are modified.

  If either restricted services or unrestricted services is given, the other
  must also be provided as a wildcard (`*`).

  If neither is given, this is a no-op.

  Args:
    ref: resources.Resource, the (unused) resource
    args: argparse namespace, the parse arguments
    req: AccesscontextmanagerAccessPoliciesAccessZonesCreateRequest

  Returns:
    The modified request.
  """
  del ref  # Unused in AddImplicitServiceWildcard
  service_perimeter_config = req.servicePerimeter.status
  if not service_perimeter_config:
    service_perimeter_config = util.GetMessages(
        version='v1beta').ServicePerimeterConfig
  if args.IsSpecified('restricted_services'):
    service_perimeter_config.unrestrictedServices = ['*']
  elif args.IsSpecified('unrestricted_services'):
    service_perimeter_config.restrictedServices = ['*']
  req.servicePerimeter.status = service_perimeter_config
  return req
Example #5
0
    def Run(self, args):
        client = zones_api.Client(version=self._API_VERSION)
        messages = util.GetMessages(version=self._API_VERSION)
        perimeter_ref = args.CONCEPTS.perimeter.Parse()
        policies.ValidateAccessPolicyArg(perimeter_ref, args)
        original_perimeter = client.Get(perimeter_ref)
        base_config = _GetBaseConfig(original_perimeter)
        if _IsFieldSpecified('resources', args):
            updated_resources = _GetRepeatedFieldValue(
                args, 'resources', base_config.resources,
                original_perimeter.useExplicitDryRunSpec)
        else:
            updated_resources = base_config.resources
        if _IsFieldSpecified('restricted_services', args):
            updated_restricted_services = _GetRepeatedFieldValue(
                args, 'restricted_services', base_config.restrictedServices,
                original_perimeter.useExplicitDryRunSpec)
        else:
            updated_restricted_services = base_config.restrictedServices
        if _IsFieldSpecified('access_levels', args):
            updated_access_levels = _GetRepeatedFieldValue(
                args, 'access_levels', base_config.accessLevels,
                original_perimeter.useExplicitDryRunSpec)
        else:
            updated_access_levels = base_config.accessLevels
        base_vpc_config = base_config.vpcAccessibleServices
        if base_vpc_config is None:
            base_vpc_config = messages.VpcAccessibleServices()
        if _IsFieldSpecified('vpc_allowed_services', args):
            updated_vpc_services = _GetRepeatedFieldValue(
                args, 'vpc-allowed-services', base_vpc_config.allowedServices,
                original_perimeter.useExplicitDryRunSpec)
        elif base_config.vpcAccessibleServices is not None:
            updated_vpc_services = base_vpc_config.allowedServices
        else:
            updated_vpc_services = None
        if args.IsSpecified('enable_vpc_accessible_services'):
            updated_vpc_enabled = args.enable_vpc_accessible_services
        elif base_config.vpcAccessibleServices is not None:
            updated_vpc_enabled = base_vpc_config.enableRestriction
        else:
            updated_vpc_enabled = None
        # Vpc allowed services list should only be populated if enable restrictions
        # is set to true.
        if updated_vpc_enabled is None:
            updated_vpc_services = None
        elif not updated_vpc_enabled:
            updated_vpc_services = []

        return client.PatchDryRunConfig(
            perimeter_ref,
            resources=updated_resources,
            levels=updated_access_levels,
            restricted_services=updated_restricted_services,
            vpc_allowed_services=updated_vpc_services,
            enable_vpc_accessible_services=updated_vpc_enabled,
            ingress_policies=perimeters.ParseUpdateDirectionalPoliciesArgs(
                args, 'ingress-policies'),
            egress_policies=perimeters.ParseUpdateDirectionalPoliciesArgs(
                args, 'egress-policies'))
def ParseServicePerimetersBase(path, version=None):
    """Parse a YAML representation of a list of Service Perimeters.

  Args:
    path: str, path to file containing service perimeters
    version: str, api version of ACM to use for proto messages

  Returns:
    list of Service Perimeters objects.

  Raises:
    ParseError: if the file could not be read into the proper object
  """

    data = yaml.load_path(path)
    if not data:
        raise ParseError(path, 'File is empty')

    messages = util.GetMessages(version=version)
    message_class = messages.ServicePerimeter
    try:
        conditions = [encoding.DictToMessage(c, message_class) for c in data]
    except Exception as err:
        raise InvalidFormatError(path, six.text_type(err), message_class)

    _ValidateAllFieldsRecognized(path, conditions)
    return conditions
Example #7
0
    def VersionedParseCustomLevel(path):
        """Parse a YAML representation of custom level conditions.

    Args:
      path: str, path to file containing custom level expression

    Returns:
      string of CEL expression.

    Raises:
      ParseError: if the file could not be read into the proper object
    """

        data = yaml.load_path(path)
        if not data:
            raise ParseError(path, 'File is empty')

        messages = util.GetMessages(version=api_version)
        message_class = messages.Expr
        try:
            expr = encoding.DictToMessage(data, message_class)
        except Exception as err:
            raise InvalidFormatError(path, six.text_type(err), message_class)

        _ValidateAllCustomFieldsRecognized(path, expr)
        return expr
Example #8
0
def GenerateDryRunConfigDiff(perimeter, api_version):
    """Generates a diff string by comparing status with spec."""
    if perimeter.spec is None and perimeter.useExplicitDryRunSpec:
        return 'This Service Perimeter has been marked for deletion dry-run mode.'
    if perimeter.status is None and perimeter.spec is None:
        return 'This Service Perimeter has no dry-run or enforcement mode config.'
    output = []
    status = perimeter.status
    if not perimeter.useExplicitDryRunSpec:
        spec = status
        output.append('This Service Perimeter does not have an explicit '
                      'dry-run mode configuration. The enforcement config '
                      'will be used as the dry-run mode configuration.')
    else:
        spec = perimeter.spec

    if status is None:
        messages = util.GetMessages(version=api_version)
        status = messages.ServicePerimeterConfig()

    perimeter.status = status
    perimeter.spec = spec

    output.append('  name: {}'.format(
        perimeter.name[perimeter.name.rfind('/') + 1:]))
    output.append('  title: {}'.format(perimeter.title))

    output.append('  type: {}'.format(perimeter.perimeterType
                                      or 'PERIMETER_TYPE_REGULAR'))

    print('\n'.join(output))
    acm_printer.Print(perimeter, 'diff[format=yaml](status, spec)')
Example #9
0
def ParseBasicLevelConditions(path):
    """Parse a YAML representation of basic level conditions..

  Args:
    path: str, path to file containing basic level conditions

  Returns:
    list of Condition objects.

  Raises:
    ParseError: if the file could not be read into the proper object
  """

    data = yaml.load_path(path)
    if not data:
        raise ParseError(path, 'File is empty')

    messages = util.GetMessages()
    message_class = messages.Condition
    try:
        conditions = [encoding.DictToMessage(c, message_class) for c in data]
    except Exception as err:
        raise InvalidFormatError(path, str(err), message_class)

    _ValidateAllFieldsRecognized(path, conditions)
    return conditions
Example #10
0
def GetCombineFunctionEnumMapper():
  return arg_utils.ChoiceEnumMapper(
      '--combine-function',
      util.GetMessages().BasicLevel.CombiningFunctionValueValuesEnum,
      custom_mappings={'AND': 'and', 'OR': 'or'},
      required=False,
      help_str='For a basic level, determines how conditions are combined.',
  )
Example #11
0
def GenerateDryRunConfigDiff(perimeter, api_version):
  """Generates a diff string by comparing status with spec."""
  if perimeter.spec is None and perimeter.useExplicitDryRunSpec:
    return 'This Service Perimeter has been marked for deletion dry-run mode.'
  if perimeter.status is None and perimeter.spec is None:
    return 'This Service Perimeter has no dry-run or enforcement mode config.'
  output = []
  status = perimeter.status
  if not perimeter.useExplicitDryRunSpec:
    spec = status
    output.append('This Service Perimeter does not have an explicit '
                  'dry-run mode configuration. The enforcement config '
                  'will be used as the dry-run mode configuration.')
  else:
    spec = perimeter.spec

  if status is None:
    messages = util.GetMessages(version=api_version)
    status = messages.ServicePerimeterConfig()

  output.append('name: {}'.format(perimeter.name[perimeter.name.rfind('/') +
                                                 1:]))
  output.append('title: {}'.format(perimeter.title))

  output.append('type: {}'.format(perimeter.perimeterType or
                                  'PERIMETER_TYPE_REGULAR'))

  output.extend(_CompareTopLevelField(status, spec, 'resources'))
  output.extend(_CompareTopLevelField(status, spec, 'restrictedServices'))
  output.extend(_CompareTopLevelField(status, spec, 'accessLevels'))

  status_vpc = status.vpcAccessibleServices
  spec_vpc = spec.vpcAccessibleServices

  output.append('vpcAccessibleServices:')
  if status_vpc is None and spec_vpc is None:
    output.append('   NONE')
  else:
    status_enabled = bool(status_vpc and status_vpc.enableRestriction)
    spec_enabled = bool(spec_vpc and spec_vpc.enableRestriction)
    output.append('  enableRestriction: {} -> {}'.format(
        status_enabled, spec_enabled))
    if status_vpc is not None:
      status_vpc_services = set(status_vpc.allowedServices)
    else:
      status_vpc_services = set()
    if spec_vpc is not None:
      spec_vpc_services = set(spec_vpc.allowedServices)
    else:
      spec_vpc_services = set()
    output.extend(
        _CompareField(
            status_vpc_services,
            spec_vpc_services,
            'allowedServices',
            line_prefix='  '))
  return '\n'.join(output)
def _AddServiceFilterRestriction(args, req, version, restriction_type):
    """Add the particular service filter message based on specified args."""
    service_restriction_config = None
    allowed_services = None
    enable_restriction = None
    restriction_modified = False
    service_perimeter_config = req.servicePerimeter.status
    if not service_perimeter_config:
        service_perimeter_config = (util.GetMessages(
            version=version).ServicePerimeterConfig)

    if args.IsSpecified(restriction_type + '_allowed_services'):
        allowed_services = getattr(args,
                                   restriction_type + '_allowed_services')
        restriction_modified = True

    if args.IsSpecified('enable_' + restriction_type + '_service_restriction'):
        enable_restriction = getattr(
            args, 'enable_' + restriction_type + '_service_restriction')
        restriction_modified = True

    if restriction_modified:
        service_restriction_config = getattr(
            service_perimeter_config, restriction_type + 'ServiceRestriction')
        if not service_restriction_config:
            service_restriction_config = (getattr(
                util.GetMessages(version=version),
                restriction_type.capitalize() + 'ServiceRestriction'))
        service_restriction_config.allowedServices = allowed_services
        service_restriction_config.enableRestriction = enable_restriction

    setattr(service_perimeter_config, restriction_type + 'ServiceRestriction',
            service_restriction_config)
    req.servicePerimeter.status = service_perimeter_config

    return req
Example #13
0
def AddAccessLevels(ref, args, req):
  """Hook to add access levels to request."""
  if args.IsSpecified('access_levels'):
    access_levels = []
    for access_level in args.access_levels:
      level_ref = resources.REGISTRY.Create(
          'accesscontextmanager.accessPolicies.accessLevels',
          accessLevelsId=access_level, **ref.Parent().AsDict())
      access_levels.append(level_ref.RelativeName())
    service_perimeter_config = req.servicePerimeter.status
    if not service_perimeter_config:
      service_perimeter_config = (
          util.GetMessages(version='v1beta').ServicePerimeterConfig)
    service_perimeter_config.accessLevels = access_levels
    req.servicePerimeter.status = service_perimeter_config
  return req
Example #14
0
def AddImplicitUnrestrictedServiceWildcard(ref, args, req):
    """Add wildcard for unrestricted services to message.

  Args:
    ref: resources.Resource, the (unused) resource
    args: argparse namespace, the parse arguments
    req: AccesscontextmanagerAccessPoliciesAccessZonesCreateRequest

  Returns:
    The modified request.
  """
    del ref, args  # Unused in AddImplicitServiceWildcard
    service_perimeter_config = req.servicePerimeter.status
    if not service_perimeter_config:
        service_perimeter_config = util.GetMessages(
            version='v1beta').ServicePerimeterConfig
    service_perimeter_config.unrestrictedServices = ['*']
    req.servicePerimeter.status = service_perimeter_config
    return req
Example #15
0
def ParseReplaceAccessLevelsResponseBase(lro, version):
    """Parse the Long Running Operation response of the ReplaceAccessLevels call.

  Args:
    lro: Long Running Operation response of ReplaceAccessLevels.
    version: version of the API. e.g. 'v1beta', 'v1'.

  Returns:
    The replacement Access Levels created by the ReplaceAccessLevels call.

  Raises:
    ParseResponseError: if the response could not be parsed into the proper
    object.
  """
    messages = util.GetMessages(version)
    message_class = messages.ReplaceAccessLevelsResponse
    try:
        return encoding.DictToMessage(encoding.MessageToDict(lro.response),
                                      message_class).accessLevels
    except Exception as err:
        raise ParseResponseError(six.text_type(err))
Example #16
0
def AddImplicitUnrestrictedServiceWildcard(ref, args, req):
  """Add wildcard for unrestricted services to message if type is regular.

  Args:
    ref: resources.Resource, the (unused) resource
    args: argparse namespace, the parse arguments
    req: AccesscontextmanagerAccessPoliciesAccessZonesCreateRequest

  Returns:
    The modified request.
  """
  del ref, args  # Unused in AddImplicitServiceWildcard

  m = util.GetMessages(version='v1beta')
  if req.servicePerimeter.perimeterType == (
      m.ServicePerimeter.PerimeterTypeValueValuesEnum.PERIMETER_TYPE_REGULAR):
    service_perimeter_config = req.servicePerimeter.status
    if not service_perimeter_config:
      service_perimeter_config = m.ServicePerimeterConfig
    service_perimeter_config.unrestrictedServices = ['*']
    req.servicePerimeter.status = service_perimeter_config
  return req
Example #17
0
def GetTypeEnumMapper():
  return arg_utils.ChoiceEnumMapper(
      '--type',
      util.GetMessages().ServicePerimeter.PerimeterTypeValueValuesEnum,
      custom_mappings={
          'PERIMETER_TYPE_REGULAR': 'regular',
          'PERIMETER_TYPE_BRIDGE': 'bridge'
      },
      required=False,
      help_str="""\
          Type of the perimeter.

          A *regular* perimeter allows resources within this service perimeter
          to import and export data amongst themselves. A project may belong to
          at most one regular service perimeter.

          A *bridge* perimeter allows resources in different regular service
          perimeters to import and export data between each other. A project may
          belong to multiple bridge service perimeters (only if it also belongs to a
          regular service perimeter). Both restricted and unrestricted service lists,
          as well as access level lists, must be empty.
          """,
  )
Example #18
0
 def ParseVersionedEgressPoliciesAlpha(path):
     return ParseAccessContextManagerMessages(
         path,
         util.GetMessages(version=api_version).EgressPolicy)