Python six.moves.http_client.UNAUTHORIZED Examples
The following are 25
code examples of six.moves.http_client.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
six.moves.http_client
, or try the search function
.
Example #1
Source File: test_requests.py From google-auth-library-python with Apache License 2.0 | 6 votes |
def test_request_refresh(self): credentials = mock.Mock(wraps=CredentialsStub()) final_response = make_response(status=http_client.OK) # First request will 401, second request will succeed. adapter = AdapterStub( [make_response(status=http_client.UNAUTHORIZED), final_response] ) authed_session = google.auth.transport.requests.AuthorizedSession( credentials, refresh_timeout=60 ) authed_session.mount(self.TEST_URL, adapter) result = authed_session.request("GET", self.TEST_URL) assert result == final_response assert credentials.before_request.call_count == 2 assert credentials.refresh.called assert len(adapter.requests) == 2 assert adapter.requests[0].url == self.TEST_URL assert adapter.requests[0].headers["authorization"] == "token" assert adapter.requests[1].url == self.TEST_URL assert adapter.requests[1].headers["authorization"] == "token1"
Example #2
Source File: test_requests.py From google-auth-library-python with Apache License 2.0 | 6 votes |
def test_request_max_allowed_time_w_transport_timeout_no_error(self, frozen_time): tick_one_second = functools.partial( frozen_time.tick, delta=datetime.timedelta(seconds=1.0) ) credentials = mock.Mock( wraps=TimeTickCredentialsStub(time_tick=tick_one_second) ) adapter = TimeTickAdapterStub( time_tick=tick_one_second, responses=[ make_response(status=http_client.UNAUTHORIZED), make_response(status=http_client.OK), ], ) authed_session = google.auth.transport.requests.AuthorizedSession(credentials) authed_session.mount(self.TEST_URL, adapter) # A short configured transport timeout does not affect max_allowed_time. # The latter is not adjusted to it and is only concerned with the actual # execution time. The call below should thus not raise a timeout error. authed_session.request("GET", self.TEST_URL, timeout=0.5, max_allowed_time=3.1)
Example #3
Source File: test_urllib3.py From google-auth-library-python with Apache License 2.0 | 6 votes |
def test_urlopen_refresh(self): credentials = mock.Mock(wraps=CredentialsStub()) final_response = ResponseStub(status=http_client.OK) # First request will 401, second request will succeed. http = HttpStub([ResponseStub(status=http_client.UNAUTHORIZED), final_response]) authed_http = google.auth.transport.urllib3.AuthorizedHttp( credentials, http=http ) authed_http = authed_http.urlopen("GET", "http://example.com") assert authed_http == final_response assert credentials.before_request.call_count == 2 assert credentials.refresh.called assert http.requests == [ ("GET", self.TEST_URL, None, {"authorization": "token"}, {}), ("GET", self.TEST_URL, None, {"authorization": "token1"}, {}), ]
Example #4
Source File: test_impersonated_credentials.py From google-auth-library-python with Apache License 2.0 | 6 votes |
def test_refresh_failure_unauthorzed(self, mock_donor_credentials): credentials = self.make_credentials(lifetime=None) response_body = { "error": { "code": 403, "message": "The caller does not have permission", "status": "PERMISSION_DENIED", } } request = self.make_request( data=json.dumps(response_body), status=http_client.UNAUTHORIZED ) with pytest.raises(exceptions.RefreshError) as excinfo: credentials.refresh(request) assert excinfo.match(impersonated_credentials._REFRESH_ERROR) assert not credentials.valid assert credentials.expired
Example #5
Source File: restclient.py From treadmill with Apache License 2.0 | 6 votes |
def _handle_error(url, response): """Handle response status codes.""" handlers = { http_client.NOT_FOUND: NotFoundError( 'Resource not found: {}'.format(url) ), # XXX: Correct code is CONFLICT. Support invalid FOUND during # migration. http_client.FOUND: AlreadyExistsError( 'Resource already exists: {}'.format(url) ), http_client.CONFLICT: AlreadyExistsError( 'Resource already exists: {}'.format(url) ), http_client.TOO_MANY_REQUESTS: TooManyRequestsError(response), http_client.FAILED_DEPENDENCY: ValidationError(response), # XXX: Correct code is FORBIDDEN. Support invalid UNAUTHORIZED during # migration. http_client.UNAUTHORIZED: NotAuthorizedError(response), http_client.FORBIDDEN: NotAuthorizedError(response), http_client.BAD_REQUEST: BadRequestError(response), } if response.status_code in handlers: raise handlers[response.status_code]
Example #6
Source File: batch.py From apitools with Apache License 2.0 | 6 votes |
def __init__(self, request, retryable_codes, service, method_config): """Initialize an individual API request. Args: request: An http_wrapper.Request object. retryable_codes: A list of integer HTTP codes that can be retried. service: A service inheriting from base_api.BaseApiService. method_config: Method config for the desired API request. """ self.__retryable_codes = list( set(retryable_codes + [http_client.UNAUTHORIZED])) self.__http_response = None self.__service = service self.__method_config = method_config self.http_request = request # TODO(user): Add some validation to these fields. self.__response = None self.__exception = None
Example #7
Source File: resource.py From st2 with Apache License 2.0 | 6 votes |
def get_resource_by_pk(self, pk, **kwargs): """ Retrieve resource by a primary key. """ try: instance = self.manager.get_by_id(pk, **kwargs) except Exception as e: traceback.print_exc() # Hack for "Unauthorized" exceptions, we do want to propagate those response = getattr(e, 'response', None) status_code = getattr(response, 'status_code', None) if status_code and status_code == http_client.UNAUTHORIZED: raise e instance = None return instance
Example #8
Source File: exc.py From python-egnyte with MIT License | 5 votes |
def __init__(self, values=None, ok_statuses=(http_client.OK, ), ignored_errors=None): super(ErrorMapping, self).__init__({ http_client.BAD_REQUEST: RequestError, http_client.UNAUTHORIZED: NotAuthorized, http_client.FORBIDDEN: InsufficientPermissions, http_client.NOT_FOUND: NotFound, http_client.CONFLICT: DuplicateRecordExists, http_client.REQUEST_ENTITY_TOO_LARGE: FileSizeExceedsLimit, http_client.SEE_OTHER: Redirected, }) if values: self.update(values) if ignored_errors: self.ignored_errors = recursive_tuple(ignored_errors) self.ok_statuses = ok_statuses
Example #9
Source File: test_file.py From jarvis with GNU General Public License v2.0 | 5 votes |
def test_token_refresh_stream_body(self): expiration = (datetime.datetime.utcnow() + datetime.timedelta(minutes=15)) credentials = self._create_test_credentials(expiration=expiration) storage = file_module.Storage(FILENAME) storage.put(credentials) credentials = storage.get() new_cred = copy.copy(credentials) new_cred.access_token = 'bar' storage.put(new_cred) valid_access_token = '1/3w' token_response = {'access_token': valid_access_token, 'expires_in': 3600} http = http_mock.HttpMockSequence([ ({'status': http_client.UNAUTHORIZED}, b'Initial token expired'), ({'status': http_client.UNAUTHORIZED}, b'Store token expired'), ({'status': http_client.OK}, json.dumps(token_response).encode('utf-8')), ({'status': http_client.OK}, 'echo_request_body') ]) body = six.StringIO('streaming body') credentials.authorize(http) _, content = transport.request(http, 'https://example.com', body=body) self.assertEqual(content, 'streaming body') self.assertEqual(credentials.access_token, valid_access_token)
Example #10
Source File: test_file.py From jarvis with GNU General Public License v2.0 | 5 votes |
def test_token_refresh_store_expires_soon(self): # Tests the case where an access token that is valid when it is read # from the store expires before the original request succeeds. expiration = (datetime.datetime.utcnow() + datetime.timedelta(minutes=15)) credentials = self._create_test_credentials(expiration=expiration) storage = file_module.Storage(FILENAME) storage.put(credentials) credentials = storage.get() new_cred = copy.copy(credentials) new_cred.access_token = 'bar' storage.put(new_cred) access_token = '1/3w' token_response = {'access_token': access_token, 'expires_in': 3600} http = http_mock.HttpMockSequence([ ({'status': http_client.UNAUTHORIZED}, b'Initial token expired'), ({'status': http_client.UNAUTHORIZED}, b'Store token expired'), ({'status': http_client.OK}, json.dumps(token_response).encode('utf-8')), ({'status': http_client.OK}, b'Valid response to original request') ]) credentials.authorize(http) transport.request(http, 'https://example.com') self.assertEqual(credentials.access_token, access_token)
Example #11
Source File: test_jwt.py From jarvis with GNU General Public License v2.0 | 5 votes |
def _credentials_refresh(self, credentials): http = http_mock.HttpMockSequence([ ({'status': http_client.OK}, b'{"access_token":"1/3w","expires_in":3600}'), ({'status': http_client.UNAUTHORIZED}, b''), ({'status': http_client.OK}, b'{"access_token":"3/3w","expires_in":3600}'), ({'status': http_client.OK}, 'echo_request_headers'), ]) http = credentials.authorize(http) _, content = transport.request(http, 'http://example.org') return content
Example #12
Source File: restclient_test.py From treadmill with Apache License 2.0 | 5 votes |
def test_get_401(self, resp_mock): """Test treadmill.restclient.get UNAUTHORIZED (401)""" # XXX: Correct code in FORBIDDEN. Support invalid UNAUTHORIZED during # migration. resp_mock.return_value.status_code = http_client.UNAUTHORIZED resp_mock.return_value.json.return_value = {} with self.assertRaises(restclient.NotAuthorizedError): restclient.get('http://foo.com', '/')
Example #13
Source File: batch.py From apitools with Apache License 2.0 | 5 votes |
def authorization_failed(self): return (self.__http_response and ( self.__http_response.status_code == http_client.UNAUTHORIZED))
Example #14
Source File: auth.py From st2 with Apache License 2.0 | 5 votes |
def run_and_print(self, args, **kwargs): try: user_info = self.run(args, **kwargs) except Exception as e: response = getattr(e, 'response', None) status_code = getattr(response, 'status_code', None) is_unathorized_error = (status_code == http_client.UNAUTHORIZED) if response and is_unathorized_error: print('Not authenticated') else: print('Unable to retrieve currently logged-in user') if self.app.client.debug: raise return print('Currently logged in as "%s".' % (user_info['username'])) print('') print('Authentication method: %s' % (user_info['authentication']['method'])) if user_info['authentication']['method'] == 'authentication token': print('Authentication token expire time: %s' % (user_info['authentication']['token_expire'])) print('') print('RBAC:') print(' - Enabled: %s' % (user_info['rbac']['enabled'])) print(' - Roles: %s' % (', '.join(user_info['rbac']['roles'])))
Example #15
Source File: test_gunicorn_configs.py From st2 with Apache License 2.0 | 5 votes |
def test_st2auth(self): port = random.randint(10000, 30000) cmd = ('gunicorn st2auth.wsgi:application -k eventlet -b "127.0.0.1:%s" --workers 1' % port) env = os.environ.copy() env['ST2_CONFIG_PATH'] = ST2_CONFIG_PATH process = subprocess.Popen(cmd, env=env, shell=True, preexec_fn=os.setsid) try: self.add_process(process=process) eventlet.sleep(8) self.assertProcessIsRunning(process=process) response = requests.post('http://127.0.0.1:%s/tokens' % (port)) self.assertEqual(response.status_code, http_client.UNAUTHORIZED) finally: kill_process(process)
Example #16
Source File: handlers.py From st2 with Apache License 2.0 | 5 votes |
def abort_request(status_code=http_client.UNAUTHORIZED, message='Invalid or missing credentials'): return abort(status_code, message)
Example #17
Source File: test_basic.py From vitrage with Apache License 2.0 | 5 votes |
def test_in_basic_mode_auth_no_header(self): resp = self.post_json('/event', expect_errors=True) self.assertEqual(httplib.UNAUTHORIZED, resp.status_code) self.assertDictEqual(ERR_MISSING_AUTH, resp.json)
Example #18
Source File: test_basic.py From vitrage with Apache License 2.0 | 5 votes |
def test_basic_mode_auth_wrong_authorization(self, *args): wrong_headers = HEADERS.copy() wrong_headers['Authorization'] = 'Basic dml0cmFnZTpwdml0cmFnZT==' resp = self.post_json('/event', params={ 'time': datetime.now().isoformat(), 'type': EVENT_TYPE, 'details': EVENT_DETAILS }, headers=wrong_headers, expect_errors=True) self.assertEqual(httplib.UNAUTHORIZED, resp.status_code) self.assertDictEqual(ERR_MISSING_VERSIONED_IDENTITY_ENDPOINTS, resp.json)
Example #19
Source File: basic_and_keystone_auth.py From vitrage with Apache License 2.0 | 5 votes |
def _unauthorized(self, message): body = {'error': { 'code': httplib.UNAUTHORIZED, 'title': httplib.responses.get(httplib.UNAUTHORIZED), 'message': message, }} raise exc.HTTPUnauthorized(body=jsonutils.dumps(body), headers=self.reject_auth_headers, charset='UTF-8', content_type='application/json')
Example #20
Source File: test_auth.py From masakari with Apache License 2.0 | 5 votes |
def test_no_user_or_user_id(self): response = self.request.get_response(self.middleware) self.assertEqual(response.status_int, http.UNAUTHORIZED)
Example #21
Source File: test_requests.py From google-auth-library-python with Apache License 2.0 | 5 votes |
def test_request_timeout_w_refresh_timeout_timeout_error(self, frozen_time): tick_one_second = functools.partial( frozen_time.tick, delta=datetime.timedelta(seconds=1.0) ) credentials = mock.Mock( wraps=TimeTickCredentialsStub(time_tick=tick_one_second) ) adapter = TimeTickAdapterStub( time_tick=tick_one_second, responses=[ make_response(status=http_client.UNAUTHORIZED), make_response(status=http_client.OK), ], ) authed_session = google.auth.transport.requests.AuthorizedSession( credentials, refresh_timeout=100 ) authed_session.mount(self.TEST_URL, adapter) # An UNAUTHORIZED response triggers a refresh (an extra request), thus # the final request that otherwise succeeds results in a timeout error # (all three requests together last 3 mocked seconds). with pytest.raises(requests.exceptions.Timeout): authed_session.request( "GET", self.TEST_URL, timeout=60, max_allowed_time=2.9 )
Example #22
Source File: test_requests.py From google-auth-library-python with Apache License 2.0 | 5 votes |
def test_request_max_allowed_time_w_refresh_timeout_no_error(self, frozen_time): tick_one_second = functools.partial( frozen_time.tick, delta=datetime.timedelta(seconds=1.0) ) credentials = mock.Mock( wraps=TimeTickCredentialsStub(time_tick=tick_one_second) ) adapter = TimeTickAdapterStub( time_tick=tick_one_second, responses=[ make_response(status=http_client.UNAUTHORIZED), make_response(status=http_client.OK), ], ) authed_session = google.auth.transport.requests.AuthorizedSession( credentials, refresh_timeout=1.1 ) authed_session.mount(self.TEST_URL, adapter) # A short configured refresh timeout does not affect max_allowed_time. # The latter is not adjusted to it and is only concerned with the actual # execution time. The call below should thus not raise a timeout error # (and `timeout` does not come into play either, as it's very long). authed_session.request("GET", self.TEST_URL, timeout=60, max_allowed_time=3.1)
Example #23
Source File: batch_test.py From apitools with Apache License 2.0 | 4 votes |
def testInternalExecute(self): with mock.patch.object(http_wrapper, 'MakeRequest', autospec=True) as mock_request: self.__ConfigureMock( mock_request, http_wrapper.Request('https://www.example.com', 'POST', { 'content-type': 'multipart/mixed; boundary="None"', 'content-length': 583, }, 'x' * 583), http_wrapper.Response({ 'status': '200', 'content-type': 'multipart/mixed; boundary="boundary"', }, textwrap.dedent("""\ --boundary content-type: text/plain content-id: <id+2> HTTP/1.1 200 OK Second response --boundary content-type: text/plain content-id: <id+1> HTTP/1.1 401 UNAUTHORIZED First response --boundary--"""), None)) test_requests = { '1': batch.RequestResponseAndHandler( http_wrapper.Request(body='first'), None, None), '2': batch.RequestResponseAndHandler( http_wrapper.Request(body='second'), None, None), } batch_request = batch.BatchHttpRequest('https://www.example.com') batch_request._BatchHttpRequest__request_response_handlers = ( test_requests) batch_request._Execute(FakeHttp()) test_responses = ( batch_request._BatchHttpRequest__request_response_handlers) self.assertEqual(http_client.UNAUTHORIZED, test_responses['1'].response.status_code) self.assertEqual(http_client.OK, test_responses['2'].response.status_code) self.assertIn( 'First response', test_responses['1'].response.content) self.assertIn( 'Second response', test_responses['2'].response.content)
Example #24
Source File: test_service_account.py From jarvis with GNU General Public License v2.0 | 4 votes |
def test_authorize_401(self, utcnow): utcnow.return_value = T1_DATE http = http_mock.HttpMockSequence([ ({'status': http_client.OK}, b''), ({'status': http_client.UNAUTHORIZED}, b''), ({'status': http_client.OK}, b''), ]) self.jwt.authorize(http) transport.request(http, self.url) token_1 = self.jwt.access_token utcnow.return_value = T2_DATE response, _ = transport.request(http, self.url) self.assertEquals(response.status, http_client.OK) token_2 = self.jwt.access_token # Check the 401 forced a new token self.assertNotEqual(token_1, token_2) # Verify mocks. certs = {'key': datafile('public_cert.pem')} self.assertEqual(len(http.requests), 3) issued_at_vals = (T1, T1, T2) exp_vals = (T1_EXPIRY, T1_EXPIRY, T2_EXPIRY) for info, issued_at, exp_val in zip(http.requests, issued_at_vals, exp_vals): self.assertEqual(info['uri'], self.url) self.assertEqual(info['method'], 'GET') self.assertIsNone(info['body']) self.assertEqual(len(info['headers']), 1) bearer, token = info['headers'][b'Authorization'].split() self.assertEqual(bearer, b'Bearer') # To parse the token, skip the time check, since this # test intentionally has stale tokens. with mock.patch('oauth2client.crypt._verify_time_range', return_value=True): payload = crypt.verify_signed_jwt_with_certs( token, certs, audience=self.url) self.assertEqual(len(payload), 5) self.assertEqual(payload['iss'], self.service_account_email) self.assertEqual(payload['sub'], self.service_account_email) self.assertEqual(payload['iat'], issued_at) self.assertEqual(payload['exp'], exp_val) self.assertEqual(payload['aud'], self.url)
Example #25
Source File: api.py From osbs-client with BSD 3-Clause "New" or "Revised" License | 4 votes |
def login(self, token=None, username=None, password=None): if self.os.use_kerberos: raise OsbsValidationException("can't use login when using kerberos") if not token: if username: self.os.username = username else: self.os.username = input("Username: ") if password: self.os.password = password else: self.os.password = getpass.getpass() self.os.use_auth = True token = self.os.get_oauth_token() self.os.token = token try: self.os.get_user() except OsbsResponseException as ex: if ex.status_code == http_client.UNAUTHORIZED: raise OsbsValidationException("token is not valid") raise token_file = utils.get_instance_token_file_name(self.os_conf.conf_section) token_file_dir = os.path.dirname(token_file) if not os.path.exists(token_file_dir): os.makedirs(token_file_dir) # Inspired by http://stackoverflow.com/a/15015748/5998718 # For security, remove file with potentially elevated mode if os.path.exists(token_file): os.remove(token_file) # Open file descriptor fdesc = os.open(token_file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, stat.S_IRUSR | stat.S_IWUSR) with os.fdopen(fdesc, 'w') as f: f.write(token + '\n')