def store_data(path): try: request = flask.request auth = request.headers.get('Authorization') if not auth: # USE PATTERN MATCHING AUTH for c in all_creds: if c.path == path: return store_public_data(path, c) raise Log.error( "No authentication provided. path={{path}} data.length={{length}}", path=path, length=len(request.get_data()), ) try: receiver = Receiver( lookup_credentials, auth, request.url, request.method, content=request.get_data(), content_type=request.headers['Content-Type'], seen_nonce=seen_nonce ) except Exception, e: e = Except.wrap(e) raise Log.error( "Authentication failed. path={{path}} data.length={{length}}\n{{auth|indent}}", path=path, length=len(request.get_data()), auth=auth, cause=e ) permissions = lookup_user(receiver.parsed_header["id"]) if path not in listwrap(permissions.resources): Log.error("{{user}} not allowed access to {{resource}}", user=permissions.hawk.id, resource=path) link, id = submit_data(path, permissions, request.json) response_content = convert.unicode2utf8(convert.value2json({ "link": link, "etl": {"id": id} })) receiver.respond( content=response_content, content_type=RESPONSE_CONTENT_TYPE ) return Response( response_content, status=200, headers={ b'Server-Authorization': receiver.response_header, b'content-type': RESPONSE_CONTENT_TYPE } )
def decorated(*args, **kwargs): try: receiver = Receiver( lookup_credentials, request.headers.get('Authorization'), request.url, request.method, content=request.data, content_type=request.headers.get('Content-Type'), ) except (MissingAuthorization, CredentialsLookupError, MacMismatch): return _unauthorized() response = make_response(function(*args, **kwargs)) receiver.respond(content=response.data, content_type=response.content_type) response.headers['Server-Authorization'] = receiver.response_header return response
def authenticate(r: Request): return Receiver(get_credentials, r.headers.get('Authorization'), url=r.url, method=r.method, content=r.data, content_type=r.content_type, timestamp_skew_in_seconds=300)
def _authorise(request): """Raises a HawkFail if the passed request cannot be authenticated""" return Receiver( _lookup_credentials, request.META['HTTP_AUTHORIZATION'], request.build_absolute_uri(), request.method, content=request.body, content_type=request.content_type, )
def authorize_request(self, sender, req, url=None, method='GET'): if not url: url = self.url # Simulate how a view authorizes a request. receiver = Receiver(default_credentials_lookup, sender.request_header, url, method, content=req.body, content_type=req.META['CONTENT_TYPE']) req.META['hawk.receiver'] = receiver
def authenticate(self, request): # In case there is an exception, tell others that the view passed # through Hawk authorization. The META dict is used because # middleware may not get an identical request object. # A dot-separated key is to work around potential environ var # pollution of META. request.META['hawk.receiver'] = None http_authorization = request.META.get('HTTP_AUTHORIZATION') if not http_authorization: log.debug('no authorization header in request') return None elif not http_authorization.startswith('Hawk '): log.debug('ignoring non-Hawk authorization header: {} ' .format(http_authorization)) return None try: receiver = Receiver( lambda cr_id: self.hawk_credentials_lookup(cr_id), http_authorization, request.build_absolute_uri(), request.method, content=request.body, seen_nonce=(seen_nonce if getattr(settings, 'USE_CACHE_FOR_HAWK_NONCE', True) else None), content_type=request.META.get('CONTENT_TYPE', ''), timestamp_skew_in_seconds=getattr(settings, 'HAWK_MESSAGE_EXPIRATION', default_message_expiration)) except HawkFail as e: etype, val, tb = sys.exc_info() log.debug(traceback.format_exc()) log.warning('access denied: {etype.__name__}: {val}' .format(etype=etype, val=val)) # The exception message is sent to the client as part of the # 401 response, so we're intentionally vague about the original # exception type/value, to avoid assisting attackers. msg = 'Hawk authentication failed' if isinstance(e, BadHeaderValue): msg += ': The request header was malformed' elif isinstance(e, TokenExpired): msg += ': The token has expired. Is your system clock correct?' raise AuthenticationFailed(msg) # Pass our receiver object to the middleware so the request header # doesn't need to be parsed again. request.META['hawk.receiver'] = receiver return self.hawk_user_lookup(request, receiver.resource.credentials)
def _authenticate(request, lookup_credentials): """ Raises a HawkFail exception if the passed request cannot be authenticated """ if settings.HAWK_AUTHENTICATION_ENABLED: return Receiver( lookup_credentials, request.META["HTTP_HAWK_AUTHENTICATION"], request.build_absolute_uri(), request.method, content=request.body, content_type=request.content_type, seen_nonce=_seen_nonce, )
def _authenticate(request): """ Raises a HawkFail exception if the passed request cannot be authenticated """ if settings.HAWK_AUTHENTICATION_ENABLED: return Receiver( _lookup_credentials, request.META["HTTP_HAWK_AUTHENTICATION"], # build_absolute_uri() returns 'http' which is incorrect since our clients communicate via https request.build_absolute_uri().replace("http", "https"), request.method, content=request.body, content_type=request.content_type, seen_nonce=_seen_nonce, )
def _verify_credentials(self, request): """Check storage for the request account HAWK credentials. """ if REIFY_KEY not in request.bound_data: try: request.receiver = Receiver(partial(self.lookup_credentials, request), request.headers['Authorization'], request.url, request.method, seen_nonce=partial(self.seen_nonce, request), accept_untrusted_content=True, content=request.body or '', content_type=request.headers.get('Content-Type', '')) except TokenExpired as expiry: request.bound_data[REIFY_KEY] = None request.response.headers['WWW-Authenticate'] = expiry.www_authenticate except HawkFail: request.bound_data[REIFY_KEY] = None else: request.bound_data[REIFY_KEY] = request.bound_data['info']['user_id'] return request.bound_data[REIFY_KEY]
def test_signature(self, request): """ Thest that the signature header matches the expected value. Args request (django.http.Request): The request to check the properties. Returns: bool or Receiver : False if rejected, Receiver instance if accepted """ content_type = get_content_type(request.META.get('CONTENT_TYPE')) try: return Receiver( self.lookup_credentials, request.META.get(self.header_name), request.get_full_path(), request.method, content=get_content(request.body), content_type=get_content_type(content_type), ) except HawkFail: return False