Skip to content

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

Refactor app tokens (#9438)

Iga Karbowiak81d02e76b22e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 73ac4a6773..c5f9677fc9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,8 @@ All notable, unreleased changes to this project will be documented in this file.
- Fix access to own resources by App - #9425 by @korycins
- Introduce custom prices - #9393 by @IKarbowiak
- Add `HANDLE_CHECKOUTS` permission (only for apps)
+- Refactor app tokens - #9438 by @IKarbowiak
+ - Store app tokens hashes instead of plain text.
# 3.1.7
diff --git a/saleor/app/installation_utils.py b/saleor/app/installation_utils.py
index 2337661735..63899cd779 100644
--- a/saleor/app/installation_utils.py
+++ b/saleor/app/installation_utils.py
@@ -62,13 +62,11 @@ def install_app(
)
extension.permissions.set(extension_data.get("permissions", []))
- token = app.tokens.create(name="Default token")
+ _, token = app.tokens.create(name="Default token")
try:
- send_app_token(
- target_url=manifest_data.get("tokenTargetUrl"), token=token.auth_token
- )
+ send_app_token(target_url=manifest_data.get("tokenTargetUrl"), token=token)
except requests.RequestException as e:
app.delete()
raise e
- return app
+ return app, token
diff --git a/saleor/app/management/commands/create_app.py b/saleor/app/management/commands/create_app.py
index 1fdc4aa449..9d2d5d32e0 100644
--- a/saleor/app/management/commands/create_app.py
+++ b/saleor/app/management/commands/create_app.py
@@ -59,9 +59,9 @@ class Command(BaseCommand):
permissions = clean_permissions(permissions)
app = App.objects.create(name=name, is_active=is_active)
app.permissions.set(permissions)
- token_obj = app.tokens.create()
+ _, auth_token = app.tokens.create()
data = {
- "auth_token": token_obj.auth_token,
+ "auth_token": auth_token,
}
if target_url:
self.send_app_data(target_url, data)
diff --git a/saleor/app/management/commands/install_app.py b/saleor/app/management/commands/install_app.py
index 93f8223245..d03567f10d 100644
--- a/saleor/app/management/commands/install_app.py
+++ b/saleor/app/management/commands/install_app.py
@@ -53,11 +53,10 @@ class Command(BaseCommand):
app_job.permissions.set(permissions)
try:
- app = install_app(app_job, activate)
+ _, token = install_app(app_job, activate)
app_job.delete()
except Exception as e:
app_job.status = JobStatus.FAILED
app_job.save()
raise e
- token = app.tokens.first()
- return json.dumps({"auth_token": token.auth_token})
+ return json.dumps({"auth_token": token})
diff --git a/saleor/app/migrations/0009_apptoken_token_last_4.py b/saleor/app/migrations/0009_apptoken_token_last_4.py
new file mode 100644
index 0000000000..654891ae36
--- /dev/null
+++ b/saleor/app/migrations/0009_apptoken_token_last_4.py
@@ -0,0 +1,23 @@
+# Generated by Django 3.2.12 on 2022-03-29 07:49
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("app", "0008_appextension_target"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="apptoken",
+ name="token_last_4",
+ field=models.CharField(max_length=4, null=True),
+ ),
+ migrations.AlterField(
+ model_name="apptoken",
+ name="auth_token",
+ field=models.CharField(max_length=128, unique=True),
+ ),
+ ]
diff --git a/saleor/app/migrations/0010_update_app_tokens.py b/saleor/app/migrations/0010_update_app_tokens.py
new file mode 100644
index 0000000000..959c0454bb
--- /dev/null
+++ b/saleor/app/migrations/0010_update_app_tokens.py
@@ -0,0 +1,48 @@
+# Generated by Django 3.2.12 on 2022-03-29 10:04
+
+from django.contrib.auth.hashers import make_password
+from django.db import migrations
+
+BATCH_SIZE = 10000
+
+
+def update_app_tokens(apps, schema_editor):
+ AppToken = apps.get_model("app", "AppToken")
+ queryset = AppToken.objects.all()
+ for batch_pks in queryset_in_batches(queryset):
+ app_tokens = AppToken.objects.filter(pk__in=batch_pks)
+ for app_token in app_tokens:
+ app_token.token_last_4 = app_token.auth_token[-4:]
+ app_token.auth_token = make_password(app_token.auth_token)
+
+ AppToken.objects.bulk_update(app_tokens, ["auth_token", "token_last_4"])
+
+
+def queryset_in_batches(queryset):
+ """Slice a queryset into batches.
+
+ Input queryset should be sorted be pk.
+ """
+ start_pk = 0
+
+ while True:
+ qs = queryset.filter(pk__gt=start_pk)[:BATCH_SIZE]
+ pks = list(qs.values_list("pk", flat=True))
+
+ if not pks:
+ break
+
+ yield pks
+
+ start_pk = pks[-1]
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("app", "0009_apptoken_token_last_4"),
+ ]
+
+ operations = [
+ migrations.RunPython(update_app_tokens, migrations.RunPython.noop),
+ ]
diff --git a/saleor/app/migrations/0011_alter_apptoken_token_last_4.py b/saleor/app/migrations/0011_alter_apptoken_token_last_4.py
new file mode 100644
index 0000000000..7d3f8c35a7
--- /dev/null
+++ b/saleor/app/migrations/0011_alter_apptoken_token_last_4.py
@@ -0,0 +1,18 @@
+# Generated by Django 3.2.12 on 2022-03-29 10:09
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("app", "0010_update_app_tokens"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="apptoken",
+ name="token_last_4",
+ field=models.CharField(max_length=4),
+ ),
+ ]
diff --git a/saleor/app/models.py b/saleor/app/models.py
index 4faa1d20b1..671ecbeb4b 100644
--- a/saleor/app/models.py
+++ b/saleor/app/models.py
@@ -1,5 +1,6 @@
from typing import Set
+from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import Permission
from django.db import models
from oauthlib.common import generate_token
@@ -99,10 +100,28 @@ class App(ModelWithMetadata):
return perm_value in self.get_permissions()
+class AppTokenManager(models.Manager):
+ def create(self, app, name="", auth_token=None, **extra_fields):
+ """Create an app token with the given name."""
+ if not auth_token:
+ auth_token = generate_token()
+ app_token = self.model(app=app, name=name, **extra_fields)
+ app_token.set_auth_token(auth_token)
+ app_token.save()
+ return app_token, auth_token
+
+
class AppToken(models.Model):
app = models.ForeignKey(App, on_delete=models.CASCADE, related_name="tokens")
name = models.CharField(blank=True, default="", max_length=128)
- auth_token = models.CharField(default=generate_token, unique=True, max_length=30)
+ auth_token = models.CharField(unique=True, max_length=128)
+ token_last_4 = models.CharField(max_length=4)
+
+ objects = AppTokenManager()
+
+ def set_auth_token(self, raw_token=None):
+ self.auth_token = make_password(raw_token)
+ self.token_last_4 = raw_token[-4:]
class AppExtension(models.Model):
diff --git a/saleor/app/tests/test_app_commands.py b/saleor/app/tests/test_app_commands.py
index f9e454c050..f2f6aba0d8 100644
--- a/saleor/app/tests/test_app_commands.py
+++ b/saleor/app/tests/test_app_commands.py
@@ -55,8 +55,6 @@ def test_creates_app_from_manifest_sends_token(monkeypatch):
call_command("install_app", manifest_url)
- app = App.objects.get()
- token = app.tokens.all()[0].auth_token
mocked_post.assert_called_once_with(
"http://localhost:3000/register",
headers={
@@ -65,7 +63,7 @@ def test_creates_app_from_manifest_sends_token(monkeypatch):
"x-saleor-domain": "mirumee.com",
"saleor-domain": "mirumee.com",
},
- json={"auth_token": token},
+ json={"auth_token": ANY},
timeout=ANY,
)
@@ -120,8 +118,6 @@ def test_sends_data_to_target_url(monkeypatch):
call_command("create_app", name, permission=permissions, target_url=target_url)
- app = App.objects.filter(name=name)[0]
- token = app.tokens.all()[0].auth_token
mocked_post.assert_called_once_with(
target_url,
headers={
@@ -129,6 +125,6 @@ def test_sends_data_to_target_url(monkeypatch):
"x-saleor-domain": "mirumee.com",
"saleor-domain": "mirumee.com",
},
- json={"auth_token": token},
+ json={"auth_token": ANY},
timeout=ANY,
)
diff --git a/saleor/app/tests/test_installation_utils.py b/saleor/app/tests/test_installation_utils.py
index fee501a54a..d5984cb21a 100644
--- a/saleor/app/tests/test_installation_utils.py
+++ b/saleor/app/tests/test_installation_utils.py
@@ -23,7 +23,7 @@ def test_install_app_created_app(
app_installation.permissions.set([permission_manage_products])
# when
- app = install_app(app_installation, activate=True)
+ app, _ = install_app(app_installation, activate=True)
# then
assert App.objects.get().id == app.id
@@ -60,7 +60,7 @@ def test_install_app_with_extension(
)
# when
- app = install_app(app_installation, activate=True)
+ app, _ = install_app(app_installation, activate=True)
# then
assert App.objects.get().id == app.id
diff --git a/saleor/graphql/app/mutations.py b/saleor/graphql/app/mutations.py
index ce343a95ac..2d9609f609 100644
--- a/saleor/graphql/app/mutations.py
+++ b/saleor/graphql/app/mutations.py
@@ -2,7 +2,9 @@ from typing import Dict, List
import graphene
import requests
+from django.contrib.auth.hashers import check_password
from django.core.exceptions import ValidationError
+from oauthlib.common import generate_token
from ...app import models
from ...app.error_codes import AppErrorCode
@@ -61,11 +63,13 @@ class AppTokenCreate(ModelMutation):
instance = cls.get_instance(info, **data)
cleaned_input = cls.clean_input(info, instance, input_data)
instance = cls.construct_instance(instance, cleaned_input)
+ auth_token = generate_token()
+ instance.set_auth_token(auth_token)
cls.clean_instance(info, instance)
cls.save(info, instance, cleaned_input)
cls._save_m2m(info, instance, cleaned_input)
response = cls.success_response(instance)
- response.auth_token = instance.auth_token
+ response.auth_token = auth_token
return response
@classmethod
@@ -120,10 +124,11 @@ class AppTokenVerify(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, **data):
token = data.get("token")
- app_token = models.AppToken.objects.filter(
- auth_token=token, app__is_active=True
- ).first()
- return AppTokenVerify(valid=bool(app_token))
+ tokens = models.AppToken.objects.filter(
+ app__is_active=True, token_last_4=token[-4:]
+ ).values_list("auth_token", flat=True)
+ valid = any([check_password(token, auth_token) for auth_token in tokens])
+ return AppTokenVerify(valid=valid)
class AppCreate(ModelMutation):
@@ -162,19 +167,23 @@ class AppCreate(ModelMutation):
@classmethod
@staff_member_required
- def perform_mutation(cls, root, info, **data):
- return super().perform_mutation(root, info, **data)
+ def perform_mutation(cls, _root, info, **data):
+ instance = cls.get_instance(info, **data)
+ data = data.get("input")
+ cleaned_input = cls.clean_input(info, instance, data)
+ instance = cls.construct_instance(instance, cleaned_input)
+ cls.clean_instance(info, instance)
+ auth_token = cls.save(info, instance, cleaned_input)
+ cls._save_m2m(info, instance, cleaned_input)
+ response = cls.success_response(instance)
+ response.auth_token = auth_token
+ return response
@classmethod
def save(cls, info, instance, cleaned_input):
instance.save()
- instance.tokens.create(name="Default")
-
- @classmethod
- def success_response(cls, instance):
- response = super().success_response(instance)
- response.auth_token = instance.tokens.get().auth_token
- return response
+ _, auth_token = instance.tokens.create(name="Default")
+ return auth_token
class AppUpdate(ModelMutation):
diff --git a/saleor/graphql/app/tests/mutations/test_app_create.py b/saleor/graphql/app/tests/mutations/test_app_create.py
index 1f3cdc37c8..7dbc88e4f1 100644
--- a/saleor/graphql/app/tests/mutations/test_app_create.py
+++ b/saleor/graphql/app/tests/mutations/test_app_create.py
@@ -57,7 +57,8 @@ def test_app_create_mutation(
assert app_data["isActive"] == app.is_active
assert app_data["name"] == app.name
assert list(app.permissions.all()) == [permission_manage_products]
- assert default_token == app.tokens.get().auth_token
+ assert default_token
+ assert default_token[-4:] == app.tokens.get().token_last_4
def test_app_is_not_allowed_to_call_create_mutation_for_app(
@@ -135,7 +136,8 @@ def test_app_create_mutation_superuser_can_create_app_with_any_perms(
assert app_data["isActive"] == app.is_active
assert app_data["name"] == app.name
assert list(app.permissions.all()) == [permission_manage_products]
- assert default_token == app.tokens.get().auth_token
+ assert default_token
+ assert default_token[-4:] == app.tokens.get().token_last_4
def test_app_create_mutation_no_permissions(
diff --git a/saleor/graphql/app/tests/mutations/test_app_token_create.py b/saleor/graphql/app/tests/mutations/test_app_token_create.py
index e699d5db63..5e3f2ccf84 100644
--- a/saleor/graphql/app/tests/mutations/test_app_token_create.py
+++ b/saleor/graphql/app/tests/mutations/test_app_token_create.py
@@ -26,7 +26,7 @@ mutation appTokenCreate($input: AppTokenInput!) {
def test_app_token_create(
permission_manage_apps, staff_api_client, staff_user, permission_manage_orders
):
-
+ # given
app = App.objects.create(name="New_app")
query = APP_TOKEN_CREATE_MUTATION
staff_user.user_permissions.add(permission_manage_orders)
@@ -34,16 +34,20 @@ def test_app_token_create(
id = graphene.Node.to_global_id("App", app.id)
variables = {"name": "Default token", "app": id}
+
+ # when
response = staff_api_client.post_graphql(
query, variables={"input": variables}, permissions=(permission_manage_apps,)
)
+
+ # then
content = get_graphql_content(response)
token_data = content["data"]["appTokenCreate"]["appToken"]
auth_token_data = content["data"]["appTokenCreate"]["authToken"]
- auth_token = app.tokens.get().auth_token
- assert auth_token_data == auth_token
-
- assert token_data["authToken"] == auth_token[-4:]
+ token_last_4 = app.tokens.get().token_last_4
+ assert auth_token_data
+ assert auth_token_data[-4:] == token_last_4
+ assert token_data["authToken"] == token_last_4
assert token_data["name"] == "Default token"
@@ -52,7 +56,7 @@ def test_app_token_create_for_app(
app_api_client,
permission_manage_orders,
):
-
+ # given
app = App.objects.create(name="New_app")
query = APP_TOKEN_CREATE_MUTATION
requestor = app_api_client.app
@@ -61,18 +65,22 @@ def test_app_token_create_for_app(
id = graphene.Node.to_global_id("App", app.id)
variables = {"name": "Default token", "app": id}
+
+ # when
response = app_api_client.post_graphql(
query,
variables={"input": variables},
permissions=(permission_manage_apps,),
)
+
+ # then
content = get_graphql_content(response)
token_data = content["data"]["appTokenCreate"]["appToken"]
auth_token_data = content["data"]["appTokenCreate"]["authToken"]
- auth_token = app.tokens.get().auth_token
- assert auth_token_data == auth_token
-
- assert token_data["authToken"] == auth_token[-4:]
+ token_last_4 = app.tokens.get().token_last_4
+ assert auth_token_data
+ assert auth_token_data[-4:] == token_last_4
+ assert token_data["authToken"] == token_last_4
assert token_data["name"] == "Default token"
@@ -83,6 +91,7 @@ def test_app_token_create_out_of_scope_app(
permission_manage_orders,
):
"""Ensure user can't create token for app with wider scope of permissions."""
+ # given
app = App.objects.create(name="New_app")
query = APP_TOKEN_CREATE_MUTATION
app.permissions.add(permission_manage_orders)
@@ -90,13 +99,15 @@ def test_app_token_create_out_of_scope_app(
id = graphene.Node.to_global_id("App", app.id)
variables = {"name": "Default token", "app": id}
+ # when
response = staff_api_client.post_graphql(
query,
variables={"input": variables},
permissions=(permission_manage_apps,),
)
- content = get_graphql_content(response)
+ # then
+ content = get_graphql_content(response)
data = content["data"]["appTokenCreate"]
errors = data["errors"]
assert not data["appToken"]
@@ -112,6 +123,7 @@ def test_app_token_create_superuser_can_create_token_for_any_app(
permission_manage_orders,
):
"""Ensure superuser can create token for app with any scope of permissions."""
+ # given
app = App.objects.create(name="New_app")
query = APP_TOKEN_CREATE_MUTATION
app.permissions.add(permission_manage_orders)
@@ -119,14 +131,17 @@ def test_app_token_create_superuser_can_create_token_for_any_app(
id = graphene.Node.to_global_id("App", app.id)
variables = {"name": "Default token", "app": id}
+ # when
response = superuser_api_client.post_graphql(query, variables={"input": variables})
+
+ # then
content = get_graphql_content(response)
token_data = content["data"]["appTokenCreate"]["appToken"]
auth_token_data = content["data"]["appTokenCreate"]["authToken"]
- auth_token = app.tokens.get().auth_token
- assert auth_token_data == auth_token
-
- assert token_data["authToken"] == auth_token[-4:]
+ token_last_4 = app.tokens.get().token_last_4
+ assert auth_token_data
+ assert auth_token_data[-4:] == token_last_4
+ assert token_data["authToken"] == token_last_4
assert token_data["name"] == "Default token"
@@ -136,17 +151,22 @@ def test_app_token_create_as_app_out_of_scope_app(
app,
permission_manage_orders,
):
+ # given
app = App.objects.create(name="New_app")
query = APP_TOKEN_CREATE_MUTATION
app.permissions.add(permission_manage_orders)
id = graphene.Node.to_global_id("App", app.id)
variables = {"name": "Default token", "app": id}
+
+ # when
response = app_api_client.post_graphql(
query,
variables={"input": variables},
permissions=(permission_manage_apps,),
)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["appTokenCreate"]
errors = data["errors"]
@@ -158,9 +178,14 @@ def test_app_token_create_as_app_out_of_scope_app(
def test_app_token_create_no_permissions(staff_api_client, staff_user):
+ # given
app = App.objects.create(name="New_app")
query = APP_TOKEN_CREATE_MUTATION
id = graphene.Node.to_global_id("App", app.id)
variables = {"name": "Default token", "app": id}
+
+ # when
response = staff_api_client.post_graphql(query, variables={"input": variables})
+
+ # then
assert_no_permission(response)
diff --git a/saleor/graphql/app/tests/mutations/test_app_token_delete.py b/saleor/graphql/app/tests/mutations/test_app_token_delete.py
index 17a3a413fd..3a39f899e7 100644
--- a/saleor/graphql/app/tests/mutations/test_app_token_delete.py
+++ b/saleor/graphql/app/tests/mutations/test_app_token_delete.py
@@ -25,11 +25,12 @@ def test_app_token_delete(
permission_manage_apps,
staff_api_client,
staff_user,
- app,
+ app_with_token,
permission_manage_products,
):
query = APP_TOKEN_DELETE_MUTATION
+ app = app_with_token
token = app.tokens.get()
staff_user.user_permissions.add(permission_manage_products)
app.permissions.add(permission_manage_products)
@@ -64,10 +65,10 @@ def test_app_token_delete_for_app(
assert not AppToken.objects.filter(id=token.id).first()
-def test_app_token_delete_no_permissions(staff_api_client, staff_user, app):
+def test_app_token_delete_no_permissions(staff_api_client, app_with_token):
query = APP_TOKEN_DELETE_MUTATION
- token = app.tokens.get()
+ token = app_with_token.tokens.get()
id = graphene.Node.to_global_id("AppToken", token.id)
variables = {"id": id}
@@ -79,14 +80,13 @@ def test_app_token_delete_no_permissions(staff_api_client, staff_user, app):
def test_app_token_delete_out_of_scope_app(
permission_manage_apps,
staff_api_client,
- staff_user,
- app,
+ app_with_token,
permission_manage_products,
):
"""Ensure user can't delete app token with wider scope of permissions."""
query = APP_TOKEN_DELETE_MUTATION
- token = app.tokens.get()
- app.permissions.add(permission_manage_products)
+ token = app_with_token.tokens.get()
+ app_with_token.permissions.add(permission_manage_products)
id = graphene.Node.to_global_id("AppToken", token.id)
variables = {"id": id}
@@ -111,11 +111,12 @@ def test_app_token_delete_out_of_scope_app(
def test_app_token_delete_superuser_can_delete_token_for_any_app(
permission_manage_apps,
superuser_api_client,
- app,
+ app_with_token,
permission_manage_products,
):
"""Ensure superuser can delete app token for app with any scope of permissions."""
query = APP_TOKEN_DELETE_MUTATION
+ app = app_with_token
token = app.tokens.get()
app.permissions.add(permission_manage_products)
id = graphene.Node.to_global_id("AppToken", token.id)
@@ -139,7 +140,7 @@ def test_app_token_delete_for_app_out_of_scope_app(
permission_manage_products,
):
app = App.objects.create(name="New_app", is_active=True)
- token = AppToken.objects.create(app=app)
+ token, _ = AppToken.objects.create(app=app)
query = APP_TOKEN_DELETE_MUTATION
app.permissions.add(permission_manage_products)
id = graphene.Node.to_global_id("AppToken", token.id)
diff --git a/saleor/graphql/app/tests/mutations/test_app_token_verify.py b/saleor/graphql/app/tests/mutations/test_app_token_verify.py
index 6d70fc2913..98accc1a52 100644
--- a/saleor/graphql/app/tests/mutations/test_app_token_verify.py
+++ b/saleor/graphql/app/tests/mutations/test_app_token_verify.py
@@ -10,7 +10,7 @@ mutation AppTokenVerify($token: String!){
def test_app_token_verify_valid_token(app, api_client):
- token = app.tokens.first().auth_token
+ _, token = app.tokens.create()
query = APP_TOKEN_VERIFY_MUTATION
variables = {"token": token}
@@ -20,7 +20,7 @@ def test_app_token_verify_valid_token(app, api_client):
def test_app_token_verify_invalid_token(app, api_client):
- token = app.tokens.first().auth_token
+ _, token = app.tokens.create()
token += "incorrect"
query = APP_TOKEN_VERIFY_MUTATION
diff --git a/saleor/graphql/app/tests/mutations/test_app_update.py b/saleor/graphql/app/tests/mutations/test_app_update.py
index 7ea90d2e17..a2d4313e5f 100644
--- a/saleor/graphql/app/tests/mutations/test_app_update.py
+++ b/saleor/graphql/app/tests/mutations/test_app_update.py
@@ -33,7 +33,7 @@ mutation AppUpdate($id: ID!, $permissions: [PermissionEnum!]){
def test_app_update_mutation(
- app,
+ app_with_token,
permission_manage_apps,
permission_manage_products,
permission_manage_users,
@@ -41,6 +41,7 @@ def test_app_update_mutation(
staff_user,
):
query = APP_UPDATE_MUTATION
+ app = app_with_token
staff_user.user_permissions.add(permission_manage_products, permission_manage_users)
id = graphene.Node.to_global_id("App", app.id)
@@ -151,7 +152,7 @@ def test_app_update_mutation_out_of_scope_permissions(
def test_app_update_mutation_superuser_can_add_any_permissions_to_app(
- app,
+ app_with_token,
permission_manage_apps,
permission_manage_products,
permission_manage_users,
@@ -159,6 +160,7 @@ def test_app_update_mutation_superuser_can_add_any_permissions_to_app(
):
"""Ensure superuser can add any permissions to app."""
query = APP_UPDATE_MUTATION
+ app = app_with_token
id = graphene.Node.to_global_id("App", app.id)
variables = {
@@ -265,7 +267,7 @@ def test_app_update_mutation_out_of_scope_app(
def test_app_update_mutation_superuser_can_update_any_app(
- app,
+ app_with_token,
permission_manage_apps,
permission_manage_products,
permission_manage_orders,
@@ -274,6 +276,7 @@ def test_app_update_mutation_superuser_can_update_any_app(
):
"""Ensure superuser can manage any app."""
query = APP_UPDATE_MUTATION
+ app = app_with_token
app.permissions.add(permission_manage_orders)
id = graphene.Node.to_global_id("App", app.id)
diff --git a/saleor/graphql/app/tests/queries/test_app.py b/saleor/graphql/app/tests/queries/test_app.py
index c6c9a68fcd..292e753d81 100644
--- a/saleor/graphql/app/tests/queries/test_app.py
+++ b/saleor/graphql/app/tests/queries/test_app.py
@@ -60,10 +60,11 @@ def test_app_query(
staff_api_client,
permission_manage_apps,
permission_manage_staff,
- app,
+ app_with_token,
external_app,
webhook,
):
+ app = app_with_token
app = app if app_type == "custom" else external_app
app.permissions.add(permission_manage_staff)
diff --git a/saleor/graphql/app/types.py b/saleor/graphql/app/types.py
index f4568eceed..81ed074eb8 100644
--- a/saleor/graphql/app/types.py
+++ b/saleor/graphql/app/types.py
@@ -168,7 +168,7 @@ class AppToken(graphene.ObjectType):
@staticmethod
def resolve_auth_token(root: models.AppToken, _info, **_kwargs):
- return root.auth_token[-4:]
+ return root.token_last_4
@federated_entity("id")
diff --git a/saleor/graphql/context.py b/saleor/graphql/context.py
index 3ecae3b174..10407b8f6b 100644
--- a/saleor/graphql/context.py
+++ b/saleor/graphql/context.py
@@ -1,6 +1,7 @@
from typing import Optional
from django.contrib.auth import authenticate
+from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import AnonymousUser
from django.db.models import Exists, OuterRef
from django.utils.functional import SimpleLazyObject
@@ -16,10 +17,15 @@ def get_context_value(request):
return request
-def get_app(auth_token) -> Optional[App]:
- tokens = AppToken.objects.filter(auth_token=auth_token).values("pk")
+def get_app(raw_auth_token) -> Optional[App]:
+ tokens = AppToken.objects.filter(token_last_4=raw_auth_token[-4:]).values_list(
+ "id", "auth_token"
+ )
+ token_ids = [
+ id for id, auth_token in tokens if check_password(raw_auth_token, auth_token)
+ ]
return App.objects.filter(
- Exists(tokens.filter(app_id=OuterRef("pk"))), is_active=True
+ Exists(tokens.filter(id__in=token_ids, app_id=OuterRef("pk"))), is_active=True
).first()
diff --git a/saleor/graphql/core/tests/test_context.py b/saleor/graphql/core/tests/test_context.py
index 5e35572872..f6cf25af45 100644
--- a/saleor/graphql/core/tests/test_context.py
+++ b/saleor/graphql/core/tests/test_context.py
@@ -7,7 +7,7 @@ def test_app_middleware_accepts_app_requests(app, rf):
# given
# Retrieve sample request object
request = rf.get(reverse("api"))
- token = app.tokens.first().auth_token
+ _, token = app.tokens.create()
request.META = {"HTTP_AUTHORIZATION": f"Bearer {token}"}
# when
@@ -20,7 +20,7 @@ def test_app_middleware_accepts_app_requests(app, rf):
def test_app_middleware_accepts_saleors_header(app, rf):
# given
request = rf.get(reverse("api"))
- token = app.tokens.first().auth_token
+ _, token = app.tokens.create()
request.META = {"HTTP_AUTHORIZATION_BEARER": f"{token}"}
# when
@@ -30,7 +30,9 @@ def test_app_middleware_accepts_saleors_header(app, rf):
assert request.app == app
-def test_app_middleware_skips_when_token_length_is_different_than_30(app, rf):
+def test_app_middleware_skips_when_token_length_is_different_than_30(
+ app_with_token, rf
+):
# given
request = rf.get(reverse("api"))
request.META = {"HTTP_AUTHORIZATION_BEARER": "a" * 31}
diff --git a/saleor/graphql/tests/fixtures.py b/saleor/graphql/tests/fixtures.py
index f11a70b547..be2816c88e 100644
--- a/saleor/graphql/tests/fixtures.py
+++ b/saleor/graphql/tests/fixtures.py
@@ -38,8 +38,8 @@ class ApiClient(Client):
if not user.is_anonymous:
self.token = create_access_token(user)
elif app:
- token = app.tokens.first()
- self.app_token = token.auth_token if token else None
+ _, auth_token = app.tokens.create(name="Default")
+ self.app_token = auth_token
super().__init__(*args, **kwargs)
def _base_environ(self, **request):
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 2636d40c96..7b71ebdb75 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -5115,14 +5115,20 @@ def other_description_json():
@pytest.fixture
def app(db):
app = App.objects.create(name="Sample app objects", is_active=True)
- app.tokens.create(name="Default")
return app
@pytest.fixture
-def app_with_extensions(app, permission_manage_products):
+def app_with_token(db):
+ app = App.objects.create(name="Sample app objects", is_active=True)
+ app.tokens.create(name="Test")
+ return app
+
+
+def app_with_extensions(app_with_token, permission_manage_products):
first_app_extension = AppExtension(
- app=app,
+ app=app_with_token,
label="Create product with App",
url="www.example.com/app-product",
mount=AppExtensionMount.PRODUCT_OVERVIEW_MORE_ACTIONS,
@@ -5131,7 +5137,7 @@ def app_with_extensions(app, permission_manage_products):
[
first_app_extension,
AppExtension(
- app=app,
+ app=app_with_token,
label="Update product with App",
url="www.example.com/app-product-update",
mount=AppExtensionMount.PRODUCT_DETAILS_MORE_ACTIONS,
@@ -5139,7 +5145,7 @@ def app_with_extensions(app, permission_manage_products):
]
)
first_app_extension.permissions.add(permission_manage_products)
- return app, extensions
+ return app_with_token, extensions
@pytest.fixture