Build a default assume role policy.

    .. versionadded:: 2015.8.0

    CLI Example:

    .. code-block:: bash

        salt myminion boto_iam.build_policy
173299
def build_policy(region=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    if hasattr(conn, 'build_policy'):
        policy = salt.utils.json.loads(conn.build_policy())
    elif hasattr(conn, '_build_policy'):
        policy = salt.utils.json.loads(conn._build_policy())
    else:
        return {}
    # The format we get from build_policy isn't going to be what we get back
    # from AWS for the exact same policy. AWS converts single item list values
    # into strings, so let's do the same here.
    for key, policy_val in policy.items():
        for statement in policy_val:
            if (isinstance(statement['Action'], list)
                    and len(statement['Action']) == 1):
                statement['Action'] = statement['Action'][0]
            if (isinstance(statement['Principal']['Service'], list)
                    and len(statement['Principal']['Service']) == 1):
                statement['Principal']['Service'] = statement['Principal']['Service'][0]
    # build_policy doesn't add a version field, which AWS is going to set to a
    # default value, when we get it back, so let's set it.
    policy['Version'] = '2008-10-17'
    return policy
48959
def _generate_iam_invoke_role(self):
        

        invoke_assume = {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Action": "sts:AssumeRole",
                    "Principal": {
                        "Service": "apigateway.amazonaws.com"
                    },
                    "Effect": "Allow",
                    "Sid": ""
                }
            ]
        }
        self.tf_conf['resource']['aws_iam_role']['invoke_role'] = {
            'name': self.resource_name + '-invoke',
            'assume_role_policy': json.dumps(invoke_assume),
        }
        self.tf_conf['output']['iam_invoke_role_arn'] = {
            'value': '${aws_iam_role.invoke_role.arn}'
        }
        self.tf_conf['output']['iam_invoke_role_unique_id'] = {
            'value': '${aws_iam_role.invoke_role.unique_id}'
        }
1099983
def _get_policies(minion_id, config):
    '''
    
    '''
    _, grains, _ = salt.utils.minions.get_minion_data(minion_id, __opts__)
    policy_patterns = config.get(
                                 'policies',
                                 ['saltstack/minion/{minion}', 'saltstack/minions']
                                )
    mappings = {'minion': minion_id, 'grains': grains or {}}

    policies = []
    for pattern in policy_patterns:
        try:
            for expanded_pattern in _expand_pattern_lists(pattern, **mappings):
                policies.append(
                                expanded_pattern.format(**mappings)
                                                .lower()  # Vault requirement
                               )
        except KeyError:
            log.warning('Could not resolve policy pattern %s', pattern)

    log.debug('%s policies: %s', minion_id, policies)
    return policies
389647
def default_vsan_policy_configured(name, policy):
    '''
    
    '''
    # TODO Refactor when recurse_differ supports list_differ
    # It's going to make the whole thing much easier
    policy_copy = copy.deepcopy(policy)
    proxy_type = __salt__['vsphere.get_proxy_type']()
    log.trace('proxy_type = %s', proxy_type)
    # All allowed proxies have a shim execution module with the same
    # name which implementes a get_details function
    # All allowed proxies have a vcenter detail
    vcenter = __salt__['{0}.get_details'.format(proxy_type)]()['vcenter']
    log.info('Running %s on vCenter \'%s\'', name, vcenter)
    log.trace('policy = %s', policy)
    changes_required = False
    ret = {'name': name,
           'changes': {},
           'result': None,
           'comment': None}
    comments = []
    changes = {}
    changes_required = False
    si = None

    try:
        #TODO policy schema validation
        si = __salt__['vsphere.get_service_instance_via_proxy']()
        current_policy = __salt__['vsphere.list_default_vsan_policy'](si)
        log.trace('current_policy = %s', current_policy)
        # Building all diffs between the current and expected policy
        # XXX We simplify the comparison by assuming we have at most 1
        # sub_profile
        if policy.get('subprofiles'):
            if len(policy['subprofiles']) > 1:
                raise ArgumentValueError('Multiple sub_profiles ({0}) are not '
                                         'supported in the input policy')
            subprofile = policy['subprofiles'][0]
            current_subprofile = current_policy['subprofiles'][0]
            capabilities_differ = list_diff(current_subprofile['capabilities'],
                                            subprofile.get('capabilities', []),
                                            key='id')
            del policy['subprofiles']
            if subprofile.get('capabilities'):
                del subprofile['capabilities']
            del current_subprofile['capabilities']
            # Get the subprofile diffs without the capability keys
            subprofile_differ = recursive_diff(current_subprofile,
                                               dict(subprofile))

        del current_policy['subprofiles']
        policy_differ = recursive_diff(current_policy, policy)
        if policy_differ.diffs or capabilities_differ.diffs or \
           subprofile_differ.diffs:

            if 'name' in policy_differ.new_values or \
               'description' in policy_differ.new_values:

                raise ArgumentValueError(
                    '\'name\' and \'description\' of the default VSAN policy '
                    'cannot be updated')
            changes_required = True
            if __opts__['test']:
                str_changes = []
                if policy_differ.diffs:
                    str_changes.extend([change for change in
                                        policy_differ.changes_str.split('\n')])
                if subprofile_differ.diffs or capabilities_differ.diffs:
                    str_changes.append('subprofiles:')
                    if subprofile_differ.diffs:
                        str_changes.extend(
                            ['  {0}'.format(change) for change in
                             subprofile_differ.changes_str.split('\n')])
                    if capabilities_differ.diffs:
                        str_changes.append('  capabilities:')
                        str_changes.extend(
                            ['  {0}'.format(change) for change in
                             capabilities_differ.changes_str2.split('\n')])
                comments.append(
                    'State {0} will update the default VSAN policy on '
                    'vCenter \'{1}\':\n{2}'
                    ''.format(name, vcenter, '\n'.join(str_changes)))
            else:
                __salt__['vsphere.update_storage_policy'](
                    policy=current_policy['name'],
                    policy_dict=policy_copy,
                    service_instance=si)
                comments.append('Updated the default VSAN policy in vCenter '
                                '\'{0}\''.format(vcenter))
            log.info(comments[-1])

            new_values = policy_differ.new_values
            new_values['subprofiles'] = [subprofile_differ.new_values]
            new_values['subprofiles'][0]['capabilities'] = \
                    capabilities_differ.new_values
            if not new_values['subprofiles'][0]['capabilities']:
                del new_values['subprofiles'][0]['capabilities']
            if not new_values['subprofiles'][0]:
                del new_values['subprofiles']
            old_values = policy_differ.old_values
            old_values['subprofiles'] = [subprofile_differ.old_values]
            old_values['subprofiles'][0]['capabilities'] = \
                    capabilities_differ.old_values
            if not old_values['subprofiles'][0]['capabilities']:
                del old_values['subprofiles'][0]['capabilities']
            if not old_values['subprofiles'][0]:
                del old_values['subprofiles']
            changes.update({'default_vsan_policy':
                            {'new': new_values,
                             'old': old_values}})
            log.trace(changes)
        __salt__['vsphere.disconnect'](si)
    except CommandExecutionError as exc:
        log.error('Error: %s', exc)
        if si:
            __salt__['vsphere.disconnect'](si)
        if not __opts__['test']:
            ret['result'] = False
        ret.update({'comment': exc.strerror,
                    'result': False if not __opts__['test'] else None})
        return ret
    if not changes_required:
        # We have no changes
        ret.update({'comment': ('Default VSAN policy in vCenter '
                                '\'{0}\' is correctly configured. '
                                'Nothing to be done.'.format(vcenter)),
                    'result': True})
    else:
        ret.update({
            'comment': '\n'.join(comments),
            'changes': changes,
            'result': None if __opts__['test'] else True,
        })
    return ret
181333
def _cli_check_role(role):
    ''''''

    if role is None:
        return None

    role = role.lower()
    if not role in api.get_roles():
        errstr = "Role format '" + role + "' does not exist.\n"
        errstr += "For a complete list of roles, use the 'bse list-roles' command"
        raise RuntimeError(errstr)

    return role
672320
def build_role(self, name, policies=False):
        
        # Build role template
        if policies:
            role = self.__template.add_resource(
                Role(
                    self.name_strip(name),
                    AssumeRolePolicyDocument=Policy(
                        Version=self.VERSION_IAM,
                        Statement=[
                            Statement(
                                Effect=Allow,
                                Principal=Principal(
                                    "Service", self.__role_principals
                                ),
                                Action=[AssumeRole],
                            )
                        ]
                    ),
                    Path=self.__role_path,
                    ManagedPolicyArns=policies,
                ))
            # Add role to list for default policy
            self.__roles_list.append(troposphere.Ref(role))
        else:
            role = self.__template.add_resource(
                Role(
                    self.name_strip(name),
                    AssumeRolePolicyDocument=Policy(
                        Version=self.VERSION_IAM,
                        Statement=[
                            Statement(
                                Effect=Allow,
                                Principal=Principal(
                                    "Service", self.__role_principals
                                ),
                                Action=[AssumeRole],
                            )
                        ]
                    ),
                    Path=self.__role_path,
                ))
            # Add role to list for default policy
            self.__roles_list.append(troposphere.Ref(role))

        return role
737260
def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    try:
        info = conn.get_user_policy(user_name, policy_name)
        log.debug('Info for IAM user %s policy %s: %s.', user_name, policy_name, info)
        if not info:
            return False
        info = info.get_user_policy_response.get_user_policy_result.policy_document
        info = _unquote(info)
        info = salt.utils.json.loads(info, object_pairs_hook=odict.OrderedDict)
        return info
    except boto.exception.BotoServerError as e:
        log.debug(e)
        log.error('Failed to get policy %s for IAM user %s.', policy_name, user_name)
        return False
470652
def get_default_role(request):
    
    global DEFAULT_ROLE
    default = getattr(settings, "OPENSTACK_KEYSTONE_DEFAULT_ROLE", None)
    if default and DEFAULT_ROLE is None:
        try:
            roles = keystoneclient(request, admin=True).roles.list()
        except Exception:
            roles = []
            exceptions.handle(request)
        for role in roles:
            if default in (role.id, role.name):
                DEFAULT_ROLE = role
                break
    return DEFAULT_ROLE
1102553
def make_default(self, user, group_membership):
        
        return self._put(self._build_url(self.endpoint.make_default(user, group_membership)), payload={})
1295766
def role_create(auth=None, **kwargs):
    '''
    
    '''
    cloud = get_operator_cloud(auth)
    kwargs = _clean_kwargs(keep_name=True, **kwargs)
    return cloud.create_role(**kwargs)
116018
function authorize(req, res, next) {
  const role = findRoleFromRequest(
    req,
    options.roleSearchPath,
    options.defaultRole,
    options.decodedObjectName
  );

  if (req.originalUrl === '/') {
    return next();
  }

  const policy = options.policies.get(role);

  if (!policy) {
    return res.status(403).json({
      status: 'Access denied',
      success: false,
      message: `REQUIRED: Policy for role ${role} is not defined`
    });
  }

  const permission = findPermissionForRoute(
    req.originalUrl,
    req.method,
    options.baseUrl,
    policy
  );

  if (!permission) {
    if (typeof options.denyCallback === 'function') {
      return options.denyCallback(res);
    }
    return res.status(403).json(deny(options.customMessage, options.response));
  }

  return checkIfHasAccess(
    req.method,
    res,
    next,
    permission,
    options.customMessage,
    options.response,
    options.denyCallback
  );
}
367056
function configurePolicyForBucket(aws, bucketName, customPolicy) {
  const policy = customPolicy || {
    Version: '2012-10-17',
    Statement: [
      {
        Effect: 'Allow',
        Principal: {
          AWS: '*'
        },
        Action: 's3:GetObject',
        Resource: `arn:aws:s3:::${bucketName}/*`
      }
    ]
  };

  const params = {
    Bucket: bucketName,
    Policy: JSON.stringify(policy)
  };

  return aws.request('S3', 'putBucketPolicy', params);
}
527218
def _link_policy(self, role):
        
        policy_arn = self.get_policy_arn()
        if role is not None and policy_arn not in role.ManagedPolicyArns:
            role.ManagedPolicyArns.append(policy_arn)
984483
def _generate_iam_role(self):
        
        pol = {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Action": "sts:AssumeRole",
                    "Principal": {
                        "Service": "lambda.amazonaws.com"
                    },
                    "Effect": "Allow",
                    "Sid": ""
                }
            ]
        }

        self.tf_conf['resource']['aws_iam_role'] = {}
        self.tf_conf['resource']['aws_iam_role']['lambda_role'] = {
            'name': self.resource_name,
            'assume_role_policy': json.dumps(pol),
        }
        self.tf_conf['output']['iam_role_arn'] = {
            'value': '${aws_iam_role.lambda_role.arn}'
        }
        self.tf_conf['output']['iam_role_unique_id'] = {
            'value': '${aws_iam_role.lambda_role.unique_id}'
        }
42494
def _generate_iam_role_policy(self):
        
        endpoints = self.config.get('endpoints')
        queue_arns = []
        for ep in endpoints:
            for qname in endpoints[ep]['queues']:
                qarn = 'arn:aws:sqs:%s:%s:%s' % (self.aws_region,
                                                 self.aws_account_id, qname)
                if qarn not in queue_arns:
                    queue_arns.append(qarn)
        pol = {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Action": "logs:CreateLogGroup",
                    "Resource": "arn:aws:logs:%s:%s:*" % (
                        self.aws_region, self.aws_account_id
                    )
                },
                {
                    "Effect": "Allow",
                    "Action": [
                        "logs:CreateLogStream",
                        "logs:PutLogEvents"
                    ],
                    "Resource": [
                        "arn:aws:logs:%s:%s:log-group:%s:*" % (
                            self.aws_region, self.aws_account_id,
                            '/aws/lambda/%s' % self.resource_name
                        )
                    ]
                },
                {
                    'Effect': 'Allow',
                    'Action': [
                        'sqs:ListQueues'
                    ],
                    'Resource': '*'
                },
                {
                    "Effect": "Allow",
                    "Action": [
                        "sqs:GetQueueUrl",
                        "sqs:SendMessage"
                    ],
                    "Resource": sorted(queue_arns)
                }
            ]
        }
        self.tf_conf['resource']['aws_iam_role_policy']['role_policy'] = {
            'name': self.resource_name,
            'role': '${aws_iam_role.lambda_role.id}',
            'policy': json.dumps(pol)
        }
550520
def _port_add_or_delete_policy(action, name, sel_type=None, protocol=None, port=None, sel_range=None):
    '''
    
    '''
    if action not in ['add', 'delete']:
        raise SaltInvocationError('Actions supported are "add" and "delete", not "{0}".'.format(action))
    if action == 'add' and not sel_type:
        raise SaltInvocationError('SELinux Type is required to add a policy')
    (protocol, port) = _parse_protocol_port(name, protocol, port)
    cmd = 'semanage port --{0} --proto {1}'.format(action, protocol)
    if sel_type:
        cmd += ' --type {0}'.format(sel_type)
    if sel_range:
        cmd += ' --range {0}'.format(sel_range)
    cmd += ' {0}'.format(port)
    return __salt__['cmd.run_all'](cmd)
142940
def default_roles(*role_list):
    """"""
    def selectively_attach(func):
        """Only decorate if nothing specified on command line"""
        # pylint: disable=W0142
        if not env.roles and not env.hosts:
            return roles(*role_list)(func)
        else:
            if env.hosts:
                func = hosts(*env.hosts)(func)
            if env.roles:
                func = roles(*env.roles)(func)
            return func
    return selectively_attach