This is a convenience function that wraps the "authorize ip
        permission" functionality of the C{authorize_security_group} method.

        For an explanation of the parameters, see C{authorize_security_group}.
779963
def authorize_ip_permission(
        self, group_name, ip_protocol, from_port, to_port, cidr_ip):
        
        d = self.authorize_security_group(
            group_name,
            ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
            cidr_ip=cidr_ip)
        return d
173932
def get_request_authorization(method, resource, key, params, headers):
        
        if not key:
            return six.b('')
        content = method + "\n"
        if 'Content-MD5' in headers:
            content += headers['Content-MD5']
        content += '\n'
        if 'Content-Type' in headers:
            content += headers['Content-Type']
        content += "\n"
        content += headers['Date'] + "\n"
        content += Util.canonicalized_log_headers(headers)
        content += Util.canonicalized_resource(resource, params)
        return Util.hmac_sha1(content, key)
1212044
def permission_manager(self, permission_manager):
        
        self.check_permissions = permission_manager

        for resource in self.resource_registry:
            if getattr(resource, 'disable_permission', None) is not True:
                for method in getattr(resource, 'methods', ('GET', 'POST', 'PATCH', 'DELETE')):
                    setattr(resource,
                            method.lower(),
                            self.has_permission()(getattr(resource, method.lower())))
1275747
def group_required(self, group):
        

        def decorator(view):
            @functools.wraps(view)
            def decorated(*args, **kwargs):
                log.info("Trying to get access to resource: %s protected by group: %s", view.__name__, group)
                if request.method == 'POST':
                    token = request.form['token']
                    if self.development or self.group_authenticated(token, group):
                        return view(*args, **kwargs)
                    else:
                        log.warning("User has not been authorized to get access to resource: %s", view.__name__)
                else:
                    log.error("Bad request type! Expected 'POST', actual '%s'", request.method)

                return abort(403)

            return decorated
        return decorator
97636
def update_instance_security_group(self, instance_id,
                                       new_security_group_ids):
        """"""
        ports = port_list(self.request, device_id=instance_id)
        for p in ports:
            params = {'security_groups': new_security_group_ids}
            port_update(self.request, p.id, **params)
1098272
def grant(self, source_cidr):
        
        self.manager.api.secgroup_rules.create(self.id, source_cidr)
112471
private IPermission[] primGetPermissionsForPrincipal(IAuthorizationPrincipal principal)
            throws AuthorizationException {
        if (!this.cachePermissions) {
            return getUncachedPermissionsForPrincipal(principal, null, null, null);
        }

        IPermissionSet ps = null;
        // Check the caching service for the Permissions first.
        ps = cacheGet(principal);

        if (ps == null)
            synchronized (principal) {
                ps = cacheGet(principal);
                if (ps == null) {
                    IPermission[] permissions =
                            getUncachedPermissionsForPrincipal(principal, null, null, null);
                    ps = new PermissionSetImpl(permissions, principal);
                    cacheAdd(ps);
                }
            } // end synchronized
        return ps.getPermissions();
    }
914236
def permission(id, props={})
      defaults = { action: "lambda:InvokeFunction" }
      props = defaults.merge(props)
      resource(id, "AWS::Lambda::Permission", props)
    end
934710
def add_permission_for_apigateway(self, function_name,
                                      region_name, account_id,
                                      rest_api_id, random_id=None):
        # type: (str, str, str, str, Optional[str]) -> None
        
        source_arn = self._build_source_arn_str(region_name, account_id,
                                                rest_api_id)
        self._add_lambda_permission_if_needed(
            source_arn=source_arn,
            function_arn=function_name,
            service_name='apigateway',
        )
811682
private void requestAuthorization(HttpServletResponse resp) throws IOException {

        // Authorisation is required for the requested action.
        resp.setHeader(CmsRequestUtil.HEADER_WWW_AUTHENTICATE, "Basic realm=\"" + BASIC_REALM + "\"");

        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
297029
def authorize(self, ctx, identity, ops):
        '''
        '''
        allowed = []
        caveats = []
        for op in ops:
            ok, fcaveats = self._f(ctx, identity, op)
            allowed.append(ok)
            if fcaveats is not None:
                caveats.extend(fcaveats)
        return allowed, caveats
693378
def security_group_delete(auth=None, **kwargs):
    '''
    

    '''
    cloud = get_operator_cloud(auth)
    kwargs = _clean_kwargs(**kwargs)
    return cloud.delete_security_group(**kwargs)
960387
def ssh_authorized_peers(peer_interface, user, group=None,
                         ensure_local_user=False):
    
    if ensure_local_user:
        ensure_user(user, group)
    priv_key, pub_key = get_keypair(user)
    hook = hook_name()
    if hook == '%s-relation-joined' % peer_interface:
        relation_set(ssh_pub_key=pub_key)
    elif hook == '%s-relation-changed' % peer_interface or \
            hook == '%s-relation-departed' % peer_interface:
        hosts = []
        keys = []

        for r_id in relation_ids(peer_interface):
            for unit in related_units(r_id):
                ssh_pub_key = relation_get('ssh_pub_key',
                                           rid=r_id,
                                           unit=unit)
                priv_addr = relation_get('private-address',
                                         rid=r_id,
                                         unit=unit)
                if ssh_pub_key:
                    keys.append(ssh_pub_key)
                    hosts.append(priv_addr)
                else:
                    log('ssh_authorized_peers(): ssh_pub_key '
                        'missing for unit %s, skipping.' % unit)
        write_authorized_keys(user, keys)
        write_known_hosts(user, hosts)
        authed_hosts = ':'.join(hosts)
        relation_set(ssh_authorized_hosts=authed_hosts)
275577
def describe_security_groups(self, xml_bytes):
        
        root = XML(xml_bytes)
        result = []
        for group_info in root.findall("securityGroupInfo/item"):
            id = group_info.findtext("groupId")
            name = group_info.findtext("groupName")
            description = group_info.findtext("groupDescription")
            owner_id = group_info.findtext("ownerId")
            allowed_groups = []
            allowed_ips = []
            ip_permissions = group_info.find("ipPermissions")
            if ip_permissions is None:
                ip_permissions = ()
            for ip_permission in ip_permissions:

                # openstack doesn't handle self authorized groups properly
                # XXX this is an upstream problem and should be addressed there
                # lp bug #829609
                ip_protocol = ip_permission.findtext("ipProtocol")
                from_port = ip_permission.findtext("fromPort")
                to_port = ip_permission.findtext("toPort")

                if from_port:
                    from_port = int(from_port)

                if to_port:
                    to_port = int(to_port)

                for groups in ip_permission.findall("groups/item") or ():
                    user_id = groups.findtext("userId")
                    group_name = groups.findtext("groupName")
                    if user_id and group_name:
                        if (user_id, group_name) not in allowed_groups:
                            allowed_groups.append((user_id, group_name))
                for ip_ranges in ip_permission.findall("ipRanges/item") or ():
                    cidr_ip = ip_ranges.findtext("cidrIp")
                    allowed_ips.append(
                        model.IPPermission(
                            ip_protocol, from_port, to_port, cidr_ip))

            allowed_groups = [model.UserIDGroupPair(user_id, group_name)
                              for user_id, group_name in allowed_groups]

            security_group = model.SecurityGroup(
                id, name, description, owner_id=owner_id,
                groups=allowed_groups, ips=allowed_ips)
            result.append(security_group)
        return result
258921
def requires_auth(f):
    
    @wraps(f)

    def decorated(self, *args, **kwargs):
        

        # Fetch auth options from args
        auth_options = {}
        nipap_args = {}

        # validate function arguments
        if len(args) == 1:
            nipap_args = args[0]
        else:
            self.logger.debug("Malformed request: got %d parameters" % len(args))
            raise Fault(1000, ("NIPAP API functions take exactly 1 argument (%d given)") % len(args))

        if type(nipap_args) != dict:
            self.logger.debug("Function argument is not struct")
            raise Fault(1000, ("Function argument must be XML-RPC struct/Python dict (Python %s given)." %
                type(nipap_args).__name__ ))

        # fetch auth options
        try:
            auth_options = nipap_args['auth']
            if type(auth_options) is not dict:
                raise ValueError()
        except (KeyError, ValueError):
            self.logger.debug("Missing/invalid authentication options in request.")
            raise Fault(1000, ("Missing/invalid authentication options in request."))

        # fetch authoritative source
        try:
            auth_source = auth_options['authoritative_source']
        except KeyError:
            self.logger.debug("Missing authoritative source in auth options.")
            raise Fault(1000, ("Missing authoritative source in auth options."))

        if not request.authorization:
            return authenticate()

        # init AuthFacory()
        af = AuthFactory()
        auth = af.get_auth(request.authorization.username,
                request.authorization.password, auth_source, auth_options or {})

        # authenticated?
        if not auth.authenticate():
            self.logger.debug("Incorrect username or password.")
            raise Fault(1510, ("Incorrect username or password."))

        # Replace auth options in API call arguments with auth object
        new_args = dict(args[0])
        new_args['auth'] = auth

        return f(self, *(new_args,), **kwargs)

    return decorated
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
  );
}
444340
private void authorizeClassicDbSecurityGroup(String groupName, String sourceCidr) throws CloudException, InternalException {
        Map<String,String> parameters = getProvider().getStandardRdsParameters(getProvider().getContext(), AUTHORIZE_DB_SECURITY_GROUP_INGRESS);
        parameters.put("DBSecurityGroupName", groupName);
        parameters.put("CIDRIP", sourceCidr);
        EC2Method method = new EC2Method(SERVICE_ID, getProvider(), parameters);
        try {
            method.invoke();
        }
        catch( EC2Exception e ) {
            String code = e.getCode();
            if( code != null && code.equals("AuthorizationAlreadyExists") ) {
                return;
            }
            throw new CloudException(e);
        }
    }