def requires_admin_auth(): request_helper.check_proxy_header_before_request() auth_token = get_auth_token(request) client = __get_token_issuer(auth_token) if client == current_app.config.get('ADMIN_CLIENT_USER_NAME'): g.service_id = current_app.config.get('ADMIN_CLIENT_USER_NAME') for secret in current_app.config.get('API_INTERNAL_SECRETS'): try: decode_jwt_token(auth_token, secret) return except TokenExpiredError: raise AuthError( "Invalid token: expired, check that your system clock is accurate", 403) except TokenDecodeError: # TODO: Change this so it doesn't also catch `TokenIssuerError` or `TokenIssuedAtError` exceptions # (which are children of `TokenDecodeError`) as these should cause an auth error immediately rather # than continue on to check the next admin client secret continue # Either there are no admin client secrets or their token didn't match one of them so error raise AuthError("Unauthorized: admin authentication token not found", 401) else: raise AuthError('Unauthorized: admin authentication token required', 401)
def handle_admin_key(auth_token, secret): try: decode_jwt_token(auth_token, secret) except TokenExpiredError: raise AuthError("Invalid token: expired, check that your system clock is accurate", 403) except TokenDecodeError: raise AuthError("Invalid token: signature, api token is not valid", 403)
def test_should_reject_token_that_is_just_out_of_bounds_future(): # make token 31 seconds ago with freeze_time('2001-01-01T12:00:31'): token = create_jwt_token("key", "client_id") with freeze_time('2001-01-01T12:00:00'), pytest.raises(TokenExpiredError) as e: decode_jwt_token(token, "key") assert e.value.token['iss'] == "client_id"
def test_decode_jwt_token_raises_token_error_if_jwt_invalid_token_error_exception( decode_mock, exception_class): token = create_jwt_token("key", "client_id") decode_mock.side_effect = exception_class with pytest.raises(TokenError) as err: decode_jwt_token(token, "key") assert str(err.value.message) == TOKEN_ERROR_DEFAULT_ERROR_MESSAGE
def requires_auth(): request_helper.check_proxy_header_before_request() auth_token = get_auth_token(request) issuer = __get_token_issuer(auth_token) # ie the `iss` claim which should be a service ID try: with AUTH_DB_CONNECTION_DURATION_SECONDS.time(): service = SerialisedService.from_id(issuer) except DataError: raise AuthError("Invalid token: service id is not the right data type", 403) except NoResultFound: raise AuthError("Invalid token: service not found", 403) if not service.api_keys: raise AuthError("Invalid token: service has no API keys", 403, service_id=service.id) if not service.active: raise AuthError("Invalid token: service is archived", 403, service_id=service.id) for api_key in service.api_keys: try: decode_jwt_token(auth_token, api_key.secret) except TokenExpiredError: err_msg = "Error: Your system clock must be accurate to within 30 seconds" raise AuthError(err_msg, 403, service_id=service.id, api_key_id=api_key.id) except TokenAlgorithmError: err_msg = "Invalid token: algorithm used is not HS256" raise AuthError(err_msg, 403, service_id=service.id, api_key_id=api_key.id) except TokenDecodeError: # we attempted to validate the token but it failed meaning it was not signed using this api key. # Let's try the next one # TODO: Change this so it doesn't also catch `TokenIssuerError` or `TokenIssuedAtError` exceptions (which # are children of `TokenDecodeError`) as these should cause an auth error immediately rather than # continue on to check the next API key continue except TokenError: # General error when trying to decode and validate the token raise AuthError(GENERAL_TOKEN_ERROR_MESSAGE, 403, service_id=service.id, api_key_id=api_key.id) if api_key.expiry_date: raise AuthError("Invalid token: API key revoked", 403, service_id=service.id, api_key_id=api_key.id) g.service_id = service.id _request_ctx_stack.top.authenticated_service = service _request_ctx_stack.top.api_user = api_key current_app.logger.info('API authorised for service {} with api key {}, using issuer {} for URL: {}'.format( service.id, api_key.id, request.headers.get('User-Agent'), request.base_url )) return else: # service has API keys, but none matching the one the user provided raise AuthError("Invalid token: API key not found", 403, service_id=service.id)
def requires_auth(): request_helper.check_proxy_header_before_request() auth_token = get_auth_token(request) client = __get_token_issuer(auth_token) try: service = dao_fetch_service_by_id_with_api_keys(client) except DataError: raise AuthError("Invalid token: service id is not the right data type", 403) except NoResultFound: raise AuthError("Invalid token: service not found", 403) if not service.api_keys: raise AuthError("Invalid token: service has no API keys", 403, service_id=service.id) if not service.active: raise AuthError("Invalid token: service is archived", 403, service_id=service.id) for api_key in service.api_keys: try: decode_jwt_token(auth_token, api_key.secret) except TokenDecodeError: continue except TokenExpiredError: err_msg = ( "Error: Your system clock must be accurate to within 30 seconds" ) raise AuthError(err_msg, 403, service_id=service.id, api_key_id=api_key.id) if api_key.expiry_date: raise AuthError("Invalid token: API key revoked", 403, service_id=service.id, api_key_id=api_key.id) g.service_id = api_key.service_id _request_ctx_stack.top.authenticated_service = service _request_ctx_stack.top.api_user = api_key current_app.logger.info( 'API authorised for service {} with api key {}, using client {}'. format(service.id, api_key.id, request.headers.get('User-Agent'))) return else: # service has API keys, but none matching the one the user provided raise AuthError("Invalid token: signature, api token not found", 403, service_id=service.id)
def test_should_reject_token_that_is_just_out_of_bounds_future(): # make token 31 seconds ago with freeze_time('2001-01-01T12:00:31'): token = create_jwt_token("key", "client_id") with freeze_time('2001-01-01T12:00:00'), pytest.raises( TokenExpiredError) as e: decode_jwt_token(token, "key") assert e.value.token['iss'] == "client_id"
def test_should_reject_token_that_is_too_old(): # make token 31 seconds ago with freeze_time('2001-01-01T12:00:00'): token = create_jwt_token("key", "client_id") with freeze_time('2001-01-01T12:00:31'), pytest.raises( TokenExpiredError) as e: decode_jwt_token(token, "key") assert "Token has expired. See our requirements" in e.value.message assert e.value.token['iss'] == "client_id"
def test_decode_should_handle_invalid_token_with_non_hs256_algorithm(): payload = {'iss': '1234', 'iat': '1234'} token = jwt.encode(payload=payload, key='bar', headers={ 'typ': 'JWT', 'alg': 'HS512' }) with pytest.raises(TokenAlgorithmError) as e: decode_jwt_token(token, 'bar') assert "Invalid token: algorithm used is not HS256. See our requirements" in e.value.message
def test_decode_should_handle_invalid_token_with_missing_field( missing_field, exception_class): payload = {'iss': '1234', 'iat': '1234'} payload.pop(missing_field) token = jwt.encode(payload=payload, key='bar', headers={ 'typ': 'JWT', 'alg': 'HS256' }) with pytest.raises(exception_class): decode_jwt_token(token, 'bar')
def requires_auth(): request_helper.check_proxy_header_before_request() auth_type, auth_token = get_auth_token(request) if auth_type == API_KEY_V1_AUTH_TYPE: _auth_by_api_key(auth_token) return client = __get_token_issuer(auth_token) try: service = dao_fetch_service_by_id_with_api_keys(client) except DataError: raise AuthError("Invalid token: service id is not the right data type", 403) except NoResultFound: raise AuthError("Invalid token: service not found", 403) if not service.api_keys: raise AuthError("Invalid token: service has no API keys", 403, service_id=service.id) if not service.active: raise AuthError("Invalid token: service is archived", 403, service_id=service.id) for api_key in service.api_keys: try: decode_jwt_token(auth_token, api_key.secret) except TokenDecodeError: continue except TokenExpiredError: err_msg = ( "Error: Your system clock must be accurate to within 30 seconds" ) raise AuthError(err_msg, 403, service_id=service.id, api_key_id=api_key.id) _auth_with_api_key(api_key, service) return else: # service has API keys, but none matching the one the user provided raise AuthError("Invalid token: signature, api token not found", 403, service_id=service.id)
def test_should_accept_token_that_is_just_within_bounds_future(): # make token 30 seconds in the future with freeze_time('2001-01-01T12:00:30'): token = create_jwt_token("key", "client_id") with freeze_time('2001-01-01T12:00:00'): assert decode_jwt_token(token, "key")
def test_should_accept_token_that_just_within_bounds_old(): # make token 31 seconds ago with freeze_time('2001-01-01T12:00:00'): token = create_jwt_token("key", "client_id") with freeze_time('2001-01-01T12:00:30'): assert decode_jwt_token(token, "key")
def test_should_handle_random_inputs(): with pytest.raises(TokenDecodeError) as e: decode_jwt_token("token", "key") assert e.value.message == "Invalid token"
def test_should_handle_random_inputs(): with pytest.raises(TokenDecodeError) as e: decode_jwt_token("token", "key") assert "Invalid token: signature. See our requirements" in e.value.message
def get_decode_errors(auth_token, unsigned_secret): try: decode_jwt_token(auth_token, unsigned_secret) except TokenExpiredError: raise AuthError("Invalid token: expired", 403)
def test_should_handle_random_inputs(): with pytest.raises(TokenDecodeError) as e: decode_jwt_token("token", "key") assert e.value.message == "Invalid token: signature"
def test_should_reject_token_with_invalid_key(): token = create_jwt_token("key", "client_id") with pytest.raises(TokenDecodeError) as e: decode_jwt_token(token=token, secret="wrong-key") assert "Invalid token: signature. See our requirements" in e.value.message
def test_should_reject_token_with_invalid_key(): token = create_jwt_token("key", "client_id") with pytest.raises(TokenDecodeError) as e: decode_jwt_token(token=token, secret="wrong-key") assert e.value.message == "Invalid token"