Endpoint that SNS accesses. Includes logic verifying request
337694
def endpoint(request):
    """"""
    # pylint: disable=too-many-return-statements,too-many-branches

    # In order to 'hide' the endpoint, all non-POST requests should return
    # the site's default HTTP404
    if request.method != 'POST':
        raise Http404

    # If necessary, check that the topic is correct
    if hasattr(settings, 'BOUNCY_TOPIC_ARN'):
        # Confirm that the proper topic header was sent
        if 'HTTP_X_AMZ_SNS_TOPIC_ARN' not in request.META:
            return HttpResponseBadRequest('No TopicArn Header')

        # Check to see if the topic is in the settings
        # Because you can have bounces and complaints coming from multiple
        # topics, BOUNCY_TOPIC_ARN is a list
        if (not request.META['HTTP_X_AMZ_SNS_TOPIC_ARN']
                in settings.BOUNCY_TOPIC_ARN):
            return HttpResponseBadRequest('Bad Topic')

    # Load the JSON POST Body
    if isinstance(request.body, str):
        # requests return str in python 2.7
        request_body = request.body
    else:
        # and return bytes in python 3.4
        request_body = request.body.decode()
    try:
        data = json.loads(request_body)
    except ValueError:
        logger.warning('Notification Not Valid JSON: {}'.format(request_body))
        return HttpResponseBadRequest('Not Valid JSON')

    # Ensure that the JSON we're provided contains all the keys we expect
    # Comparison code from http://stackoverflow.com/questions/1285911/
    if not set(VITAL_NOTIFICATION_FIELDS) <= set(data):
        logger.warning('Request Missing Necessary Keys')
        return HttpResponseBadRequest('Request Missing Necessary Keys')

    # Ensure that the type of notification is one we'll accept
    if not data['Type'] in ALLOWED_TYPES:
        logger.info('Notification Type Not Known %s', data['Type'])
        return HttpResponseBadRequest('Unknown Notification Type')

    # Confirm that the signing certificate is hosted on a correct domain
    # AWS by default uses sns.{region}.amazonaws.com
    # On the off chance you need this to be a different domain, allow the
    # regex to be overridden in settings
    domain = urlparse(data['SigningCertURL']).netloc
    pattern = getattr(
        settings, 'BOUNCY_CERT_DOMAIN_REGEX', r"sns.[a-z0-9\-]+.amazonaws.com$"
    )
    if not re.search(pattern, domain):
        logger.warning(
            'Improper Certificate Location %s', data['SigningCertURL'])
        return HttpResponseBadRequest('Improper Certificate Location')

    # Verify that the notification is signed by Amazon
    if (getattr(settings, 'BOUNCY_VERIFY_CERTIFICATE', True)
            and not verify_notification(data)):
        logger.error('Verification Failure %s', )
        return HttpResponseBadRequest('Improper Signature')

    # Send a signal to say a valid notification has been received
    signals.notification.send(
        sender='bouncy_endpoint', notification=data, request=request)

    # Handle subscription-based messages.
    if data['Type'] == 'SubscriptionConfirmation':
        # Allow the disabling of the auto-subscription feature
        if not getattr(settings, 'BOUNCY_AUTO_SUBSCRIBE', True):
            raise Http404
        return approve_subscription(data)
    elif data['Type'] == 'UnsubscribeConfirmation':
        # We won't handle unsubscribe requests here. Return a 200 status code
        # so Amazon won't redeliver the request. If you want to remove this
        # endpoint, remove it either via the API or the AWS Console
        logger.info('UnsubscribeConfirmation Not Handled')
        return HttpResponse('UnsubscribeConfirmation Not Handled')

    try:
        message = json.loads(data['Message'])
    except ValueError:
        # This message is not JSON. But we need to return a 200 status code
        # so that Amazon doesn't attempt to deliver the message again
        logger.info('Non-Valid JSON Message Received')
        return HttpResponse('Message is not valid JSON')

    return process_message(message, data)
985158
def setup_dns(endpoint):
    """"""
    print("Setting up DNS...")

    yass = Yass(CWD)
    target = endpoint.lower()

    sitename = yass.sitename
    if not sitename:
        raise ValueError("Missing site name")

    endpoint = yass.config.get("hosting.%s" % target)
    if not endpoint:
        raise ValueError(
            "%s endpoint is missing in the hosting config" % target.upper())

    if target == "s3":
        p = publisher.S3Website(sitename=sitename,
                                aws_access_key_id=endpoint.get("aws_access_key_id"),
                                aws_secret_access_key=endpoint.get("aws_secret_access_key"),
                                region=endpoint.get("aws_region"))

        print("Setting AWS Route53 for: %s ..." % p.sitename)
        p.setup_dns()
        print("")
        print("Yass! Route53 setup successfully!")
        print("You can now visit the site at :")
        print(p.sitename_endpoint)
    footer()
1096003
def _api_private_request(self, endpoint, user, params=None, method=None, headers=None):
		params = params or {}
		url = self._get_api_endpoint_url(endpoint)

		params['access_token'] = user.access_token
		r = self._request(url, params = params, method = method, headers = headers)
		
		if r.status_code == 401:
			self._refresh_access_token(user)
			""" Repeat the request """
			r = self._request(url, params = params, method = method, headers = headers)
		return r
641428
def is_valid_endpoint_host(interfaces, endpoint):
        
        result = urlparse(endpoint)
        hostname = result.hostname
        if hostname is None:
            return False

        for interface in interfaces:
            if interface == hostname:
                return False

        return True
1064031
def register_endpoints(self, backend_names):
        
        url_map = [("^{}".format(self.name), self.ping_endpoint)]

        return url_map
1320985
def get_endpoint_obj(client, endpoint, object_id):
    '''  '''
    endpoint = '/'.join([endpoint, str(object_id)])
    return client.authenticated_request(endpoint).json()
468273
def get_sns_token openid, persistent_code
      path = "/sns/get_sns_token?access_token=#{refreshed_access_token}"
      fire_request path, {openid: openid, persistent_code: persistent_code}
    end
1162978
private function checkEndpoint($endpoint, $isCName)
    {
        $ret_endpoint = null;
        if (strpos($endpoint, 'http://') === 0) {
            $ret_endpoint = substr($endpoint, strlen('http://'));
        } elseif (strpos($endpoint, 'https://') === 0) {
            $ret_endpoint = substr($endpoint, strlen('https://'));
            $this->useSSL = true;
        } else {
            $ret_endpoint = $endpoint;
        }

        if ($isCName) {
            $this->hostType = self::OSS_HOST_TYPE_CNAME;
        } elseif (OssUtil::isIPFormat($ret_endpoint)) {
            $this->hostType = self::OSS_HOST_TYPE_IP;
        } else {
            $this->hostType = self::OSS_HOST_TYPE_NORMAL;
        }
        return $ret_endpoint;
    }
835392
def endpoint(f):
    """"""

    def check_authentication(self, **kwargs):
        """If the `authentication` variable is defined and not None, the
           specified method will be run. On True the request will continue
           otherwise it will fail with a 401 authentication error"""
        if getattr(self, 'authentication', None) is None:
            current_app.logger.debug("No authentication method")
            return

        a = self.authentication()
        if not hasattr(a, 'is_authenticated'):
            current_app.logger.debug("No is_authenticated method")
            return

        if not a.is_authenticated(**kwargs):
            msg = getattr(g, 'authentication_error', 'Authentication failed')
            current_app.logger.warning("Authentication failed: {}".format(msg))
            return self._make_response(401, msg, abort=True)
        current_app.logger.debug("Authentication successful")

    def check_authorization(self):
        """If the `authorization` variable is defined and not None, the
           specified method will be run. On True the request will continue
           otherwise it will fail with a 403 authorization error"""
        current_app.logger.info("Checking authentication/authorization")
        auth_class = getattr(self, 'authorization',
                             getattr(self, 'authentication', None))
        if auth_class is None:
            current_app.logger.debug("No authorization class")
            return

        a = auth_class()
        if not hasattr(a, 'is_authorized'):
            current_app.logger.debug("No is_authorized method")
            return

        if not a.is_authorized(record=g._resource_instance):
            current_app.logger.warning("Authorization failed")
            return self._make_response(403, "Authorization failed", abort=True)
        current_app.logger.debug("Authorization successful")

    def validate_request(self, **kwargs):
        """Call the validator class and validate the request_data. This method
           returns True or False. On False, a 400 will be returned with the
           reasons for the validation error. On True, the operation will
           continue."""
        current_app.logger.info(
            "Checking {} validation".format(request.method))
        if getattr(self, 'validation', None) is None:
            current_app.logger.warning("No validation specified")
            return

        v = self.validation()
        method = 'validate_{}'.format(request.method.lower())

        if not hasattr(v, method):
            current_app.logger.warning("No validation method specified")
            return
        errors = getattr(v, method)(**kwargs)
        current_app.logger.debug("Validation errors: {}".format(errors))

        if errors is not None and len(errors) > 0:
            current_app.logger.warning("Validation errors found")
            self._make_response(400, errors, abort=True)

    def load_request_data(self):
        if request.method in ['GET', 'DELETE']:
            return
        current_app.logger.info("Saving json payload in memory")
        # For now we assume JSON. Later in life we can make this more
        # payload agnostic
        try:
            d = request.data.decode('utf-8')
            g._rq_data = {} if d.strip() == "" else json.loads(d)
        except ValueError:
            return self._make_response(400, "Malformed JSON in request body",
                                       abort=True)

        if self.enforce_json_root and g._rq_data != {} and \
                list(g._rq_data.keys()) != [self._payload_root()]:
            msg = "Invalid JSON root in request body"
            current_app.logger.error(msg)
            current_app.logger.debug(
                "Found {}, expecting {}".format(
                    list(g._rq_data.keys()), self._payload_root()))
            return self._make_response(400, msg, abort=True)
        elif self._payload_root() in list(g._rq_data.keys()):
                current_app.logger.debug("Removing JSON root from rq payload")
                g._rq_data = g._rq_data[self._payload_root()]
        current_app.logger.debug("g._rq_data: {}".format(g._rq_data))
        return g._rq_data

    @wraps(f)
    def decorator(self, *args, **kwargs):
        current_app.logger.info("Got {} request".format(request.method))
        current_app.logger.info("Endpoint: {}".format(request.url))
        if request.method not in self.allowed_methods:
            msg = "Request method {} is unavailable".format(request.method)
            current_app.logger.error(msg)
            return self._make_response(405, msg, abort=True)

        current_app.logger.info("Checking db table/collection is defined")
        if self.enforce_payload_collection and self.db_collection is None:
            msg = "No DB collection defined"
            current_app.logger.error(msg)
            return make_response(Response(msg, 424))

        if request.method in ['POST', 'PUT', 'PATCH']:
            load_request_data(self)

        check_authentication(self, **kwargs)
        if kwargs.get('obj_id', False):
            kwargs['obj_id'] = self.fiddle_id(kwargs['obj_id'])
            self._get_instance(**kwargs)
        else:
            g._resource_instance = {}

        if request.method in ['POST', 'PUT', 'PATCH']:
            check_authorization(self)
            r = self.transform_record(g._rq_data.get(self._payload_root(),
                                                     g._rq_data))
            g._saveable_record = dict(self.merge_record_data(
                r, dict(getattr(g, '_resource_instance', r))))
            validate_request(self, data=g._saveable_record)
        else:
            check_authorization(self)
            validate_request(self)
        return f(self, *args, **kwargs)
    return decorator
1373316
function endpointInvalidHeaders(endpoint) {
  const invalid = []

  for (const path of Object.keys(endpoint.headers)) {
    let pathIsUseful = false
    for (const useful of UsefulHeaders) {
      if (path === useful) {
        pathIsUseful = true
        break
      }
    }
    if (!pathIsUseful) invalid.push(path)
  }

  return invalid.length === 0 ? null : `${endpoint.path} (${invalid.join(', ')})`
}
519399
private static TraceServiceGrpc.TraceServiceStub getTraceServiceStub(
      String endPoint, Boolean useInsecure, SslContext sslContext) {
    ManagedChannelBuilder<?> channelBuilder;
    if (useInsecure) {
      channelBuilder = ManagedChannelBuilder.forTarget(endPoint).usePlaintext();
    } else {
      channelBuilder =
          NettyChannelBuilder.forTarget(endPoint)
              .negotiationType(NegotiationType.TLS)
              .sslContext(sslContext);
    }
    ManagedChannel channel = channelBuilder.build();
    return TraceServiceGrpc.newStub(channel);
  }
454405
def verify_sns_subscription_current(self, subscription_arn, topic_name,
                                        function_arn):
        # type: (str, str, str) -> bool
        
        sns_client = self._client('sns')
        try:
            attributes = sns_client.get_subscription_attributes(
                SubscriptionArn=subscription_arn)['Attributes']
            return (
                # Splitting on ':' is safe because topic names can't have
                # a ':' char.
                attributes['TopicArn'].rsplit(':', 1)[1] == topic_name and
                attributes['Endpoint'] == function_arn
            )
        except sns_client.exceptions.NotFoundException:
            return False
1123613
def endpoint_search(auth=None, **kwargs):
    '''
    
    '''
    cloud = get_operator_cloud(auth)
    kwargs = _clean_kwargs(**kwargs)
    return cloud.search_endpoints(**kwargs)
901639
def validate_v2_endpoint_data(self, endpoints, admin_port, internal_port,
                                  public_port, expected):
        
        self.log.debug('Validating endpoint data...')
        self.log.debug('actual: {}'.format(repr(endpoints)))
        found = False
        for ep in endpoints:
            self.log.debug('endpoint: {}'.format(repr(ep)))
            if (admin_port in ep.adminurl and
                    internal_port in ep.internalurl and
                    public_port in ep.publicurl):
                found = True
                actual = {'id': ep.id,
                          'region': ep.region,
                          'adminurl': ep.adminurl,
                          'internalurl': ep.internalurl,
                          'publicurl': ep.publicurl,
                          'service_id': ep.service_id}
                ret = self._validate_dict_data(expected, actual)
                if ret:
                    return 'unexpected endpoint data - {}'.format(ret)

        if not found:
            return 'endpoint not found'
1281305
def _check(peers):

    ''''''

    if not isinstance(peers, list):
        return False

    for peer in peers:
        if not isinstance(peer, six.string_types):
            return False

    if not HAS_NETADDR:  # if does not have this lib installed, will simply try to load what user specified
        # if the addresses are not correctly specified, will trow error when loading the actual config
        return True

    ip_only_peers = []
    for peer in peers:
        try:
            ip_only_peers.append(six.text_type(IPAddress(peer)))  # append the str value
        except AddrFormatError:
            # if not a valid IP Address
            # will try to see if it is a nameserver and resolve it
            if not HAS_DNSRESOLVER:
                continue  # without the dns resolver cannot populate the list of NTP entities based on their nameserver
                # so we'll move on
            dns_reply = []
            try:
                # try to see if it is a valid NS
                dns_reply = dns.resolver.query(peer)
            except dns.resolver.NoAnswer:
                # no a valid DNS entry either
                return False
            for dns_ip in dns_reply:
                ip_only_peers.append(six.text_type(dns_ip))

    peers = ip_only_peers

    return True
204846
def _verify(
        self,
        request,
        return_payload=False,
        verify=True,
        raise_missing=False,
        request_args=None,
        request_kwargs=None,
        *args,
        **kwargs
    ):
        
        try:
            token = self._get_token(request)
            is_valid = True
            reason = None
        except (
            exceptions.MissingAuthorizationCookie,
            exceptions.MissingAuthorizationQueryArg,
            exceptions.MissingAuthorizationHeader,
        ) as e:
            token = None
            is_valid = False
            reason = list(e.args)
            status = e.status_code if self.config.debug() else 401

            if raise_missing:
                if not self.config.debug():
                    e.status_code = 401
                raise e

        if token:
            try:
                payload = self._decode(token, verify=verify)

                if verify:
                    if self._extra_verifications:
                        self._verify_extras(payload)
                    if self._custom_claims:
                        self._verify_custom_claims(payload)
            except (
                jwt.exceptions.ExpiredSignatureError,
                jwt.exceptions.InvalidIssuerError,
                jwt.exceptions.ImmatureSignatureError,
                jwt.exceptions.InvalidIssuedAtError,
                jwt.exceptions.InvalidAudienceError,
                InvalidVerificationError,
                InvalidCustomClaimError,
            ) as e:
                # Make sure that the reasons all end with '.' for consistency
                reason = [
                    x if x.endswith(".") else "{}.".format(x)
                    for x in list(e.args)
                ]
                payload = None
                status = 401
                is_valid = False
            except jwt.exceptions.DecodeError as e:
                self._reasons = e.args
                # Make sure that the reasons all end with '.' for consistency
                reason = (
                    [
                        x if x.endswith(".") else "{}.".format(x)
                        for x in list(e.args)
                    ]
                    if self.config.debug()
                    else "Auth required."
                )
                logger.debug(e.args)
                is_valid = False
                payload = None
                status = 400 if self.config.debug() else 401
        else:
            payload = None

        if return_payload:
            return payload

        status = 200 if is_valid else status

        return is_valid, status, reason
1021799
def get(self, endpoint, **kwargs):
        
        return self._request(requests.get, endpoint, **kwargs)