Skip to content

Commit 4d82169

Browse files
committed
Updated pr.
1 parent 3be88d7 commit 4d82169

File tree

3 files changed

+61
-5
lines changed

3 files changed

+61
-5
lines changed

ads/common/auth.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,7 @@
1616

1717
import ads.telemetry
1818
import oci
19-
from oci_cli import cli_util
20-
from ads.common import logger
19+
from ads.common import logger, utils
2120
from ads.common.decorator.deprecate import deprecated
2221
from ads.common.extended_enum import ExtendedEnumMeta
2322
from oci.config import DEFAULT_LOCATION # "~/.oci/config"
@@ -877,7 +876,7 @@ def _validate_and_refresh_token(self, configuration: Dict[str, Any]):
877876

878877
def _refresh_security_token(self, configuration: Dict[str, Any]):
879878
"""Refreshes security token. The logic is mainly taken reference from:
880-
https://github.com/oracle/oci-cli/blob/9a0978344950d7b7c24a688892f24968dce20ad3/src/oci_cli/cli_session.py#L152
879+
https://github.com/oracle/oci-cli/blob/master/src/oci_cli/cli_session.py#L152
881880
882881
Parameters
883882
----------
@@ -919,7 +918,7 @@ def _refresh_security_token(self, configuration: Dict[str, Any]):
919918
refreshed_token = json.loads(response.content.decode('UTF-8'))['token']
920919
with open(expanded_security_token_location, 'w') as security_token_file:
921920
security_token_file.write(refreshed_token)
922-
cli_util.apply_user_only_access_permissions(expanded_security_token_location)
921+
utils.apply_user_only_access_permissions(expanded_security_token_location)
923922
logger.info("Successfully refreshed token")
924923
elif response.status_code == 401:
925924
raise SecurityTokenError(

ads/common/utils.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@
1717
import random
1818
import re
1919
import shutil
20+
import stat
2021
import string
22+
import subprocess
2123
import sys
2224
import tempfile
2325
from datetime import datetime
@@ -1599,3 +1601,58 @@ def is_path_exists(uri: str, auth: Optional[Dict] = None) -> bool:
15991601
if fsspec.filesystem(path_scheme, **storage_options).exists(uri):
16001602
return True
16011603
return False
1604+
1605+
def apply_user_only_access_permissions(path: str):
1606+
"""Applies user-only access permission to path. The logic is mainly taken reference from:
1607+
https://github.com/oracle/oci-cli/blob/master/src/oci_cli/cli_util.py#L2555
1608+
1609+
Parameters
1610+
----------
1611+
path: str
1612+
Path to the file or folder
1613+
"""
1614+
if not os.path.exists(path):
1615+
raise RuntimeError("Failed attempting to set permissions on path that does not exist: {}".format(path))
1616+
1617+
if is_windows():
1618+
# General permissions strategy is:
1619+
# - if we create a new folder (e.g. C:\Users\opc\.oci), set access to allow full control for current user and no access for anyone else
1620+
# - if we create a new file, set access to allow full control for current user and no access for anyone else
1621+
# - thus if the user elects to place a new file (config or key) in an existing directory, we will not change the
1622+
# permissions of that directory but will explicitly set the permissions on that file
1623+
username = os.environ['USERNAME']
1624+
userdomain = os.environ['UserDomain']
1625+
userWithDomain = os.environ['USERNAME']
1626+
if userdomain:
1627+
userWithDomain = userdomain + "\\" + username
1628+
admin_grp = '*S-1-5-32-544'
1629+
system_usr = '*S-1-5-18'
1630+
try:
1631+
if os.path.isfile(path):
1632+
subprocess.check_output('icacls "{path}" /reset'.format(path=path), stderr=subprocess.STDOUT)
1633+
try:
1634+
subprocess.check_output('icacls "{path}" /inheritance:r /grant:r "{username}:F" /grant {admin_grp}:F /grant {system_usr}:F'.format(path=path, username=userWithDomain, admin_grp=admin_grp, system_usr=system_usr), stderr=subprocess.STDOUT)
1635+
except subprocess.CalledProcessError:
1636+
subprocess.check_output('icacls "{path}" /inheritance:r /grant:r "{username}:F" /grant {admin_grp}:F /grant {system_usr}:F'.format(path=path, username=username, admin_grp=admin_grp, system_usr=system_usr), stderr=subprocess.STDOUT)
1637+
else:
1638+
if os.listdir(path):
1639+
# safety check to make sure we aren't changing permissions of existing files
1640+
raise RuntimeError("Failed attempting to set permissions on existing folder that is not empty.")
1641+
subprocess.check_output('icacls "{path}" /reset'.format(path=path), stderr=subprocess.STDOUT)
1642+
try:
1643+
subprocess.check_output('icacls "{path}" /inheritance:r /grant:r "{username}:(OI)(CI)F" /grant:r {admin_grp}:(OI)(CI)F /grant:r {system_usr}:(OI)(CI)F'.format(path=path, username=userWithDomain, admin_grp=admin_grp, system_usr=system_usr), stderr=subprocess.STDOUT)
1644+
except subprocess.CalledProcessError:
1645+
subprocess.check_output('icacls "{path}" /inheritance:r /grant:r "{username}:(OI)(CI)F" /grant:r {admin_grp}:(OI)(CI)F /grant:r {system_usr}:(OI)(CI)F'.format(path=path, username=username, admin_grp=admin_grp, system_usr=system_usr), stderr=subprocess.STDOUT)
1646+
except subprocess.CalledProcessError as exc_info:
1647+
print("Error occurred while attempting to set permissions for {path}: {exception}".format(path=path, exception=str(exc_info)))
1648+
sys.exit(exc_info.returncode)
1649+
else:
1650+
if os.path.isfile(path):
1651+
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR)
1652+
else:
1653+
# For directories, we need to apply S_IXUSER otherwise it looks like on Linux/Unix/macOS if we create the directory then
1654+
# it won't behave like a directory and let files be put into it
1655+
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
1656+
1657+
def is_windows():
1658+
return sys.platform == 'win32' or sys.platform == 'cygwin'

tests/unitary/default_setup/auth/test_auth.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -638,7 +638,7 @@ def test_validate_and_refresh_token(
638638
mock_get_jwt.assert_called()
639639
mock_refresh_security_token.assert_called_with(configuration)
640640

641-
@mock.patch("oci_cli.cli_util.apply_user_only_access_permissions")
641+
@mock.patch("ads.common.utils.apply_user_only_access_permissions")
642642
@mock.patch("json.loads")
643643
@mock.patch("requests.post")
644644
@mock.patch("json.dumps")

0 commit comments

Comments
 (0)