Python httplib.UNAUTHORIZED Examples

The following are 30 code examples of httplib.UNAUTHORIZED(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module httplib , or try the search function .
Example #1
Source File: playground.py    From cloud-playground with Apache License 2.0 6 votes vote down vote up
def post(self):  # pylint:disable-msg=invalid-name
    """Handles HTTP POST requests."""
    if not users.is_current_user_admin():
      self.response.set_status(httplib.UNAUTHORIZED)
      return
    key = self.request.data['key']
    url = self.request.data['url']
    client_id = self.request.data.get('client_id')
    client_secret = self.request.data.get('client_secret')
    if client_id and client_secret:
      credential = model.SetOAuth2Credential(key, client_id, client_secret)
    else:
      credential = model.GetOAuth2Credential(key) or model.OAuth2Credential()
    r = {
        'key': key,
        'url': url,
        'client_id': credential.client_id,
        'client_secret': credential.client_secret,
    }
    return r 
Example #2
Source File: twitter.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def VerifyCredentials(self):
    '''Returns a twitter.User instance if the authenticating user is valid.

    Returns: 
      A twitter.User instance representing that user if the
      credentials are valid, None otherwise.
    '''
    if not self._username:
      raise TwitterError("Api instance must first be given user credentials.")
    url = 'http://twitter.com/account/verify_credentials.json'
    try:
      json = self._FetchUrl(url, no_cache=True)
    except urllib2.HTTPError, http_error:
      if http_error.code == httplib.UNAUTHORIZED:
        return None
      else:
        raise http_error 
Example #3
Source File: brightcove.py    From xblock-video with GNU General Public License v3.0 6 votes vote down vote up
def get(self, url, headers=None, can_retry=True):
        """
        Issue REST GET request to a given URL. Can throw ApiClientError or its subclass.

        Arguments:
            url (str): API url to fetch a resource from.
            headers (dict): Headers necessary as per API, e.g. authorization bearer to perform authorised requests.
            can_retry (bool): True if in a case of authentication error it can refresh access token and retry a call.
        Returns:
            Response in python native data format.
        """
        headers_ = {'Authorization': 'Bearer ' + str(self.access_token)}
        if headers is not None:
            headers_.update(headers)
        resp = requests.get(url, headers=headers_)
        if resp.status_code == httplib.OK:
            return resp.json()
        elif resp.status_code == httplib.UNAUTHORIZED and can_retry:
            self.access_token = self._refresh_access_token()
            return self.get(url, headers, can_retry=False)
        else:
            raise BrightcoveApiClientError 
Example #4
Source File: hmac_plugin.py    From JediHTTP with Apache License 2.0 6 votes vote down vote up
def __call__(self, callback):
        def wrapper(*args, **kwargs):
            if not is_local_request():
                self._logger.info('Dropping request with bad Host header.')
                abort(httplib.UNAUTHORIZED,
                      'Unauthorized, received request from non-local Host.')
                return

            if not self.is_request_authenticated():
                self._logger.info('Dropping request with bad HMAC.')
                abort(httplib.UNAUTHORIZED, 'Unauthorized, received bad HMAC.')
                return

            body = callback(*args, **kwargs)
            self.sign_response_headers(response.headers, body)
            return body
        return wrapper 
Example #5
Source File: wistia.py    From xblock-video with GNU General Public License v3.0 6 votes vote down vote up
def authenticate_api(self, **kwargs):
        """
        Call a sample Wistia API url to check on authentication success.

        Reference:
            https://wistia.com/doc/data-api#authentication

        Arguments:
            kwargs (dict): Wistia master token key-value pair.

        Returns:
            auth_data (dict): Master token, provided by a user, which is to be stored in Wistia's player metadata.
            error_status_message (str): Message with authentication outcomes for the sake of verbosity.
        """
        token, media_id = kwargs.get('token'), kwargs.get('video_id')  # pylint: disable=unused-variable
        auth_data, error_message = {}, ''
        auth_data['token'] = token
        url = self.captions_api.get('auth_sample_url').format(token=str(token))
        response = requests.get('https://' + url)
        if response.status_code == httplib.UNAUTHORIZED:
            error_message = "Authentication failed. " \
                            "Please ensure you have provided a valid master token, using Video API Token field."
        return auth_data, error_message 
Example #6
Source File: playground.py    From cloud-playground with Apache License 2.0 5 votes vote down vote up
def PerformAccessCheck(self):
    if not shared.HasProjectWriteAccess(self.request.environ):
      Abort(httplib.UNAUTHORIZED, 'no project write access') 
Example #7
Source File: playground.py    From cloud-playground with Apache License 2.0 5 votes vote down vote up
def PerformAccessCheck(self):
    if not shared.HasProjectReadAccess(self.request.environ):
      Abort(httplib.UNAUTHORIZED, 'no project read access') 
Example #8
Source File: playground.py    From cloud-playground with Apache License 2.0 5 votes vote down vote up
def PerformAccessCheck(self):
    if not shared.HasProjectReadAccess(self.request.environ):
      Abort(httplib.UNAUTHORIZED, 'no project read access') 
Example #9
Source File: playground.py    From cloud-playground with Apache License 2.0 5 votes vote down vote up
def PerformAccessCheck(self):
    if not shared.HasProjectWriteAccess(self.request.environ):
      Abort(httplib.UNAUTHORIZED, 'no project write access') 
Example #10
Source File: playground.py    From cloud-playground with Apache License 2.0 5 votes vote down vote up
def PerformAccessCheck(self):
    if not shared.HasProjectWriteAccess(self.request.environ):
      Abort(httplib.UNAUTHORIZED, 'no project write access') 
Example #11
Source File: playground.py    From cloud-playground with Apache License 2.0 5 votes vote down vote up
def PerformAccessCheck(self):
    if not shared.HasProjectWriteAccess(self.request.environ):
      Abort(httplib.UNAUTHORIZED, 'no project write access') 
Example #12
Source File: middleware.py    From cloud-playground with Apache License 2.0 5 votes vote down vote up
def _PerformCsrfRequestValidation(session, environ):
  session_xsrf = session['xsrf']
  client_xsrf = environ.get(_XSRF_TOKEN_HEADER)
  if not client_xsrf:
    Abort(httplib.UNAUTHORIZED, 'Missing client XSRF token.')
  if client_xsrf != session_xsrf:
    # do not log tokens in production
    if common.IsDevMode():
      logging.error('Client XSRF token={0!r}, session XSRF token={1!r}'
                    .format(client_xsrf, session_xsrf))
    Abort(httplib.UNAUTHORIZED,
          'Client XSRF token does not match session XSRF token.') 
Example #13
Source File: client.py    From python-quickbooks with MIT License 5 votes vote down vote up
def download_pdf(self, qbbo, item_id):
        if self.session is None:
            raise exceptions.QuickbooksException('No session')

        url = "{0}/company/{1}/{2}/{3}/pdf".format(
            self.api_url, self.company_id, qbbo.lower(), item_id)

        headers = {
            'Content-Type': 'application/pdf',
            'Accept': 'application/pdf, application/json',
            'User-Agent': 'python-quickbooks V3 library'
        }

        response = self.process_request("GET", url, headers=headers)

        if response.status_code != httplib.OK:

            if response.status_code == httplib.UNAUTHORIZED:
                # Note that auth errors have different result structure which can't be parsed by handle_exceptions()
                raise exceptions.AuthorizationException("Application authentication failed", detail=response.text)

            try:
                result = response.json()
            except:
                raise exceptions.QuickbooksException("Error reading json response: {0}".format(response.text), 10000)

            self.handle_exceptions(result["Fault"])
        else:
            return response.content 
Example #14
Source File: test_web.py    From psdash with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def test_missing_credentials(self):
        self._enable_basic_auth(self.default_username, self.default_password)
        resp = self.client.get('/')
        self.assertEqual(resp.status_code, httplib.UNAUTHORIZED) 
Example #15
Source File: test_web.py    From psdash with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def test_incorrect_credentials(self):
        self._enable_basic_auth(self.default_username, self.default_password)

        headers = self._create_auth_headers(self.default_username, 'wrongpass')
        resp = self.client.get('/', headers=headers)

        self.assertEqual(resp.status_code, httplib.UNAUTHORIZED) 
Example #16
Source File: test_web.py    From psdash with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def test_incorrect_remote_address(self):
        r = PsDashRunner({'PSDASH_ALLOWED_REMOTE_ADDRESSES': '127.0.0.1'})
        resp = r.app.test_client().get('/', environ_overrides={'REMOTE_ADDR': '10.0.0.1'})
        self.assertEqual(resp.status_code, httplib.UNAUTHORIZED) 
Example #17
Source File: test_web.py    From psdash with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def test_multiple_remote_addresses(self):
        r = PsDashRunner({'PSDASH_ALLOWED_REMOTE_ADDRESSES': '127.0.0.1, 10.0.0.1'})

        resp = r.app.test_client().get('/', environ_overrides={'REMOTE_ADDR': '10.0.0.1'})
        self.assertEqual(resp.status_code, httplib.OK)

        resp = r.app.test_client().get('/', environ_overrides={'REMOTE_ADDR': '127.0.0.1'})
        self.assertEqual(resp.status_code, httplib.OK)

        resp = r.app.test_client().get('/', environ_overrides={'REMOTE_ADDR': '10.124.0.1'})
        self.assertEqual(resp.status_code, httplib.UNAUTHORIZED) 
Example #18
Source File: test_web.py    From psdash with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def test_multiple_remote_addresses_using_list(self):
        r = PsDashRunner({'PSDASH_ALLOWED_REMOTE_ADDRESSES': ['127.0.0.1', '10.0.0.1']})

        resp = r.app.test_client().get('/', environ_overrides={'REMOTE_ADDR': '10.0.0.1'})
        self.assertEqual(resp.status_code, httplib.OK)

        resp = r.app.test_client().get('/', environ_overrides={'REMOTE_ADDR': '127.0.0.1'})
        self.assertEqual(resp.status_code, httplib.OK)

        resp = r.app.test_client().get('/', environ_overrides={'REMOTE_ADDR': '10.124.0.1'})
        self.assertEqual(resp.status_code, httplib.UNAUTHORIZED) 
Example #19
Source File: api.py    From EasY_HaCk with Apache License 2.0 5 votes vote down vote up
def client(host=RESTAPI_DEFAULT_ADDRESS, port=RESTAPI_DEFAULT_PORT, username=None, password=None):
    """
    REST-JSON API client
    """

    DataStore.username = username
    DataStore.password = password

    dbgMsg = "Example client access from command line:"
    dbgMsg += "\n\t$ taskid=$(curl http://%s:%d/task/new 2>1 | grep -o -I '[a-f0-9]\{16\}') && echo $taskid" % (host, port)
    dbgMsg += "\n\t$ curl -H \"Content-Type: application/json\" -X POST -d '{\"url\": \"http://testphp.vulnweb.com/artists.php?artist=1\"}' http://%s:%d/scan/$taskid/start" % (host, port)
    dbgMsg += "\n\t$ curl http://%s:%d/scan/$taskid/data" % (host, port)
    dbgMsg += "\n\t$ curl http://%s:%d/scan/$taskid/log" % (host, port)
    logger.debug(dbgMsg)

    addr = "http://%s:%d" % (host, port)
    logger.info("Starting REST-JSON API client to '%s'..." % addr)

    try:
        _client(addr)
    except Exception, ex:
        if not isinstance(ex, urllib2.HTTPError) or ex.code == httplib.UNAUTHORIZED:
            errMsg = "There has been a problem while connecting to the "
            errMsg += "REST-JSON API server at '%s' " % addr
            errMsg += "(%s)" % ex
            logger.critical(errMsg)
            return 
Example #20
Source File: middleware.py    From cloud-playground with Apache License 2.0 5 votes vote down vote up
def __call__(self, environ, start_response):
    if appids.TWO_COLLABORATING_APP_IDS:
      self._AssertCollaboratingAppIdAccessCheck(environ)

    if environ['PATH_INFO'] in common.CONTROL_PATHS_REQUIRING_TREE:
      if shared.IsHttpReadMethod(environ):
        if not shared.HasProjectReadAccess(environ):
          Abort(httplib.UNAUTHORIZED, 'no project read access to mimic control')
      else:
        if not shared.HasProjectWriteAccess(environ):
          Abort(httplib.UNAUTHORIZED,
                'no project write access to mimic control')
    return self.app(environ, start_response) 
Example #21
Source File: frontend_test.py    From loaner with Apache License 2.0 5 votes vote down vote up
def test_no_user(self):
    self.logout_user()

    response = self.testapp.get(r'/', expect_errors=True)

    self.assertEqual(response.status_int, httplib.UNAUTHORIZED) 
Example #22
Source File: brightcove.py    From xblock-video with GNU General Public License v3.0 5 votes vote down vote up
def post(self, url, payload, headers=None, can_retry=True):
        """
        Issue REST POST request to a given URL. Can throw ApiClientError or its subclass.

        Arguments:
            url (str): API url to fetch a resource from.
            payload (dict): POST data.
            headers (dict): Headers necessary as per API, e.g. authorization bearer to perform authorised requests.
            can_retry (bool): True if in a case of authentication error it can refresh access token and retry a call.
        Returns:
            Response in Python native data format.
        """
        headers_ = {
            'Authorization': 'Bearer ' + self.access_token,
            'Content-type': 'application/json'
        }
        if headers is not None:
            headers_.update(headers)

        resp = requests.post(url, data=payload, headers=headers_)
        log.debug("BC response status: {}".format(resp.status_code))
        if resp.status_code in (httplib.OK, httplib.CREATED):
            return resp.json()
        elif resp.status_code == httplib.UNAUTHORIZED and can_retry:
            self.access_token = self._refresh_access_token()
            return self.post(url, payload, headers, can_retry=False)

        try:
            resp_dict = resp.json()[0]
            log.warn("API error code: %s - %s", resp_dict.get(u'error_code'), resp_dict.get(u'message'))
        except (ValueError, IndexError):
            message = _("Can't parse unexpected response during POST request to Brightcove API!")
            log.exception(message)
            resp_dict = {"message": message}
        return resp_dict 
Example #23
Source File: GetworkSource.py    From poclbm with GNU General Public License v3.0 5 votes vote down vote up
def request(self, connection, url, headers, data=None, timeout=0):
		result = response = None
		try:
			if data: connection.request('POST', url, data, headers)
			else: connection.request('GET', url, headers=headers)
			response = self.timeout_response(connection, timeout)
			if not response:
				return None
			if response.status == httplib.UNAUTHORIZED:
				say_line('Wrong username or password for %s', self.server().name)
				self.authorization_failed = True
				raise NotAuthorized()
			r = self.max_redirects
			while response.status == httplib.TEMPORARY_REDIRECT:
				response.read()
				url = response.getheader('Location', '')
				if r == 0 or url == '': raise HTTPException('Too much or bad redirects')
				connection.request('GET', url, headers=headers)
				response = self.timeout_response(connection, timeout)
				r -= 1
			self.long_poll_url = response.getheader('X-Long-Polling', '')
			self.switch.update_time = bool(response.getheader('X-Roll-NTime', ''))
			hostList = response.getheader('X-Host-List', '')
			self.stratum_header = response.getheader('x-stratum', '')
			if (not self.options.nsf) and hostList: self.switch.add_servers(loads(hostList))
			result = loads(response.read())
			if result['error']:
				say_line('server error: %s', result['error']['message'])
				raise RPCError(result['error']['message'])
			return (connection, result)
		finally:
			if not result or not response or (response.version == 10 and response.getheader('connection', '') != 'keep-alive') or response.getheader('connection', '') == 'close':
				connection.close()
				connection = None 
Example #24
Source File: wsgi.py    From endpoints-management-python with Apache License 2.0 5 votes vote down vote up
def _handle_missing_api_key(self, app_info, start_response):
        code = httplib.UNAUTHORIZED
        detail = self._NO_API_KEY_MSG
        _logger.warn(u'Check not performed %d, %s', code, detail)
        app_info.response_code = code
        app_info.api_key_valid = False
        return self._return_simple_http_response(start_response, code, detail) 
Example #25
Source File: frontend.py    From loaner with Apache License 2.0 5 votes vote down vote up
def get(self, path):
    user = users.get_current_user()
    if not user:
      self.response.status = httplib.UNAUTHORIZED
      self.response.out.write('You must be logged in to access this app.')
      return
    elif user.email().split('@')[1] not in constants.APP_DOMAINS:
      self.response.status = httplib.FORBIDDEN
      self.response.out.write('Forbidden.')
      return

    if path == '/application.js':
      self._serve_frontend_javascript()
      return

    if self.bootstrap_completed or re.match(
        r'^/(bootstrap|authorization)', path):
      self._serve_frontend()
    else:
      self._sync_roles_if_necessary()
      # Re-checks if the bootstrap status did not change since the handler was
      # first loaded.
      self.bootstrap_completed = bootstrap.is_bootstrap_completed()
      if self.bootstrap_completed:
        self.redirect(path)
      else:
        datastore_user = user_model.User.get_user(user.email())
        if (permissions.Permissions.BOOTSTRAP in
            datastore_user.get_permissions()):
          self.redirect(BOOTSTRAP_URL)
        else:
          self.redirect('/maintenance') 
Example #26
Source File: googlecode_upload.py    From wfrog with GNU General Public License v3.0 4 votes vote down vote up
def upload_find_auth(file_path, project_name, summary, labels=None,
                     user_name=None, password=None, tries=3):
  """Find credentials and upload a file to a Google Code project's file server.

  file_path, project_name, summary, and labels are passed as-is to upload.

  Args:
    file_path: The local path to the file.
    project_name: The name of your project on Google Code.
    summary: A small description for the file.
    labels: an optional list of label strings with which to tag the file.
    config_dir: Path to Subversion configuration directory, 'none', or None.
    user_name: Your Google account name.
    tries: How many attempts to make.
  """

  while tries > 0:
    if user_name is None:
      # Read username if not specified or loaded from svn config, or on
      # subsequent tries.
      sys.stdout.write('Please enter your googlecode.com username: ')
      sys.stdout.flush()
      user_name = sys.stdin.readline().rstrip()
    if password is None:
      # Read password if not loaded from svn config, or on subsequent tries.
      print 'Please enter your googlecode.com password.'
      print '** Note that this is NOT your Gmail account password! **'
      print 'It is the password you use to access Subversion repositories,'
      print 'and can be found here: http://code.google.com/hosting/settings'
      password = getpass.getpass()

    status, reason, url = upload(file_path, project_name, user_name, password,
                                 summary, labels)
    # Returns 403 Forbidden instead of 401 Unauthorized for bad
    # credentials as of 2007-07-17.
    if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
      # Rest for another try.
      user_name = password = None
      tries = tries - 1
    else:
      # We're done.
      break

  return status, reason, url 
Example #27
Source File: errors.py    From luci-py with Apache License 2.0 4 votes vote down vote up
def check_status(status, expected, path, headers=None,
                 resp_headers=None, body=None, extras=None):
  """Check HTTP response status is expected.

  Args:
    status: HTTP response status. int.
    expected: a list of expected statuses. A list of ints.
    path: filename or a path prefix.
    headers: HTTP request headers.
    resp_headers: HTTP response headers.
    body: HTTP response body.
    extras: extra info to be logged verbatim if error occurs.

  Raises:
    AuthorizationError: if authorization failed.
    NotFoundError: if an object that's expected to exist doesn't.
    TimeoutError: if HTTP request timed out.
    ServerError: if server experienced some errors.
    FatalError: if any other unexpected errors occurred.
  """
  if status in expected:
    return

  msg = ('Expect status %r from Google Storage. But got status %d.\n'
         'Path: %r.\n'
         'Request headers: %r.\n'
         'Response headers: %r.\n'
         'Body: %r.\n'
         'Extra info: %r.\n' %
         (expected, status, path, headers, resp_headers, body, extras))

  if status == httplib.UNAUTHORIZED:
    raise AuthorizationError(msg)
  elif status == httplib.FORBIDDEN:
    raise ForbiddenError(msg)
  elif status == httplib.NOT_FOUND:
    raise NotFoundError(msg)
  elif status == httplib.REQUEST_TIMEOUT:
    raise TimeoutError(msg)
  elif status == httplib.REQUESTED_RANGE_NOT_SATISFIABLE:
    raise InvalidRange(msg)
  elif (status == httplib.OK and 308 in expected and
        httplib.OK not in expected):
    raise FileClosedError(msg)
  elif status >= 500:
    raise ServerError(msg)
  else:
    raise FatalError(msg) 
Example #28
Source File: errors.py    From luci-py with Apache License 2.0 4 votes vote down vote up
def check_status(status, expected, path, headers=None,
                 resp_headers=None, body=None, extras=None):
  """Check HTTP response status is expected.

  Args:
    status: HTTP response status. int.
    expected: a list of expected statuses. A list of ints.
    path: filename or a path prefix.
    headers: HTTP request headers.
    resp_headers: HTTP response headers.
    body: HTTP response body.
    extras: extra info to be logged verbatim if error occurs.

  Raises:
    AuthorizationError: if authorization failed.
    NotFoundError: if an object that's expected to exist doesn't.
    TimeoutError: if HTTP request timed out.
    ServerError: if server experienced some errors.
    FatalError: if any other unexpected errors occurred.
  """
  if status in expected:
    return

  msg = ('Expect status %r from Google Storage. But got status %d.\n'
         'Path: %r.\n'
         'Request headers: %r.\n'
         'Response headers: %r.\n'
         'Body: %r.\n'
         'Extra info: %r.\n' %
         (expected, status, path, headers, resp_headers, body, extras))

  if status == httplib.UNAUTHORIZED:
    raise AuthorizationError(msg)
  elif status == httplib.FORBIDDEN:
    raise ForbiddenError(msg)
  elif status == httplib.NOT_FOUND:
    raise NotFoundError(msg)
  elif status == httplib.REQUEST_TIMEOUT:
    raise TimeoutError(msg)
  elif status == httplib.REQUESTED_RANGE_NOT_SATISFIABLE:
    raise InvalidRange(msg)
  elif (status == httplib.OK and 308 in expected and
        httplib.OK not in expected):
    raise FileClosedError(msg)
  elif status >= 500:
    raise ServerError(msg)
  else:
    raise FatalError(msg) 
Example #29
Source File: errors.py    From MyLife with MIT License 4 votes vote down vote up
def check_status(status, expected, path, headers=None,
                 resp_headers=None, body=None, extras=None):
  """Check HTTP response status is expected.

  Args:
    status: HTTP response status. int.
    expected: a list of expected statuses. A list of ints.
    path: filename or a path prefix.
    headers: HTTP request headers.
    resp_headers: HTTP response headers.
    body: HTTP response body.
    extras: extra info to be logged verbatim if error occurs.

  Raises:
    AuthorizationError: if authorization failed.
    NotFoundError: if an object that's expected to exist doesn't.
    TimeoutError: if HTTP request timed out.
    ServerError: if server experienced some errors.
    FatalError: if any other unexpected errors occurred.
  """
  if status in expected:
    return

  msg = ('Expect status %r from Google Storage. But got status %d.\n'
         'Path: %r.\n'
         'Request headers: %r.\n'
         'Response headers: %r.\n'
         'Body: %r.\n'
         'Extra info: %r.\n' %
         (expected, status, path, headers, resp_headers, body, extras))

  if status == httplib.UNAUTHORIZED:
    raise AuthorizationError(msg)
  elif status == httplib.FORBIDDEN:
    raise ForbiddenError(msg)
  elif status == httplib.NOT_FOUND:
    raise NotFoundError(msg)
  elif status == httplib.REQUEST_TIMEOUT:
    raise TimeoutError(msg)
  elif status == httplib.REQUESTED_RANGE_NOT_SATISFIABLE:
    raise InvalidRange(msg)
  elif (status == httplib.OK and 308 in expected and
        httplib.OK not in expected):
    raise FileClosedError(msg)
  elif status >= 500:
    raise ServerError(msg)
  else:
    raise FatalError(msg) 
Example #30
Source File: errors.py    From billing-export-python with Apache License 2.0 4 votes vote down vote up
def check_status(status, expected, path, headers=None,
                 resp_headers=None, extras=None):
  """Check HTTP response status is expected.

  Args:
    status: HTTP response status. int.
    expected: a list of expected statuses. A list of ints.
    path: filename or a path prefix.
    headers: HTTP request headers.
    resp_headers: HTTP response headers.
    extras: extra info to be logged verbatim if error occurs.

  Raises:
    AuthorizationError: if authorization failed.
    NotFoundError: if an object that's expected to exist doesn't.
    TimeoutError: if HTTP request timed out.
    ServerError: if server experienced some errors.
    FatalError: if any other unexpected errors occurred.
  """
  if status in expected:
    return

  msg = ('Expect status %r from Google Storage. But got status %d.\n'
         'Path: %r.\n'
         'Request headers: %r.\n'
         'Response headers: %r.\n'
         'Extra info: %r.\n' %
         (expected, status, path, headers, resp_headers, extras))

  if status == httplib.UNAUTHORIZED:
    raise AuthorizationError(msg)
  elif status == httplib.FORBIDDEN:
    raise ForbiddenError(msg)
  elif status == httplib.NOT_FOUND:
    raise NotFoundError(msg)
  elif status == httplib.REQUEST_TIMEOUT:
    raise TimeoutError(msg)
  elif status == httplib.REQUESTED_RANGE_NOT_SATISFIABLE:
    raise InvalidRange(msg)
  elif status >= 500:
    raise ServerError(msg)
  else:
    raise FatalError(msg)