Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions earthaccess/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
get_s3_filesystem,
get_s3fs_session,
granule_query,
in_us_west_2,
login,
open,
search_data,
Expand Down
16 changes: 16 additions & 0 deletions earthaccess/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -644,3 +644,19 @@ def auth_environ() -> Dict[str, str]:
"`auth_environ()` requires you to first authenticate with `earthaccess.login()`"
)
return {"EARTHDATA_USERNAME": auth.username, "EARTHDATA_PASSWORD": auth.password}


def in_us_west_2() -> str:
"""Returns a message indicating if the user is in AWS region us-west-2

Returns:
str: string indicating if the user is in AWS region us-west-2
"""
if earthaccess.__store__._running_in_us_west_2() is True:
return "You are running in AWS region 'us-west-2'"
else:
raise ValueError(
"Your instance is not running inside the"
" AWS us-west-2 region."
" You will not be able to directly access NASA Earthdata S3 buckets."
)
29 changes: 23 additions & 6 deletions earthaccess/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,29 @@ def __init__(self) -> None:
self.token: Optional[Mapping[str, str]] = None
self._set_earthdata_system(PROD)

def login(
self,
strategy: str = "netrc",
persist: bool = False,
system: Optional[System] = None,
) -> Any:
def __repr__(self) -> str:
print_str = "Authentication Info\n" + "-------------------\n"
for k, v in self.auth_info.items():
print_str += str("{}: {}\n".format(k, v))

return print_str
Comment on lines +98 to +103
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I strongly discourage this implementation of __repr__ for at least 2 reasons:

  1. (minor) this is arguably an "abuse" of __repr__, which should generally be: "If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment)." (see https://docs.python.org/3/reference/datamodel.html#object.__repr__)
  2. (very important) this can lead to inadvertent leaking of the user's token(s) during logging since auth_info includes those tokens

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about something like (and get rid of the auth_info function) instead:

    def __str__(self) -> str:
        print_str = str("Authenticated?: {}\n".format(self.authenticated))
        print_str += str("View your token with `.tokens`")

        return print_str


@property
def auth_info(self) -> Dict:
"""Get information about the authentication session.

Returns:
Dict: information about the auth object
"""
summary_dict: Dict[str, Any]
summary_dict = {
"authenticated?": self.authenticated,
"tokens": self.tokens,
}

return summary_dict

def login(self, strategy: str = "netrc", persist: bool = False) -> Any:
"""Authenticate with Earthdata login.

Parameters:
Expand Down
23 changes: 4 additions & 19 deletions earthaccess/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from typing import Any, Dict, List, Mapping, Optional, Tuple, Union
from uuid import uuid4

import botocore.session
import fsspec
import requests
import s3fs
Expand Down Expand Up @@ -231,26 +232,10 @@ def _own_s3_credentials(self, links: List[Dict[str, Any]]) -> Union[str, None]:
return None

def _running_in_us_west_2(self) -> bool:
session = self.auth.get_session()
try:
# https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html
token_ = session.put(
"http://169.254.169.254/latest/api/token",
headers={"X-aws-ec2-metadata-token-ttl-seconds": "21600"},
timeout=1,
)
resp = session.get(
"http://169.254.169.254/latest/meta-data/placement/region",
timeout=1,
headers={"X-aws-ec2-metadata-token": token_.text},
)
except Exception:
return False

if resp.status_code == 200 and b"us-west-2" == resp.content:
# On AWS, in region us-west-2
if botocore.session.get_session().get_config_variable("region") == "us-west-2":
return True
return False
else:
return False

def set_requests_session(
self, url: str, method: str = "get", bearer_token: bool = True
Expand Down
Loading