From 868ed17661c2956e33bcd3cefef3e7013293a421 Mon Sep 17 00:00:00 2001 From: Mateusz Mandera Date: Tue, 4 Jan 2022 21:59:51 +0100 Subject: [PATCH] remote_server: Handle invalid server uuid being given authing to API. get_remote_server_by_uuid (called in validate_api_key) raises ValidationError when given an invalid UUID due to how Django handles UUIDField. We don't want that exception and prefer the ordinary DoesNotExist exception to be raised. --- zerver/tests/test_push_notifications.py | 14 ++++++++++++++ zilencer/models.py | 6 +++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/zerver/tests/test_push_notifications.py b/zerver/tests/test_push_notifications.py index 367b7932d9..fb6f63eb01 100644 --- a/zerver/tests/test_push_notifications.py +++ b/zerver/tests/test_push_notifications.py @@ -241,6 +241,20 @@ class PushBouncerNotificationTest(BouncerTestCase): del self.API_KEYS[self.server_uuid] + self.API_KEYS["invalid_uuid"] = "invalid" + result = self.uuid_post( + "invalid_uuid", + endpoint, + dict(user_id=user_id, token_kind=token_kind, token=token), + subdomain="zulip", + ) + self.assert_json_error( + result, + "Zulip server auth failure: invalid_uuid is not registered -- did you run `manage.py register_server`?", + status_code=401, + ) + del self.API_KEYS["invalid_uuid"] + credentials_uuid = str(uuid.uuid4()) credentials = "{}:{}".format(credentials_uuid, "invalid") api_auth = "Basic " + base64.b64encode(credentials.encode()).decode() diff --git a/zilencer/models.py b/zilencer/models.py index 0cc0089f92..10d3495fae 100644 --- a/zilencer/models.py +++ b/zilencer/models.py @@ -3,6 +3,7 @@ from typing import List, Tuple from uuid import UUID from django.conf import settings +from django.core.exceptions import ValidationError from django.db import models from analytics.models import BaseCount @@ -12,7 +13,10 @@ from zerver.models import AbstractPushDeviceToken, AbstractRealmAuditLog def get_remote_server_by_uuid(uuid: str) -> "RemoteZulipServer": - return RemoteZulipServer.objects.get(uuid=uuid) + try: + return RemoteZulipServer.objects.get(uuid=uuid) + except ValidationError: + raise RemoteZulipServer.DoesNotExist() class RemoteZulipServer(models.Model):