From 7282cf06efbcf6a72fcdc343e690c3e83b0263f3 Mon Sep 17 00:00:00 2001 From: Casey Schneider-Mizell Date: Wed, 23 Oct 2024 22:58:40 -0700 Subject: [PATCH] Auth does not save if secrets directory is read-only (#258) * Do not attempt to write token files if file system not writable * use correct directory * don't write token if everything is already good --- caveclient/auth.py | 43 +++++++++++++++++++++++++++++++++---------- 1 file changed, 33 insertions(+), 10 deletions(-) diff --git a/caveclient/auth.py b/caveclient/auth.py index 6b68736c..0559977a 100644 --- a/caveclient/auth.py +++ b/caveclient/auth.py @@ -24,7 +24,7 @@ ] -def write_token(token, filepath, key, overwrite=True): +def write_token(token, filepath, key, overwrite=True, ignore_readonly=False): if os.path.exists(filepath): with open(filepath, "r") as f: secrets = json.load(f) @@ -34,15 +34,21 @@ def write_token(token, filepath, key, overwrite=True): else: secrets = {} - secrets[key] = token + if secrets.get(key) == token: + return + else: + secrets[key] = token - secret_dir = os.path.dirname(filepath) - if not os.path.exists(secret_dir): - full_dir = os.path.expanduser(secret_dir) - os.makedirs(full_dir) + secret_dir = os.path.dirname(filepath) + if not os.path.exists(secret_dir): + full_dir = os.path.expanduser(secret_dir) + os.makedirs(full_dir) - with open(filepath, "w") as f: - json.dump(secrets, f) + if not os.access(secret_dir, os.W_OK) and ignore_readonly: + return + else: + with open(filepath, "w") as f: + json.dump(secrets, f) def server_token_filename(server_address): @@ -231,6 +237,7 @@ def save_token( token_file: Optional[str] = None, switch_token: bool = True, write_to_server_file: bool = True, + ignore_readonly: bool = True, ): """Conveniently save a token in the correct format. @@ -258,6 +265,8 @@ def save_token( write_to_server_file: bool, optional If True, will write token to a server specific file to support this machine interacting with multiple auth servers. + ignore_readonly: bool, optional + If True, will only attempt to save a token if the directory is writeable. """ if token is None: token = self.token @@ -270,8 +279,20 @@ def save_token( if save_token_file is None: raise ValueError("No token file is set") if write_to_server_file: - write_token(token, self._server_file_path, token_key, overwrite=overwrite) - write_token(token, save_token_file, token_key, overwrite=overwrite) + write_token( + token, + self._server_file_path, + token_key, + overwrite=overwrite, + ignore_readonly=ignore_readonly, + ) + write_token( + token, + save_token_file, + token_key, + overwrite=overwrite, + ignore_readonly=ignore_readonly, + ) if switch_token: self._token = token @@ -351,10 +372,12 @@ def _synchronize_local_server_file(self): token=self.token, token_file=self.local_server_filepath, overwrite=True, + ignore_readonly=True, ) else: self.save_token( token=self.token, token_file=self.local_server_filepath, overwrite=True, + ignore_readonly=True, )