Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

bots: Restrict bot_storage endpoints to bot accounts.

Agnish Bauri49903cf310c8
diff --git a/api_docs/changelog.md b/api_docs/changelog.md
index fe4068a763a..c02e7bb6a40 100644
--- a/api_docs/changelog.md
+++ b/api_docs/changelog.md
@@ -20,6 +20,15 @@ format used by the Zulip server that they are interacting with.
## Changes in Zulip 12.0
+**Feature level 494**
+
+* [`PUT /bot_storage`](/api/update-bot-storage),
+ [`GET /bot_storage`](/api/get-bot-storage),
+ [`DELETE /bot_storage`](/api/remove-bot-storage): These
+ endpoints now require the caller to be a bot user account.
+ Previously, any authenticated user account could call these
+ endpoints.
+
**Feature level 493**
* [`POST /register`](/api/register-queue), [`GET /events`](/api/get-events),
diff --git a/version.py b/version.py
index c24abee5a38..5639c87a582 100644
--- a/version.py
+++ b/version.py
@@ -33,7 +33,7 @@ DESKTOP_WARNING_VERSION = "5.9.3"
# https://zulip.readthedocs.io/en/latest/documentation/api.html#step-by-step-guide
# Also available at docs/documentation/api.md.
-API_FEATURE_LEVEL = 493
+API_FEATURE_LEVEL = 494
# Bump the minor PROVISION_VERSION to indicate that folks should provision
# only when going from an old version of the code to a newer version. Bump
diff --git a/zerver/decorator.py b/zerver/decorator.py
index 03457fb4d2d..197454a7295 100644
--- a/zerver/decorator.py
+++ b/zerver/decorator.py
@@ -30,6 +30,7 @@ from zerver.context_processors import get_valid_realm_from_request
from zerver.lib.exceptions import (
AccessDeniedError,
AnomalousWebhookPayloadError,
+ BotRequiredError,
InvalidAPIKeyError,
InvalidAPIKeyFormatError,
InvalidJSONError,
@@ -166,6 +167,24 @@ def require_realm_admin(
return wrapper
+def require_bot_user(
+ func: Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse],
+) -> Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse]:
+ @wraps(func)
+ def wrapper(
+ request: HttpRequest,
+ user_profile: UserProfile,
+ /,
+ *args: ParamT.args,
+ **kwargs: ParamT.kwargs,
+ ) -> HttpResponse:
+ if not user_profile.is_bot:
+ raise BotRequiredError
+ return func(request, user_profile, *args, **kwargs)
+
+ return wrapper
+
+
def check_if_user_can_manage_default_streams(
func: Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse],
) -> Callable[Concatenate[HttpRequest, UserProfile, ParamT], HttpResponse]:
diff --git a/zerver/lib/exceptions.py b/zerver/lib/exceptions.py
index ba87c2fd11f..4a6ebc53148 100644
--- a/zerver/lib/exceptions.py
+++ b/zerver/lib/exceptions.py
@@ -67,6 +67,7 @@ class ErrorCode(Enum):
FAILED_TO_CONNECT_BOUNCER = auto()
INTERNAL_SERVER_ERROR_ON_BOUNCER = auto()
ADMIN_ACTION_REQUIRED = auto()
+ PERMISSION_DENIED = auto()
class JsonableError(Exception):
@@ -336,6 +337,18 @@ class OrganizationOwnerRequiredError(JsonableError):
return _("Must be an organization owner")
+class BotRequiredError(JsonableError):
+ code: ErrorCode = ErrorCode.PERMISSION_DENIED
+
+ def __init__(self) -> None:
+ pass
+
+ @staticmethod
+ @override
+ def msg_format() -> str:
+ return _("Must be a bot user")
+
+
class AuthenticationFailedError(JsonableError):
# Generic class for authentication failures
code: ErrorCode = ErrorCode.AUTHENTICATION_FAILED
diff --git a/zerver/lib/test_classes.py b/zerver/lib/test_classes.py
index c3e71b18afa..6f3c061f864 100644
--- a/zerver/lib/test_classes.py
+++ b/zerver/lib/test_classes.py
@@ -1172,6 +1172,22 @@ Output:
**extra,
)
+ def api_put(
+ self, user: UserProfile, url: str, info: Mapping[str, Any] = {}, **extra: str
+ ) -> "TestHttpResponse":
+ assert not url.startswith("/json/"), "Invalid URL for API authentication"
+ extra["HTTP_AUTHORIZATION"] = self.encode_user(user)
+ return self.client_put(
+ url,
+ info,
+ skip_user_agent=False,
+ follow=False,
+ secure=False,
+ headers=None,
+ query_params=None,
+ **extra,
+ )
+
def api_patch(
self, user: UserProfile, url: str, info: Mapping[str, Any] = {}, **extra: str
) -> "TestHttpResponse":
diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yaml
index 304b8b9d421..6416d1eded6 100644
--- a/zerver/openapi/zulip.yaml
+++ b/zerver/openapi/zulip.yaml
@@ -7128,8 +7128,16 @@ paths:
summary: Get a bot's stored data
tags: ["bots"]
description: |
+ !!! warn ""
+
+ **Note:** This endpoint is only available to [bot user](/help/bots-overview)
+ accounts.
+
Retrieve [data stored](/help/interactive-bots-api#bot_handlerstorage)
for a bot user.
+
+ **Changes**: Prior to Zulip 12.0 (feature level 494), users who
+ were not bots could access this endpoint.
x-curl-examples-parameters:
oneOf:
- type: exclude
@@ -7201,16 +7209,34 @@ paths:
description: |
A typical failed JSON response when a requested key does not exist
in the bot's storage:
+ - allOf:
+ - $ref: "#/components/schemas/CodedError"
+ - example:
+ {
+ "code": "PERMISSION_DENIED",
+ "msg": "Must be a bot user",
+ "result": "error",
+ }
+ description: |
+ A typical failed JSON response when the user is not a bot:
put:
operationId: update-bot-storage
summary: Update a bot's stored data
tags: ["bots"]
description: |
+ !!! warn ""
+
+ **Note:** This endpoint is only available to [bot user](/help/bots-overview)
+ accounts.
+
Add or update [data stored](/help/interactive-bots-api#bot_handlerstorage)
for a bot user.
Each bot has a limited storage set by the server, which normally is a
default of 10,000,000 characters.
+
+ **Changes**: Prior to Zulip 12.0 (feature level 494), users who
+ were not bots could access this endpoint.
requestBody:
required: true
content:
@@ -7254,13 +7280,31 @@ paths:
description: |
A typical failed JSON response when the request would exceed the
server's storage size limit:
+ - allOf:
+ - $ref: "#/components/schemas/CodedError"
+ - example:
+ {
+ "code": "PERMISSION_DENIED",
+ "msg": "Must be a bot user",
+ "result": "error",
+ }
+ description: |
+ A typical failed JSON response when the user is not a bot:
delete:
operationId: remove-bot-storage
summary: Remove a bot's stored data
tags: ["bots"]
description: |
+ !!! warn ""
+
+ **Note:** This endpoint is only available to [bot user](/help/bots-overview)
+ accounts.
+
Delete [data stored](/help/interactive-bots-api#bot_handlerstorage)
for a bot user.
+
+ **Changes**: Prior to Zulip 12.0 (feature level 494), users who
+ were not bots could access this endpoint.
requestBody:
required: false
content:
@@ -7301,6 +7345,16 @@ paths:
description: |
A typical failed JSON response when a key to be deleted does not exist
in the bot's storage:
+ - allOf:
+ - $ref: "#/components/schemas/CodedError"
+ - example:
+ {
+ "code": "PERMISSION_DENIED",
+ "msg": "Must be a bot user",
+ "result": "error",
+ }
+ description: |
+ A typical failed JSON response when the user is not a bot:
/drafts:
get:
operationId: get-drafts
diff --git a/zerver/tests/test_service_bot_system.py b/zerver/tests/test_service_bot_system.py
index d4c618d0b7d..885c075858c 100644
--- a/zerver/tests/test_service_bot_system.py
+++ b/zerver/tests/test_service_bot_system.py
@@ -258,27 +258,36 @@ class TestServiceBotStateHandler(ZulipTestCase):
self.assertTrue(storage.contains("another key"))
self.assertRaises(StateError, lambda: storage.remove("some key"))
- def test_internal_endpoint(self) -> None:
- self.login_user(self.user_profile)
+ def test_bot_storage_restrictions(self) -> None:
+ bot_storage_url = "/api/v1/bot_storage"
+ result = self.api_put(self.user_profile, bot_storage_url, {"storage": "{}"})
+ self.assert_json_error(result, "Must be a bot user")
+ result = self.api_get(self.user_profile, bot_storage_url)
+ self.assert_json_error(result, "Must be a bot user")
+ result = self.api_delete(self.user_profile, bot_storage_url)
+ self.assert_json_error(result, "Must be a bot user")
+
+ def test_bot_storage_endpoint(self) -> None:
+ bot_storage_url = "/api/v1/bot_storage"
# Store some data.
initial_dict = {"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
params = {
"storage": orjson.dumps(initial_dict).decode(),
}
- result = self.client_put("/json/bot_storage", params)
+ result = self.api_put(self.bot_profile, bot_storage_url, params)
self.assert_json_success(result)
# Assert the stored data for some keys.
params = {
"keys": orjson.dumps(["key 1", "key 3"]).decode(),
}
- result = self.client_get("/json/bot_storage", params)
+ result = self.api_get(self.bot_profile, bot_storage_url, params)
response_dict = self.assert_json_success(result)
self.assertEqual(response_dict["storage"], {"key 3": "value 3", "key 1": "value 1"})
# Assert the stored data for all keys.
- result = self.client_get("/json/bot_storage")
+ result = self.api_get(self.bot_profile, bot_storage_url)
response_dict = self.assert_json_success(result)
self.assertEqual(response_dict["storage"], initial_dict)
@@ -287,13 +296,13 @@ class TestServiceBotStateHandler(ZulipTestCase):
params = {
"storage": orjson.dumps(dict_update).decode(),
}
- result = self.client_put("/json/bot_storage", params)
+ result = self.api_put(self.bot_profile, bot_storage_url, params)
self.assert_json_success(result)
# Assert the data was updated.
updated_dict = initial_dict.copy()
updated_dict.update(dict_update)
- result = self.client_get("/json/bot_storage")
+ result = self.api_get(self.bot_profile, bot_storage_url)
response_dict = self.assert_json_success(result)
self.assertEqual(response_dict["storage"], updated_dict)
@@ -301,19 +310,19 @@ class TestServiceBotStateHandler(ZulipTestCase):
invalid_params = {
"keys": ["This is a list, but should be a serialized string."],
}
- result = self.client_get("/json/bot_storage", invalid_params)
+ result = self.api_get(self.bot_profile, bot_storage_url, invalid_params)
self.assert_json_error(result, "keys is not valid JSON")
params = {
"keys": orjson.dumps(["key 1", "nonexistent key"]).decode(),
}
- result = self.client_get("/json/bot_storage", params)
+ result = self.api_get(self.bot_profile, bot_storage_url, params)
self.assert_json_error(result, "Key does not exist.")
params = {
"storage": orjson.dumps({"foo": [1, 2, 3]}).decode(),
}
- result = self.client_put("/json/bot_storage", params)
+ result = self.api_put(self.bot_profile, bot_storage_url, params)
self.assert_json_error(result, 'storage["foo"] is not a string')
# Remove some entries.
@@ -321,13 +330,13 @@ class TestServiceBotStateHandler(ZulipTestCase):
params = {
"keys": orjson.dumps(keys_to_remove).decode(),
}
- result = self.client_delete("/json/bot_storage", params)
+ result = self.api_delete(self.bot_profile, bot_storage_url, params)
self.assert_json_success(result)
# Assert the entries were removed.
for key in keys_to_remove:
updated_dict.pop(key)
- result = self.client_get("/json/bot_storage")
+ result = self.api_get(self.bot_profile, bot_storage_url)
response_dict = self.assert_json_success(result)
self.assertEqual(response_dict["storage"], updated_dict)
@@ -335,20 +344,20 @@ class TestServiceBotStateHandler(ZulipTestCase):
params = {
"keys": orjson.dumps(["key 3", "nonexistent key"]).decode(),
}
- result = self.client_delete("/json/bot_storage", params)
+ result = self.api_delete(self.bot_profile, bot_storage_url, params)
self.assert_json_error(result, "Key does not exist.")
# Assert an error has been thrown and no entries were removed.
- result = self.client_get("/json/bot_storage")
+ result = self.api_get(self.bot_profile, bot_storage_url)
response_dict = self.assert_json_success(result)
self.assertEqual(response_dict["storage"], updated_dict)
# Remove the entire storage.
- result = self.client_delete("/json/bot_storage")
+ result = self.api_delete(self.bot_profile, bot_storage_url)
self.assert_json_success(result)
# Assert the entire storage has been removed.
- result = self.client_get("/json/bot_storage")
+ result = self.api_get(self.bot_profile, bot_storage_url)
response_dict = self.assert_json_success(result)
self.assertEqual(response_dict["storage"], {})
diff --git a/zerver/views/storage.py b/zerver/views/storage.py
index ba0b92ad681..fd4fc371cc4 100644
--- a/zerver/views/storage.py
+++ b/zerver/views/storage.py
@@ -1,6 +1,7 @@
from django.http import HttpRequest, HttpResponse
from pydantic import Json
+from zerver.decorator import require_bot_user
from zerver.lib.bot_storage import (
StateError,
get_bot_storage,
@@ -14,6 +15,7 @@ from zerver.lib.typed_endpoint import typed_endpoint
from zerver.models import UserProfile
+@require_bot_user
@typed_endpoint
def update_storage(
request: HttpRequest,
@@ -28,6 +30,7 @@ def update_storage(
return json_success(request)
+@require_bot_user
@typed_endpoint
def get_storage(
request: HttpRequest,
@@ -44,6 +47,7 @@ def get_storage(
return json_success(request, data={"storage": storage})
+@require_bot_user
@typed_endpoint
def remove_storage(
request: HttpRequest,