Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Make OIDC plugin public (#9406)

Maciej Korycinski7d2e77c5f235
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1e10a37d5d..7b0e0795ec 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,7 @@ All notable, unreleased changes to this project will be documented in this file.
### Other changes
- Fix failing `checkoutCustomerAttach` mutation - #9401 by @IKarbowiak
+- Add OpenID Connect Plugin - #9406 by @korycins
- Add new mutation `orderCreateFromCheckout` - #9343 by @korycins
- Add `language_code` field to webhook payload for `Order`, `Checkout` and `Customer` - #9433 by @rafalp
- Add handling webhook payload via GraphQL subscriptions (#9394) @jakubkuc
diff --git a/poetry.lock b/poetry.lock
index 84c66b44c0..2a7a627dec 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -96,6 +96,17 @@ docs = ["furo", "sphinx", "zope.interface", "sphinx-notfound-page"]
tests = ["coverage[toml] (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "six", "mypy", "pytest-mypy-plugins", "zope.interface", "cloudpickle"]
tests_no_zope = ["coverage[toml] (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "six", "mypy", "pytest-mypy-plugins", "cloudpickle"]
+[[package]]
+name = "authlib"
+version = "1.0.0"
+description = "The ultimate Python library in building OAuth and OpenID Connect servers and clients."
+category = "main"
+optional = false
+python-versions = "*"
+
+[package.dependencies]
+cryptography = ">=3.2"
+
[[package]]
name = "authorizenet"
version = "1.1.4"
@@ -2758,8 +2769,8 @@ test = ["pytest"]
[metadata]
lock-version = "1.1"
-python-versions = "~3.9"
-content-hash = "7e3879258b85b5edeb76a69b0a6322759e50e8c40ca646993d76856fd57917c4"
+ python-versions = "~3.9"
+content-hash = "747647912d3b28921f2a5a8b07ad1a3b58989a595a088a03bed9c90265f07a90"
[metadata.files]
adyen = [
@@ -2797,6 +2808,10 @@ attrs = [
{file = "attrs-21.4.0-py2.py3-none-any.whl", hash = "sha256:2d27e3784d7a565d36ab851fe94887c5eccd6a463168875832a1be79c82828b4"},
{file = "attrs-21.4.0.tar.gz", hash = "sha256:626ba8234211db98e869df76230a137c4c40a12d72445c45d5f5b716f076e2fd"},
]
+authlib = [
+ {file = "Authlib-1.0.0-py2.py3-none-any.whl", hash = "sha256:e8d589a886b5bcde64ebf961157bf619d613666ef6703822c06254c5b108b3e6"},
+ {file = "Authlib-1.0.0.tar.gz", hash = "sha256:2b13b4ba6465bdc46b89b1a07b2707c85b3434502d5a5fe202f5bdef8ebd5ac9"},
+]
authorizenet = [
{file = "authorizenet-1.1.4.tar.gz", hash = "sha256:d1f910953b5a31a49340b52469c4023f3b1e0d66ec1a02ab3558b01741b84006"},
]
diff --git a/pyproject.toml b/pyproject.toml
index 8782d1271e..3469b48334 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -68,6 +68,7 @@ documentation = "https://docs.saleor.io/"
cryptography = "^36.0.0"
graphene = "<3.0"
uvicorn = {extras = ["standard"], version = "^0.17.5"}
+ Authlib = "^1.0.0"
[tool.poetry.dependencies.celery]
version = ">=4.4.5,<6.0.0"
diff --git a/requirements.txt b/requirements.txt
index a495596d78..3cea348568 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -4,6 +4,7 @@ aniso8601==7.0.0
anyio==3.5.0; python_version >= "3.7" and python_full_version >= "3.6.2"
asgiref==3.5.0; python_version >= "3.7"
async-timeout==4.0.2; python_version >= "3.7"
+authlib==1.0.0
authorizenet==1.1.4
babel==2.9.1; (python_version >= "2.7" and python_full_version < "3.0.0") or (python_full_version >= "3.4.0")
beautifulsoup4==4.7.1
diff --git a/requirements_dev.txt b/requirements_dev.txt
index 764d260274..457a3e4ba4 100644
--- a/requirements_dev.txt
+++ b/requirements_dev.txt
@@ -7,6 +7,7 @@ astroid==2.11.2; python_full_version >= "3.6.2"
async-timeout==4.0.2; python_version >= "3.7"
atomicwrites==1.4.0; python_version >= "3.7" and python_full_version < "3.0.0" and sys_platform == "win32" and python_version < "4.0" or sys_platform == "win32" and python_version >= "3.7" and python_full_version >= "3.4.0" and python_version < "4.0"
attrs==21.4.0; python_version >= "3.7" and python_full_version < "3.0.0" and python_version < "4.0" or python_full_version >= "3.5.0" and python_version >= "3.7" and python_version < "4.0"
+authlib==1.0.0
authorizenet==1.1.4
babel==2.9.1; (python_version >= "2.7" and python_full_version < "3.0.0") or (python_full_version >= "3.4.0")
beautifulsoup4==4.7.1
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 44fbe87f79..1850c4fafb 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -137,7 +137,9 @@ class BasePlugin:
# Authenticate user which should be assigned to the request.
#
# Overwrite this method if the plugin handles authentication flow.
- authenticate_user: Callable[[WSGIRequest], Union["User", NoneType]]
+ authenticate_user: Callable[
+ [WSGIRequest, Optional["User"]], Union["User", NoneType]
+ ]
authorize_payment: Callable[["PaymentData", Any], GatewayResponse]
@@ -280,28 +282,35 @@ class BasePlugin:
# Handle authentication request.
#
# Overwrite this method if the plugin handles authentication flow.
- external_authentication_url: Callable[[dict, WSGIRequest], dict]
+ external_authentication_url: Callable[[dict, WSGIRequest, dict], dict]
# Handle logout request.
#
# Overwrite this method if the plugin handles logout flow.
- external_logout: Callable[[dict], Any]
+ external_logout: Callable[[dict, WSGIRequest, dict], Any]
# Handle authentication request responsible for obtaining access tokens.
#
# Overwrite this method if the plugin handles authentication flow.
- external_obtain_access_tokens: Callable[[dict, WSGIRequest], ExternalAccessTokens]
+ external_obtain_access_tokens: Callable[
+ [dict, WSGIRequest, ExternalAccessTokens], ExternalAccessTokens
+ ]
# Handle authentication refresh request.
#
# Overwrite this method if the plugin handles authentication flow and supports
# refreshing the access.
- external_refresh: Callable[[dict, WSGIRequest], ExternalAccessTokens]
+ external_refresh: Callable[
+ [dict, WSGIRequest, ExternalAccessTokens], ExternalAccessTokens
+ ]
# Verify the provided authentication data.
#
# Overwrite this method if the plugin should validate the authentication data.
- external_verify: Callable[[dict, WSGIRequest], Tuple[Union["User", NoneType], dict]]
+ external_verify: Callable[
+ [dict, WSGIRequest, Tuple[Union["User", NoneType], dict]],
+ Tuple[Union["User", NoneType], dict],
+ ]
# Triggered when ShopFetchTaxRates mutation is called.
fetch_taxes_data: Callable[[Any], Any]
diff --git a/saleor/plugins/openid_connect/__init__.py b/saleor/plugins/openid_connect/__init__.py
new file mode 100644
index 0000000000..0697e151bc
--- /dev/null
+++ b/saleor/plugins/openid_connect/__init__.py
@@ -0,0 +1 @@
+PLUGIN_ID = "mirumee.authentication.openidconnect"
diff --git a/saleor/plugins/openid_connect/const.py b/saleor/plugins/openid_connect/const.py
new file mode 100644
index 0000000000..bf024d2dfa
--- /dev/null
+++ b/saleor/plugins/openid_connect/const.py
@@ -0,0 +1 @@
+SALEOR_STAFF_PERMISSION = "saleor:staff"
diff --git a/saleor/plugins/openid_connect/dataclasses.py b/saleor/plugins/openid_connect/dataclasses.py
new file mode 100644
index 0000000000..df281787ea
--- /dev/null
+++ b/saleor/plugins/openid_connect/dataclasses.py
@@ -0,0 +1,15 @@
+from dataclasses import dataclass
+
+
+@dataclass
+class OpenIDConnectConfig:
+ client_id: str
+ client_secret: str
+ enable_refresh_token: bool
+ json_web_key_set_url: str
+ authorization_url: str
+ logout_url: str
+ token_url: str
+ user_info_url: str
+ audience: str
+ use_scope_permissions: bool
diff --git a/saleor/plugins/openid_connect/exceptions.py b/saleor/plugins/openid_connect/exceptions.py
new file mode 100644
index 0000000000..a59822492d
--- /dev/null
+++ b/saleor/plugins/openid_connect/exceptions.py
@@ -0,0 +1,2 @@
+class AuthenticationError(Exception):
+ """Raises when error occurred during authentication."""
diff --git a/saleor/plugins/openid_connect/plugin.py b/saleor/plugins/openid_connect/plugin.py
new file mode 100644
index 0000000000..8cbd44c645
--- /dev/null
+++ b/saleor/plugins/openid_connect/plugin.py
@@ -0,0 +1,449 @@
+import logging
+from typing import Optional, Tuple
+
+from authlib.common.errors import AuthlibBaseError
+from authlib.integrations.requests_client import OAuth2Session
+from django.core import signing
+from django.core.exceptions import ValidationError
+from django.core.handlers.wsgi import WSGIRequest
+from jwt import ExpiredSignatureError, InvalidTokenError
+from requests import HTTPError, PreparedRequest
+
+from ...account.models import User
+from ...core.auth import get_token_from_request
+from ...core.jwt import (
+ JWT_REFRESH_TOKEN_COOKIE_NAME,
+ PERMISSIONS_FIELD,
+ get_user_from_access_payload,
+ get_user_from_payload,
+ jwt_decode,
+)
+from ...core.permissions import get_permissions_codename, get_permissions_from_names
+from ..base_plugin import BasePlugin, ConfigurationTypeField, ExternalAccessTokens
+from ..error_codes import PluginErrorCode
+from ..models import PluginConfiguration
+from . import PLUGIN_ID
+from .const import SALEOR_STAFF_PERMISSION
+from .dataclasses import OpenIDConnectConfig
+from .exceptions import AuthenticationError
+from .utils import (
+ OAUTH_TOKEN_REFRESH_FIELD,
+ create_tokens_from_oauth_payload,
+ get_incorrect_fields,
+ get_or_create_user_from_payload,
+ get_parsed_id_token,
+ get_saleor_permission_names,
+ get_saleor_permissions_qs_from_scope,
+ get_user_from_oauth_access_token,
+ get_user_from_token,
+ is_owner_of_token_valid,
+ validate_refresh_token,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class OpenIDConnectPlugin(BasePlugin):
+ PLUGIN_ID = PLUGIN_ID
+ DEFAULT_CONFIGURATION = [
+ {"name": "client_id", "value": None},
+ {"name": "client_secret", "value": None},
+ {"name": "enable_refresh_token", "value": True},
+ {"name": "oauth_authorization_url", "value": None},
+ {"name": "oauth_token_url", "value": None},
+ {"name": "json_web_key_set_url", "value": None},
+ {"name": "oauth_logout_url", "value": None},
+ {"name": "user_info_url", "value": None},
+ {"name": "audience", "value": None},
+ {"name": "use_oauth_scope_permissions", "value": False},
+ ]
+ PLUGIN_NAME = "OpenID Connect"
+ CONFIGURATION_PER_CHANNEL = False
+
+ CONFIG_STRUCTURE = {
+ "client_id": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": (
+ "Your Client ID required to authenticate on the provider side."
+ ),
+ "label": "Client ID",
+ },
+ "client_secret": {
+ "type": ConfigurationTypeField.SECRET,
+ "help_text": (
+ "Your client secret required to authenticate on provider side."
+ ),
+ "label": "Client Secret",
+ },
+ "enable_refresh_token": {
+ "type": ConfigurationTypeField.BOOLEAN,
+ "help_text": (
+ "Determine if the refresh token should be also fetched from provider. "
+ "By disabling it, users will need to re-login after the access token "
+ "expired. By enabling it, frontend apps will be able to refresh the "
+ "access token. OAuth provider needs to have included scope "
+ "`offline_access`."
+ ),
+ "label": "Enable refreshing token",
+ },
+ "oauth_authorization_url": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": "The endpoint used to redirect user to authorization page.",
+ "label": "OAuth Authorization URL",
+ },
+ "oauth_token_url": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": (
+ "The endpoint to exchange an Authorization Code for a Token."
+ ),
+ "label": "OAuth Token URL",
+ },
+ "json_web_key_set_url": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": (
+ "The JSON Web Key Set (JWKS) is a set of keys containing the public "
+ "keys used to verify any JSON Web Token (JWT) issued by the "
+ "authorization server and signed using the RS256 signing algorithm."
+ ),
+ "label": "JSON Web Key Set URL",
+ },
+ "oauth_logout_url": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": (
+ "The URL for logging out the user from the OAuth provider side."
+ ),
+ "label": "OAuth logout URL",
+ },
+ "user_info_url": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": (
+ "The URL which can be used to fetch user details by using an access "
+ "token."
+ ),
+ "label": "User info URL",
+ },
+ "audience": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": (
+ "The OAuth resource identifier. If provided, Saleor will define "
+ "audience for each authorization request."
+ ),
+ "label": "Audience",
+ },
+ "use_oauth_scope_permissions": {
+ "type": ConfigurationTypeField.BOOLEAN,
+ "help_text": (
+ "Use OAuth scope permissions to grant a logged-in user access to "
+ "protected resources. Your OAuth provider needs to have defined "
+ "Saleor's permission scopes in format saleor:<saleor-perm>. Check"
+ " Saleor docs for more details."
+ ),
+ "label": "Use OAuth scope permissions",
+ },
+ }
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ # Convert to dict to easier take config elements
+ configuration = {item["name"]: item["value"] for item in self.configuration}
+ self.config = OpenIDConnectConfig(
+ client_id=configuration["client_id"],
+ client_secret=configuration["client_secret"],
+ enable_refresh_token=configuration["enable_refresh_token"],
+ json_web_key_set_url=configuration["json_web_key_set_url"],
+ authorization_url=configuration["oauth_authorization_url"],
+ token_url=configuration["oauth_token_url"],
+ logout_url=configuration["oauth_logout_url"],
+ audience=configuration["audience"],
+ use_scope_permissions=configuration["use_oauth_scope_permissions"],
+ user_info_url=configuration["user_info_url"],
+ )
+
+ # Determine, if we have defined all fields required to use OAuth access token
+ # as Saleor's authorization token.
+ self.use_oauth_access_token = bool(
+ self.config.user_info_url and self.config.json_web_key_set_url
+ )
+
+ # Determine, if we have defined all fields required to process the
+ # authorization flow.
+ self.use_authorization_flow = bool(
+ self.config.json_web_key_set_url
+ and self.config.authorization_url
+ and self.config.token_url
+ )
+ self.oauth = self._get_oauth_session()
+
+ @classmethod
+ def validate_plugin_configuration(
+ cls, plugin_configuration: "PluginConfiguration", **kwargs
+ ):
+ """Validate if provided configuration is correct."""
+ incorrect_fields = get_incorrect_fields(plugin_configuration)
+ if incorrect_fields:
+ error_msg = "To enable a plugin, you need to provide values for this field."
+ raise ValidationError(
+ {
+ field: ValidationError(
+ error_msg, code=PluginErrorCode.PLUGIN_MISCONFIGURED.value
+ )
+ for field in incorrect_fields
+ }
+ )
+
+ def _get_oauth_session(self):
+ scope = "openid profile email"
+ if self.config.use_scope_permissions:
+ permissions = [f"saleor:{perm}" for perm in get_permissions_codename()]
+ permissions.append(SALEOR_STAFF_PERMISSION)
+ scope_permissions = " ".join(permissions)
+ scope += f" {scope_permissions}"
+ if self.config.enable_refresh_token:
+ scope += " offline_access"
+ return OAuth2Session(
+ client_id=self.config.client_id,
+ client_secret=self.config.client_secret,
+ scope=scope,
+ )
+
+ def _use_scope_permissions(self, user, scope):
+ user_permissions = []
+ if scope:
+ permissions = get_saleor_permissions_qs_from_scope(scope)
+ user_permissions = get_saleor_permission_names(permissions)
+ user.effective_permissions = permissions
+ return user_permissions
+
+ def external_obtain_access_tokens(
+ self, data: dict, request: WSGIRequest, previous_value
+ ) -> ExternalAccessTokens:
+ if not self.active:
+ return previous_value
+
+ if not self.use_authorization_flow:
+ return previous_value
+
+ code = data.get("code")
+ if not code:
+ msg = "Missing required field - code"
+ raise ValidationError(
+ {"code": ValidationError(msg, code=PluginErrorCode.NOT_FOUND.value)}
+ )
+
+ state = data.get("state")
+ if not state:
+ msg = "Missing required field - state"
+ raise ValidationError(
+ {"state": ValidationError(msg, code=PluginErrorCode.NOT_FOUND.value)}
+ )
+
+ try:
+ state_data = signing.loads(state)
+ except signing.BadSignature:
+ msg = "Bad signature"
+ raise ValidationError(
+ {"state": ValidationError(msg, code=PluginErrorCode.INVALID.value)}
+ )
+
+ redirect_uri = state_data.get("redirectUri")
+ if not redirect_uri:
+ msg = "The state value is incorrect"
+ raise ValidationError(
+ {"code": ValidationError(msg, code=PluginErrorCode.INVALID.value)}
+ )
+
+ token_data = self.oauth.fetch_token(
+ self.config.token_url, code=code, redirect_uri=redirect_uri
+ )
+
+ parsed_id_token = get_parsed_id_token(
+ token_data, self.config.json_web_key_set_url
+ )
+
+ user = get_or_create_user_from_payload(
+ parsed_id_token, self.config.authorization_url
+ )
+
+ user_permissions = []
+ if self.config.use_scope_permissions:
+ scope = token_data.get("scope")
+ user_permissions = self._use_scope_permissions(user, scope)
+ if not user.is_staff and bool(
+ SALEOR_STAFF_PERMISSION in scope or user_permissions
+ ):
+ user.is_staff = True
+ user.save(update_fields=["is_staff"])
+ elif user.is_staff and not bool(
+ SALEOR_STAFF_PERMISSION in scope or user_permissions
+ ):
+ user.is_staff = False
+ user.save(update_fields=["is_staff"])
+
+ tokens = create_tokens_from_oauth_payload(
+ token_data, user, parsed_id_token, user_permissions, owner=self.PLUGIN_ID
+ )
+ return ExternalAccessTokens(user=user, **tokens)
+
+ def external_authentication_url(
+ self, data: dict, request: WSGIRequest, previous_value
+ ) -> dict:
+ if not self.active:
+ return previous_value
+
+ if not self.use_authorization_flow:
+ return previous_value
+
+ redirect_uri = data.get("redirectUri")
+ if not redirect_uri:
+ msg = "Missing required field - redirectUri"
+ raise ValidationError(
+ {
+ "redirectUri": ValidationError(
+ msg, code=PluginErrorCode.NOT_FOUND.value
+ )
+ }
+ )
+ kwargs = {
+ "redirect_uri": redirect_uri,
+ "state": signing.dumps({"redirectUri": redirect_uri}),
+ }
+ if self.config.audience:
+ kwargs["audience"] = self.config.audience
+ uri, state = self.oauth.create_authorization_url(
+ self.config.authorization_url, **kwargs
+ )
+ return {"authorizationUrl": uri}
+
+ def external_refresh(
+ self, data: dict, request: WSGIRequest, previous_value
+ ) -> ExternalAccessTokens:
+ if not self.active:
+ return previous_value
+
+ if not self.use_authorization_flow:
+ return previous_value
+
+ error_code = PluginErrorCode.INVALID.value
+ if not self.config.enable_refresh_token:
+ msg = (
+ "Unable to refresh the token. Support for refreshing tokens is disabled"
+ )
+ raise ValidationError(
+ {"refresh_token": ValidationError(msg, code=error_code)}
+ )
+ refresh_token = request.COOKIES.get(JWT_REFRESH_TOKEN_COOKIE_NAME, None)
+ refresh_token = data.get("refreshToken") or refresh_token
+
+ validate_refresh_token(refresh_token, data)
+ saleor_refresh_token = jwt_decode(refresh_token) # type: ignore
+ token_endpoint = self.config.token_url
+ try:
+ token_data = self.oauth.refresh_token(
+ token_endpoint,
+ refresh_token=saleor_refresh_token[OAUTH_TOKEN_REFRESH_FIELD],
+ )
+ except (AuthlibBaseError, HTTPError):
+ logger.warning("Unable to refresh the token.", exc_info=True)
+ raise ValidationError(
+ {
+ "refresh_token": ValidationError(
+ "Unable to refresh the token.",
+ code=error_code,
+ )
+ }
+ )
+ try:
+ parsed_id_token = get_parsed_id_token(
+ token_data, self.config.json_web_key_set_url
+ )
+ user = get_user_from_token(parsed_id_token)
+
+ user_permissions = []
+ if self.config.use_scope_permissions:
+ user_permissions = self._use_scope_permissions(
+ user, token_data.get("scope")
+ )
+
+ tokens = create_tokens_from_oauth_payload(
+ token_data,
+ user,
+ parsed_id_token,
+ user_permissions,
+ owner=self.PLUGIN_ID,
+ )
+ return ExternalAccessTokens(user=user, **tokens)
+ except AuthenticationError as e:
+ raise ValidationError(
+ {"refreshToken": ValidationError(str(e), code=error_code)}
+ )
+
+ def external_logout(self, data: dict, request: WSGIRequest, previous_value):
+ if not self.active:
+ return previous_value
+
+ if not self.use_authorization_flow:
+ return previous_value
+
+ if not self.config.logout_url:
+ # Logout url doesn't exist
+ return {}
+ req = PreparedRequest()
+ req.prepare_url(self.config.logout_url, data)
+
+ return {"logoutUrl": req.url}
+
+ def external_verify(
+ self, data: dict, request: WSGIRequest, previous_value
+ ) -> Tuple[Optional[User], dict]:
+ if not self.active:
+ return previous_value
+
+ if not self.use_authorization_flow:
+ return previous_value
+
+ token = data.get("token")
+ if not token:
+ return previous_value
+ valid = is_owner_of_token_valid(token, owner=self.PLUGIN_ID)
+ if not valid:
+ return previous_value
+ try:
+ payload = jwt_decode(token)
+ user = get_user_from_payload(payload)
+ if not user:
+ return previous_value
+ user.is_staff = False
+ except (ExpiredSignatureError, InvalidTokenError) as e:
+ raise ValidationError({"token": e})
+ permissions = payload.get(PERMISSIONS_FIELD)
+ if permissions is not None:
+ user.effective_permissions = get_permissions_from_names( # type: ignore
+ permissions
+ )
+ user.is_staff = True
+ return user, payload
+
+ def authenticate_user(self, request: WSGIRequest, previous_value) -> Optional[User]:
+ if not self.active:
+ return previous_value
+ token = get_token_from_request(request)
+ if not token:
+ return previous_value
+ user = previous_value
+ if self.use_authorization_flow and is_owner_of_token_valid(
+ token, owner=self.PLUGIN_ID
+ ):
+ # Check if the token is created by this plugin
+ payload = jwt_decode(token)
+ user = get_user_from_access_payload(payload)
+ return user
+
+ if self.use_oauth_access_token:
+ user = get_user_from_oauth_access_token(
+ token,
+ self.config.json_web_key_set_url,
+ self.config.user_info_url,
+ self.config.use_scope_permissions,
+ self.config.audience,
+ )
+ return user or previous_value
diff --git a/saleor/plugins/openid_connect/tests/__init__.py b/saleor/plugins/openid_connect/tests/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/plugins/openid_connect/tests/cassettes/test_plugin/test_external_obtain_access_tokens.yaml b/saleor/plugins/openid_connect/tests/cassettes/test_plugin/test_external_obtain_access_tokens.yaml
new file mode 100644
index 0000000000..46ddfc6c3e
--- /dev/null
+++ b/saleor/plugins/openid_connect/tests/cassettes/test_plugin/test_external_obtain_access_tokens.yaml
@@ -0,0 +1,238 @@
+interactions:
+- request:
+ body: null
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate
+ Connection:
+ - keep-alive
+ User-Agent:
+ - python-requests/2.24.0
+ method: GET
+ uri: https://saleor.io/.well-known/jwks.json
+ response:
+ body:
+ string: !!binary |
+ H4sIAAAAAAAAA9xWSa/zuBH8L+/qedBmbXOjdsnaV0tBYJjaJUuyrV2D+e/x+wIkl0GAueZW7GaT
+ jepCkX98tfk+fv3+jz++7o/y6/cv18NJ6uu3r3baf63AB89j/sFjXX5w/0HdoCvrOxcB1+Qk/5KK
+ rEkC9iaP6Bu2RktSOAcdc6RQOn8uuYAW+EN1YVqUc1aawO4Lx2IgWCIHSyisxq32XuAJy3gUWpl5
+ 5EPK7NMIptpxri9DN0Tz991lfdlREh8rdL2tQ51/9YQgZ65SWEcBMVkcSc0qeFnNrL4GPCNMmf4N
+ vfRqSvcomWg6ESSsiXNULef3NLN1IxcPShn93KrZ2/kJDw28rw27eFLz4PydrMsXdNzAZ/ypbxhq
+ 0qZk/WZqaigTWgCBv+40JpmYy0LVUrrqeIZmqfQ9x0XC7TYbZe/4mVQrUPRpm9Z0KiJzt3Oou2WL
+ JNsHlQLyex/016G5juCbKeD6IfeHZuAA7of/Ovvh/3bcWGgnn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l8MZ5unCzG1BCzuj1+6K6PzY
+ AmswzFlc/ACmSM89F6ncNpJ9qVBLxxDbo/g2YMK6EpughSBSXSnFyAXF2tR5D8l2P2+OyFd3mHaL
+ NaXd63gLNXYCwedLziWvuXYyBRJHXly61ZwFF2v37+rK0+2ZcwK4uXOiMxQsiAGFtyYW/XG/yiVa
+ 6Ve+H+D//P4Bihyfd+wLAAA=
+ headers:
+ Access-Control-Allow-Credentials:
+ - 'false'
+ Access-Control-Allow-Origin:
+ - '*'
+ Access-Control-Expose-Headers:
+ - X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset
+ CF-Cache-Status:
+ - REVALIDATED
+ CF-Ray:
+ - 5d9cf7e0eaeaf2bc-WAW
+ Cache-Control:
+ - public, max-age=15, stale-while-revalidate=15, stale-if-error=15
+ Connection:
+ - keep-alive
+ Content-Encoding:
+ - gzip
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Mon, 28 Sep 2020 11:01:45 GMT
+ ETag:
+ - W/"bec-GggneSfmYLDK9HQV1PLJX5tHMns"
+ Expect-CT:
+ - max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
+ Server:
+ - cloudflare
+ Set-Cookie:
+ - __cfduid=d1904c475b9bba4829fff18abc4889fd01601290905; expires=Wed, 28-Oct-20
+ 11:01:45 GMT; path=/; domain=.eu.auth0.com; HttpOnly; SameSite=Lax; Secure
+ - __cf_bm=087b77946e5c30aca13c3583c7818fd977c0454a-1601290905-1800-AXZDwTgF/HpVt4/f/1LKjF+Uguo/2KRecRbZIhfyAxqHWUCseFezCxNyGQDnKLKLGuRrGi/iRj+u6aqVin5BviE=;
+ path=/; expires=Mon, 28-Sep-20 11:31:45 GMT; domain=.eu.auth0.com; HttpOnly;
+ Secure; SameSite=None
+ Transfer-Encoding:
+ - chunked
+ Vary:
+ - Accept-Encoding, Accept-Encoding
+ X-Auth0-RequestId:
+ - 049d410ac97d6b835b5a
+ X-Cache-Status:
+ - MISS
+ X-Content-Type-Options:
+ - nosniff
+ X-RateLimit-Limit:
+ - '20'
+ X-RateLimit-Remaining:
+ - '19'
+ X-RateLimit-Reset:
+ - '1601282137'
+ alt-svc:
+ - h3-27=":443"; ma=86400, h3-28=":443"; ma=86400, h3-29=":443"; ma=86400
+ cf-request-id:
+ - 0575f940920000f2bcfc892200000001
+ ot-baggage-auth0-request-id:
+ - 5d9c21c9bb71f2a0
+ ot-tracer-sampled:
+ - 'true'
+ ot-tracer-spanid:
+ - 6591b95e76b97335
+ ot-tracer-traceid:
+ - 625c281a4fb037bb
+ status:
+ code: 200
+ message: OK
+- request:
+ body: null
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate
+ Connection:
+ - keep-alive
+ User-Agent:
+ - python-requests/2.24.0
+ method: GET
+ uri: https://saleor.io/.well-known/jwks.json
+ response:
+ body:
+ string: !!binary |
+ H4sIAAAAAAAAA9xWSa/zuBH8L+/qedBmbXOjdsnaV0tBYJjaJUuyrV2D+e/x+wIkl0GAueZW7GaT
+ jepCkX98tfk+fv3+jz++7o/y6/cv18NJ6uu3r3baf63AB89j/sFjXX5w/0HdoCvrOxcB1+Qk/5KK
+ rEkC9iaP6Bu2RktSOAcdc6RQOn8uuYAW+EN1YVqUc1aawO4Lx2IgWCIHSyisxq32XuAJy3gUWpl5
+ 5EPK7NMIptpxri9DN0Tz991lfdlREh8rdL2tQ51/9YQgZ65SWEcBMVkcSc0qeFnNrL4GPCNMmf4N
+ vfRqSvcomWg6ESSsiXNULef3NLN1IxcPShn93KrZ2/kJDw28rw27eFLz4PydrMsXdNzAZ/ypbxhq
+ 0qZk/WZqaigTWgCBv+40JpmYy0LVUrrqeIZmqfQ9x0XC7TYbZe/4mVQrUPRpm9Z0KiJzt3Oou2WL
+ JNsHlQLyex/016G5juCbKeD6IfeHZuAA7of/Ovvh/3bcWGgnnGkDYQfnI+qC7ZPdyOlnIiLxPcDI
+ Jdw8G3mjrODWyLDL0QH9tS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LxxDbo/g2YMK6EpughSBSXSnFyAXF2tR5D8l2P2+OyFd3mHaL
+ NaXd63gLNXYCwedLziWvuXYyBRJHXly61ZwFF2v37+rK0+2ZcwK4uXOiMxQsiAGFtyYW/XG/yiVa
+ 6Ve+H+D//P4Bihyfd+wLAAA=
+ headers:
+ Access-Control-Allow-Credentials:
+ - 'false'
+ Access-Control-Allow-Origin:
+ - '*'
+ Access-Control-Expose-Headers:
+ - X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset
+ Age:
+ - '0'
+ CF-Cache-Status:
+ - HIT
+ CF-Ray:
+ - 5d9cf7e1cd0acc9b-WAW
+ Cache-Control:
+ - public, max-age=15, stale-while-revalidate=15, stale-if-error=15
+ Connection:
+ - keep-alive
+ Content-Encoding:
+ - gzip
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Mon, 28 Sep 2020 11:01:45 GMT
+ ETag:
+ - W/"bec-GggneSfmYLDK9HQV1PLJX5tHMns"
+ Expect-CT:
+ - max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
+ Server:
+ - cloudflare
+ Set-Cookie:
+ - __cfduid=d7d9d34a9112f1adfaee2389d42359c021601290905; expires=Wed, 28-Oct-20
+ 11:01:45 GMT; path=/; domain=.eu.auth0.com; HttpOnly; SameSite=Lax; Secure
+ - __cf_bm=bd77ff153909899b32e17f8047e48a707309d49d-1601290905-1800-Afdw9ZYuFkE5DAZ0yhjP9GE7MjYUFmW9UaKdUTUXVvcTZbXPveMm4UJk147fLa6ZybPNjdGlc9VswMvHLn01CmM=;
+ path=/; expires=Mon, 28-Sep-20 11:31:45 GMT; domain=.eu.auth0.com; HttpOnly;
+ Secure; SameSite=None
+ Transfer-Encoding:
+ - chunked
+ Vary:
+ - Accept-Encoding, Accept-Encoding
+ X-Auth0-RequestId:
+ - 049d410ac97d6b835b5a
+ X-Cache-Status:
+ - MISS
+ X-Content-Type-Options:
+ - nosniff
+ X-RateLimit-Limit:
+ - '20'
+ X-RateLimit-Remaining:
+ - '19'
+ X-RateLimit-Reset:
+ - '1601282137'
+ alt-svc:
+ - h3-27=":443"; ma=86400, h3-28=":443"; ma=86400, h3-29=":443"; ma=86400
+ cf-request-id:
+ - 0575f9411a0000cc9b6522d200000001
+ ot-baggage-auth0-request-id:
+ - 5d9c21c9bb71f2a0
+ ot-tracer-sampled:
+ - 'true'
+ ot-tracer-spanid:
+ - 6591b95e76b97335
+ ot-tracer-traceid:
+ - 625c281a4fb037bb
+ status:
+ code: 200
+ message: OK
+version: 1
diff --git a/saleor/plugins/openid_connect/tests/cassettes/test_plugin/test_external_obtain_access_tokens_user_which_is_not_more_staff.yaml b/saleor/plugins/openid_connect/tests/cassettes/test_plugin/test_external_obtain_access_tokens_user_which_is_not_more_staff.yaml
new file mode 100644
index 0000000000..b9d864ba0c
--- /dev/null
+++ b/saleor/plugins/openid_connect/tests/cassettes/test_plugin/test_external_obtain_access_tokens_user_which_is_not_more_staff.yaml
@@ -0,0 +1,114 @@
+interactions:
+- request:
+ body: null
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate
+ Connection:
+ - keep-alive
+ User-Agent:
+ - python-requests/2.25.1
+ method: GET
+ uri: https://saleor.io/.well-known/jwks.json
+ response:
+ body:
+ string: !!binary |
+ H4sIAAAAAAAAA9xWSa/zuBH8L+/qedBmbXOjdsnaV0tBYJjaJUuyrV2D+e/x+wIkl0GAueZW7GaT
+ jepCkX98tfk+fv3+jz++7o/y6/cv18NJ6uu3r3baf63AB89j/sFjXX5w/0HdoCvrOxcB1+Qk/5KK
+ rEkC9iaP6Bu2RktSOAcdc6RQOn8uuYAW+EN1YVqUc1aawO4Lx2IgWCIHSyisxq32XuAJy3gUWpl5
+ 5EPK7NMIptpxri9DN0Tz991lfdlREh8rdL2tQ51/9YQgZ65SWEcBMVkcSc0qeFnNrL4GPCNMmf4N
+ vfRqSvcomWg6ESSsiXNULef3NLN1IxcPShn93KrZ2/kJDw28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AyCl3zSyinKkMCOodDvJys8oHS9
+ XGCfjclXmyt8kukp8gIxyTiqtxv/hZXl3R0dHMCWFuCW74KsW4g1ftrIlaKsU29v8hq+n6FsGsEt
+ M7yK8cEyfm4Xwh5jp8+pEmqhwg6YD54zNmKO5+lB4jl26Mw3ZTE2l8MZ5unCzG1BCzuj1+6K6PzY
+ AmswzFlc/ACmSM89F6ncNpJ9qVBLxxDbo/g2YMK6EpughSBSXSnFyAXF2tR5D8l2P2+OyFd3mHaL
+ NaXd63gLNXYCwedLziWvuXYyBRJHXly61ZwFF2v37+rK0+2ZcwK4uXOiMxQsiAGFtyYW/XG/yiVa
+ 6Ve+H+D//P4Bihyfd+wLAAA=
+ headers:
+ Access-Control-Allow-Credentials:
+ - 'false'
+ Access-Control-Allow-Origin:
+ - '*'
+ Access-Control-Expose-Headers:
+ - X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset
+ CF-Cache-Status:
+ - MISS
+ CF-Ray:
+ - 6644e2d6ead31655-WAW
+ Cache-Control:
+ - public, max-age=15, stale-while-revalidate=15, stale-if-error=86400
+ Connection:
+ - keep-alive
+ Content-Encoding:
+ - gzip
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Thu, 24 Jun 2021 09:21:28 GMT
+ ETag:
+ - W/"bec-GggneSfmYLDK9HQV1PLJX5tHMns"
+ Expect-CT:
+ - max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
+ Server:
+ - cloudflare
+ Strict-Transport-Security:
+ - max-age=31536000
+ Transfer-Encoding:
+ - chunked
+ Vary:
+ - Accept-Encoding, Origin, Accept-Encoding
+ X-Auth0-RequestId:
+ - 8a63fae1a6038d443c04
+ X-Content-Type-Options:
+ - nosniff
+ X-RateLimit-Limit:
+ - '20'
+ X-RateLimit-Remaining:
+ - '19'
+ X-RateLimit-Reset:
+ - '1624526489'
+ alt-svc:
+ - h3-27=":443"; ma=86400, h3-28=":443"; ma=86400, h3-29=":443"; ma=86400, h3=":443";
+ ma=86400
+ cf-request-id:
+ - 0adeec1a5000001655253a2000000001
+ ot-baggage-auth0-request-id:
+ - 6644e2d6ead31655
+ ot-tracer-sampled:
+ - 'true'
+ ot-tracer-spanid:
+ - 763f57106a918241
+ ot-tracer-traceid:
+ - 3323a1db3d8c0c3f
+ status:
+ code: 200
+ message: OK
+version: 1
diff --git a/saleor/plugins/openid_connect/tests/cassettes/test_plugin/test_external_obtain_access_tokens_with_saleor_staff.yaml b/saleor/plugins/openid_connect/tests/cassettes/test_plugin/test_external_obtain_access_tokens_with_saleor_staff.yaml
new file mode 100644
index 0000000000..b9d864ba0c
--- /dev/null
+++ b/saleor/plugins/openid_connect/tests/cassettes/test_plugin/test_external_obtain_access_tokens_with_saleor_staff.yaml
@@ -0,0 +1,114 @@
+interactions:
+- request:
+ body: null
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate
+ Connection:
+ - keep-alive
+ User-Agent:
+ - python-requests/2.25.1
+ method: GET
+ uri: https://saleor.io/.well-known/jwks.json
+ response:
+ body:
+ string: !!binary |
+ H4sIAAAAAAAAA9xWSa/zuBH8L+/qedBmbXOjdsnaV0tBYJjaJUuyrV2D+e/x+wIkl0GAueZW7GaT
+ jepCkX98tfk+fv3+jz++7o/y6/cv18NJ6uu3r3baf63AB89j/sFjXX5w/0HdoCvrOxcB1+Qk/5KK
+ rEkC9iaP6Bu2RktSOAcdc6RQOn8uuYAW+EN1YVqUc1aawO4Lx2IgWCIHSyisxq32XuAJy3gUWpl5
+ 5EPK7NMIptpxri9DN0Tz991lfdlREh8rdL2tQ51/9YQgZ65SWEcBMVkcSc0qeFnNrL4GPCNMmf4N
+ vfRqSvcomWg6ESSsiXNULef3NLN1IxcPShn93KrZ2/kJDw28rw27eFLz4PydrMsXdNzAZ/ypbxhq
+ 0qZk/WZqaigTWgCBv+40JpmYy0LVUrrqeIZmqfQ9x0XC7TYbZe/4mVQrUPRpm9Z0KiJzt3Oou2WL
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Eyfm4Xwh5jp8+pEmqhwg6YD54zNmKO5+lB4jl26Mw3ZTE2l8MZ5unCzG1BCzuj1+6K6PzY
+ AmswzFlc/ACmSM89F6ncNpJ9qVBLxxDbo/g2YMK6EpughSBSXSnFyAXF2tR5D8l2P2+OyFd3mHaL
+ NaXd63gLNXYCwedLziWvuXYyBRJHXly61ZwFF2v37+rK0+2ZcwK4uXOiMxQsiAGFtyYW/XG/yiVa
+ 6Ve+H+D//P4Bihyfd+wLAAA=
+ headers:
+ Access-Control-Allow-Credentials:
+ - 'false'
+ Access-Control-Allow-Origin:
+ - '*'
+ Access-Control-Expose-Headers:
+ - X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset
+ CF-Cache-Status:
+ - MISS
+ CF-Ray:
+ - 6644e2d6ead31655-WAW
+ Cache-Control:
+ - public, max-age=15, stale-while-revalidate=15, stale-if-error=86400
+ Connection:
+ - keep-alive
+ Content-Encoding:
+ - gzip
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Thu, 24 Jun 2021 09:21:28 GMT
+ ETag:
+ - W/"bec-GggneSfmYLDK9HQV1PLJX5tHMns"
+ Expect-CT:
+ - max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
+ Server:
+ - cloudflare
+ Strict-Transport-Security:
+ - max-age=31536000
+ Transfer-Encoding:
+ - chunked
+ Vary:
+ - Accept-Encoding, Origin, Accept-Encoding
+ X-Auth0-RequestId:
+ - 8a63fae1a6038d443c04
+ X-Content-Type-Options:
+ - nosniff
+ X-RateLimit-Limit:
+ - '20'
+ X-RateLimit-Remaining:
+ - '19'
+ X-RateLimit-Reset:
+ - '1624526489'
+ alt-svc:
+ - h3-27=":443"; ma=86400, h3-28=":443"; ma=86400, h3-29=":443"; ma=86400, h3=":443";
+ ma=86400
+ cf-request-id:
+ - 0adeec1a5000001655253a2000000001
+ ot-baggage-auth0-request-id:
+ - 6644e2d6ead31655
+ ot-tracer-sampled:
+ - 'true'
+ ot-tracer-spanid:
+ - 763f57106a918241
+ ot-tracer-traceid:
+ - 3323a1db3d8c0c3f
+ status:
+ code: 200
+ message: OK
+version: 1
diff --git a/saleor/plugins/openid_connect/tests/cassettes/test_plugin/test_external_refresh_from_cookie.yaml b/saleor/plugins/openid_connect/tests/cassettes/test_plugin/test_external_refresh_from_cookie.yaml
new file mode 100644
index 0000000000..8a61d950b6
--- /dev/null
+++ b/saleor/plugins/openid_connect/tests/cassettes/test_plugin/test_external_refresh_from_cookie.yaml
@@ -0,0 +1,119 @@
+interactions:
+- request:
+ body: null
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate
+ Connection:
+ - keep-alive
+ User-Agent:
+ - python-requests/2.24.0
+ method: GET
+ uri: https://saleor.io/.well-known/jwks.json
+ response:
+ body:
+ string: !!binary |
+ H4sIAAAAAAAAA9xWSa/zuBH8L+/qedBmbXOjdsnaV0tBYJjaJUuyrV2D+e/x+wIkl0GAueZW7GaT
+ jepCkX98tfk+fv3+jz++7o/y6/cv18NJ6uu3r3baf63AB89j/sFjXX5w/0HdoCvrOxcB1+Qk/5KK
+ rEkC9iaP6Bu2RktSOAcdc6RQOn8uuYAW+EN1YVqUc1aawO4Lx2IgWCIHSyisxq32XuAJy3gUWpl5
+ 5EPK7NMIptpxri9DN0Tz991lfdlREh8rdL2tQ51/9YQgZ65SWEcBMVkcSc0qeFnNrL4GPCNMmf4N
+ vfRqSvcomWg6ESSsiXNULef3NLN1IxcPShn93KrZ2/kJDw28rw27eFLz4PydrMsXdNzAZ/ypbxhq
+ 0qZk/WZqaigTWgCBv+40JpmYy0LVUrrqeIZmqfQ9x0XC7TYbZe/4mVQrUPRpm9Z0KiJzt3Oou2WL
+ JNsHlQLyex/016G5juCbKeD6IfeHZuAA7of/Ovvh/3bcWGgnnGkDYQfnI+qC7ZPdyOlnIiLxPcDI
+ Jdw8G3mjrODWyLDL0QH9tSf9zPXLUFWBP3geFFYJVpUDpaqlI2QSi443VY0Ng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2+OyFd3mHaL
+ NaXd63gLNXYCwedLziWvuXYyBRJHXly61ZwFF2v37+rK0+2ZcwK4uXOiMxQsiAGFtyYW/XG/yiVa
+ 6Ve+H+D//P4Bihyfd+wLAAA=
+ headers:
+ Access-Control-Allow-Credentials:
+ - 'false'
+ Access-Control-Allow-Origin:
+ - '*'
+ Access-Control-Expose-Headers:
+ - X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset
+ CF-Cache-Status:
+ - REVALIDATED
+ CF-Ray:
+ - 5d7b40db9b25163c-WAW
+ Cache-Control:
+ - public, max-age=15, stale-while-revalidate=15, stale-if-error=15
+ Connection:
+ - keep-alive
+ Content-Encoding:
+ - gzip
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Thu, 24 Sep 2020 08:49:39 GMT
+ ETag:
+ - W/"bec-GggneSfmYLDK9HQV1PLJX5tHMns"
+ Expect-CT:
+ - max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
+ Server:
+ - cloudflare
+ Set-Cookie:
+ - __cfduid=d60ec38f73268bf8cf0f617ef85bab7251600937379; expires=Sat, 24-Oct-20
+ 08:49:39 GMT; path=/; domain=.eu.auth0.com; HttpOnly; SameSite=Lax; Secure
+ - __cf_bm=447ecca538216c23f5b734091ea8087366565673-1600937379-1800-AdListCBapoCb63mU60nViDcX9TiFOBgVtD10Lgi4sRZlI3q6YQcjJzLv6SMDtfO5l0JbaD8ywlovhXBPyCDydA=;
+ path=/; expires=Thu, 24-Sep-20 09:19:39 GMT; domain=.eu.auth0.com; HttpOnly;
+ Secure; SameSite=None
+ Transfer-Encoding:
+ - chunked
+ Vary:
+ - Accept-Encoding, Accept-Encoding
+ X-Auth0-RequestId:
+ - 3a176e8943b587bcb15f
+ X-Cache-Status:
+ - MISS
+ X-Content-Type-Options:
+ - nosniff
+ X-RateLimit-Limit:
+ - '20'
+ X-RateLimit-Remaining:
+ - '19'
+ X-RateLimit-Reset:
+ - '1600761001'
+ alt-svc:
+ - h3-27=":443"; ma=86400, h3-28=":443"; ma=86400, h3-29=":443"; ma=86400
+ cf-request-id:
+ - 0560e6dd3e0000163c5c107200000001
+ ot-baggage-auth0-request-id:
+ - 5d6a6ebe58d71642
+ ot-tracer-sampled:
+ - 'true'
+ ot-tracer-spanid:
+ - 3d4cb6b714c4de86
+ ot-tracer-traceid:
+ - 0721eb9f5be6ad58
+ status:
+ code: 200
+ message: OK
+version: 1
diff --git a/saleor/plugins/openid_connect/tests/cassettes/test_plugin/test_external_refresh_from_input.yaml b/saleor/plugins/openid_connect/tests/cassettes/test_plugin/test_external_refresh_from_input.yaml
new file mode 100644
index 0000000000..1653b30a9d
--- /dev/null
+++ b/saleor/plugins/openid_connect/tests/cassettes/test_plugin/test_external_refresh_from_input.yaml
@@ -0,0 +1,119 @@
+interactions:
+- request:
+ body: null
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate
+ Connection:
+ - keep-alive
+ User-Agent:
+ - python-requests/2.24.0
+ method: GET
+ uri: https://saleor.io/.well-known/jwks.json
+ response:
+ body:
+ string: !!binary |
+ H4sIAAAAAAAAA9xWSa/zuBH8L+/qedBmbXOjdsnaV0tBYJjaJUuyrV2D+e/x+wIkl0GAueZW7GaT
+ jepCkX98tfk+fv3+jz++7o/y6/cv18NJ6uu3r3baf63AB89j/sFjXX5w/0HdoCvrOxcB1+Qk/5KK
+ rEkC9iaP6Bu2RktSOAcdc6RQOn8uuYAW+EN1YVqUc1aawO4Lx2IgWCIHSyisxq32XuAJy3gUWpl5
+ 5EPK7NMIptpxri9DN0Tz991lfdlREh8rdL2tQ51/9YQgZ65SWEcBMVkcSc0qeFnNrL4GPCNMmf4N
+ vfRqSvcomWg6ESSsiXNULef3NLN1IxcPShn93KrZ2/kJDw28rw27eFLz4PydrMsXdNzAZ/ypbxhq
+ 0qZk/WZqaigTWgCBv+40JpmYy0LVUrrqeIZmqfQ9x0XC7TYbZe/4mVQrUPRpm9Z0KiJzt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+ M7yK8cEyfm4Xwh5jp8+pEmqhwg6YD54zNmKO5+lB4jl26Mw3ZTE2l8MZ5unCzG1BCzuj1+6K6PzY
+ AmswzFlc/ACmSM89F6ncNpJ9qVBLxxDbo/g2YMK6EpughSBSXSnFyAXF2tR5D8l2P2+OyFd3mHaL
+ NaXd63gLNXYCwedLziWvuXYyBRJHXly61ZwFF2v37+rK0+2ZcwK4uXOiMxQsiAGFtyYW/XG/yiVa
+ 6Ve+H+D//P4Bihyfd+wLAAA=
+ headers:
+ Access-Control-Allow-Credentials:
+ - 'false'
+ Access-Control-Allow-Origin:
+ - '*'
+ Access-Control-Expose-Headers:
+ - X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset
+ CF-Cache-Status:
+ - REVALIDATED
+ CF-Ray:
+ - 5d9cf4f8b8d7ffcc-WAW
+ Cache-Control:
+ - public, max-age=15, stale-while-revalidate=15, stale-if-error=15
+ Connection:
+ - keep-alive
+ Content-Encoding:
+ - gzip
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Mon, 28 Sep 2020 10:59:46 GMT
+ ETag:
+ - W/"bec-GggneSfmYLDK9HQV1PLJX5tHMns"
+ Expect-CT:
+ - max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
+ Server:
+ - cloudflare
+ Set-Cookie:
+ - __cfduid=d24e7cfe5ae0506dcd70b1b6f3c32cfb31601290786; expires=Wed, 28-Oct-20
+ 10:59:46 GMT; path=/; domain=.eu.auth0.com; HttpOnly; SameSite=Lax; Secure
+ - __cf_bm=ef2828d719d7b680fa33baa4e6f73589c32815df-1601290786-1800-AdHxf24eqiXLV7x7a/y3doXnQUoTs3ltZhGC3hYfxj63zFS85kC/heO+Y2yE3HPbijI9o5CdK3Ufi5NyEoIRfqo=;
+ path=/; expires=Mon, 28-Sep-20 11:29:46 GMT; domain=.eu.auth0.com; HttpOnly;
+ Secure; SameSite=None
+ Transfer-Encoding:
+ - chunked
+ Vary:
+ - Accept-Encoding, Accept-Encoding
+ X-Auth0-RequestId:
+ - 049d410ac97d6b835b5a
+ X-Cache-Status:
+ - MISS
+ X-Content-Type-Options:
+ - nosniff
+ X-RateLimit-Limit:
+ - '20'
+ X-RateLimit-Remaining:
+ - '19'
+ X-RateLimit-Reset:
+ - '1601282137'
+ alt-svc:
+ - h3-27=":443"; ma=86400, h3-28=":443"; ma=86400, h3-29=":443"; ma=86400
+ cf-request-id:
+ - 0575f76f730000ffccbb2b1200000001
+ ot-baggage-auth0-request-id:
+ - 5d9c21c9bb71f2a0
+ ot-tracer-sampled:
+ - 'true'
+ ot-tracer-spanid:
+ - 6591b95e76b97335
+ ot-tracer-traceid:
+ - 625c281a4fb037bb
+ status:
+ code: 200
+ message: OK
+version: 1
diff --git a/saleor/plugins/openid_connect/tests/cassettes/test_plugin/test_external_refresh_raises_error.yaml b/saleor/plugins/openid_connect/tests/cassettes/test_plugin/test_external_refresh_raises_error.yaml
new file mode 100644
index 0000000000..ad97d406b7
--- /dev/null
+++ b/saleor/plugins/openid_connect/tests/cassettes/test_plugin/test_external_refresh_raises_error.yaml
@@ -0,0 +1,84 @@
+interactions:
+- request:
+ body: grant_type=refresh_token&refresh_token=refresh&scope=openid+profile+email+offline_access
+ headers:
+ Accept:
+ - application/json
+ Accept-Encoding:
+ - gzip, deflate
+ Authorization:
+ - Basic Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '88'
+ Content-Type:
+ - application/x-www-form-urlencoded;charset=UTF-8
+ User-Agent:
+ - python-requests/2.24.0
+ method: POST
+ uri: https://saleor.io/oauth/token
+ response:
+ body:
+ string: '{"error":"access_denied","error_description":"Unauthorized"}'
+ headers:
+ CF-Cache-Status:
+ - DYNAMIC
+ CF-Ray:
+ - 5d7b53640c8cf2a0-WAW
+ Cache-Control:
+ - private, no-store, no-cache, must-revalidate, post-check=0, pre-check=0, no-transform
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '60'
+ Content-Type:
+ - application/json
+ Date:
+ - Thu, 24 Sep 2020 09:02:18 GMT
+ Expect-CT:
+ - max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
+ Server:
+ - cloudflare
+ Set-Cookie:
+ - __cfduid=dda572364d1d8477fb4d0b180ed6a27231600938138; expires=Sat, 24-Oct-20
+ 09:02:18 GMT; path=/; domain=.eu.auth0.com; HttpOnly; SameSite=Lax; Secure
+ - did=s%3Av0%3Aa5eaa130-fe44-11ea-88fd-69241534caf5.UhSNGlnYpEgd9Z%2BFw81Pm%2BMSa%2BCpFh1inxuK93XDc7k;
+ Max-Age=31557600; Path=/; Expires=Fri, 24 Sep 2021 15:02:18 GMT; HttpOnly;
+ Secure; SameSite=None
+ - did_compat=s%3Av0%3Aa5eaa130-fe44-11ea-88fd-69241534caf5.UhSNGlnYpEgd9Z%2BFw81Pm%2BMSa%2BCpFh1inxuK93XDc7k;
+ Max-Age=31557600; Path=/; Expires=Fri, 24 Sep 2021 15:02:18 GMT; HttpOnly;
+ Secure
+ - __cf_bm=1d7ae185306bf91d9341a5428e946fa6f7791a4b-1600938138-1800-Ae0o0+RxpBzmlWEI79FgL7ObfCZSXDqYPMCKJwffgaK2swmQcWyHb/qtREJRU0aFAZUXR23/3ykt1NTVNisGmps=;
+ path=/; expires=Thu, 24-Sep-20 09:32:18 GMT; domain=.eu.auth0.com; HttpOnly;
+ Secure; SameSite=None
+ Strict-Transport-Security:
+ - max-age=31536000
+ Vary:
+ - Accept-Encoding
+ X-Auth0-RequestId:
+ - b1042397b9c8d5c739bd
+ X-Content-Type-Options:
+ - nosniff
+ X-RateLimit-Limit:
+ - '30'
+ X-RateLimit-Remaining:
+ - '29'
+ X-RateLimit-Reset:
+ - '1600938139'
+ alt-svc:
+ - h3-27=":443"; ma=86400, h3-28=":443"; ma=86400, h3-29=":443"; ma=86400
+ cf-request-id:
+ - 0560f272880000f2a0d421c200000001
+ ot-baggage-auth0-request-id:
+ - 5d7b53640c8cf2a0
+ ot-tracer-sampled:
+ - 'true'
+ ot-tracer-spanid:
+ - 48c2f8fa6f549fb7
+ ot-tracer-traceid:
+ - 0eb00c3945b70d62
+ status:
+ code: 401
+ message: Unauthorized
+version: 1
diff --git a/saleor/plugins/openid_connect/tests/cassettes/test_plugin/test_external_refresh_raises_error_when_token_is_invalid.yaml b/saleor/plugins/openid_connect/tests/cassettes/test_plugin/test_external_refresh_raises_error_when_token_is_invalid.yaml
new file mode 100644
index 0000000000..841a82406e
--- /dev/null
+++ b/saleor/plugins/openid_connect/tests/cassettes/test_plugin/test_external_refresh_raises_error_when_token_is_invalid.yaml
@@ -0,0 +1,121 @@
+interactions:
+- request:
+ body: null
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate
+ Connection:
+ - keep-alive
+ User-Agent:
+ - python-requests/2.24.0
+ method: GET
+ uri: https://saleor.io/.well-known/jwks.json
+ response:
+ body:
+ string: !!binary |
+ H4sIAAAAAAAAA9xWSa/zuBH8L+/qedBmbXOjdsnaV0tBYJjaJUuyrV2D+e/x+wIkl0GAueZW7GaT
+ jepCkX98tfk+fv3+jz++7o/y6/cv18NJ6uu3r3baf63AB89j/sFjXX5w/0HdoCvrOxcB1+Qk/5KK
+ rEkC9iaP6Bu2RktSOAcdc6RQOn8uuYAW+EN1YVqUc1aawO4Lx2IgWCIHSyisxq32XuAJy3gUWpl5
+ 5EPK7NMIptpxri9DN0Tz991lfdlREh8rdL2tQ51/9YQgZ65SWEcBMVkcSc0qeFnNrL4GPCNMmf4N
+ vfRqSvcomWg6ESSsiXNULef3NLN1IxcPShn93KrZ2/kJDw28rw27eFLz4PydrMsXdNzAZ/ypbxhq
+ 0qZk/WZqaigTWgCBv+40JpmYy0LVUrrqeIZmqfQ9x0XC7TYbZe/4mVQrUPRpm9Z0KiJzt3Oou2WL
+ JNsHlQLyex/016G5juCbKeD6IfeHZuAA7of/Ovvh/3bcWGgnnGkDYQfnI+qC7ZPdyOl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K6PzY
+ AmswzFlc/ACmSM89F6ncNpJ9qVBLxxDbo/g2YMK6EpughSBSXSnFyAXF2tR5D8l2P2+OyFd3mHaL
+ NaXd63gLNXYCwedLziWvuXYyBRJHXly61ZwFF2v37+rK0+2ZcwK4uXOiMxQsiAGFtyYW/XG/yiVa
+ 6Ve+H+D//P4Bihyfd+wLAAA=
+ headers:
+ Access-Control-Allow-Credentials:
+ - 'false'
+ Access-Control-Allow-Origin:
+ - '*'
+ Access-Control-Expose-Headers:
+ - X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset
+ Age:
+ - '0'
+ CF-Cache-Status:
+ - HIT
+ CF-Ray:
+ - 5d9cf4fa2ee2162a-WAW
+ Cache-Control:
+ - public, max-age=15, stale-while-revalidate=15, stale-if-error=15
+ Connection:
+ - keep-alive
+ Content-Encoding:
+ - gzip
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Mon, 28 Sep 2020 10:59:46 GMT
+ ETag:
+ - W/"bec-GggneSfmYLDK9HQV1PLJX5tHMns"
+ Expect-CT:
+ - max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
+ Server:
+ - cloudflare
+ Set-Cookie:
+ - __cfduid=df5979bac483bfce8c862f4e6efbc4d4c1601290786; expires=Wed, 28-Oct-20
+ 10:59:46 GMT; path=/; domain=.eu.auth0.com; HttpOnly; SameSite=Lax; Secure
+ - __cf_bm=bc0d749456bd6968f02e44f6885fe8d945be701b-1601290786-1800-AVlS8hq9RnG30OE9Xa256N7w5IrKMnSBORGE116O6TpB2I/4Y21qdo0G3DJBj8VYSjEBK3ixHu5BnuLMdqxaJqE=;
+ path=/; expires=Mon, 28-Sep-20 11:29:46 GMT; domain=.eu.auth0.com; HttpOnly;
+ Secure; SameSite=None
+ Transfer-Encoding:
+ - chunked
+ Vary:
+ - Accept-Encoding, Accept-Encoding
+ X-Auth0-RequestId:
+ - 049d410ac97d6b835b5a
+ X-Cache-Status:
+ - MISS
+ X-Content-Type-Options:
+ - nosniff
+ X-RateLimit-Limit:
+ - '20'
+ X-RateLimit-Remaining:
+ - '19'
+ X-RateLimit-Reset:
+ - '1601282137'
+ alt-svc:
+ - h3-27=":443"; ma=86400, h3-28=":443"; ma=86400, h3-29=":443"; ma=86400
+ cf-request-id:
+ - 0575f770560000162af9be5200000001
+ ot-baggage-auth0-request-id:
+ - 5d9c21c9bb71f2a0
+ ot-tracer-sampled:
+ - 'true'
+ ot-tracer-spanid:
+ - 6591b95e76b97335
+ ot-tracer-traceid:
+ - 625c281a4fb037bb
+ status:
+ code: 200
+ message: OK
+version: 1
diff --git a/saleor/plugins/openid_connect/tests/cassettes/test_utils/test_fetch_jwks.yaml b/saleor/plugins/openid_connect/tests/cassettes/test_utils/test_fetch_jwks.yaml
new file mode 100644
index 0000000000..fec8cbb5b8
--- /dev/null
+++ b/saleor/plugins/openid_connect/tests/cassettes/test_utils/test_fetch_jwks.yaml
@@ -0,0 +1,119 @@
+interactions:
+- request:
+ body: null
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate
+ Connection:
+ - keep-alive
+ User-Agent:
+ - python-requests/2.24.0
+ method: GET
+ uri: https://saleor.io/.well-known/jwks.json
+ response:
+ body:
+ string: !!binary |
+ H4sIAAAAAAAAA9xWSa/zuBH8L+/qedBmbXOjdsnaV0tBYJjaJUuyrV2D+e/x+wIkl0GAueZW7GaT
+ jepCkX98tfk+fv3+jz++7o/y6/cv18NJ6uu3r3baf63AB89j/sFjXX5w/0HdoCvrOxcB1+Qk/5KK
+ rEkC9iaP6Bu2RktSOAcdc6RQOn8uuYAW+EN1YVqUc1aawO4Lx2IgWCIHSyisxq32XuAJy3gUWpl5
+ 5EPK7NMIptpxri9DN0Tz991lfdlREh8rdL2tQ51/9YQgZ65SWEcBMVkcSc0qeFnNrL4GPCNMmf4N
+ vfRqSvcomWg6ESSsiXNULef3NLN1IxcPShn93KrZ2/kJDw28rw27eFLz4PydrMsXdNzAZ/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S9
+ XGCfjclXmyt8kukp8gIxyTiqtxv/hZXl3R0dHMCWFuCW74KsW4g1ftrIlaKsU29v8hq+n6FsGsEt
+ M7yK8cEyfm4Xwh5jp8+pEmqhwg6YD54zNmKO5+lB4jl26Mw3ZTE2l8MZ5unCzG1BCzuj1+6K6PzY
+ AmswzFlc/ACmSM89F6ncNpJ9qVBLxxDbo/g2YMK6EpughSBSXSnFyAXF2tR5D8l2P2+OyFd3mHaL
+ NaXd63gLNXYCwedLziWvuXYyBRJHXly61ZwFF2v37+rK0+2ZcwK4uXOiMxQsiAGFtyYW/XG/yiVa
+ 6Ve+H+D//P4Bihyfd+wLAAA=
+ headers:
+ Access-Control-Allow-Credentials:
+ - 'false'
+ Access-Control-Allow-Origin:
+ - '*'
+ Access-Control-Expose-Headers:
+ - X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset
+ CF-Cache-Status:
+ - REVALIDATED
+ CF-Ray:
+ - 5d6c8cb87e9acca7-WAW
+ Cache-Control:
+ - public, max-age=15, stale-while-revalidate=15, stale-if-error=15
+ Connection:
+ - keep-alive
+ Content-Encoding:
+ - gzip
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Tue, 22 Sep 2020 14:00:00 GMT
+ ETag:
+ - W/"bec-GggneSfmYLDK9HQV1PLJX5tHMns"
+ Expect-CT:
+ - max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
+ Server:
+ - cloudflare
+ Set-Cookie:
+ - __cfduid=d410ec64832db30beb7a25c832d90c5c61600783200; expires=Thu, 22-Oct-20
+ 14:00:00 GMT; path=/; domain=.eu.auth0.com; HttpOnly; SameSite=Lax; Secure
+ - __cf_bm=a87bdf4f55f84e739200887a1fd183917e9ddf73-1600783200-1800-AalpsLcjHkRfHu6I0QvhmDbtrc0nyXGwbvPKEMXuyZH4uOdDG+vlZ1rR3h1jontrvEEgzyY8f2Ct0PQcHd/K7pk=;
+ path=/; expires=Tue, 22-Sep-20 14:30:00 GMT; domain=.eu.auth0.com; HttpOnly;
+ Secure; SameSite=None
+ Transfer-Encoding:
+ - chunked
+ Vary:
+ - Accept-Encoding, Accept-Encoding
+ X-Auth0-RequestId:
+ - 3a176e8943b587bcb15f
+ X-Cache-Status:
+ - MISS
+ X-Content-Type-Options:
+ - nosniff
+ X-RateLimit-Limit:
+ - '20'
+ X-RateLimit-Remaining:
+ - '19'
+ X-RateLimit-Reset:
+ - '1600761001'
+ alt-svc:
+ - h3-27=":443"; ma=86400, h3-28=":443"; ma=86400, h3-29=":443"; ma=86400
+ cf-request-id:
+ - 0557b647460000cca7b1174200000001
+ ot-baggage-auth0-request-id:
+ - 5d6a6ebe58d71642
+ ot-tracer-sampled:
+ - 'true'
+ ot-tracer-spanid:
+ - 3d4cb6b714c4de86
+ ot-tracer-traceid:
+ - 0721eb9f5be6ad58
+ status:
+ code: 200
+ message: OK
+version: 1
diff --git a/saleor/plugins/openid_connect/tests/conftest.py b/saleor/plugins/openid_connect/tests/conftest.py
new file mode 100644
index 0000000000..9244959f77
--- /dev/null
+++ b/saleor/plugins/openid_connect/tests/conftest.py
@@ -0,0 +1,168 @@
+import jwt
+import pytest
+
+from ...manager import get_plugins_manager
+from ..plugin import OpenIDConnectPlugin
+
+
+def plugin_configuration():
+ def fun(
+ client_id=None,
+ client_secret=None,
+ enable_refresh_token=True,
+ oauth_authorization_url=None,
+ oauth_token_url=None,
+ json_web_key_set_url=None,
+ oauth_logout_url=None,
+ user_info_url=None,
+ use_oauth_scope_permissions=False,
+ audience=None,
+ ):
+ return [
+ {"name": "client_id", "value": client_id},
+ {"name": "client_secret", "value": client_secret},
+ {"name": "enable_refresh_token", "value": enable_refresh_token},
+ {"name": "oauth_authorization_url", "value": oauth_authorization_url},
+ {"name": "oauth_token_url", "value": oauth_token_url},
+ {"name": "json_web_key_set_url", "value": json_web_key_set_url},
+ {"name": "oauth_logout_url", "value": oauth_logout_url},
+ {"name": "user_info_url", "value": user_info_url},
+ {
+ "name": "use_oauth_scope_permissions",
+ "value": use_oauth_scope_permissions,
+ },
+ {"name": "audience", "value": audience},
+ ]
+
+ return fun
+
+
+def openid_plugin(settings, plugin_configuration):
+ def fun(
+ active=True,
+ client_id="client_id",
+ client_secret="client_secret",
+ enable_refresh_token=True,
+ oauth_authorization_url="https://saleor.io/oauth/authorize",
+ oauth_token_url="https://saleor.io/oauth/token",
+ json_web_key_set_url="https://saleor.io/.well-known/jwks.json",
+ oauth_logout_url="",
+ use_oauth_scope_permissions=False,
+ user_info_url="https://saleor.io/userinfo",
+ audience="perms",
+ ):
+ settings.PLUGINS = ["saleor.plugins.openid_connect.plugin.OpenIDConnectPlugin"]
+ manager = get_plugins_manager()
+ manager.save_plugin_configuration(
+ OpenIDConnectPlugin.PLUGIN_ID,
+ None,
+ {
+ "active": active,
+ "configuration": plugin_configuration(
+ client_id=client_id,
+ client_secret=client_secret,
+ enable_refresh_token=enable_refresh_token,
+ oauth_authorization_url=oauth_authorization_url,
+ oauth_token_url=oauth_token_url,
+ json_web_key_set_url=json_web_key_set_url,
+ oauth_logout_url=oauth_logout_url,
+ use_oauth_scope_permissions=use_oauth_scope_permissions,
+ user_info_url=user_info_url,
+ audience=audience,
+ ),
+ },
+ )
+ manager = get_plugins_manager()
+ return manager.all_plugins[0]
+
+ return fun
+
+
+def decoded_access_token():
+ return {
+ "iss": "https://saleor-test.eu.auth0.com/",
+ "sub": "google-oauth2|114622651317794521039",
+ "aud": ["perms", "https://saleor.io/userinfo"],
+ "iat": 1615374231,
+ "exp": 1615460631,
+ "azp": "mnrVS8QkVOjtvC2zeapSkLLkwowr37Lt",
+ "scope": (
+ "openid profile email saleor:manage_apps saleor:manage_orders "
+ "saleor:manage_products saleor:staff"
+ ),
+ }
+
+
+def user_info_response():
+ return {
+ "sub": "google-oauth2|114622651317794521011",
+ "given_name": "John",
+ "family_name": "Doe",
+ "nickname": "doe",
+ "name": "John Doe",
+ "picture": "https://lh3.googleusercontent.com/a-/123",
+ "locale": "pl",
+ "updated_at": "2021-03-08T12:40:53.894Z",
+ "email": "[email protected]",
+ "email_verified": True,
+ }
+
+
+def id_payload():
+ return {
+ "given_name": "Saleor",
+ "family_name": "Admin",
+ "nickname": "saloer",
+ "name": "Saleor Admin",
+ "picture": "",
+ "locale": "pl",
+ "updated_at": "2020-09-22T08:50:50.110Z",
+ "email": "[email protected]",
+ "email_verified": True,
+ "iss": "https://saleor.io/",
+ "sub": "google-oauth2|",
+ "aud": "",
+ "iat": 1600764712,
+ "exp": 1600800712,
+ }
+
+
+def id_token(id_payload):
+ private_key = """-----BEGIN RSA PRIVATE KEY-----
+MIIEogIBAAKCAQEAnzyis1ZjfNB0bBgKFMSvvkTtwlvBsaJq7S5wA+kzeVOVpVWw
+kWdVha4s38XM/pa/yr47av7+z3VTmvDRyAHcaT92whREFpLv9cj5lTeJSibyr/Mr
+m/YtjCZVWgaOYIhwrXwKLqPr/11inWsAkfIytvHWTxZYEcXLgAXFuUuaS3uF9gEi
+NQwzGTU1v0FqkqTBr4B8nW3HCN47XUu0t8Y0e+lf4s4OxQawWD79J9/5d3Ry0vbV
+3Am1FtGJiJvOwRsIfVChDpYStTcHTCMqtvWbV6L11BWkpzGXSW4Hv43qa+GSYOD2
+QU68Mb59oSk2OB+BtOLpJofmbGEGgvmwyCI9MwIDAQABAoIBACiARq2wkltjtcjs
+kFvZ7w1JAORHbEufEO1Eu27zOIlqbgyAcAl7q+/1bip4Z/x1IVES84/yTaM8p0go
+amMhvgry/mS8vNi1BN2SAZEnb/7xSxbflb70bX9RHLJqKnp5GZe2jexw+wyXlwaM
++bclUCrh9e1ltH7IvUrRrQnFJfh+is1fRon9Co9Li0GwoN0x0byrrngU8Ak3Y6D9
+D8GjQA4Elm94ST3izJv8iCOLSDBmzsPsXfcCUZfmTfZ5DbUDMbMxRnSo3nQeoKGC
+0Lj9FkWcfmLcpGlSXTO+Ww1L7EGq+PT3NtRae1FZPwjddQ1/4V905kyQFLamAA5Y
+lSpE2wkCgYEAy1OPLQcZt4NQnQzPz2SBJqQN2P5u3vXl+zNVKP8w4eBv0vWuJJF+
+hkGNnSxXQrTkvDOIUddSKOzHHgSg4nY6K02ecyT0PPm/UZvtRpWrnBjcEVtHEJNp
+bU9pLD5iZ0J9sbzPU/LxPmuAP2Bs8JmTn6aFRspFrP7W0s1Nmk2jsm0CgYEAyH0X
++jpoqxj4efZfkUrg5GbSEhf+dZglf0tTOA5bVg8IYwtmNk/pniLG/zI7c+GlTc9B
+BwfMr59EzBq/eFMI7+LgXaVUsM/sS4Ry+yeK6SJx/otIMWtDfqxsLD8CPMCRvecC
+2Pip4uSgrl0MOebl9XKp57GoaUWRWRHqwV4Y6h8CgYAZhI4mh4qZtnhKjY4TKDjx
+QYufXSdLAi9v3FxmvchDwOgn4L+PRVdMwDNms2bsL0m5uPn104EzM6w1vzz1zwKz
+5pTpPI0OjgWN13Tq8+PKvm/4Ga2MjgOgPWQkslulO/oMcXbPwWC3hcRdr9tcQtn9
+Imf9n2spL/6EDFId+Hp/7QKBgAqlWdiXsWckdE1Fn91/NGHsc8syKvjjk1onDcw0
+NvVi5vcba9oGdElJX3e9mxqUKMrw7msJJv1MX8LWyMQC5L6YNYHDfbPF1q5L4i8j
+8mRex97UVokJQRRA452V2vCO6S5ETgpnad36de3MUxHgCOX3qL382Qx9/THVmbma
+3YfRAoGAUxL/Eu5yvMK8SAt/dJK6FedngcM3JEFNplmtLYVLWhkIlNRGDwkg3I5K
+y18Ae9n7dHVueyslrb6weq7dTkYDi3iOYRW8HRkIQh06wEdbxt0shTzAJvvCQfrB
+jg/3747WSsf/zBTcHihTRBdAv6OmdhV4/dD5YBfLAkLrd+mX7iE=
+-----END RSA PRIVATE KEY-----"""
+ return jwt.encode(
+ id_payload,
+ private_key,
+ "RS256", # type: ignore
+ )
diff --git a/saleor/plugins/openid_connect/tests/test_plugin.py b/saleor/plugins/openid_connect/tests/test_plugin.py
new file mode 100644
index 0000000000..301d684b83
--- /dev/null
+++ b/saleor/plugins/openid_connect/tests/test_plugin.py
@@ -0,0 +1,1462 @@
+from unittest.mock import MagicMock, Mock
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from authlib.jose.errors import JoseError
+from django.core import signing
+from django.core.exceptions import ValidationError
+from django.middleware.csrf import _get_new_csrf_token
+from freezegun import freeze_time
+
+from ....core.jwt import (
+ JWT_ACCESS_TYPE,
+ JWT_REFRESH_TOKEN_COOKIE_NAME,
+ PERMISSIONS_FIELD,
+ jwt_decode,
+ jwt_encode,
+ jwt_user_payload,
+)
+from ...base_plugin import ExternalAccessTokens
+from ...models import PluginConfiguration
+from ..utils import (
+ create_jwt_refresh_token,
+ create_jwt_token,
+ create_tokens_from_oauth_payload,
+ get_or_create_user_from_payload,
+ get_parsed_id_token,
+)
+
+
+def test_get_oauth_session_adds_refresh_scope_when_enabled(openid_plugin):
+ plugin = openid_plugin(enable_refresh_token=True)
+ session = plugin._get_oauth_session()
+ assert "offline_access" in session.scope
+
+
+def test_get_oauth_session_dont_add_refresh_scope_when_disabled(openid_plugin):
+ plugin = openid_plugin(enable_refresh_token=False)
+ session = plugin._get_oauth_session()
+ assert "offline_access" not in session.scope
+
+
+def test_external_authentication_url_returns_redirect_url(openid_plugin, settings, rf):
+ settings.ALLOWED_CLIENT_HOSTS = ["*"]
+ authorize_path = "/authorize"
+ domain = "saleor.io"
+ authorize_url = f"https://{domain}{authorize_path}"
+ client_id = "test_client"
+ plugin = openid_plugin(oauth_authorization_url=authorize_url, client_id=client_id)
+
+ redirect_uri = "http://localhost:3000/oauth-callback/"
+ input = {"redirectUri": redirect_uri}
+ response = plugin.external_authentication_url(input, rf.request(), None)
+ assert isinstance(response, dict)
+ auth_url = response.get("authorizationUrl")
+ parsed_url = urlparse(auth_url)
+ parsed_qs = parse_qs(parsed_url.query)
+ state = signing.loads(parsed_qs["state"][0])
+ assert parsed_url.netloc == domain
+ assert parsed_url.path == authorize_path
+ assert parsed_qs["redirect_uri"][0] == redirect_uri
+ assert parsed_qs["client_id"][0] == client_id
+ assert state["redirectUri"] == redirect_uri
+
+
+def test_external_authentication_plugin_disabled(openid_plugin, rf):
+ plugin = openid_plugin(active=False)
+ input = {"redirectUrl": "http://localhost:3000/authorization/"}
+ previous_value = "previous"
+ response = plugin.external_authentication_url(input, rf.request(), previous_value)
+ assert response == previous_value
+
+
+def test_external_authentication_raises_error_when_missing_redirect(openid_plugin, rf):
+ client_id = "test_client"
+ plugin = openid_plugin(client_id=client_id)
+ input = {}
+ with pytest.raises(ValidationError):
+ plugin.external_authentication_url(input, rf.request(), None)
+
+
+def test_external_authentication_raises_error_when_redirect_is_wrong(openid_plugin, rf):
+ client_id = "test_client"
+ plugin = openid_plugin(client_id=client_id)
+ input = {"redirectUrl": "localhost:3000/authorization/"}
+ with pytest.raises(ValidationError):
+ plugin.external_authentication_url(input, rf.request(), None)
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_external_refresh_from_cookie(
+ openid_plugin, admin_user, monkeypatch, rf, id_token, id_payload
+):
+ mocked_jwt_validator = MagicMock()
+ mocked_jwt_validator.__getitem__.side_effect = id_payload.__getitem__
+ mocked_jwt_validator.get.side_effect = id_payload.get
+
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.jwt.decode",
+ Mock(return_value=mocked_jwt_validator),
+ )
+ oauth_payload = {
+ "access_token": "FeHkE_QbuU3cYy1a1eQUrCE5jRcUnBK3",
+ "refresh_token": "new_refresh",
+ "id_token": id_token,
+ "scope": "openid profile email offline_access",
+ "expires_in": 86400,
+ "token_type": "Bearer",
+ "expires_at": 1600851112,
+ }
+ mocked_refresh_token = Mock(return_value=oauth_payload)
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.OAuth2Session.refresh_token",
+ mocked_refresh_token,
+ )
+
+ oauth_refresh_token = "refresh"
+ plugin = openid_plugin()
+ csrf_token = _get_new_csrf_token()
+ saleor_refresh_token = create_jwt_refresh_token(
+ admin_user, oauth_refresh_token, csrf_token, plugin.PLUGIN_ID
+ )
+ request = rf.request()
+ request.COOKIES[JWT_REFRESH_TOKEN_COOKIE_NAME] = saleor_refresh_token
+
+ data = {"csrfToken": csrf_token}
+ response = plugin.external_refresh(data, request, None)
+
+ decoded_token = jwt_decode(response.token)
+ assert decoded_token["exp"] == id_payload["exp"]
+ assert decoded_token["oauth_access_key"] == oauth_payload["access_token"]
+
+ decoded_refresh_token = jwt_decode(response.refresh_token)
+ assert decoded_refresh_token["oauth_refresh_token"] == "new_refresh"
+ assert decoded_refresh_token["csrf_token"] == response.csrf_token
+ mocked_refresh_token.assert_called_once_with(
+ "https://saleor.io/oauth/token",
+ refresh_token=oauth_refresh_token,
+ )
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_external_refresh_from_input(
+ openid_plugin, admin_user, monkeypatch, rf, id_token, id_payload
+):
+ mocked_jwt_validator = MagicMock()
+ mocked_jwt_validator.__getitem__.side_effect = id_payload.__getitem__
+ mocked_jwt_validator.get.side_effect = id_payload.get
+
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.jwt.decode",
+ Mock(return_value=mocked_jwt_validator),
+ )
+ oauth_payload = {
+ "access_token": "FeHkE_QbuU3cYy1a1eQUrCE5jRcUnBK3",
+ "refresh_token": "new_refresh",
+ "id_token": id_token,
+ "scope": "openid profile email offline_access",
+ "expires_in": 86400,
+ "token_type": "Bearer",
+ "expires_at": 1600851112,
+ }
+ mocked_refresh_token = Mock(return_value=oauth_payload)
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.OAuth2Session.refresh_token",
+ mocked_refresh_token,
+ )
+
+ oauth_refresh_token = "refresh"
+ plugin = openid_plugin()
+ csrf_token = _get_new_csrf_token()
+ saleor_refresh_token = create_jwt_refresh_token(
+ admin_user, oauth_refresh_token, csrf_token, plugin.PLUGIN_ID
+ )
+
+ request = rf.request()
+ data = {"refreshToken": saleor_refresh_token}
+ response = plugin.external_refresh(data, request, None)
+
+ decoded_token = jwt_decode(response.token)
+ assert decoded_token["exp"] == id_payload["exp"]
+ assert decoded_token["oauth_access_key"] == oauth_payload["access_token"]
+
+ decoded_refresh_token = jwt_decode(response.refresh_token)
+ assert decoded_refresh_token["oauth_refresh_token"] == "new_refresh"
+ assert decoded_refresh_token["csrf_token"] == response.csrf_token
+ mocked_refresh_token.assert_called_once_with(
+ "https://saleor.io/oauth/token",
+ refresh_token=oauth_refresh_token,
+ )
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_external_refresh_with_scope_permissions(
+ openid_plugin, admin_user, monkeypatch, rf, id_token, id_payload
+):
+ mocked_jwt_validator = MagicMock()
+ mocked_jwt_validator.__getitem__.side_effect = id_payload.__getitem__
+ mocked_jwt_validator.get.side_effect = id_payload.get
+
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.get_parsed_id_token",
+ Mock(return_value=mocked_jwt_validator),
+ )
+ oauth_payload = {
+ "access_token": "FeHkE_QbuU3cYy1a1eQUrCE5jRcUnBK3",
+ "refresh_token": "new_refresh",
+ "id_token": id_token,
+ "scope": (
+ "openid profile email offline_access saleor:manage_orders saleor:staff"
+ ),
+ "expires_in": 86400,
+ "token_type": "Bearer",
+ "expires_at": 1600851112,
+ }
+ mocked_refresh_token = Mock(return_value=oauth_payload)
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.OAuth2Session.refresh_token",
+ mocked_refresh_token,
+ )
+
+ oauth_refresh_token = "refresh"
+ plugin = openid_plugin(use_oauth_scope_permissions=True)
+ csrf_token = _get_new_csrf_token()
+ saleor_refresh_token = create_jwt_refresh_token(
+ admin_user, oauth_refresh_token, csrf_token, plugin.PLUGIN_ID
+ )
+
+ request = rf.request()
+ data = {"refreshToken": saleor_refresh_token}
+ response = plugin.external_refresh(data, request, None)
+
+ decoded_token = jwt_decode(response.token)
+ assert decoded_token["exp"] == id_payload["exp"]
+ assert decoded_token["oauth_access_key"] == oauth_payload["access_token"]
+ assert decoded_token["permissions"] == ["MANAGE_ORDERS"]
+
+ decoded_refresh_token = jwt_decode(response.refresh_token)
+ assert decoded_refresh_token["oauth_refresh_token"] == "new_refresh"
+ assert decoded_refresh_token["csrf_token"] == response.csrf_token
+ mocked_refresh_token.assert_called_once_with(
+ "https://saleor.io/oauth/token",
+ refresh_token=oauth_refresh_token,
+ )
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_external_refresh_raises_error_when_token_is_invalid(
+ openid_plugin, admin_user, monkeypatch, rf, id_token, id_payload
+):
+ mocked_jwt_validator = MagicMock()
+ mocked_jwt_validator.__getitem__.side_effect = id_payload.__getitem__
+
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.jwt.decode", Mock(side_effect=JoseError())
+ )
+ oauth_payload = {
+ "access_token": "FeHkE_QbuU3cYy1a1eQUrCE5jRcUnBK3",
+ "refresh_token": "new_refresh",
+ "id_token": id_token,
+ "scope": "openid profile email offline_access",
+ "expires_in": 86400,
+ "token_type": "Bearer",
+ "expires_at": 1600851112,
+ }
+ mocked_refresh_token = Mock(return_value=oauth_payload)
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.OAuth2Session.refresh_token",
+ mocked_refresh_token,
+ )
+
+ oauth_refresh_token = "refresh"
+ plugin = openid_plugin()
+ csrf_token = _get_new_csrf_token()
+ saleor_refresh_token = create_jwt_refresh_token(
+ admin_user, oauth_refresh_token, csrf_token, plugin.PLUGIN_ID
+ )
+
+ request = rf.request()
+ data = {"refreshToken": saleor_refresh_token}
+ with pytest.raises(ValidationError):
+ plugin.external_refresh(data, request, None)
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_external_refresh_disabled_refreshing(
+ openid_plugin, admin_user, monkeypatch, rf, id_token, id_payload
+):
+ plugin = openid_plugin(enable_refresh_token=False)
+
+ request = rf.request()
+ data = {"refreshToken": "ABC"}
+ with pytest.raises(ValidationError):
+ plugin.external_refresh(data, request, None)
+
+
+def test_external_refresh_when_plugin_is_disabled(openid_plugin, rf):
+ request = rf.request()
+ data = {"refreshToken": "token"}
+ plugin = openid_plugin(active=False)
+ previous_value = "previous"
+ plugin.external_refresh(data, request, previous_value)
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_external_refresh_raises_error(
+ openid_plugin, admin_user, monkeypatch, rf, id_token, id_payload
+):
+
+ plugin = openid_plugin()
+ csrf_token = _get_new_csrf_token()
+ oauth_refresh_token = "refresh"
+ saleor_refresh_token = create_jwt_refresh_token(
+ admin_user, oauth_refresh_token, csrf_token, plugin.PLUGIN_ID
+ )
+ request = rf.request()
+ request.COOKIES[JWT_REFRESH_TOKEN_COOKIE_NAME] = saleor_refresh_token
+
+ data = {"csrfToken": csrf_token}
+ with pytest.raises(ValidationError):
+ plugin.external_refresh(data, request, None)
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_external_refresh_incorrect_csrf(
+ openid_plugin, admin_user, monkeypatch, rf, id_token, id_payload
+):
+ plugin = openid_plugin()
+ csrf_token = _get_new_csrf_token()
+ oauth_refresh_token = "refresh"
+ saleor_refresh_token = create_jwt_refresh_token(
+ admin_user, oauth_refresh_token, csrf_token, plugin.PLUGIN_ID
+ )
+ request = rf.request()
+ request.COOKIES[JWT_REFRESH_TOKEN_COOKIE_NAME] = saleor_refresh_token
+
+ data = {"csrfToken": "incorrect"}
+ with pytest.raises(ValidationError):
+ plugin.external_refresh(data, request, None)
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_external_obtain_access_tokens(
+ openid_plugin, monkeypatch, rf, id_token, id_payload
+):
+ mocked_jwt_validator = MagicMock()
+ mocked_jwt_validator.__getitem__.side_effect = id_payload.__getitem__
+ mocked_jwt_validator.get.side_effect = id_payload.get
+
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.get_decoded_token",
+ Mock(return_value=mocked_jwt_validator),
+ )
+ plugin = openid_plugin(use_oauth_scope_permissions=True)
+ oauth_payload = {
+ "access_token": "FeHkE_QbuU3cYy1a1eQUrCE5jRcUnBK3",
+ "refresh_token": "refresh",
+ "id_token": id_token,
+ "scope": "openid profile email offline_access",
+ "expires_in": 86400,
+ "token_type": "Bearer",
+ "expires_at": 1600851112,
+ }
+ mocked_fetch_token = Mock(return_value=oauth_payload)
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.OAuth2Session.fetch_token",
+ mocked_fetch_token,
+ )
+ redirect_uri = "http://localhost:3000/used-logged-in"
+ state = signing.dumps({"redirectUri": redirect_uri})
+ code = "oauth-code"
+ tokens = plugin.external_obtain_access_tokens(
+ {"state": state, "code": code}, rf.request(), previous_value=None
+ )
+
+ mocked_fetch_token.assert_called_once_with(
+ "https://saleor.io/oauth/token",
+ code=code,
+ redirect_uri=redirect_uri,
+ )
+
+ claims = get_parsed_id_token(
+ oauth_payload,
+ plugin.config.json_web_key_set_url,
+ )
+ user = get_or_create_user_from_payload(claims, oauth_url="https://saleor.io/oauth")
+ expected_tokens = create_tokens_from_oauth_payload(
+ oauth_payload, user, claims, permissions=[], owner=plugin.PLUGIN_ID
+ )
+
+ decoded_access_token = jwt_decode(tokens.token)
+ assert decoded_access_token["permissions"] == []
+ assert decoded_access_token["is_staff"] is False
+ assert tokens.token == expected_tokens["token"]
+ decoded_refresh_token = jwt_decode(tokens.refresh_token)
+ assert tokens.csrf_token == decoded_refresh_token["csrf_token"]
+ assert decoded_refresh_token["oauth_refresh_token"] == "refresh"
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_external_obtain_access_tokens_with_permissions(
+ openid_plugin, monkeypatch, rf, id_token, id_payload
+):
+ mocked_jwt_validator = MagicMock()
+ mocked_jwt_validator.__getitem__.side_effect = id_payload.__getitem__
+ mocked_jwt_validator.get.side_effect = id_payload.get
+
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.get_decoded_token",
+ Mock(return_value=mocked_jwt_validator),
+ )
+ plugin = openid_plugin(use_oauth_scope_permissions=True)
+ oauth_payload = {
+ "access_token": "FeHkE_QbuU3cYy1a1eQUrCE5jRcUnBK3",
+ "refresh_token": "refresh",
+ "id_token": id_token,
+ "scope": "openid profile email offline_access saleor:manage_orders",
+ "expires_in": 86400,
+ "token_type": "Bearer",
+ "expires_at": 1600851112,
+ }
+ mocked_fetch_token = Mock(return_value=oauth_payload)
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.OAuth2Session.fetch_token",
+ mocked_fetch_token,
+ )
+ redirect_uri = "http://localhost:3000/used-logged-in"
+ state = signing.dumps({"redirectUri": redirect_uri})
+ code = "oauth-code"
+ tokens = plugin.external_obtain_access_tokens(
+ {"state": state, "code": code}, rf.request(), previous_value=None
+ )
+
+ mocked_fetch_token.assert_called_once_with(
+ "https://saleor.io/oauth/token",
+ code=code,
+ redirect_uri=redirect_uri,
+ )
+
+ claims = get_parsed_id_token(
+ oauth_payload,
+ plugin.config.json_web_key_set_url,
+ )
+ user = get_or_create_user_from_payload(claims, "https://saleor.io/oauth")
+ user.is_staff = True
+ expected_tokens = create_tokens_from_oauth_payload(
+ oauth_payload,
+ user,
+ claims,
+ permissions=[
+ "MANAGE_ORDERS",
+ ],
+ owner=plugin.PLUGIN_ID,
+ )
+
+ decoded_access_token = jwt_decode(tokens.token)
+ assert decoded_access_token["permissions"] == [
+ "MANAGE_ORDERS",
+ ]
+ assert decoded_access_token["is_staff"] is True
+
+ assert tokens.token == expected_tokens["token"]
+ decoded_refresh_token = jwt_decode(tokens.refresh_token)
+ assert tokens.csrf_token == decoded_refresh_token["csrf_token"]
+ assert decoded_refresh_token["oauth_refresh_token"] == "refresh"
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_external_obtain_access_tokens_with_saleor_staff(
+ openid_plugin, monkeypatch, rf, id_token, id_payload
+):
+ mocked_jwt_validator = MagicMock()
+ mocked_jwt_validator.__getitem__.side_effect = id_payload.__getitem__
+ mocked_jwt_validator.get.side_effect = id_payload.get
+
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.jwt.decode",
+ Mock(return_value=mocked_jwt_validator),
+ )
+ plugin = openid_plugin(use_oauth_scope_permissions=True)
+ oauth_payload = {
+ "access_token": "FeHkE_QbuU3cYy1a1eQUrCE5jRcUnBK3",
+ "refresh_token": "refresh",
+ "id_token": id_token,
+ "scope": "openid profile email offline_access saleor:staff",
+ "expires_in": 86400,
+ "token_type": "Bearer",
+ "expires_at": 1600851112,
+ }
+ mocked_fetch_token = Mock(return_value=oauth_payload)
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.OAuth2Session.fetch_token",
+ mocked_fetch_token,
+ )
+ redirect_uri = "http://localhost:3000/used-logged-in"
+ state = signing.dumps({"redirectUri": redirect_uri})
+ code = "oauth-code"
+ tokens = plugin.external_obtain_access_tokens(
+ {"state": state, "code": code}, rf.request(), previous_value=None
+ )
+
+ mocked_fetch_token.assert_called_once_with(
+ "https://saleor.io/oauth/token",
+ code=code,
+ redirect_uri=redirect_uri,
+ )
+
+ claims = get_parsed_id_token(
+ oauth_payload,
+ plugin.config.json_web_key_set_url,
+ )
+ user = get_or_create_user_from_payload(claims, "https://saleor.io/oauth")
+ user.refresh_from_db()
+
+ assert user.is_staff is True
+
+ expected_tokens = create_tokens_from_oauth_payload(
+ oauth_payload, user, claims, permissions=[], owner=plugin.PLUGIN_ID
+ )
+
+ decoded_access_token = jwt_decode(tokens.token)
+ assert decoded_access_token["permissions"] == []
+ assert decoded_access_token["is_staff"] is True
+
+ assert tokens.token == expected_tokens["token"]
+ decoded_refresh_token = jwt_decode(tokens.refresh_token)
+ assert tokens.csrf_token == decoded_refresh_token["csrf_token"]
+ assert decoded_refresh_token["oauth_refresh_token"] == "refresh"
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_external_obtain_access_tokens_user_which_is_no_more_staff(
+ openid_plugin, monkeypatch, rf, id_token, id_payload, staff_user
+):
+ staff_user.is_staff = False
+ staff_user.email = "[email protected]"
+ staff_user.save()
+
+ mocked_jwt_validator = MagicMock()
+ mocked_jwt_validator.__getitem__.side_effect = id_payload.__getitem__
+ mocked_jwt_validator.get.side_effect = id_payload.get
+
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.jwt.decode",
+ Mock(return_value=mocked_jwt_validator),
+ )
+ plugin = openid_plugin(use_oauth_scope_permissions=True)
+ oauth_payload = {
+ "access_token": "FeHkE_QbuU3cYy1a1eQUrCE5jRcUnBK3",
+ "refresh_token": "refresh",
+ "id_token": id_token,
+ "scope": "openid profile email offline_access",
+ "expires_in": 86400,
+ "token_type": "Bearer",
+ "expires_at": 1600851112,
+ }
+ mocked_fetch_token = Mock(return_value=oauth_payload)
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.OAuth2Session.fetch_token",
+ mocked_fetch_token,
+ )
+ redirect_uri = "http://localhost:3000/used-logged-in"
+ state = signing.dumps({"redirectUri": redirect_uri})
+ code = "oauth-code"
+ tokens = plugin.external_obtain_access_tokens(
+ {"state": state, "code": code}, rf.request(), previous_value=None
+ )
+
+ mocked_fetch_token.assert_called_once_with(
+ "https://saleor.io/oauth/token",
+ code=code,
+ redirect_uri=redirect_uri,
+ )
+
+ claims = get_parsed_id_token(
+ oauth_payload,
+ plugin.config.json_web_key_set_url,
+ )
+ user = get_or_create_user_from_payload(claims, "https://saleor.io/oauth")
+
+ staff_user.refresh_from_db()
+ assert staff_user == user
+ assert user.is_staff is False
+
+ decoded_access_token = jwt_decode(tokens.token)
+ assert decoded_access_token["permissions"] == []
+ assert decoded_access_token["is_staff"] is False
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_external_obtain_access_tokens_plugin_disabled(openid_plugin, rf):
+ plugin = openid_plugin(active=False)
+ redirect_uri = "http://localhost:3000/used-logged-in"
+ state = signing.dumps({"redirectUri": redirect_uri})
+ code = "oauth-code"
+ previous_value = ExternalAccessTokens(token="previous")
+ tokens = plugin.external_obtain_access_tokens(
+ {"state": state, "code": code}, rf.request(), previous_value=previous_value
+ )
+ assert tokens == previous_value
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_external_obtain_access_tokens_missing_code(openid_plugin, rf):
+ plugin = openid_plugin()
+ redirect_uri = "http://localhost:3000/used-logged-in"
+ state = signing.dumps({"redirectUri": redirect_uri})
+ with pytest.raises(ValidationError):
+ plugin.external_obtain_access_tokens(
+ {"state": state}, rf.request(), previous_value=None
+ )
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_external_obtain_access_tokens_missing_state(openid_plugin, rf):
+ plugin = openid_plugin()
+ code = "oauth-code"
+ with pytest.raises(ValidationError):
+ plugin.external_obtain_access_tokens(
+ {"code": code}, rf.request(), previous_value=None
+ )
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_external_obtain_access_tokens_missing_redirect_uri_in_state(openid_plugin, rf):
+ plugin = openid_plugin()
+ state = signing.dumps({})
+ code = "oauth-code"
+ with pytest.raises(ValidationError):
+ plugin.external_obtain_access_tokens(
+ {"state": state, "code": code}, rf.request(), previous_value=None
+ )
+
+
+test_url = "http://saleor.io/"
+
+
+ "c_id,c_secret,authorization_url,token_url,jwks_url,user_info_url",
+ (
+ ["", "ss", f"{test_url}auth", f"{test_url}token", f"{test_url}jwks", ""],
+ ["cc", "", f"{test_url}auth", f"{test_url}token", f"{test_url}jwks", ""],
+ ["cc", "123", "", f"{test_url}token", f"{test_url}jwks", ""],
+ ["cc", "123", f"{test_url}auth", "", f"{test_url}jwks", ""],
+ ["cc", "123", f"{test_url}auth", f"{test_url}token", "", ""],
+ [
+ "cc",
+ "123",
+ "saleor.io/auth",
+ f"{test_url}token",
+ f"{test_url}token",
+ "",
+ ],
+ ["cc", "123", f"{test_url}auth", "http://", f"{test_url}token", ""],
+ ["cc", "123", f"{test_url}auth", "http://", f"{test_url}token", ""],
+ ["cc", "123", "not_url", f"{test_url}token", f"{test_url}token", ""],
+ ["cc", "123", "", "", "", "not_url"],
+ ["cc", "123", "", "", "", f"{test_url}/userinfo"],
+ ["cc", "123", "", "", "", ""],
+ ),
+)
+def test_validate_plugin_configuration_raises_error(
+ c_id,
+ c_secret,
+ authorization_url,
+ token_url,
+ jwks_url,
+ user_info_url,
+ plugin_configuration,
+ openid_plugin,
+):
+ configuration = plugin_configuration(
+ client_id=c_id,
+ client_secret=c_secret,
+ enable_refresh_token=True,
+ oauth_authorization_url=authorization_url,
+ oauth_token_url=token_url,
+ json_web_key_set_url=jwks_url,
+ user_info_url=user_info_url,
+ )
+ conf = PluginConfiguration(active=True, configuration=configuration)
+ plugin = openid_plugin()
+ with pytest.raises(ValidationError):
+ plugin.validate_plugin_configuration(conf)
+
+
+def test_validate_plugin_configuration(plugin_configuration, openid_plugin):
+ configuration = plugin_configuration(
+ client_id="c_id",
+ client_secret="c_secret",
+ enable_refresh_token=True,
+ oauth_authorization_url="http://saleor.io/auth",
+ oauth_token_url="http://saleor.io/token",
+ json_web_key_set_url="http://saleor.io/jwks",
+ )
+ conf = PluginConfiguration(active=True, configuration=configuration)
+ plugin = openid_plugin()
+ plugin.validate_plugin_configuration(conf)
+
+
+def test_external_logout_missing_logout_url(openid_plugin, rf):
+ plugin = openid_plugin(oauth_logout_url="")
+ response = plugin.external_logout({}, rf.request(), None)
+ assert response == {}
+
+
+def test_external_logout_plugin_inactive(openid_plugin, rf):
+ plugin = openid_plugin(oauth_logout_url="", active=False)
+ response = plugin.external_logout({}, rf.request(), None)
+ assert response is None
+
+
+def test_external_logout(openid_plugin, rf):
+ client_id = "AVC"
+ domain = "saleor.io"
+ path = "/logout"
+ plugin = openid_plugin(oauth_logout_url=f"http://{domain}{path}?client_id=AVC")
+ input_data = {"redirectUrl": "http://localhost:3000/logout", "field1": "value1"}
+ response = plugin.external_logout(input_data, rf.request(), None)
+ logout_url = response["logoutUrl"]
+
+ parsed_url = urlparse(logout_url)
+ parsed_qs = parse_qs(parsed_url.query)
+ assert parsed_url.netloc == domain
+ assert parsed_url.path == path
+ assert parsed_qs["redirectUrl"][0] == "http://localhost:3000/logout"
+ assert parsed_qs["field1"][0] == "value1"
+ assert parsed_qs["client_id"][0] == client_id
+
+
+def test_external_verify_plugin_disabled(openid_plugin, rf):
+ plugin = openid_plugin(active=False)
+ input = {"token": "token"}
+ previous_value = "previous"
+ response = plugin.external_verify(input, rf.request(), previous_value)
+ assert response == previous_value
+
+
+def test_external_verify_missing_token(openid_plugin, rf):
+ plugin = openid_plugin(active=True)
+ input = {}
+ previous_value = "previous"
+ response = plugin.external_verify(input, rf.request(), previous_value)
+ assert response == previous_value
+
+
+def test_external_verify_wrong_token_owner(openid_plugin, rf):
+ plugin = openid_plugin(active=True)
+ input = {"token": "wrong_format"}
+ previous_value = "previous"
+ response = plugin.external_verify(input, rf.request(), previous_value)
+ assert response == previous_value
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_external_verify(id_payload, customer_user, openid_plugin, rf):
+ plugin = openid_plugin()
+ token = create_jwt_token(
+ id_payload,
+ customer_user,
+ access_token="access",
+ permissions=[],
+ owner=plugin.PLUGIN_ID,
+ )
+ input = {"token": token}
+ previous_value = "previous"
+ response = plugin.external_verify(input, rf.request(), previous_value)
+ user, data = response
+ assert user == customer_user
+ assert list(user.effective_permissions) == []
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_external_verify_user_with_effective_permissions(
+ permission_manage_orders, id_payload, customer_user, openid_plugin, rf
+):
+ plugin = openid_plugin()
+ token = create_jwt_token(
+ id_payload,
+ customer_user,
+ access_token="access",
+ permissions=["MANAGE_ORDERS"],
+ owner=plugin.PLUGIN_ID,
+ )
+ input = {"token": token}
+ previous_value = "previous"
+ response = plugin.external_verify(input, rf.request(), previous_value)
+ user, data = response
+ assert user == customer_user
+ assert list(user.effective_permissions) == [permission_manage_orders]
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_authenticate_user(openid_plugin, id_payload, customer_user, monkeypatch, rf):
+ plugin = openid_plugin()
+ token = create_jwt_token(
+ id_payload,
+ customer_user,
+ access_token="access",
+ permissions=[],
+ owner=plugin.PLUGIN_ID,
+ )
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.get_token_from_request", lambda _: token
+ )
+ user = plugin.authenticate_user(rf.request(), None)
+ assert user == customer_user
+
+
+@freeze_time("2021-03-08 12:00:00")
+def test_authenticate_user_with_access_token(
+ openid_plugin,
+ decoded_access_token,
+ user_info_response,
+ customer_user,
+ monkeypatch,
+ rf,
+):
+ plugin = openid_plugin(
+ oauth_authorization_url=None,
+ oauth_token_url=None,
+ json_web_key_set_url="https://saleor.io/.well-known/jwks.json",
+ user_info_url="https://saleor.io/userinfo",
+ use_oauth_scope_permissions=True,
+ )
+ decoded_access_token["scope"] = ""
+
+ # mock get token from request
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.get_token_from_request",
+ lambda _: "OAuth_access_token",
+ )
+
+ # decode access token returns payload when access token is in JWT format
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.decode_access_token", lambda x, y: None
+ )
+ # mock request to api to fetch user info details
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.get_user_info",
+ lambda x, z: user_info_response,
+ )
+ # mock cache used for caching user info details
+ monkeypatch.setattr("saleor.plugins.openid_connect.utils.cache.set", Mock())
+
+ user = plugin.authenticate_user(rf.request(), None)
+
+ assert user == customer_user
+ assert user.is_staff is False
+ assert list(user.effective_permissions) == []
+
+
+@freeze_time("2021-03-08 12:00:00")
+def test_authenticate_user_with_access_token_unable_to_fetch_user_info(
+ openid_plugin, decoded_access_token, monkeypatch, rf
+):
+ plugin = openid_plugin(
+ oauth_authorization_url=None,
+ oauth_token_url=None,
+ json_web_key_set_url="https://saleor.io/.well-known/jwks.json",
+ user_info_url="https://saleor.io/userinfo",
+ use_oauth_scope_permissions=True,
+ )
+ decoded_access_token["scope"] = ""
+
+ # mock get token from request
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.get_token_from_request",
+ lambda _: "OAuth_access_token",
+ )
+
+ # decode access token returns payload when access token is in JWT format
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.decode_access_token", lambda x, y: None
+ )
+ # mock request to api to fetch user info details
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.get_user_info", lambda x, z: None
+ )
+ # mock cache used for caching user info details
+ monkeypatch.setattr("saleor.plugins.openid_connect.utils.cache.set", Mock())
+
+ user = plugin.authenticate_user(rf.request(), None)
+
+ assert user is None
+
+
+@freeze_time("2021-03-08 12:00:00")
+def test_authenticate_user_with_jwt_access_token(
+ openid_plugin,
+ decoded_access_token,
+ user_info_response,
+ customer_user,
+ monkeypatch,
+ rf,
+):
+ plugin = openid_plugin(
+ oauth_authorization_url=None,
+ oauth_token_url=None,
+ json_web_key_set_url="https://saleor.io/.well-known/jwks.json",
+ user_info_url="https://saleor.io/userinfo",
+ use_oauth_scope_permissions=True,
+ )
+ decoded_access_token["scope"] = ""
+ decoded_token = MagicMock()
+ decoded_token.__getitem__.side_effect = decoded_access_token.__getitem__
+
+ # mock get token from request
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.get_token_from_request",
+ lambda _: "OAuth_access_token",
+ )
+ # decode access token returns payload when access token is in JWT format
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.decode_access_token",
+ lambda x, y: decoded_token,
+ )
+ # mock request to api to fetch user info details
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.get_user_info",
+ lambda x, z: user_info_response,
+ )
+ # mock cache used for caching user info details
+ monkeypatch.setattr("saleor.plugins.openid_connect.utils.cache.set", Mock())
+
+ user = plugin.authenticate_user(rf.request(), None)
+
+ assert user == customer_user
+ assert user.is_staff is False
+ assert list(user.effective_permissions) == []
+
+
+@freeze_time("2021-03-08 12:00:00")
+def test_authenticate_user_with_jwt_access_token_which_is_no_more_staff(
+ openid_plugin,
+ decoded_access_token,
+ user_info_response,
+ customer_user,
+ monkeypatch,
+ rf,
+):
+ customer_user.is_staff = True
+ customer_user.email = "[email protected]"
+ customer_user.save()
+
+ plugin = openid_plugin(
+ oauth_authorization_url=None,
+ oauth_token_url=None,
+ json_web_key_set_url="https://saleor.io/.well-known/jwks.json",
+ user_info_url="https://saleor.io/userinfo",
+ use_oauth_scope_permissions=True,
+ )
+ decoded_access_token["scope"] = ""
+ decoded_token = MagicMock()
+ decoded_token.__getitem__.side_effect = decoded_access_token.__getitem__
+ decoded_token.get.side_effect = decoded_access_token.get
+
+ # mock get token from request
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.get_token_from_request",
+ lambda _: "OAuth_access_token",
+ )
+ # decode access token returns payload when access token is in JWT format
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.decode_access_token",
+ lambda x, y: decoded_token,
+ )
+ # mock request to api to fetch user info details
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.get_user_info",
+ lambda x, z: user_info_response,
+ )
+ # mock cache used for caching user info details
+ monkeypatch.setattr("saleor.plugins.openid_connect.utils.cache.set", Mock())
+
+ user = plugin.authenticate_user(rf.request(), None)
+
+ user.refresh_from_db()
+ assert user == customer_user
+ assert user.is_staff is False
+ assert list(user.effective_permissions) == []
+
+
+@freeze_time("2021-03-08 12:00:00")
+def test_authenticate_staff_user_with_jwt_access_token_and_staff_scope(
+ openid_plugin,
+ decoded_access_token,
+ user_info_response,
+ customer_user,
+ monkeypatch,
+ rf,
+):
+ plugin = openid_plugin(
+ oauth_authorization_url=None,
+ oauth_token_url=None,
+ json_web_key_set_url="https://saleor.io/.well-known/jwks.json",
+ user_info_url="https://saleor.io/userinfo",
+ use_oauth_scope_permissions=True,
+ )
+ decoded_access_token["scope"] = "openid profile email saleor:staff"
+ decoded_token = MagicMock()
+ decoded_token.__getitem__.side_effect = decoded_access_token.__getitem__
+ decoded_token.get.side_effect = decoded_access_token.get
+
+ # mock get token from request
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.get_token_from_request",
+ lambda _: "OAuth_access_token",
+ )
+ # decode access token returns payload when access token is in JWT format
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.decode_access_token",
+ lambda x, y: decoded_token,
+ )
+ # mock request to api to fetch user info details
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.get_user_info",
+ lambda x, z: user_info_response,
+ )
+ # mock cache used for caching user info details
+ monkeypatch.setattr("saleor.plugins.openid_connect.utils.cache.set", Mock())
+
+ user = plugin.authenticate_user(rf.request(), None)
+
+ user.refresh_from_db()
+ assert user == customer_user
+ assert user.is_staff is True
+ assert list(user.effective_permissions) == []
+
+
+@freeze_time("2021-03-08 12:00:00")
+def test_authenticate_staff_user_with_jwt_access_token_and_staff_in_permissions_field(
+ openid_plugin,
+ decoded_access_token,
+ user_info_response,
+ customer_user,
+ monkeypatch,
+ rf,
+):
+ plugin = openid_plugin(
+ oauth_authorization_url=None,
+ oauth_token_url=None,
+ json_web_key_set_url="https://saleor.io/.well-known/jwks.json",
+ user_info_url="https://saleor.io/userinfo",
+ use_oauth_scope_permissions=True,
+ )
+ decoded_access_token["scope"] = "openid profile email"
+ decoded_access_token["permissions"] = ["saleor:staff"]
+ decoded_token = MagicMock()
+ decoded_token.__getitem__.side_effect = decoded_access_token.__getitem__
+ decoded_token.get.side_effect = decoded_access_token.get
+
+ # mock get token from request
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.get_token_from_request",
+ lambda _: "OAuth_access_token",
+ )
+ # decode access token returns payload when access token is in JWT format
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.decode_access_token",
+ lambda x, y: decoded_token,
+ )
+ # mock request to api to fetch user info details
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.get_user_info",
+ lambda x, z: user_info_response,
+ )
+ # mock cache used for caching user info details
+ monkeypatch.setattr("saleor.plugins.openid_connect.utils.cache.set", Mock())
+
+ user = plugin.authenticate_user(rf.request(), None)
+
+ user.refresh_from_db()
+ assert user == customer_user
+ assert user.is_staff is True
+ assert list(user.effective_permissions) == []
+
+
+@freeze_time("2021-03-08 12:00:00")
+def test_authenticate_staff_user_with_jwt_access_token_with_permissions_field(
+ permission_manage_orders,
+ permission_manage_apps,
+ openid_plugin,
+ decoded_access_token,
+ user_info_response,
+ customer_user,
+ monkeypatch,
+ rf,
+):
+ plugin = openid_plugin(
+ oauth_authorization_url=None,
+ oauth_token_url=None,
+ json_web_key_set_url="https://saleor.io/.well-known/jwks.json",
+ user_info_url="https://saleor.io/userinfo",
+ use_oauth_scope_permissions=True,
+ )
+ decoded_access_token["scope"] = "openid profile email"
+ decoded_access_token["permissions"] = ["saleor:manage_orders", "saleor:manage_apps"]
+ decoded_token = MagicMock()
+ decoded_token.__getitem__.side_effect = decoded_access_token.__getitem__
+ decoded_token.get.side_effect = decoded_access_token.get
+
+ # mock get token from request
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.get_token_from_request",
+ lambda _: "OAuth_access_token",
+ )
+ # decode access token returns payload when access token is in JWT format
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.decode_access_token",
+ lambda x, y: decoded_token,
+ )
+ # mock request to api to fetch user info details
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.get_user_info",
+ lambda x, z: user_info_response,
+ )
+ # mock cache used for caching user info details
+ monkeypatch.setattr("saleor.plugins.openid_connect.utils.cache.set", Mock())
+
+ user = plugin.authenticate_user(rf.request(), None)
+
+ user.refresh_from_db()
+ assert user == customer_user
+ assert user.is_staff is True
+ assert set(user.effective_permissions) == {
+ permission_manage_apps,
+ permission_manage_orders,
+ }
+
+
+@freeze_time("2021-03-08 12:00:00")
+def test_authenticate_user_with_jwt_access_token_unable_to_fetch_user_info(
+ openid_plugin, decoded_access_token, monkeypatch, rf
+):
+ plugin = openid_plugin(
+ oauth_authorization_url=None,
+ oauth_token_url=None,
+ json_web_key_set_url="https://saleor.io/.well-known/jwks.json",
+ user_info_url="https://saleor.io/userinfo",
+ use_oauth_scope_permissions=True,
+ )
+ decoded_access_token["scope"] = ""
+
+ decoded_token = MagicMock()
+ decoded_token.__getitem__.side_effect = decoded_access_token.__getitem__
+
+ # mock get token from request
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.get_token_from_request",
+ lambda _: "OAuth_access_token",
+ )
+ # decode access token returns payload when access token is in JWT format
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.decode_access_token",
+ lambda x, y: decoded_token,
+ )
+ # mock request to api to fetch user info details
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.get_user_info", Mock(return_value=None)
+ )
+ # mock cache used for caching user info details
+ monkeypatch.setattr("saleor.plugins.openid_connect.utils.cache.set", Mock())
+
+ user = plugin.authenticate_user(rf.request(), None)
+
+ assert user is None
+
+
+@freeze_time("2021-03-08 12:00:00")
+def test_authenticate_user_with_jwt_invalid_access_token(
+ openid_plugin,
+ decoded_access_token,
+ user_info_response,
+ monkeypatch,
+ rf,
+):
+ plugin = openid_plugin(
+ oauth_authorization_url=None,
+ oauth_token_url=None,
+ json_web_key_set_url="https://saleor.io/.well-known/jwks.json",
+ user_info_url="https://saleor.io/userinfo",
+ use_oauth_scope_permissions=True,
+ )
+ decoded_access_token["scope"] = ""
+
+ decoded_token = MagicMock()
+ decoded_token.__getitem__.side_effect = decoded_access_token.__getitem__
+ decoded_token.validate.side_effect = JoseError()
+
+ # mock get token from request
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.get_token_from_request",
+ lambda _: "OAuth_access_token",
+ )
+ # decode access token returns payload when access token is in JWT format
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.decode_access_token",
+ lambda x, y: decoded_token,
+ )
+
+ # mock request to api to fetch user info details
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.get_user_info",
+ lambda x, z: user_info_response,
+ )
+ # mock cache used for caching user info details
+ monkeypatch.setattr("saleor.plugins.openid_connect.utils.cache.set", Mock())
+
+ user = plugin.authenticate_user(rf.request(), None)
+
+ assert user is None
+
+
+@freeze_time("2021-03-08 12:00:00")
+def test_authenticate_staff_user_with_jwt_access_token(
+ openid_plugin,
+ decoded_access_token,
+ user_info_response,
+ staff_user,
+ monkeypatch,
+ rf,
+ permission_manage_orders,
+ permission_manage_apps,
+ permission_manage_products,
+):
+ staff_user.is_staff = False
+ staff_user.save()
+
+ plugin = openid_plugin(
+ oauth_authorization_url=None,
+ oauth_token_url=None,
+ json_web_key_set_url="https://saleor.io/.well-known/jwks.json",
+ user_info_url="https://saleor.io/userinfo",
+ use_oauth_scope_permissions=True,
+ audience=decoded_access_token["aud"][0],
+ )
+
+ decoded_token = MagicMock()
+ decoded_token.__getitem__.side_effect = decoded_access_token.__getitem__
+ decoded_token.get.side_effect = decoded_access_token.get
+
+ user_info_response["email"] = staff_user.email
+
+ # mock get token from request
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.get_token_from_request",
+ lambda _: "OAuth_access_token",
+ )
+ # decode access token returns payload when access token is in JWT format
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.decode_access_token",
+ lambda x, y: decoded_token,
+ )
+ # mock request to api to fetch user info details
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.get_user_info",
+ lambda x, z: user_info_response,
+ )
+ # mock cache used for caching user info details
+ monkeypatch.setattr("saleor.plugins.openid_connect.utils.cache.set", Mock())
+
+ user = plugin.authenticate_user(rf.request(), None)
+
+ user.refresh_from_db()
+ assert user == staff_user
+ assert user.is_staff is True
+ assert set(user.effective_permissions) == {
+ permission_manage_orders,
+ permission_manage_apps,
+ permission_manage_products,
+ }
+
+
+@freeze_time("2021-03-08 12:00:00")
+def test_authenticate_staff_user_with_jwt_access_token_and_disabled_scope_permission(
+ openid_plugin, decoded_access_token, user_info_response, staff_user, monkeypatch, rf
+):
+ plugin = openid_plugin(
+ oauth_authorization_url=None,
+ oauth_token_url=None,
+ json_web_key_set_url="https://saleor.io/.well-known/jwks.json",
+ user_info_url="https://saleor.io/userinfo",
+ use_oauth_scope_permissions=False,
+ )
+
+ decoded_token = MagicMock()
+ decoded_token.__getitem__.side_effect = decoded_access_token.__getitem__
+ decoded_token.get.side_effect = decoded_access_token.get
+
+ user_info_response["email"] = staff_user.email
+
+ # mock get token from request
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.get_token_from_request",
+ lambda _: "OAuth_access_token",
+ )
+
+ # decode access token returns payload when access token is in JWT format
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.decode_access_token",
+ lambda x, y: decoded_token,
+ )
+
+ # mock request to api to fetch user info details
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.get_user_info",
+ lambda x, z: user_info_response,
+ )
+
+ # mock cache used for caching user info details
+ monkeypatch.setattr("saleor.plugins.openid_connect.utils.cache.set", Mock())
+
+ user = plugin.authenticate_user(rf.request(), None)
+
+ assert user == staff_user
+ assert user.is_staff is False
+ assert list(user.effective_permissions) == []
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_authenticate_user_wrong_owner(
+ openid_plugin, id_payload, customer_user, staff_user, monkeypatch, rf
+):
+ plugin = openid_plugin(user_info_url="")
+ token = create_jwt_token(
+ id_payload,
+ customer_user,
+ access_token="access",
+ permissions=[],
+ owner="DifferentPlugin",
+ )
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.get_token_from_request", lambda _: token
+ )
+ user = plugin.authenticate_user(rf.request(), previous_value=staff_user)
+ assert user == staff_user
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_authenticate_user_missing_owner(
+ openid_plugin, id_payload, customer_user, monkeypatch, rf
+):
+ plugin = openid_plugin(user_info_url="")
+ additional_payload = {
+ "exp": id_payload["exp"],
+ "oauth_access_key": "access",
+ PERMISSIONS_FIELD: [],
+ }
+ jwt_payload = jwt_user_payload(
+ customer_user,
+ JWT_ACCESS_TYPE,
+ exp_delta=None,
+ additional_payload=additional_payload,
+ )
+ token = jwt_encode(jwt_payload)
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.get_token_from_request", lambda _: token
+ )
+ user = plugin.authenticate_user(rf.request(), None)
+ assert user is None
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_authenticate_user_missing_token_in_request(openid_plugin, id_payload, rf):
+ plugin = openid_plugin()
+ user = plugin.authenticate_user(rf.request(), None)
+ assert user is None
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_authenticate_user_plugin_is_disabled(
+ openid_plugin, customer_user, monkeypatch, id_payload, rf
+):
+ plugin = openid_plugin(active=False)
+ token = create_jwt_token(
+ id_payload,
+ customer_user,
+ access_token="access",
+ permissions=[],
+ owner=plugin.PLUGIN_ID,
+ )
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.get_token_from_request", lambda _: token
+ )
+
+ user = plugin.authenticate_user(rf.request(), None)
+ assert user is None
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_authenticate_user_unable_to_decode_token(openid_plugin, monkeypatch, rf):
+ plugin = openid_plugin(user_info_url="")
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.get_token_from_request", lambda _: "ABC"
+ )
+ user = plugin.authenticate_user(rf.request(), None)
+ assert user is None
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_authenticate_user_staff_user_with_effective_permissions(
+ openid_plugin,
+ id_payload,
+ staff_user,
+ permission_manage_orders,
+ permission_manage_users,
+ permission_manage_checkouts,
+ permission_manage_gift_card,
+ monkeypatch,
+ rf,
+):
+ plugin = openid_plugin()
+ staff_user.user_permissions.add(
+ permission_manage_gift_card, permission_manage_checkouts
+ )
+ permissions = ["MANAGE_USERS", "MANAGE_ORDERS"]
+ token = create_jwt_token(
+ id_payload,
+ staff_user,
+ access_token="access",
+ permissions=permissions,
+ owner=plugin.PLUGIN_ID,
+ )
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.get_token_from_request", lambda _: token
+ )
+ user = plugin.authenticate_user(rf.request(), None)
+ assert user == staff_user
+ assert set(user.effective_permissions) == {
+ permission_manage_orders,
+ permission_manage_users,
+ }
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_authenticate_user_staff_user_without_permissions(
+ openid_plugin,
+ id_payload,
+ staff_user,
+ monkeypatch,
+ rf,
+):
+ plugin = openid_plugin()
+ token = create_jwt_token(
+ id_payload,
+ staff_user,
+ access_token="access",
+ permissions=[],
+ owner=plugin.PLUGIN_ID,
+ )
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.plugin.get_token_from_request", lambda _: token
+ )
+ user = plugin.authenticate_user(rf.request(), None)
+ assert user == staff_user
diff --git a/saleor/plugins/openid_connect/tests/test_utils.py b/saleor/plugins/openid_connect/tests/test_utils.py
new file mode 100644
index 0000000000..92d6e5ff7c
--- /dev/null
+++ b/saleor/plugins/openid_connect/tests/test_utils.py
@@ -0,0 +1,333 @@
+import json
+import time
+import warnings
+from datetime import datetime
+from unittest import mock
+from unittest.mock import MagicMock, Mock
+
+import pytest
+import pytz
+import requests
+from django.core.exceptions import ValidationError
+from django.utils.timezone import make_aware
+from freezegun import freeze_time
+from requests import Response
+
+from ....account.models import User
+from ....core.jwt import (
+ JWT_REFRESH_TYPE,
+ PERMISSIONS_FIELD,
+ jwt_decode,
+ jwt_encode,
+ jwt_user_payload,
+)
+from ..exceptions import AuthenticationError
+from ..utils import (
+ JWKS_CACHE_TIME,
+ JWKS_KEY,
+ create_jwt_refresh_token,
+ create_jwt_token,
+ create_tokens_from_oauth_payload,
+ fetch_jwks,
+ get_or_create_user_from_payload,
+ get_saleor_permission_names,
+ get_saleor_permissions_qs_from_scope,
+ get_user_from_token,
+ get_user_info,
+ validate_refresh_token,
+)
+
+
+ "error",
+ [
+ json.JSONDecodeError(msg="", doc="", pos=0),
+ requests.exceptions.RequestException(),
+ ],
+)
+def test_fetch_jwks_raises_error(monkeypatch, error):
+ mocked_get = Mock()
+ mocked_get.side_effect = error
+ jwks_url = "http://localhost:3000/"
+ monkeypatch.setattr("saleor.plugins.openid_connect.utils.requests.get", mocked_get)
+
+ with pytest.raises(AuthenticationError):
+ fetch_jwks(jwks_url)
+
+
[email protected]("saleor.plugins.openid_connect.utils.cache.set")
+def test_fetch_jwks(mocked_cache_set):
+ jwks_url = "https://saleor.io/.well-known/jwks.json"
+ keys = fetch_jwks(jwks_url)
+ assert len(keys) == 2
+ mocked_cache_set.assert_called_once_with(JWKS_KEY, keys, JWKS_CACHE_TIME)
+
+
+def test_get_or_create_user_from_token_missing_email(id_payload):
+ del id_payload["email"]
+ with pytest.raises(AuthenticationError):
+ get_or_create_user_from_payload(id_payload, "https://saleor.io/oauth")
+
+
+def test_get_or_create_user_from_token_user_not_active(id_payload, admin_user):
+ admin_user.is_active = False
+ admin_user.save()
+ with pytest.raises(AuthenticationError):
+ get_or_create_user_from_payload(id_payload, "https://saleor.io/oauth")
+
+
+def test_get_user_from_token_missing_email(id_payload):
+ del id_payload["email"]
+ with pytest.raises(AuthenticationError):
+ get_user_from_token(id_payload)
+
+
+def test_get_user_from_token_missing_user(id_payload):
+ User.objects.all().delete()
+ with pytest.raises(AuthenticationError):
+ get_user_from_token(id_payload)
+
+
+def test_get_user_from_token_user_not_active(id_payload, admin_user):
+ admin_user.is_active = False
+ admin_user.save()
+ with pytest.raises(AuthenticationError):
+ get_user_from_token(id_payload)
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_create_tokens_from_oauth_payload(monkeypatch, id_token, id_payload):
+ mocked_jwt_validator = MagicMock()
+ mocked_jwt_validator.__getitem__.side_effect = id_payload.__getitem__
+
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.jwt.decode",
+ Mock(return_value=mocked_jwt_validator),
+ )
+ permissions_from_scope = [
+ "MANAGE_ORDERS",
+ ]
+ auth_payload = {
+ "access_token": "FeHkE_QbuU3cYy1a1eQUrCE5jRcUnBK3",
+ "refresh_token": "refresh",
+ "id_token": id_token,
+ "scope": (
+ "openid profile email offline_access saleor:manage_orders saleor:staff"
+ ),
+ "expires_in": 86400,
+ "token_type": "Bearer",
+ "expires_at": 1600851112,
+ }
+ user = get_or_create_user_from_payload(id_payload, "https://saleor.io/oauth")
+ permissions = get_saleor_permissions_qs_from_scope(auth_payload.get("scope"))
+ perms = get_saleor_permission_names(permissions)
+ tokens = create_tokens_from_oauth_payload(
+ auth_payload, user, id_payload, perms, "PluginID"
+ )
+
+ created_user = User.objects.get()
+
+ token = create_jwt_token(
+ id_payload,
+ created_user,
+ auth_payload["access_token"],
+ permissions_from_scope,
+ "PluginID",
+ )
+
+ assert created_user.email == id_payload["email"]
+ assert tokens["token"] == token
+ # confirm that we have jwt token
+ decoded_token = jwt_decode(tokens["token"])
+ assert decoded_token.get(PERMISSIONS_FIELD) == permissions_from_scope
+
+ decoded_refresh_token = jwt_decode(tokens["refresh_token"])
+ assert decoded_refresh_token["oauth_refresh_token"] == "refresh"
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_validate_refresh_token_missing_csrf_token(admin_user):
+ token = create_jwt_refresh_token(admin_user, "refresh_token", "csrf", "pluginID")
+ with pytest.raises(ValidationError):
+ validate_refresh_token(token, {})
+
+
+def test_validate_refresh_token_missing_csrf_token_in_token_payload(admin_user):
+ additional_payload = {"oauth_refresh_token": "refresh_token"}
+ jwt_payload = jwt_user_payload(
+ admin_user,
+ JWT_REFRESH_TYPE,
+ # oauth_refresh_token has own expiration time. No need to duplicate it here
+ exp_delta=None,
+ additional_payload=additional_payload,
+ )
+ token = jwt_encode(jwt_payload)
+ with pytest.raises(ValidationError):
+ validate_refresh_token(token, {})
+
+
+def test_validate_refresh_token_missing_token():
+ refresh_token = ""
+ with pytest.raises(ValidationError):
+ validate_refresh_token(refresh_token, {})
+
+
+def test_get_saleor_permissions_from_scope():
+ auth_payload = {
+ "access_token": "FeHkE_QbuU3cYy1a1eQUrCE5jRcUnBK3",
+ "refresh_token": "refresh",
+ "scope": (
+ "openid profile email offline_access saleor:manage_orders "
+ "saleor:non_existing saleor saleor: saleor:manage_users"
+ ),
+ }
+ expected_permissions = {"MANAGE_USERS", "MANAGE_ORDERS"}
+ permissions = get_saleor_permissions_qs_from_scope(auth_payload.get("scope"))
+ permission_names = get_saleor_permission_names(permissions)
+ assert set(permission_names) == expected_permissions
+
+
+def test_get_user_info_raises_decode_error(monkeypatch):
+ response = Response()
+ response.status_code = 200
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.requests.get", Mock(return_value=response)
+ )
+
+ user_info = get_user_info("https://saleor.io/userinfo", "access_token")
+ assert user_info is None
+
+
+def test_get_user_info_raises_http_error(monkeypatch):
+ response = Response()
+ response.status_code = 500
+ monkeypatch.setattr(
+ "saleor.plugins.openid_connect.utils.requests.get", Mock(return_value=response)
+ )
+
+ user_info = get_user_info("https://saleor.io/userinfo", "access_token")
+ assert user_info is None
+
+
+def test_get_or_create_user_from_payload_retrieve_user_by_sub(customer_user):
+ oauth_url = "https://saleor.io/oauth"
+ sub_id = "oauth|1234"
+ customer_user.private_metadata = {f"oidc-{oauth_url}": sub_id}
+ customer_user.save()
+
+ user_from_payload = get_or_create_user_from_payload(
+ payload={"sub": sub_id, "email": customer_user.email},
+ oauth_url=oauth_url,
+ )
+
+ assert user_from_payload.id == customer_user.id
+ assert user_from_payload.private_metadata[f"oidc-{oauth_url}"] == sub_id
+
+
+def test_get_or_create_user_from_payload_updates_sub(customer_user):
+ oauth_url = "https://saleor.io/oauth"
+ sub_id = "oauth|1234"
+ customer_user.private_metadata = {f"oidc-{oauth_url}": "old-sub"}
+ customer_user.save()
+
+ user_from_payload = get_or_create_user_from_payload(
+ payload={"sub": sub_id, "email": customer_user.email},
+ oauth_url=oauth_url,
+ )
+
+ assert user_from_payload.id == customer_user.id
+ assert user_from_payload.private_metadata[f"oidc-{oauth_url}"] == sub_id
+
+
+def test_get_or_create_user_from_payload_assigns_sub(customer_user):
+ oauth_url = "https://saleor.io/oauth"
+ sub_id = "oauth|1234"
+
+ user_from_payload = get_or_create_user_from_payload(
+ payload={"sub": sub_id, "email": customer_user.email},
+ oauth_url=oauth_url,
+ )
+
+ assert user_from_payload.id == customer_user.id
+ assert user_from_payload.private_metadata[f"oidc-{oauth_url}"] == sub_id
+
+
+def test_get_or_create_user_from_payload_creates_user_with_sub():
+ oauth_url = "https://saleor.io/oauth"
+ sub_id = "oauth|1234"
+ customer_email = "[email protected]"
+
+ user_from_payload = get_or_create_user_from_payload(
+ payload={"sub": sub_id, "email": customer_email},
+ oauth_url=oauth_url,
+ )
+
+ assert user_from_payload.email == customer_email
+ assert user_from_payload.private_metadata[f"oidc-{oauth_url}"] == sub_id
+
+
+def test_get_or_create_user_from_payload_multiple_subs(customer_user, admin_user):
+ oauth_url = "https://saleor.io/oauth"
+ sub_id = "oauth|1234"
+
+ customer_user.private_metadata = {f"oidc-{oauth_url}": sub_id}
+ customer_user.save()
+
+ admin_user.private_metadata = {f"oidc-{oauth_url}": sub_id}
+ admin_user.save()
+
+ with warnings.catch_warnings(record=True):
+ user_from_payload = get_or_create_user_from_payload(
+ payload={"sub": sub_id, "email": customer_user.email},
+ oauth_url=oauth_url,
+ )
+
+ assert user_from_payload.email == customer_user.email
+ assert user_from_payload.private_metadata[f"oidc-{oauth_url}"] == sub_id
+
+
+def test_get_or_create_user_from_payload_different_email(customer_user):
+ oauth_url = "https://saleor.io/oauth"
+ sub_id = "oauth|1234"
+ new_customer_email = "[email protected]"
+
+ customer_user.private_metadata = {f"oidc-{oauth_url}": sub_id}
+ customer_user.save()
+
+ user_from_payload = get_or_create_user_from_payload(
+ payload={"sub": sub_id, "email": new_customer_email},
+ oauth_url=oauth_url,
+ )
+
+ customer_user.refresh_from_db()
+ assert user_from_payload.id == customer_user.id
+ assert customer_user.email == new_customer_email
+ assert customer_user.private_metadata[f"oidc-{oauth_url}"] == sub_id
+
+
+@freeze_time("2019-03-18 12:00:00")
+def test_get_or_create_user_from_payload_with_last_login(customer_user, settings):
+ settings.TIME_ZONE = "UTC"
+ current_ts = int(time.time())
+
+ oauth_url = "https://saleor.io/oauth"
+ sub_id = "oauth|1234"
+
+ customer_user.last_login = make_aware(
+ datetime.fromtimestamp(current_ts - 10), timezone=pytz.timezone("UTC")
+ )
+ customer_user.save()
+
+ user_from_payload = get_or_create_user_from_payload(
+ payload={"sub": sub_id, "email": customer_user.email},
+ oauth_url=oauth_url,
+ last_login=current_ts,
+ )
+
+ customer_user.refresh_from_db()
+ assert customer_user.last_login == make_aware(
+ datetime.fromtimestamp(current_ts), timezone=pytz.timezone("UTC")
+ )
+ assert user_from_payload.email == customer_user.email
+ assert user_from_payload.private_metadata[f"oidc-{oauth_url}"] == sub_id
diff --git a/saleor/plugins/openid_connect/utils.py b/saleor/plugins/openid_connect/utils.py
new file mode 100644
index 0000000000..0789537add
--- /dev/null
+++ b/saleor/plugins/openid_connect/utils.py
@@ -0,0 +1,559 @@
+import json
+import logging
+from datetime import datetime
+from typing import List, Optional
+
+import requests
+from authlib.jose import JWTClaims, jwt
+from authlib.jose.errors import DecodeError, JoseError
+from authlib.oidc.core import CodeIDToken
+from django.contrib.auth.models import Permission
+from django.core.cache import cache
+from django.core.exceptions import ValidationError
+from django.core.validators import URLValidator
+from django.db.models import QuerySet
+from django.middleware.csrf import _compare_masked_tokens # type: ignore
+from django.middleware.csrf import _get_new_csrf_token
+from django.utils.timezone import make_aware
+from jwt import PyJWTError
+
+from ...account.models import User
+from ...core.jwt import (
+ JWT_ACCESS_TYPE,
+ JWT_OWNER_FIELD,
+ JWT_REFRESH_TYPE,
+ PERMISSIONS_FIELD,
+ jwt_decode,
+ jwt_encode,
+ jwt_user_payload,
+)
+from ...core.permissions import get_permission_names, get_permissions_from_codenames
+from ..error_codes import PluginErrorCode
+from ..models import PluginConfiguration
+from . import PLUGIN_ID
+from .const import SALEOR_STAFF_PERMISSION
+from .exceptions import AuthenticationError
+
+JWKS_KEY = "oauth_jwks"
+JWKS_CACHE_TIME = 60 * 60 # 1 hour
+USER_INFO_DEFAULT_CACHE_TIME = 60 * 60 # 1 hour
+
+REQUEST_TIMEOUT = 5
+
+
+OAUTH_TOKEN_REFRESH_FIELD = "oauth_refresh_token"
+CSRF_FIELD = "csrf_token"
+
+
+logger = logging.getLogger(__name__)
+
+
+def fetch_jwks(jwks_url) -> Optional[dict]:
+ """Fetch JSON Web Key Sets from a provider.
+
+ Fetched keys will be stored in the cache to the reduced amount of possible
+ requests.
+ :raises AuthenticationError
+ """
+ response = None
+ try:
+ response = requests.get(jwks_url, timeout=REQUEST_TIMEOUT)
+ response.raise_for_status()
+ jwks = response.json()
+ except requests.exceptions.RequestException:
+ logger.exception("Unable to fetch jwks from %s", jwks_url)
+ raise AuthenticationError("Unable to finalize the authentication process.")
+ except json.JSONDecodeError:
+ content = response.content if response else "Unable to find the response"
+ logger.exception(
+ "Unable to decode the response from auth service with jwks. "
+ "Response: %s",
+ content,
+ )
+ raise AuthenticationError("Unable to finalize the authentication process.")
+ keys = jwks.get("keys", [])
+ if not keys:
+ logger.warning("List of JWKS keys is empty")
+ cache.set(JWKS_KEY, keys, JWKS_CACHE_TIME)
+ return keys
+
+
+def get_jwks_keys_from_cache_or_fetch(jwks_url: str) -> dict:
+ jwks_keys = cache.get(JWKS_KEY)
+ if jwks_keys is None:
+ jwks_keys = fetch_jwks(jwks_url)
+ return jwks_keys
+
+
+def get_user_info_from_cache_or_fetch(
+ user_info_url: str, access_token: str, exp_time: Optional[int]
+) -> Optional[dict]:
+ user_info_data = cache.get(f"{PLUGIN_ID}.{access_token}", None)
+
+ if not user_info_data:
+ user_info_data = get_user_info(user_info_url, access_token)
+ cache_time = USER_INFO_DEFAULT_CACHE_TIME
+
+ if exp_time:
+ now_ts = int(datetime.now().timestamp())
+ exp_delta = exp_time - now_ts
+ cache_time = exp_delta if exp_delta > 0 else cache_time
+
+ if user_info_data:
+ cache.set(f"{PLUGIN_ID}.{access_token}", user_info_data, cache_time)
+
+ # user_info_data is None when we were not able to use an access token to fetch
+ # the user info data
+ return user_info_data
+
+
+def get_user_info(user_info_url, access_token) -> Optional[dict]:
+ try:
+ response = requests.get(
+ user_info_url,
+ headers={"Authorization": f"Bearer {access_token}"},
+ timeout=REQUEST_TIMEOUT,
+ )
+ response.raise_for_status()
+ return response.json()
+ except requests.exceptions.HTTPError as e:
+ logger.warning(
+ "Fetching OIDC user info failed. HTTP error occurred",
+ extra={"user_info_url": user_info_url, "error": e},
+ )
+ return None
+ except requests.exceptions.RequestException as e:
+ logger.warning(
+ "Fetching OIDC user info failed",
+ extra={"user_info_url": user_info_url, "error": e},
+ )
+ return None
+ except json.JSONDecodeError as e:
+ logger.warning(
+ "Invalid OIDC user info response",
+ extra={"user_info_url": user_info_url, "error": e},
+ )
+ return None
+
+
+def decode_access_token(token, jwks_url):
+ try:
+ return get_decoded_token(token, jwks_url)
+ except (JoseError, ValueError) as e:
+ logger.info(
+ "Invalid OIDC access token format", extra={"error": e, "jwks_url": jwks_url}
+ )
+ return None
+
+
+def get_user_from_oauth_access_token_in_jwt_format(
+ token_payload: JWTClaims,
+ user_info_url: str,
+ access_token: str,
+ use_scope_permissions: bool,
+ audience: str,
+):
+ try:
+ token_payload.validate()
+ except (JoseError, ValueError) as e:
+ logger.info(
+ "OIDC access token validation failed",
+ extra={"error": e, "user_info_url": user_info_url},
+ )
+ return None
+
+ user_info = get_user_info_from_cache_or_fetch(
+ user_info_url,
+ access_token,
+ token_payload["exp"],
+ )
+ if not user_info:
+ logger.info(
+ "Failed to fetch user info for a valid OIDC access token",
+ extra={"token_exp": token_payload["exp"], "user_info_url": user_info_url},
+ )
+ return None
+
+ try:
+ user = get_or_create_user_from_payload(
+ user_info, user_info_url, last_login=token_payload.get("iat")
+ )
+ except AuthenticationError as e:
+ logger.info("Unable to create a user object", extra={"error": e})
+ return None
+
+ scope = token_payload.get("scope")
+ token_permissions = token_payload.get("permissions", [])
+
+ # check if token contains expected aud
+ aud = token_payload.get("aud")
+ if not audience:
+ audience_in_token = False
+ elif isinstance(aud, list):
+ audience_in_token = audience in aud
+ else:
+ audience_in_token = audience == aud
+
+ is_staff_id = SALEOR_STAFF_PERMISSION
+
+ if use_scope_permissions and audience_in_token:
+ permissions = get_saleor_permissions_qs_from_scope(scope)
+ if not permissions and token_permissions:
+ permissions = get_saleor_permissions_from_list(token_permissions)
+ user.effective_permissions = permissions
+ is_staff_in_scope = is_staff_id in scope
+ is_staff_in_token_permissions = is_staff_id in token_permissions
+ if is_staff_in_scope or is_staff_in_token_permissions or permissions:
+ if not user.is_staff:
+ user.is_staff = True
+ user.save(update_fields=["is_staff"])
+ elif user.is_staff:
+ user.is_staff = False
+ user.save(update_fields=["is_staff"])
+ else:
+ user.is_staff = False
+
+ return user
+
+
+def get_user_from_oauth_access_token(
+ access_token: str,
+ jwks_url: str,
+ user_info_url: str,
+ use_scope_permissions: bool,
+ audience: str,
+):
+ # we try to decode token to define if the structure is a jwt format.
+ access_token_jwt_payload = decode_access_token(access_token, jwks_url)
+ if access_token_jwt_payload:
+ return get_user_from_oauth_access_token_in_jwt_format(
+ access_token_jwt_payload,
+ user_info_url=user_info_url,
+ access_token=access_token,
+ use_scope_permissions=use_scope_permissions,
+ audience=audience,
+ )
+
+ user_info = get_user_info_from_cache_or_fetch(
+ user_info_url, access_token, exp_time=None
+ )
+ if not user_info:
+ logger.info(
+ "Failed to fetch OIDC user info", extra={"user_info_url": user_info_url}
+ )
+ return None
+ user = get_or_create_user_from_payload(user_info, oauth_url=user_info_url)
+ if not use_scope_permissions:
+ user.is_staff = False
+ return user
+
+
+def create_jwt_token(
+ id_payload: CodeIDToken,
+ user: User,
+ access_token: str,
+ permissions: Optional[List[str]],
+ owner: str,
+) -> str:
+ additional_payload = {
+ "exp": id_payload["exp"],
+ "oauth_access_key": access_token,
+ }
+ if permissions is not None:
+ additional_payload[PERMISSIONS_FIELD] = permissions
+
+ jwt_payload = jwt_user_payload(
+ user,
+ JWT_ACCESS_TYPE,
+ exp_delta=None, # we pass exp from auth service, in additional_payload
+ additional_payload=additional_payload,
+ token_owner=owner,
+ )
+ return jwt_encode(jwt_payload)
+
+
+def create_jwt_refresh_token(user: User, refresh_token: str, csrf: str, owner: str):
+ additional_payload = {
+ OAUTH_TOKEN_REFRESH_FIELD: refresh_token,
+ CSRF_FIELD: csrf,
+ }
+ jwt_payload = jwt_user_payload(
+ user,
+ JWT_REFRESH_TYPE,
+ # oauth_refresh_token has own expiration time. No need to duplicate it here
+ exp_delta=None,
+ additional_payload=additional_payload,
+ token_owner=owner,
+ )
+ return jwt_encode(jwt_payload)
+
+
+def get_decoded_token(token, jwks_url, claims_cls=None):
+ keys = get_jwks_keys_from_cache_or_fetch(jwks_url)
+ decoded_token = jwt.decode(token, keys, claims_cls=claims_cls)
+ return decoded_token
+
+
+def get_parsed_id_token(token_data, jwks_url) -> CodeIDToken:
+ id_token = token_data.get("id_token")
+ if not id_token:
+ raise AuthenticationError("Missing ID Token.")
+ try:
+ decoded_token = get_decoded_token(id_token, jwks_url, CodeIDToken)
+ decoded_token.validate()
+ return decoded_token
+ except DecodeError:
+ logger.warning("Unable to decode provided token", exc_info=True)
+ raise AuthenticationError("Unable to decode provided token")
+ except (JoseError, ValueError):
+ logger.warning("Token validation failed", exc_info=True)
+ raise AuthenticationError("Token validation failed")
+
+
+def get_or_create_user_from_payload(
+ payload: dict, oauth_url: str, last_login: Optional[int] = None
+) -> User:
+ oidc_metadata_key = f"oidc-{oauth_url}"
+ user_email = payload.get("email")
+ if not user_email:
+ raise AuthenticationError("Missing user's email.")
+
+ sub = payload.get("sub")
+ get_kwargs = {"private_metadata__contains": {oidc_metadata_key: sub}}
+ if not sub:
+ get_kwargs = {"email": user_email}
+ logger.warning("Missing sub section in OIDC payload")
+
+ defaults_create = {
+ "is_active": True,
+ "email": user_email,
+ "first_name": payload.get("given_name", ""),
+ "last_name": payload.get("family_name", ""),
+ "private_metadata": {oidc_metadata_key: sub},
+ }
+ try:
+ user = User.objects.get(**get_kwargs)
+ except User.DoesNotExist:
+ user, _ = User.objects.get_or_create(
+ email=user_email,
+ defaults=defaults_create,
+ )
+ except User.MultipleObjectsReturned:
+ logger.warning("Multiple users returned for single OIDC sub ID")
+ user, _ = User.objects.get_or_create(
+ email=user_email,
+ defaults=defaults_create,
+ )
+
+ if not user.is_active: # it is true only if we fetch disabled user.
+ raise AuthenticationError("Unable to log in.")
+
+ _update_user_details(
+ user=user,
+ oidc_key=oidc_metadata_key,
+ user_email=user_email,
+ sub=sub, # type: ignore
+ last_login=last_login,
+ )
+
+ return user
+
+
+def _update_user_details(
+ user: User, oidc_key: str, user_email: str, sub: str, last_login: Optional[int]
+):
+ user_sub = user.get_value_from_private_metadata(oidc_key)
+ fields_to_save = []
+ if user_sub != sub:
+ user.store_value_in_private_metadata({oidc_key: sub})
+ fields_to_save.append("private_metadata")
+
+ if user.email != user_email:
+ if User.objects.filter(email=user_email).exists():
+ logger.warning(
+ "Unable to update user email as the new one already exists in DB",
+ extra={"oidc_key": oidc_key},
+ )
+ return
+ user.email = user_email
+ fields_to_save.append("email")
+ if last_login:
+ if not user.last_login or user.last_login.timestamp() < last_login:
+ login_time = make_aware(datetime.fromtimestamp(last_login))
+ user.last_login = login_time
+ fields_to_save.append("last_login")
+
+ if fields_to_save:
+ user.save(update_fields=fields_to_save)
+
+
+def get_user_from_token(claims: CodeIDToken) -> User:
+ user_email = claims.get("email")
+ if not user_email:
+ raise AuthenticationError("Missing user's email.")
+ user = User.objects.filter(email=user_email, is_active=True).first()
+ if not user:
+ raise AuthenticationError("User does not exist.")
+ return user
+
+
+def is_owner_of_token_valid(token: str, owner: str) -> bool:
+ try:
+ payload = jwt_decode(token, verify_expiration=False)
+ return payload.get(JWT_OWNER_FIELD, "") == owner
+ except Exception:
+ return False
+
+
+def create_tokens_from_oauth_payload(
+ token_data: dict,
+ user: User,
+ claims: CodeIDToken,
+ permissions: Optional[List[str]],
+ owner: str,
+):
+ refresh_token = token_data.get("refresh_token")
+ access_token = token_data.get("access_token", "")
+
+ tokens = {
+ "token": create_jwt_token(claims, user, access_token, permissions, owner),
+ }
+ if refresh_token:
+ csrf_token = _get_new_csrf_token()
+ tokens["refresh_token"] = create_jwt_refresh_token(
+ user, refresh_token, csrf_token, owner
+ )
+ tokens["csrf_token"] = csrf_token
+ return tokens
+
+
+def validate_refresh_token(refresh_token, data):
+ csrf_token = data.get("csrfToken")
+ if not refresh_token:
+ raise ValidationError(
+ {
+ "refreshToken": ValidationError(
+ "Missing token.", code=PluginErrorCode.NOT_FOUND.value
+ )
+ }
+ )
+
+ try:
+ refresh_payload = jwt_decode(refresh_token, verify_expiration=True)
+ except PyJWTError:
+ raise ValidationError(
+ {
+ "refreshToken": ValidationError(
+ "Unable to decode the refresh token.",
+ code=PluginErrorCode.INVALID.value,
+ )
+ }
+ )
+
+ if not data.get("refreshToken"):
+ if not refresh_payload.get(CSRF_FIELD):
+ raise ValidationError(
+ {
+ CSRF_FIELD: ValidationError(
+ "Missing CSRF token in refresh payload.",
+ code=PluginErrorCode.INVALID.value,
+ )
+ }
+ )
+ if not csrf_token:
+ raise ValidationError(
+ {
+ "csrfToken": ValidationError(
+ "CSRF token needs to be provided.",
+ code=PluginErrorCode.INVALID.value,
+ )
+ }
+ )
+ is_valid = _compare_masked_tokens(csrf_token, refresh_payload[CSRF_FIELD])
+ if not is_valid:
+ raise ValidationError(
+ {
+ "csrfToken": ValidationError(
+ "CSRF token doesn't match.",
+ code=PluginErrorCode.INVALID.value,
+ )
+ }
+ )
+
+
+def get_incorrect_or_missing_urls(urls: dict) -> List[str]:
+ validator = URLValidator()
+ incorrect_urls = []
+ for field, url in urls.items():
+ try:
+ validator(url)
+ except ValidationError:
+ incorrect_urls.append(field)
+ return incorrect_urls
+
+
+def get_incorrect_fields(plugin_configuration: "PluginConfiguration"):
+ """Return missing or incorrect configuration fields for OpenIDConnectPlugin."""
+ configuration = plugin_configuration.configuration
+ configuration = {item["name"]: item["value"] for item in configuration}
+ incorrect_fields = []
+ if plugin_configuration.active:
+ urls_to_validate = {}
+ if any(
+ [configuration["oauth_authorization_url"], configuration["oauth_token_url"]]
+ ):
+ urls_to_validate.update(
+ {
+ "json_web_key_set_url": configuration["json_web_key_set_url"],
+ "oauth_authorization_url": configuration["oauth_authorization_url"],
+ "oauth_token_url": configuration["oauth_token_url"],
+ }
+ )
+
+ elif configuration["user_info_url"]:
+ urls_to_validate.update(
+ {
+ "json_web_key_set_url": configuration["json_web_key_set_url"],
+ "user_info_url": configuration["user_info_url"],
+ }
+ )
+ else:
+ incorrect_fields.extend(
+ [
+ "json_web_key_set_url",
+ "oauth_authorization_url",
+ "oauth_token_url",
+ "user_info_url",
+ ]
+ )
+
+ incorrect_fields.extend(get_incorrect_or_missing_urls(urls_to_validate))
+ if not configuration["client_id"]:
+ incorrect_fields.append("client_id")
+ if not configuration["client_secret"]:
+ incorrect_fields.append("client_secret")
+ return incorrect_fields
+
+
+def get_saleor_permissions_qs_from_scope(scope: str) -> QuerySet[Permission]:
+ scope_list = scope.lower().strip().split()
+ return get_saleor_permissions_from_list(scope_list)
+
+
+def get_saleor_permissions_from_list(permissions: list) -> QuerySet[Permission]:
+ saleor_permissions_str = [s for s in permissions if s.startswith("saleor:")]
+ if SALEOR_STAFF_PERMISSION in saleor_permissions_str:
+ saleor_permissions_str.remove(SALEOR_STAFF_PERMISSION)
+ if not saleor_permissions_str:
+ return Permission.objects.none()
+
+ permission_codenames = list(
+ map(lambda perm: perm.replace("saleor:", ""), saleor_permissions_str)
+ )
+ permissions = get_permissions_from_codenames(permission_codenames)
+ return permissions
+
+
+def get_saleor_permission_names(permissions: QuerySet) -> List[str]:
+ permission_names = get_permission_names(permissions)
+ return list(permission_names)
diff --git a/saleor/settings.py b/saleor/settings.py
index 927d3784c1..7c970ba890 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -613,6 +613,7 @@ BUILTIN_PLUGINS = [
"saleor.plugins.user_email.plugin.UserEmailPlugin",
"saleor.plugins.admin_email.plugin.AdminEmailPlugin",
"saleor.plugins.sendgrid.plugin.SendgridEmailPlugin",
+ "saleor.plugins.openid_connect.plugin.OpenIDConnectPlugin",
]
# Plugin discovery