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

Safe refresh #31

Merged
merged 21 commits into from
Jun 9, 2022
Merged
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
8 changes: 7 additions & 1 deletion .github/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
## Release 0.3.0 (development release)

### Improvements

* An exception is now raised when saving a refresh token with invalid characters.
[#31](https://github.com/XanaduAI/xanadu-cloud-client/pull/31)

### New features since last release

* Job lists can now be filtered by status.
Expand All @@ -17,13 +22,14 @@
xcc.Job.list(connection, status="<Status>")
```


### Contributors

This release contains contributions from (in alphabetical order):

[Jack Woehr](https://github.com/jwoehr)
[Hudhayfa Zaheem](https://github.com/HudZah).


## Release 0.2.1 (current release)

### New features since last release
Expand Down
20 changes: 20 additions & 0 deletions tests/test_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,26 @@ def test_save(self, env_file):
"XANADU_CLOUD_TLS": "False",
}

def test_save_bad_base64_url(self, settings):
"""Tests that a ValueError will be raised
if REFRESH_TOKEN contains a character outside the Base64URL with
the addition that the '.' dot character is part of the token as a
section separator.
"""
settings.REFRESH_TOKEN = "j.w.t\n"

match = r"REFRESH_TOKEN contains non-JWT character\(s\)"
with pytest.raises(ValueError, match=match):
settings.save()

# Check that the .env file was not modified since there was a "\n" in the refresh token.
assert dotenv_values(xcc.Settings.Config.env_file) == {
"XANADU_CLOUD_REFRESH_TOKEN": "j.w.t",
"XANADU_CLOUD_HOST": "example.com",
"XANADU_CLOUD_PORT": "80",
"XANADU_CLOUD_TLS": "False",
}

def test_save_multiple_times(self, settings):
"""Tests that settings can be saved to a .env file multiple times."""
path_to_env_file = xcc.Settings.Config.env_file
Expand Down
32 changes: 32 additions & 0 deletions xcc/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,19 @@
"""

import os
import re
from typing import Optional

from appdirs import user_config_dir
from dotenv import dotenv_values, set_key, unset_key
from pydantic import BaseSettings

# Matches when string contains chars outside Base64URL set
# https://base64.guru/standards/base64url
# https://en.wikipedia.org/wiki/Base64#Variants_summary_table
# Also, the dot '.' to separate sections.
_BASE64URLRE = re.compile(r"[^\.A-Za-z0-9_-]+")
Mandrenkov marked this conversation as resolved.
Show resolved Hide resolved


def get_path_to_env_file() -> str:
"""Returns the path to the .env file containing the Xanadu Cloud connection settings."""
Expand All @@ -21,6 +28,26 @@ def get_name_of_env_var(key: str = "") -> str:
return f"XANADU_CLOUD_{key}"


def _check_for_invalid_values(key: str, val: str) -> None:
"""
Check for conditions that make saving the env_file
dangerous to the user.

- REFRESH_TOKEN must not contain characters outside Base64URL set

Args:
key (str): .env file key
val (str): .env file value

Raises:
ValueError: if the value should not be saved to the .env file

"""

if key == "REFRESH_TOKEN" and val is not None and re.search(_BASE64URLRE, val) is not None:
raise ValueError("REFRESH_TOKEN contains non-JWT character(s)")


class Settings(BaseSettings):
"""Represents the configuration for connecting to the Xanadu Cloud.

Expand Down Expand Up @@ -89,12 +116,17 @@ class Config: # pylint: disable=missing-class-docstring

def save(self) -> None:
"""Saves the current settings to the .env file."""

env_file = Settings.Config.env_file
env_dir = os.path.dirname(env_file)
os.makedirs(env_dir, exist_ok=True)

saved = dotenv_values(dotenv_path=env_file)

# must be done first as dict is not ordered
for key, val in self.dict().items():
_check_for_invalid_values(key, val)

for key, val in self.dict().items():
field = get_name_of_env_var(key)

Expand Down