Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

OAuth2 DAGs and Machinery (#246)

Madison Swain-Bowden3464826dc21a
diff --git a/justfile b/justfile
index c6fb438a1..051762623 100644
--- a/justfile
+++ b/justfile
@@ -52,19 +52,31 @@ deploy:
lint:
pre-commit run --all-files
-# Run pytest using the webserver image
-test pytestargs="": up
+# Mount the tests directory and run a particular command
+@_mount-tests command: up
# The test directory is mounted into the container only during testing
docker-compose {{ DOCKER_FILES }} run \
-v {{ justfile_directory() }}/tests:/usr/local/airflow/tests/ \
--rm \
{{ SERVICE }} \
- /usr/local/airflow/.local/bin/pytest {{ pytestargs }}
+ {{ command }}
+
+# Run a container that can be used for repeated interactive testing
+test-session:
+ @just _mount-tests bash
+
+# Run pytest using the webserver image
+test pytestargs="":
+ @just _mount-tests /usr/local/airflow/.local/bin/pytest {{ pytestargs }}
# Open a shell into the webserver container
shell: up
docker-compose {{ DOCKER_FILES }} exec {{ SERVICE }} /bin/bash
+# Launch an IPython REPL within the webserver container
+ipython: up
+ docker-compose {{ DOCKER_FILES }} exec -w /usr/local/airflow/openverse_catalog/dags {{ SERVICE }} /usr/local/airflow/.local/bin/ipython
+
# Run a given airflow command using the webserver image
airflow command="": up
docker-compose {{ DOCKER_FILES }} exec {{ SERVICE }} airflow {{ command }}
diff --git a/openverse_catalog/dags/common/requester.py b/openverse_catalog/dags/common/requester.py
index 5cd1a5676..13523f71b 100644
--- a/openverse_catalog/dags/common/requester.py
+++ b/openverse_catalog/dags/common/requester.py
@@ -1,6 +1,7 @@
import logging
import time
+import oauth2
import requests
@@ -24,6 +25,7 @@ class DelayedRequester:
def __init__(self, delay=0):
self._DELAY = delay
self._last_request = 0
+ self.session = requests.Session()
def get(self, url, params=None, **kwargs):
"""
@@ -38,7 +40,7 @@ class DelayedRequester:
self._delay_processing()
self._last_request = time.time()
try:
- response = requests.get(url, params=params, **kwargs)
+ response = self.session.get(url, params=params, **kwargs)
if response.status_code == requests.codes.ok:
logger.info(f"Received response from url {response.url}")
return response
@@ -90,3 +92,10 @@ class DelayedRequester:
)
return response_json
+
+
+class OAuth2DelayedRequester(DelayedRequester):
+ def __init__(self, provider_name: str, delay: int = 0):
+ super().__init__(delay)
+ # Replace session with Oauth one
+ self.session = oauth2.get_oauth_client(provider_name)
diff --git a/openverse_catalog/dags/oauth2/README.md b/openverse_catalog/dags/oauth2/README.md
new file mode 100644
index 000000000..40cdfced0
--- /dev/null
+++ b/openverse_catalog/dags/oauth2/README.md
@@ -0,0 +1,132 @@
+# OAuth2 Setup
+
+## TL;DR
+
+- Provider secrets (e.g. `client_id`, etc.) are stored in the `OAUTH2_PROVIDER_SECRETS` Variable.
+- Authorization tokens (one time use) are stored in `OAUTH2_AUTH_KEYS`.
+- Access/refresh token pairs are stored in `OAUTH2_ACCESS_TOKENS`.
+- The Authorization DAG can be run as needed to authorize (or re-authorize) providers.
+- The Token Refresh DAG is run every 12 hours and refreshes all tokens currently stored.
+- Use the [`OAuth2DelayedRequester`](../common/requester.py) in a provider API script that requires OAuth2
+
+## Overview
+
+The functions and DAGs defined in this module provide a mechanism for generating and maintaining the tokens necessary for interacting with sources that require OAuth2 authentication.
+
+OAuth2 providers are authenticated through a three-step mechanism:
+1. Initiate authorization
+2. Use authorization to create authentication tokens
+3. (sometime later) Refresh the authentication tokens as needed
+
+The authentication tokens that are created as a result of step 2 above can be used in subsequent requests to the service to access resources that are only made available to authenticated clients.
+The expiration time for an access token differs by service.
+If a token expires before it is refreshed, the authorization step will need to be restarted from step 1.
+
+## Variables
+
+We are using three Airflow variables to store the information related to OAuth2:
+- `OAUTH2_PROVIDER_SECRETS`
+- `OAUTH2_AUTH_KEYS`
+- `OAUTH2_ACCESS_TOKENS`
+
+### `OAUTH2_PROVIDER_SECRETS`
+
+This Variable holds the provider secrets which are necessary for initiating authorization.
+At minimum, this must have a `client_id` value per-provider, and different providers may require more information.
+
+**Format**:
+```json
+{
+ "provider1": {
+ "client_id": "<p_1_client>"
+ },
+ "provider2": {
+ "client_id": "<p_2_client>",
+ "client_secret": "<p_2_secret>"
+ },
+ "provider3": {
+ "client_id": "<p_3_client>",
+ "auth_level": "<sample_val>"
+ }
+}
+```
+
+### `OAUTH2_AUTH_KEYS`
+
+This Variable holds any authorization keys that are needed to generate an access/refresh token pair for a provider.
+It will typically remain empty until one (or more) providers need new keys.
+Once this Variable has been populated, the Authorization DAG can be run.
+
+**Format**:
+```json
+{
+ "provider1": "<auth_key_1>",
+ "provider2": "<auth_key_2>"
+}
+```
+
+### `OAUTH2_ACCESS_TOKENS`
+
+This variable holds the access/refresh token pairs for all authorized providers.
+These values are updated automatically and **should not** need to be touched/modified directly.
+The Authorization DAG and Token Refresh DAG will populate it.
+
+**Format**:
+```json
+{
+ "provider1": {
+ "access_token": "<p_1_access>",
+ "refresh_token": "<p_1_refresh>",
+ },
+ "provider2": {
+ "access_token": "<p_2_access>",
+ "refresh_token": "<p_2_refresh>"
+ }
+}
+```
+
+## DAGs
+
+### Authorization DAG
+
+**File:** [`authorize_dag.py`](authorize_dag.py)
+
+This DAG will use any available authorization tokens to generate an access/refresh token pair for a provider.
+It is run as-needed once the appropriate Variable has been updated.
+
+### Token Refresh DAG
+
+**File:** [`token_refresh_dag.py`](token_refresh_dag.py)
+
+This DAG refreshes the access/token pairs for all providers.
+In order to prevent tokens from expiring, it is scheduled every 12 hours.
+
+If a provider is defined but it does not have any access/token pairs entered, the task for that provider will be skipped.
+If a provider's keys have expired, the refresh (and the task) will fail.
+
+## Authorization URLs
+
+Each provider uses a different base URL for initiating the authorization process.
+This library can assist with generating a `client_id`-specific URL for each provider.
+In order to create an authorization URL, the provider's secrets must be present (see [above](#oauth2_provider_secrets)).
+
+Example:
+```python
+In [1]: import oauth2
+
+In [2]: client = oauth2.get_oauth_client("freesound")
+
+In [3]: client.authorization_url("https://freesound.org/apiv2/oauth2/authorize/")
+Out[3]:
+('https://freesound.org/apiv2/oauth2/authorize/?response_type=code&client_id=[redacted]&state=aZz039X8nhzo1yt0iE2e7U4pqf8yTu',
+ 'aZz039X8nhzo1yt0iE2e7U4pqf8yTu')
+```
+
+### Known Authorization URLs:
+
+1. [Freesound](https://freesound.org/docs/api/authentication.html#oauth2-authentication): https://freesound.org/apiv2/oauth2/authorize/
+
+## Integration with Provider API Scripts
+
+Once everything is set up for an OAuth2 provider, the [`OAuth2DelayedRequester`](../common/requester.py) can be used instead of the `DelayedRequester` for the provider API script.
+No other changes are necessary!
diff --git a/openverse_catalog/dags/oauth2/__init__.py b/openverse_catalog/dags/oauth2/__init__.py
new file mode 100644
index 000000000..c2c8ad94c
--- /dev/null
+++ b/openverse_catalog/dags/oauth2/__init__.py
@@ -0,0 +1,8 @@
+from .oauth2 import ( # noqa: F401
+ OAUTH2_AUTH_KEY,
+ OAUTH2_TOKEN_KEY,
+ OAUTH_PROVIDERS,
+ authorize_providers,
+ get_oauth_client,
+ refresh,
+)
diff --git a/openverse_catalog/dags/oauth2/authorize_dag.py b/openverse_catalog/dags/oauth2/authorize_dag.py
new file mode 100644
index 000000000..2b026ab33
--- /dev/null
+++ b/openverse_catalog/dags/oauth2/authorize_dag.py
@@ -0,0 +1,56 @@
+"""
+# OAuth Provider Authorization
+
+**Author**: Madison Swain-Bowden
+
+**Created**: 2021-10-13
+
+"""
+from datetime import datetime
+
+import oauth2
+from airflow.models import DAG
+from airflow.operators.python import PythonOperator
+
+
+dag = DAG(
+ dag_id="oauth2_authorization",
+ schedule_interval=None,
+ description="Authorization workflow for all Oauth2 providers.",
+ max_active_runs=1,
+ catchup=False,
+ default_args={
+ "owner": "data-eng-admin",
+ "depends_on_past": False,
+ "start_date": datetime(2021, 1, 1),
+ "email_on_retry": False,
+ "retries": 0,
+ },
+)
+
+_current_providers = [
+ f"- {provider.name.title()}\n" for provider in oauth2.OAUTH_PROVIDERS
+]
+
+dag.doc_md = (
+ __doc__
+ + f"""
+
+Iterates through all the OAuth2 providers and attempts to authorize them using tokens
+found in the in the `{oauth2.OAUTH2_AUTH_KEY}` Variable. Once authorization has been
+completed successfully, the auth token is removed from that Variable. The authorization
+will create an access/refresh token pair in the `{oauth2.OAUTH2_TOKEN_KEY}` Variable.
+
+**Current Providers**:
+
+{"".join(_current_providers)}
+"""
+)
+
+
+with dag:
+ PythonOperator(
+ task_id="authorize_providers",
+ python_callable=oauth2.authorize_providers,
+ op_kwargs={"providers": oauth2.OAUTH_PROVIDERS},
+ )
diff --git a/openverse_catalog/dags/oauth2/oauth2.py b/openverse_catalog/dags/oauth2/oauth2.py
new file mode 100644
index 000000000..8cab8814b
--- /dev/null
+++ b/openverse_catalog/dags/oauth2/oauth2.py
@@ -0,0 +1,139 @@
+import logging
+from typing import Any, Collection, NamedTuple
+
+from airflow.exceptions import AirflowSkipException
+from airflow.models import Variable
+from requests_oauthlib import OAuth2Session
+
+
+log = logging.getLogger(__name__)
+
+
+class OauthProvider(NamedTuple):
+ """Representation of the information needed to define an OAuth2 provider."""
+
+ name: str
+ auth_url: str
+ refresh_url: str
+
+
+OAUTH2_TOKEN_KEY = "OAUTH2_ACCESS_TOKENS"
+OAUTH2_AUTH_KEY = "OAUTH2_AUTH_KEYS"
+OAUTH2_PROVIDERS_KEY = "OAUTH2_PROVIDER_SECRETS"
+OAUTH_PROVIDERS = [
+ OauthProvider(
+ name="freesound",
+ auth_url="https://freesound.org/apiv2/oauth2/access_token/",
+ refresh_url="https://freesound.org/apiv2/oauth2/access_token/",
+ ),
+]
+
+
+def _var_get(key: str) -> dict[str, Any]:
+ """
+ Helper function for Variable retrieval with deserialization and dictionary default.
+ """
+ return Variable.get(key, default_var={}, deserialize_json=True)
+
+
+def _update_tokens(
+ provider_name: str,
+ tokens: dict[str, str],
+) -> None:
+ """
+ Update the access/refresh tokens for a specific provider in the Airflow Variable
+ store. This update does not affect the tokens for any other existing providers.
+ """
+ log.info(f"Updating tokens for provider: {provider_name}")
+ current_tokens = _var_get(OAUTH2_TOKEN_KEY)
+ current_tokens[provider_name] = {
+ "access_token": tokens["access_token"],
+ "refresh_token": tokens["refresh_token"],
+ }
+ Variable.set(OAUTH2_TOKEN_KEY, current_tokens, serialize_json=True)
+
+
+def _get_provider_secrets(
+ name: str, provider_secrets: dict[str, dict] = None
+) -> dict[str, str]:
+ """
+ Retrieve provider secrets from the Airflow Variable store. Optionally provide
+ a previously retrieved Variable value for improved performance.
+
+ Providers are expected to *at least* have a `client_id`, and may have more
+ information defined as necessary.
+ """
+ if provider_secrets is None:
+ provider_secrets = _var_get(OAUTH2_PROVIDERS_KEY)
+ secrets = provider_secrets.get(name)
+ if secrets is None or "client_id" not in secrets:
+ raise ValueError(
+ f"Authorization requested for provider {name} but no secrets "
+ f"were provided! Add secrets to the {OAUTH2_PROVIDERS_KEY} Variable and"
+ f" ensure the provider has a client_id."
+ )
+ return secrets
+
+
+def get_oauth_client(provider_name: str) -> OAuth2Session:
+ """
+ Create an OAuth2 client. This client behaves like a `requests.Session` instance,
+ but will automatically add the authorization necessary for a particular provider.
+ """
+ secrets = _get_provider_secrets(provider_name)
+ tokens = _var_get(OAUTH2_TOKEN_KEY)
+ if provider_name not in tokens:
+ raise KeyError(f"Access token not found for provider {provider_name}")
+ return OAuth2Session(
+ client_id=secrets["client_id"],
+ token={**tokens[provider_name], "token_type": "Bearer"},
+ )
+
+
+def authorize_providers(providers: Collection[OauthProvider]) -> None:
+ """
+ Iterate through all of the specified providers and authorize those that may need it.
+ The authorization flow will only be attempted if a provider has an authorization
+ key defined in the Airflow Variable store.
+ """
+ provider_secrets = _var_get(OAUTH2_PROVIDERS_KEY)
+ auth_tokens = _var_get(OAUTH2_AUTH_KEY)
+ for provider in providers:
+ # Only authorize if a token was provided
+ if provider.name not in auth_tokens:
+ continue
+ auth_token = auth_tokens[provider.name]
+ log.info(f"Attempting to authorize provider: {provider.name}")
+ secrets = _get_provider_secrets(provider.name, provider_secrets)
+ client = OAuth2Session(secrets["client_id"])
+ # NOTE: It's possible that the secrets being stored might not all be needed
+ # here, and may in fact be rejected. We won't know until we add more providers.
+ tokens = client.fetch_token(provider.auth_url, code=auth_token, **secrets)
+ _update_tokens(provider.name, tokens)
+ # Remove the auth token since it is no longer needed nor accurate
+ auth_tokens.pop(provider.name)
+ Variable.set(OAUTH2_AUTH_KEY, auth_tokens, serialize_json=True)
+
+
+def refresh(provider: OauthProvider) -> None:
+ """
+ Refresh the tokens for a given provider. This will use the stored refresh token to
+ attempt a fetch of a new access/refresh token pair. The new tokens will be updated
+ in the Airflow Variable store. Raises an AirflowSkipException if no tokens are
+ defined for the provider.
+ """
+ current_tokens = _var_get(OAUTH2_TOKEN_KEY)
+ if provider.name not in current_tokens:
+ raise AirflowSkipException(
+ f"Provider {provider.name} had no stored tokens, it may need to be "
+ f"authorized first."
+ )
+ refresh_token = current_tokens[provider.name]["refresh_token"]
+ secrets = _get_provider_secrets(provider.name)
+ client = OAuth2Session(secrets["client_id"])
+ log.info(f"Attempting token refresh for provider: {provider.name}")
+ # NOTE: Same as above, **secrets may be too much info for some requests.
+ new_tokens = client.refresh_token(
+ provider.refresh_url, refresh_token=refresh_token, **secrets
+ )
+ _update_tokens(provider.name, new_tokens)
diff --git a/openverse_catalog/dags/oauth2/token_refresh_dag.py b/openverse_catalog/dags/oauth2/token_refresh_dag.py
new file mode 100644
index 000000000..5fe22e1cc
--- /dev/null
+++ b/openverse_catalog/dags/oauth2/token_refresh_dag.py
@@ -0,0 +1,55 @@
+"""
+# OAuth Provider Token Refresh
+
+**Author**: Madison Swain-Bowden
+
+**Created**: 2021-10-13
+"""
+from datetime import datetime
+
+import oauth2
+from airflow.models import DAG
+from airflow.operators.python import PythonOperator
+
+
+dag = DAG(
+ dag_id="oauth2_token_refresh",
+ schedule_interval="0 */12 * * *",
+ description="Refresh tokens for all Oauth2 providers",
+ max_active_runs=1,
+ catchup=False,
+ default_args={
+ "owner": "data-eng-admin",
+ "depends_on_past": False,
+ "start_date": datetime(2021, 1, 1),
+ "email_on_retry": False,
+ "retries": 0,
+ },
+)
+
+_current_providers = [
+ f"- {provider.name.title()}\n" for provider in oauth2.OAUTH_PROVIDERS
+]
+
+dag.doc_md = (
+ __doc__
+ + f"""
+
+Iterates through all OAuth2 providers and attempts to refresh the access token using
+the refresh token stored in the `{oauth2.OAUTH2_TOKEN_KEY}` Variable. This DAG will
+update the tokens stored in the Variable upon successful refresh.
+
+**Current Providers**:
+
+{"".join(_current_providers)}
+"""
+)
+
+
+with dag:
+ for provider in oauth2.OAUTH_PROVIDERS:
+ PythonOperator(
+ task_id=f"refresh__{provider.name}",
+ python_callable=oauth2.refresh,
+ op_kwargs={"provider": provider},
+ )
diff --git a/requirements_dev.txt b/requirements_dev.txt
index b82938124..67fe83908 100644
--- a/requirements_dev.txt
+++ b/requirements_dev.txt
@@ -1,4 +1,6 @@
-r requirements_prod.txt
+ipython==7.25.0
pytest-mock==3.6.1
+pytest-raises==0.11
pytest-socket==0.4.0
diff --git a/requirements_prod.txt b/requirements_prod.txt
index 51c28cadc..cdcd555e4 100644
--- a/requirements_prod.txt
+++ b/requirements_prod.txt
@@ -4,4 +4,5 @@ apache-airflow[amazon,postgres]==2.1.2
lxml==4.6.3
psycopg2-binary
requests-file==1.5.1
+requests-oauthlib==1.1.0
tldextract==3.1.0
diff --git a/tests/dags/common/test_requester.py b/tests/dags/common/test_requester.py
index 29367f3e4..a1fddd4b5 100644
--- a/tests/dags/common/test_requester.py
+++ b/tests/dags/common/test_requester.py
@@ -4,6 +4,9 @@ from unittest.mock import MagicMock, patch
import pytest
import requests
from common import requester
+from requests_oauthlib import OAuth2Session
+
+from tests.dags.conftest import FAKE_OAUTH_PROVIDER_NAME
def test_get_waits_before_getting(monkeypatch):
@@ -12,7 +15,7 @@ def test_get_waits_before_getting(monkeypatch):
def mock_requests_get(url, params, **kwargs):
return requests.Response()
- monkeypatch.setattr(requester.requests, "get", mock_requests_get)
+ monkeypatch.setattr(requester.requests.Session, "get", mock_requests_get)
dq = requester.DelayedRequester(delay)
s = time.time()
dq.get("https://google.com")
@@ -88,3 +91,9 @@ def test_get_response_json_returns_response_json_when_all_ok():
assert mock_get.call_count == 1
assert actual_response_json == expect_response_json
+
+
+def test_oauth_requester_initializes_correctly(oauth_provider_var_mock):
+ odq = requester.OAuth2DelayedRequester(FAKE_OAUTH_PROVIDER_NAME, 1)
+ assert isinstance(odq.session, OAuth2Session)
+ assert odq.session.client_id == "fakeclient"
diff --git a/tests/dags/conftest.py b/tests/dags/conftest.py
new file mode 100644
index 000000000..aa5d165c8
--- /dev/null
+++ b/tests/dags/conftest.py
@@ -0,0 +1,33 @@
+from unittest import mock
+
+import pytest
+from oauth2 import oauth2
+
+
+FAKE_OAUTH_PROVIDER_NAME = "fakeprovider"
+
+
+def _var_get_replacement(*args, **kwargs):
+ values = {
+ oauth2.OAUTH2_TOKEN_KEY: {
+ FAKE_OAUTH_PROVIDER_NAME: {
+ "access_token": "fakeaccess",
+ "refresh_token": "fakerefresh",
+ }
+ },
+ oauth2.OAUTH2_AUTH_KEY: {FAKE_OAUTH_PROVIDER_NAME: "fakeauthtoken"},
+ oauth2.OAUTH2_PROVIDERS_KEY: {
+ FAKE_OAUTH_PROVIDER_NAME: {
+ "client_id": "fakeclient",
+ "client_secret": "fakesecret",
+ }
+ },
+ }
+ return values[args[0]]
+
+
+def oauth_provider_var_mock():
+ with mock.patch("oauth2.oauth2.Variable") as MockVariable:
+ MockVariable.get.side_effect = _var_get_replacement
+ yield MockVariable
diff --git a/tests/dags/oauth2/__init__.py b/tests/dags/oauth2/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/dags/oauth2/test_oauth2.py b/tests/dags/oauth2/test_oauth2.py
new file mode 100644
index 000000000..1a7b2be51
--- /dev/null
+++ b/tests/dags/oauth2/test_oauth2.py
@@ -0,0 +1,124 @@
+from unittest import mock
+
+import pytest
+from airflow.exceptions import AirflowSkipException
+from oauth2 import oauth2
+
+from tests.dags.conftest import FAKE_OAUTH_PROVIDER_NAME
+
+
+FAKE_OAUTH_PROVIDER = oauth2.OauthProvider(
+ FAKE_OAUTH_PROVIDER_NAME, "auth_url", "refresh_url"
+)
+
+
+def test_var_get():
+ expected = "fakeval"
+ with mock.patch("oauth2.oauth2.Variable") as MockVariable:
+ MockVariable.get.return_value = expected
+ actual = oauth2._var_get("key")
+ assert actual == expected
+ assert MockVariable.get.call_args == mock.call(
+ "key", default_var={}, deserialize_json=True
+ )
+
+
+def test_update_tokens(oauth_provider_var_mock):
+ new_tokens = {"access_token": "new_access", "refresh_token": "new_refresh"}
+ oauth2._update_tokens(FAKE_OAUTH_PROVIDER_NAME, new_tokens)
+ expected = {FAKE_OAUTH_PROVIDER_NAME: new_tokens}
+ assert oauth_provider_var_mock.set.call_args.args == (
+ oauth2.OAUTH2_TOKEN_KEY,
+ expected,
+ )
+
+
+def test_update_tokens_does_not_affect_other_providers(oauth_provider_var_mock):
+ oauth_provider_var_mock.get.side_effect = None
+ oauth_provider_var_mock.get.return_value = {
+ FAKE_OAUTH_PROVIDER_NAME: {},
+ "other_provider": {"access_token": "foo", "refresh_token": "bar"},
+ }
+ new_tokens = {"access_token": "new_access", "refresh_token": "new_refresh"}
+ expected = {
+ FAKE_OAUTH_PROVIDER_NAME: new_tokens,
+ "other_provider": {"access_token": "foo", "refresh_token": "bar"},
+ }
+ oauth2._update_tokens(FAKE_OAUTH_PROVIDER_NAME, new_tokens)
+ assert oauth_provider_var_mock.set.call_args.args == (
+ oauth2.OAUTH2_TOKEN_KEY,
+ expected,
+ )
+
+
+ "expected",
+ [
+ # Happy path
+ {"client_id": "foo", "other_secret": "bar"},
+ # Missing client_id
+ pytest.param(
+ {"missing_client": "bar"},
+ marks=pytest.mark.raises(exception=ValueError),
+ ),
+ # Missing altogether
+ pytest.param(None, marks=pytest.mark.raises(exception=ValueError)),
+ ],
+)
+def test_get_provider_secrets(expected):
+ provider_secrets = {FAKE_OAUTH_PROVIDER_NAME: expected}
+ actual = oauth2._get_provider_secrets(FAKE_OAUTH_PROVIDER_NAME, provider_secrets)
+ assert actual == expected
+
+
+def test_get_provider_secrets_pulled_if_not_provided(oauth_provider_var_mock):
+ actual = oauth2._get_provider_secrets(FAKE_OAUTH_PROVIDER_NAME)
+ assert actual["client_id"] == "fakeclient"
+
+
+def test_get_oauth_client(oauth_provider_var_mock):
+ actual = oauth2.get_oauth_client(FAKE_OAUTH_PROVIDER_NAME)
+ assert actual.client_id == "fakeclient"
+ # Ensure token type has been added
+ assert actual.token["token_type"] == "Bearer"
+
+
+def test_get_oauth_client_missing(oauth_provider_var_mock, monkeypatch):
+ monkeypatch.setattr(oauth2, "_get_provider_secrets", lambda x: {})
+ with pytest.raises(KeyError):
+ oauth2.get_oauth_client("missing")
+
+
+def test_authorize_providers(oauth_provider_var_mock):
+ with mock.patch("oauth2.oauth2.OAuth2Session") as MockOAuth2Session:
+ oauth2.authorize_providers([FAKE_OAUTH_PROVIDER])
+ # A new token was fetched
+ MockOAuth2Session.return_value.fetch_token.assert_called_once()
+ # 2 variables were set, one to update the token and one to remove the auth
+ assert oauth_provider_var_mock.set.call_count == 2
+ # The auth tokens should now be empty, since the provider was authorized
+ assert oauth_provider_var_mock.set.call_args.args[1] == {}
+
+
+def test_authorize_providers_no_providers_to_auth(oauth_provider_var_mock):
+ with mock.patch("oauth2.oauth2.OAuth2Session") as MockOAuth2Session:
+ oauth2.authorize_providers(
+ [oauth2.OauthProvider("other", auth_url="auth", refresh_url="refresh")]
+ )
+ MockOAuth2Session.assert_not_called()
+ oauth_provider_var_mock.set.assert_not_called()
+
+
+def test_refresh(oauth_provider_var_mock):
+ with mock.patch("oauth2.oauth2.OAuth2Session") as MockOAuth2Session:
+ oauth2.refresh(FAKE_OAUTH_PROVIDER)
+ # A token was refreshed
+ MockOAuth2Session.return_value.refresh_token.assert_called_once()
+ # Tokens were updated
+ assert oauth_provider_var_mock.set.call_args.args[0] == oauth2.OAUTH2_TOKEN_KEY
+
+
+def test_refresh_no_tokens(oauth_provider_var_mock):
+ provider = oauth2.OauthProvider("other", auth_url="auth", refresh_url="refresh")
+ with pytest.raises(AirflowSkipException):
+ oauth2.refresh(provider)
diff --git a/tests/dags/test_dag_parsing.py b/tests/dags/test_dag_parsing.py
index c54c3b49c..1a96e8a8f 100644
--- a/tests/dags/test_dag_parsing.py
+++ b/tests/dags/test_dag_parsing.py
@@ -44,6 +44,8 @@ ADDITIONAL_DAGS = [
"refresh_all_image_popularity_data.py",
"refresh_image_view_data.py",
"commoncrawl_etl.py",
+ "oauth2/authorize_dag.py",
+ "oauth2/token_refresh_dag.py",
]
# Expected count from the DagBag once a file has been parsed