From 7d683018bdef0d3dd91b072017ab1427017b1bca Mon Sep 17 00:00:00 2001 From: Zixuan James Li Date: Mon, 14 Aug 2023 17:54:59 -0400 Subject: [PATCH] webhooks: Migrate travis to use @typed_endpoint. To perform the same check, we define a Pydantic model. This includes some keys "build_url" and "type" that we did not check for previously. --- zerver/webhooks/travis/view.py | 42 +++++++++++++++++----------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/zerver/webhooks/travis/view.py b/zerver/webhooks/travis/view.py index 17cc4b073f..75ba7c5a85 100644 --- a/zerver/webhooks/travis/view.py +++ b/zerver/webhooks/travis/view.py @@ -1,12 +1,12 @@ # Webhooks for external integrations. -from typing import Dict from django.http import HttpRequest, HttpResponse +from pydantic import BaseModel, Json +from typing_extensions import Annotated from zerver.decorator import webhook_view -from zerver.lib.request import REQ, has_request_variables from zerver.lib.response import json_success -from zerver.lib.validator import check_bool, check_dict, check_string +from zerver.lib.typed_endpoint import ApiParamConfig, typed_endpoint from zerver.lib.webhooks.common import check_send_webhook_message from zerver.models import UserProfile @@ -24,26 +24,26 @@ Build status: {} {} Details: [changes]({}), [build log]({})""" +class TravisPayload(BaseModel): + author_name: str + status_message: str + compare_url: str + build_url: str + type: str + + @webhook_view("Travis", all_event_types=ALL_EVENT_TYPES) -@has_request_variables +@typed_endpoint def api_travis_webhook( request: HttpRequest, user_profile: UserProfile, - ignore_pull_requests: bool = REQ(json_validator=check_bool, default=True), - message: Dict[str, object] = REQ( - "payload", - json_validator=check_dict( - [ - ("author_name", check_string), - ("status_message", check_string), - ("compare_url", check_string), - ] - ), - ), + *, + message: Annotated[Json[TravisPayload], ApiParamConfig("payload")], + ignore_pull_requests: Json[bool] = True, ) -> HttpResponse: - event = str(message["type"]) - message_status = message["status_message"] - if ignore_pull_requests and message["type"] == "pull_request": + event = message.type + message_status = message.status_message + if ignore_pull_requests and message.type == "pull_request": return json_success(request) if message_status in GOOD_STATUSES: @@ -56,11 +56,11 @@ def api_travis_webhook( emoji = f"(No emoji specified for status '{message_status}'.)" body = MESSAGE_TEMPLATE.format( - message["author_name"], + message.author_name, message_status, emoji, - message["compare_url"], - message["build_url"], + message.compare_url, + message.build_url, ) topic = "builds"