From 227a56cee140617a089cd3e22efcf2fcc8cfe8e3 Mon Sep 17 00:00:00 2001 From: Rezaan Syed Date: Thu, 11 Mar 2021 16:46:14 -0500 Subject: [PATCH] Introduce ApiAccess for representing access scopes --- README.md | 73 +++++-------------- docs/api-access.md | 73 +++++++++++++++++++ docs/session-tokens.md | 54 ++++++++++++++ shopify/__init__.py | 1 + shopify/api_access.py | 52 ++++++++++++++ test/api_access_test.py | 153 ++++++++++++++++++++++++++++++++++++++++ 6 files changed, 351 insertions(+), 55 deletions(-) create mode 100644 docs/api-access.md create mode 100644 docs/session-tokens.md create mode 100644 shopify/api_access.py create mode 100644 test/api_access_test.py diff --git a/README.md b/README.md index 5a2cac93..6dc85ff6 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,24 @@ To easily install or upgrade to the latest release, use [pip](http://www.pip-ins pip install --upgrade ShopifyAPI ``` +### Table of Contents + +- [Getting Started](#getting-started) + - [Public and Custom Apps](#public-and-custom-apps) + - [Private Apps](#private-apps) +- [Billing](#billing) +- [Session Tokens](docs/session-tokens) +- [Handling Access Scope Operations](docs/api-access.md) +- [Advanced Usage](#advanced-usage) +- [Prefix Options](#prefix-options) +- [Console](#console) +- [GraphQL](#graphql) +- [Using Development Version](#using-development-version) +- [Relative Cursor Pagination](#relative-cursor-pagination) +- [Limitations](#limitations) +- [Additional Resources](#additional-resources) + + ### Getting Started #### Public and Custom Apps @@ -120,61 +138,6 @@ _Note: Your application must be public to test the billing process. To test on a has_been_billed = activated_charge.status == 'active' ``` -### Session tokens - -The Shopify Python API library provides helper methods to decode [session tokens](https://shopify.dev/concepts/apps/building-embedded-apps-using-session-tokens). You can use the `decode_from_header` function to extract and decode a session token from an HTTP Authorization header. - -#### Basic usage - -```python -from shopify import session_token - -decoded_payload = session_token.decode_from_header( - authorization_header=your_auth_request_header, - api_key=your_api_key, - secret=your_api_secret, -) -``` - -#### Create a decorator using `session_token` - -Here's a sample decorator that protects your app views/routes by requiring the presence of valid session tokens as part of a request's headers. - -```python -from shopify import session_token - - -def session_token_required(func): - def wrapper(*args, **kwargs): - request = args[0] # Or flask.request if you use Flask - try: - decoded_session_token = session_token.decode_from_header( - authorization_header = request.headers.get('Authorization'), - api_key = SHOPIFY_API_KEY, - secret = SHOPIFY_API_SECRET - ) - with shopify_session(decoded_session_token): - return func(*args, **kwargs) - except session_token.SessionTokenError as e: - # Log the error here - return unauthorized_401_response() - - return wrapper - - -def shopify_session(decoded_session_token): - shopify_domain = decoded_session_token.get("dest") - access_token = get_offline_access_token_by_shop_domain(shopify_domain) - - return shopify.Session.temp(shopify_domain, SHOPIFY_API_VERSION, access_token) - - -@session_token_required # Requests to /products require session tokens -def products(request): - products = shopify.Product.find() - ... -``` - ### Advanced Usage It is recommended to have at least a basic grasp on the principles of the [pyactiveresource](https://github.com/Shopify/pyactiveresource) library, which is a port of rails/ActiveResource to Python and upon which this package relies heavily. diff --git a/docs/api-access.md b/docs/api-access.md new file mode 100644 index 00000000..41de61db --- /dev/null +++ b/docs/api-access.md @@ -0,0 +1,73 @@ +# Handling access scope operations + +#### Table of contents + +- [Common ApiAccess operations](#common-apiaccess-operations) +- [Using ApiAccess to handle changes in app access scopes](#using-apiaccess-to-handle-changes-in-app-access-scopes) + +There are common operations that are used for managing [access scopes](https://shopify.dev/docs/admin-api/access-scopes) in apps. Such operations include serializing, deserializing and normalizing scopes. Other operations can include checking whether two sets of scopes grant the same API access or whether one set covers the access granted by another set. + +To encapsulate the access granted by access scopes, you can use the `ApiAccess` value object. + +## Common ApiAccess operations + +### Constructing an ApiAccess + +```python +api_access = ApiAccess(["read_products", "write_orders"]) # List of access scopes +another_api_access = ApiAccess("read_products, write_products, unauthenticated_read_themes") # String of comma-delimited access scopes +``` + +### Serializing ApiAccess + +```python +api_access = ApiAccess(["read_products", "write_orders", "unauthenticated_read_themes"]) + +access_scopes_list = list(api_access) # ["read_products", "write_orders", "unauthenticated_read_themes"] +comma_delmited_access_scopes = str(api_access) # "read_products,write_orders,unauthenticated_read_themes" +``` + +### Comparing ApiAccess objects + +#### Checking for API access equality + +```python +expected_api_access = ApiAccess(["read_products", "write_orders"]) + +actual_api_access = ApiAccess(["read_products", "read_orders", "write_orders"]) +non_equal_api_access = ApiAccess(["read_products", "write_orders", "read_themes"]) + +actual_api_access == expected_api_access # True +non_equal_api_access == expected_api_access # False +``` + +#### Checking if ApiAccess covers the access of another + +```python +superset_access = ApiAccess(["write_products", "write_orders", "read_themes"]) +subset_access = ApiAccess(["read_products", "write_orders"]) + +superset_access.covers(subset_access) # True +``` + +## Using ApiAccess to handle changes in app access scopes + +If your app has changes in the access scopes it requests, you can use the `ApiAccess` object to determine whether the merchant needs to go through OAuth based on the scopes currently granted. A sample decorator shows how this can be achieved when loading an app. + +```python +from shopify import ApiAccess + + +def oauth_on_access_scopes_mismatch(func): + def wrapper(*args, **kwargs): + shop_domain = get_shop_query_paramer(request) # shop query param when loading app + current_shop_scopes = ApiAccess(ShopStore.get_record(shopify_domain = shop_domain).access_scopes) + expected_access_scopes = ApiAccess(SHOPIFY_API_SCOPES) + + if current_shop_scopes != expected_access_scopes: + return redirect_to_login() # redirect to OAuth to update access scopes granted + + return func(*args, **kwargs) + + return wrapper +``` diff --git a/docs/session-tokens.md b/docs/session-tokens.md new file mode 100644 index 00000000..7349cd3a --- /dev/null +++ b/docs/session-tokens.md @@ -0,0 +1,54 @@ +# Session tokens + +The Shopify Python API library provides helper methods to decode [session tokens](https://shopify.dev/concepts/apps/building-embedded-apps-using-session-tokens). You can use the `decode_from_header` function to extract and decode a session token from an HTTP Authorization header. + +## Basic usage + +```python +from shopify import session_token + +decoded_payload = session_token.decode_from_header( + authorization_header=your_auth_request_header, + api_key=your_api_key, + secret=your_api_secret, +) +``` + +## Create a decorator using `session_token` + +Here's a sample decorator that protects your app views/routes by requiring the presence of valid session tokens as part of a request's headers. + +```python +from shopify import session_token + + +def session_token_required(func): + def wrapper(*args, **kwargs): + request = args[0] # Or flask.request if you use Flask + try: + decoded_session_token = session_token.decode_from_header( + authorization_header = request.headers.get('Authorization'), + api_key = SHOPIFY_API_KEY, + secret = SHOPIFY_API_SECRET + ) + with shopify_session(decoded_session_token): + return func(*args, **kwargs) + except session_token.SessionTokenError as e: + # Log the error here + return unauthorized_401_response() + + return wrapper + + +def shopify_session(decoded_session_token): + shopify_domain = decoded_session_token.get("dest") + access_token = get_offline_access_token_by_shop_domain(shopify_domain) + + return shopify.Session.temp(shopify_domain, SHOPIFY_API_VERSION, access_token) + + +@session_token_required # Requests to /products require session tokens +def products(request): + products = shopify.Product.find() + ... +``` diff --git a/shopify/__init__.py b/shopify/__init__.py index b10d9a48..d3f53de9 100644 --- a/shopify/__init__.py +++ b/shopify/__init__.py @@ -3,4 +3,5 @@ from shopify.resources import * from shopify.limits import Limits from shopify.api_version import * +from shopify.api_access import * from shopify.collection import PaginatedIterator diff --git a/shopify/api_access.py b/shopify/api_access.py new file mode 100644 index 00000000..35495a4b --- /dev/null +++ b/shopify/api_access.py @@ -0,0 +1,52 @@ +import re + + +class ApiAccessError(Exception): + pass + + +class ApiAccess: + + SCOPE_DELIMITER = "," + SCOPE_RE = re.compile(r"\A(?Punauthenticated_)?(write|read)_(?P.*)\Z") + IMPLIED_SCOPE_RE = re.compile(r"\A(?Punauthenticated_)?write_(?P.*)\Z") + + def __init__(self, scopes): + if type(scopes) == str: + scopes = scopes.split(self.SCOPE_DELIMITER) + + self.__store_scopes(scopes) + + def covers(self, api_access): + return api_access._compressed_scopes <= self._expanded_scopes + + def __str__(self): + return self.SCOPE_DELIMITER.join(self._compressed_scopes) + + def __iter__(self): + return iter(self._compressed_scopes) + + def __eq__(self, other): + return type(self) == type(other) and self._compressed_scopes == other._compressed_scopes + + def __store_scopes(self, scopes): + sanitized_scopes = frozenset(filter(None, [scope.strip() for scope in scopes])) + self.__validate_scopes(sanitized_scopes) + + implied_scopes = frozenset(self.__implied_scope(scope) for scope in sanitized_scopes) + self._compressed_scopes = sanitized_scopes - implied_scopes + self._expanded_scopes = sanitized_scopes.union(implied_scopes) + + def __validate_scopes(self, scopes): + for scope in scopes: + if not self.SCOPE_RE.match(scope): + error_message = "'{s}' is not a valid access scope".format(s=scope) + raise ApiAccessError(error_message) + + def __implied_scope(self, scope): + match = self.IMPLIED_SCOPE_RE.match(scope) + if match: + return "{unauthenticated}read_{resource}".format( + unauthenticated=match.group("unauthenticated") or "", + resource=match.group("resource"), + ) diff --git a/test/api_access_test.py b/test/api_access_test.py new file mode 100644 index 00000000..21866a09 --- /dev/null +++ b/test/api_access_test.py @@ -0,0 +1,153 @@ +from shopify import ApiAccess, ApiAccessError +from test.test_helper import TestCase + + +class ApiAccessTest(TestCase): + def test_creating_scopes_from_a_string_works_with_a_comma_separated_list(self): + deserialized_read_products_write_orders = ApiAccess("read_products,write_orders") + serialized_read_products_write_orders = str(deserialized_read_products_write_orders) + expected_read_products_write_orders = ApiAccess(["read_products", "write_orders"]) + + self.assertEqual(expected_read_products_write_orders, ApiAccess(serialized_read_products_write_orders)) + + def test_creating_api_access_from_invalid_scopes_raises(self): + with self.assertRaises(ApiAccessError) as cm: + api_access = ApiAccess("bad_scope, read_orders,write_orders") + + self.assertEqual("'bad_scope' is not a valid access scope", str(cm.exception)) + + def test_returns_list_of_reduced_scopes(self): + api_access = ApiAccess("read_products, read_orders,write_orders") + expected_scopes = set(["read_products", "write_orders"]) + scopes = list(api_access) + + self.assertEqual(expected_scopes, set(scopes)) + + def test_write_is_the_same_access_as_read_write_on_the_same_resource(self): + read_write_orders = ApiAccess(["read_orders", "write_orders"]) + write_orders = ApiAccess("write_orders") + + self.assertEqual(write_orders, read_write_orders) + + def test_write_is_the_same_access_as_read_write_on_the_same_unauthenticated_resource(self): + unauthenticated_read_write_orders = ApiAccess(["unauthenticated_read_orders", "unauthenticated_write_orders"]) + unauthenticated_write_orders = ApiAccess("unauthenticated_write_orders") + + self.assertEqual(unauthenticated_write_orders, unauthenticated_read_write_orders) + + def test_read_is_not_the_same_as_read_write_on_the_same_resource(self): + read_orders = ApiAccess("read_orders") + read_write_orders = ApiAccess(["write_orders", "read_orders"]) + + self.assertNotEqual(read_write_orders, read_orders) + + def test_two_different_resources_are_not_equal(self): + read_orders = ApiAccess("read_orders") + read_products = ApiAccess("read_products") + + self.assertNotEqual(read_orders, read_products) + + def test_two_identical_scopes_are_equal(self): + read_orders = ApiAccess("read_orders") + read_orders_identical = ApiAccess("read_orders") + + self.assertEqual(read_orders, read_orders_identical) + + def test_unauthenticated_is_not_implied_by_authenticated_access(self): + unauthenticated_orders = ApiAccess("unauthenticated_read_orders") + authenticated_read_orders = ApiAccess("read_orders") + authenticated_write_orders = ApiAccess("write_orders") + + self.assertNotEqual(unauthenticated_orders, authenticated_read_orders) + self.assertNotEqual(unauthenticated_orders, authenticated_write_orders) + + def test_scopes_covers_is_truthy_for_same_scopes(self): + read_orders = ApiAccess("read_orders") + read_orders_identical = ApiAccess("read_orders") + + self.assertTrue(read_orders.covers(read_orders_identical)) + + def test_covers_is_falsy_for_different_scopes(self): + read_orders = ApiAccess("read_orders") + read_products = ApiAccess("read_products") + + self.assertFalse(read_orders.covers(read_products)) + + def test_covers_is_truthy_for_read_when_the_set_has_read_write(self): + write_products = ApiAccess("write_products") + read_products = ApiAccess("read_products") + + self.assertTrue(write_products.covers(read_products)) + + def test_covers_is_truthy_for_read_when_the_set_has_read_write_for_that_resource_and_others(self): + write_products_and_orders = ApiAccess(["write_products", "write_orders"]) + read_orders = ApiAccess("read_orders") + + self.assertTrue(write_products_and_orders.covers(read_orders)) + + def test_covers_is_truthy_for_write_when_the_set_has_read_write_for_that_resource_and_others(self): + write_products_and_orders = ApiAccess(["write_products", "write_orders"]) + write_orders = ApiAccess("write_orders") + + self.assertTrue(write_products_and_orders.covers(write_orders)) + + def test_covers_is_truthy_for_subset_of_scopes(self): + write_products_orders_customers = ApiAccess(["write_products", "write_orders", "write_customers"]) + write_orders_products = ApiAccess(["write_orders", "read_products"]) + + self.assertTrue(write_products_orders_customers.covers(write_orders_products)) + + def test_covers_is_falsy_for_sets_of_scopes_that_have_no_common_elements(self): + write_products_orders_customers = ApiAccess(["write_products", "write_orders", "write_customers"]) + write_images_read_content = ApiAccess(["write_images", "read_content"]) + + self.assertFalse(write_products_orders_customers.covers(write_images_read_content)) + + def test_covers_is_falsy_for_sets_of_scopes_that_have_only_some_common_access(self): + write_products_orders_customers = ApiAccess(["write_products", "write_orders", "write_customers"]) + write_products_read_content = ApiAccess(["write_products", "read_content"]) + + self.assertFalse(write_products_orders_customers.covers(write_products_read_content)) + + def test_duplicate_scopes_resolve_to_one_scope(self): + read_orders_duplicated = ApiAccess(["read_orders", "read_orders", "read_orders", "read_orders"]) + read_orders = ApiAccess("read_orders") + + self.assertEqual(read_orders, read_orders_duplicated) + + def test_to_s_outputs_scopes_as_a_comma_separated_list_without_implied_read_scopes(self): + serialized_read_products_write_orders = "read_products,write_orders" + read_products_write_orders = ApiAccess(["read_products", "read_orders", "write_orders"]) + + self.assertIn("read_products", str(read_products_write_orders)) + self.assertIn("write_orders", str(read_products_write_orders)) + + def test_to_a_outputs_scopes_as_an_array_of_strings_without_implied_read_scopes(self): + serialized_read_products_write_orders = ["write_orders", "read_products"] + read_products_write_orders = ApiAccess(["read_products", "read_orders", "write_orders"]) + + self.assertEqual(set(serialized_read_products_write_orders), set(list(read_products_write_orders))) + + def test_creating_scopes_removes_extra_whitespace_from_scope_name_and_blank_scope_names(self): + deserialized_read_products_write_orders = ApiAccess([" read_products", " ", "write_orders "]) + serialized_read_products_write_orders = str(deserialized_read_products_write_orders) + expected_read_products_write_orders = ApiAccess(["read_products", "write_orders"]) + + self.assertEqual(expected_read_products_write_orders, ApiAccess(serialized_read_products_write_orders)) + + def test_creating_scopes_from_a_string_works_with_a_comma_separated_list(self): + deserialized_read_products_write_orders = ApiAccess("read_products,write_orders") + serialized_read_products_write_orders = str(deserialized_read_products_write_orders) + expected_read_products_write_orders = ApiAccess(["read_products", "write_orders"]) + + self.assertEqual(expected_read_products_write_orders, ApiAccess(serialized_read_products_write_orders)) + + def test_using_to_s_from_one_scopes_to_construct_another_will_be_equal(self): + read_products_write_orders = ApiAccess(["read_products", "write_orders"]) + + self.assertEqual(read_products_write_orders, ApiAccess(str(read_products_write_orders))) + + def test_using_to_a_from_one_scopes_to_construct_another_will_be_equal(self): + read_products_write_orders = ApiAccess(["read_products", "write_orders"]) + + self.assertEqual(read_products_write_orders, ApiAccess(list(read_products_write_orders)))