Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: forbidden and unauthorized errors in token auth #791

Merged
merged 4 commits into from
Aug 24, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
35 changes: 32 additions & 3 deletions eodag/plugins/authentication/token.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,28 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging

import requests
from requests import RequestException
from requests.adapters import HTTPAdapter
from urllib3 import Retry

from eodag.plugins.authentication.base import Authentication
from eodag.utils import USER_AGENT, RequestsTokenAuth
from eodag.utils.exceptions import AuthenticationError, MisconfiguredError
from eodag.utils.stac_reader import HTTP_REQ_TIMEOUT

logger = logging.getLogger("eodag.authentication.token")


class TokenAuth(Authentication):
"""TokenAuth authentication plugin"""

def __init__(self, provider, config):
super(TokenAuth, self).__init__(provider, config)
self.token = ""

def validate_config_credentials(self):
"""Validate configured credentials"""
super(TokenAuth, self).validate_config_credentials()
Expand Down Expand Up @@ -56,18 +65,23 @@ def authenticate(self):
if hasattr(self.config, "headers")
else {"headers": USER_AGENT}
)
s = requests.Session()
retries = Retry(
total=3, backoff_factor=2, status_forcelist=[401, 429, 500, 502, 503, 504]
)
s.mount(self.config.auth_uri, HTTPAdapter(max_retries=retries))
try:
# First get the token
if getattr(self.config, "request_method", "POST") == "POST":
response = requests.post(
response = s.post(
self.config.auth_uri,
data=self.config.credentials,
timeout=HTTP_REQ_TIMEOUT,
**req_kwargs,
)
else:
cred = self.config.credentials
response = requests.get(
response = s.get(
self.config.auth_uri,
auth=(cred["username"], cred["password"]),
timeout=HTTP_REQ_TIMEOUT,
Expand All @@ -76,6 +90,11 @@ def authenticate(self):
response.raise_for_status()
except RequestException as e:
response_text = getattr(e.response, "text", "").strip()
logger.error(
f"Could no get authentication token: {str(e)}, {response_text}"
)
if e.response and e.response.status_code == 401:
raise Exception # do not forward unauthorized from provider to user
sbrunato marked this conversation as resolved.
Show resolved Hide resolved
raise AuthenticationError(
f"Could no get authentication token: {str(e)}, {response_text}"
)
Expand All @@ -84,11 +103,21 @@ def authenticate(self):
token = response.json()[self.config.token_key]
else:
token = response.text
headers = self._get_headers(token)
self.token = token
# Return auth class set with obtained token
return RequestsTokenAuth(token, "header", headers=self._get_headers(token))
return RequestsTokenAuth(token, "header", headers=headers)

def _get_headers(self, token):
headers = self.config.headers
if "Authorization" in headers and "$" in headers["Authorization"]:
headers["Authorization"] = headers["Authorization"].replace("$token", token)
if (
self.token
and token != self.token
and self.token in headers["Authorization"]
):
headers["Authorization"] = headers["Authorization"].replace(
self.token, token
)
return headers
14 changes: 10 additions & 4 deletions tests/units/test_auth_plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,9 @@ def test_plugins_auth_tokenauth_validate_credentials_format_url_ok(self):
auth_plugin.config.credentials = {"foo": "bar", "username": "john"}
auth_plugin.validate_config_credentials()

@mock.patch("eodag.plugins.authentication.token.requests.post", autospec=True)
@mock.patch(
"eodag.plugins.authentication.token.requests.Session.post", autospec=True
)
def test_plugins_auth_tokenauth_text_token_authenticate(self, mock_requests_post):
"""TokenAuth.authenticate must return a RequestsTokenAuth object using text token"""
auth_plugin = self.get_auth_plugin("provider_text_token_header")
Expand All @@ -146,7 +148,7 @@ def test_plugins_auth_tokenauth_text_token_authenticate(self, mock_requests_post

# check token post request call arguments
args, kwargs = mock_requests_post.call_args
assert args[0] == auth_plugin.config.auth_uri
assert args[1] == auth_plugin.config.auth_uri
assert kwargs["data"] == auth_plugin.config.credentials
assert kwargs["headers"] == dict(auth_plugin.config.headers, **USER_AGENT)

Expand All @@ -156,7 +158,9 @@ def test_plugins_auth_tokenauth_text_token_authenticate(self, mock_requests_post
assert req.headers["Authorization"] == "Bearer this_is_test_token"
assert req.headers["foo"] == "bar"

@mock.patch("eodag.plugins.authentication.token.requests.post", autospec=True)
@mock.patch(
"eodag.plugins.authentication.token.requests.Session.post", autospec=True
)
def test_plugins_auth_tokenauth_json_token_authenticate(self, mock_requests_post):
"""TokenAuth.authenticate must return a RequestsTokenAuth object using json token"""
auth_plugin = self.get_auth_plugin("provider_json_token_simple_url")
Expand All @@ -179,7 +183,9 @@ def test_plugins_auth_tokenauth_json_token_authenticate(self, mock_requests_post
auth(req)
assert req.headers["Authorization"] == "Bearer this_is_test_token"

@mock.patch("eodag.plugins.authentication.token.requests.post", autospec=True)
@mock.patch(
"eodag.plugins.authentication.token.requests.Session.post", autospec=True
)
def test_plugins_auth_tokenauth_request_error(self, mock_requests_post):
"""TokenAuth.authenticate must raise an AuthenticationError if a request error occurs"""
auth_plugin = self.get_auth_plugin("provider_json_token_simple_url")
Expand Down
4 changes: 3 additions & 1 deletion tests/units/test_search_plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -936,7 +936,9 @@ def raise_for_status(self):


class TestSearchPluginDataRequestSearch(BaseSearchPluginTest):
@mock.patch("eodag.plugins.authentication.token.requests.get", autospec=True)
@mock.patch(
"eodag.plugins.authentication.token.requests.Session.get", autospec=True
)
def setUp(self, mock_requests_get):

# One of the providers that has a BuildPostSearchResult Search plugin
Expand Down