Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
bitbucket2: Strengthen types using WildValue.
Anders Kaseorg652853818830
diff --git a/zerver/webhooks/bitbucket2/tests.py b/zerver/webhooks/bitbucket2/tests.pyindex c14f69c7e95..4d1af5e9479 100644--- a/zerver/webhooks/bitbucket2/tests.py+++ b/zerver/webhooks/bitbucket2/tests.py@@ -1,6 +1,7 @@from unittest.mock import MagicMock, patchfrom zerver.lib.test_classes import WebhookTestCase+from zerver.lib.validator import wrap_wild_valuefrom zerver.webhooks.bitbucket2.view import get_user_infoTOPIC = "Repository name"@@ -430,7 +431,7 @@ class Bitbucket2HookTests(WebhookTestCase):self.assert_json_success(result)def test_get_user_info(self) -> None:- self.assertEqual(get_user_info({}), "Unknown user")+ self.assertEqual(get_user_info(wrap_wild_value("request", {})), "Unknown user")dct = dict(nickname="alice",@@ -438,10 +439,10 @@ class Bitbucket2HookTests(WebhookTestCase):display_name="Alice Smith",)- self.assertEqual(get_user_info(dct), "Alice Smith")+ self.assertEqual(get_user_info(wrap_wild_value("request", dct)), "Alice Smith")del dct["display_name"]- self.assertEqual(get_user_info(dct), "alice")+ self.assertEqual(get_user_info(wrap_wild_value("request", dct)), "alice")del dct["nickname"]- self.assertEqual(get_user_info(dct), "Unknown user")+ self.assertEqual(get_user_info(wrap_wild_value("request", dct)), "Unknown user")diff --git a/zerver/webhooks/bitbucket2/view.py b/zerver/webhooks/bitbucket2/view.pyindex 785fbfe5fd1..1ea5d6cef7d 100644--- a/zerver/webhooks/bitbucket2/view.py+++ b/zerver/webhooks/bitbucket2/view.py@@ -2,7 +2,7 @@import reimport stringfrom functools import partial-from typing import Any, Dict, List, Optional+from typing import Dict, List, Optionalfrom django.http import HttpRequest, HttpResponsefrom typing_extensions import Protocol@@ -11,6 +11,7 @@ from zerver.decorator import log_unsupported_webhook_event, webhook_viewfrom zerver.lib.exceptions import UnsupportedWebhookEventTypefrom zerver.lib.request import REQ, has_request_variablesfrom zerver.lib.response import json_success+from zerver.lib.validator import WildValue, check_bool, check_int, check_string, to_wild_valuefrom zerver.lib.webhooks.common import (check_send_webhook_message,validate_extract_webhook_http_header,@@ -79,7 +80,7 @@ ALL_EVENT_TYPES = [def api_bitbucket2_webhook(request: HttpRequest,user_profile: UserProfile,- payload: Dict[str, Any] = REQ(argument_type="body"),+ payload: WildValue = REQ(argument_type="body", converter=to_wild_value),branches: Optional[str] = REQ(default=None),user_specified_topic: Optional[str] = REQ("topic", default=None),) -> HttpResponse:@@ -116,7 +117,7 @@ def api_bitbucket2_webhook(def get_subject_for_branch_specified_events(- payload: Dict[str, Any], branch_name: Optional[str] = None+ payload: WildValue, branch_name: Optional[str] = None) -> str:return TOPIC_WITH_BRANCH_TEMPLATE.format(repo=get_repository_name(payload["repository"]),@@ -124,63 +125,62 @@ def get_subject_for_branch_specified_events()-def get_push_subjects(payload: Dict[str, Any]) -> List[str]:+def get_push_subjects(payload: WildValue) -> List[str]:subjects_list = []for change in payload["push"]["changes"]:- potential_tag = (change["new"] or change["old"] or {}).get("type")+ potential_tag = (change["new"] or change["old"])["type"].tame(check_string)if potential_tag == "tag":- subjects_list.append(str(get_subject(payload)))+ subjects_list.append(get_subject(payload))else:if change.get("new"):- branch_name = change["new"]["name"]+ branch_name = change["new"]["name"].tame(check_string)else:- branch_name = change["old"]["name"]- subjects_list.append(str(get_subject_for_branch_specified_events(payload, branch_name)))+ branch_name = change["old"]["name"].tame(check_string)+ subjects_list.append(get_subject_for_branch_specified_events(payload, branch_name))return subjects_list-def get_subject(payload: Dict[str, Any]) -> str:- assert payload["repository"] is not None+def get_subject(payload: WildValue) -> str:return BITBUCKET_TOPIC_TEMPLATE.format(repository_name=get_repository_name(payload["repository"]))-def get_subject_based_on_type(payload: Dict[str, Any], type: str) -> str:+def get_subject_based_on_type(payload: WildValue, type: str) -> str:if type.startswith("pull_request"):return TOPIC_WITH_PR_OR_ISSUE_INFO_TEMPLATE.format(repo=get_repository_name(payload["repository"]),type="PR",- id=payload["pullrequest"]["id"],- title=payload["pullrequest"]["title"],+ id=payload["pullrequest"]["id"].tame(check_int),+ title=payload["pullrequest"]["title"].tame(check_string),)if type.startswith("issue"):return TOPIC_WITH_PR_OR_ISSUE_INFO_TEMPLATE.format(repo=get_repository_name(payload["repository"]),type="issue",- id=payload["issue"]["id"],- title=payload["issue"]["title"],+ id=payload["issue"]["id"].tame(check_int),+ title=payload["issue"]["title"].tame(check_string),)assert type != "push"return get_subject(payload)-def get_type(request: HttpRequest, payload: Dict[str, Any]) -> str:- if payload.get("push"):+def get_type(request: HttpRequest, payload: WildValue) -> str:+ if "push" in payload:return "push"- elif payload.get("fork"):+ elif "fork" in payload:return "fork"- elif payload.get("comment") and payload.get("commit"):+ elif "comment" in payload and "commit" in payload:return "commit_comment"- elif payload.get("commit_status"):+ elif "commit_status" in payload:return "change_commit_status"- elif payload.get("issue"):- if payload.get("changes"):+ elif "issue" in payload:+ if "changes" in payload:return "issue_updated"- if payload.get("comment"):+ if "comment" in payload:return "issue_commented"return "issue_created"- elif payload.get("pullrequest"):+ elif "pullrequest" in payload:pull_request_template = "pull_request_{}"# Note that we only need the HTTP header to determine pullrequest events.# We rely on the payload itself to determine the other ones.@@ -200,7 +200,7 @@ def get_type(request: HttpRequest, payload: Dict[str, Any]) -> str:class BodyGetter(Protocol):- def __call__(self, payload: Dict[str, Any], include_title: bool) -> str:+ def __call__(self, payload: WildValue, include_title: bool) -> str:...@@ -210,65 +210,65 @@ def get_body_based_on_type(return GET_SINGLE_MESSAGE_BODY_DEPENDING_ON_TYPE_MAPPER[type]-def get_push_bodies(payload: Dict[str, Any]) -> List[str]:+def get_push_bodies(payload: WildValue) -> List[str]:messages_list = []for change in payload["push"]["changes"]:- potential_tag = (change["new"] or change["old"] or {}).get("type")+ potential_tag = (change["new"] or change["old"])["type"].tame(check_string)if potential_tag == "tag":messages_list.append(get_push_tag_body(payload, change))# if change['new'] is None, that means a branch was deleted- elif change.get("new") is None:+ elif change["new"].value is None:messages_list.append(get_remove_branch_push_body(payload, change))- elif change.get("forced"):+ elif change["forced"].tame(check_bool):messages_list.append(get_force_push_body(payload, change))else:messages_list.append(get_normal_push_body(payload, change))return messages_list-def get_remove_branch_push_body(payload: Dict[str, Any], change: Dict[str, Any]) -> str:+def get_remove_branch_push_body(payload: WildValue, change: WildValue) -> str:return get_remove_branch_event_message(get_actor_info(payload),- change["old"]["name"],+ change["old"]["name"].tame(check_string),)-def get_force_push_body(payload: Dict[str, Any], change: Dict[str, Any]) -> str:+def get_force_push_body(payload: WildValue, change: WildValue) -> str:return get_force_push_commits_event_message(get_actor_info(payload),- change["links"]["html"]["href"],- change["new"]["name"],- change["new"]["target"]["hash"],+ change["links"]["html"]["href"].tame(check_string),+ change["new"]["name"].tame(check_string),+ change["new"]["target"]["hash"].tame(check_string),)-def get_commit_author_name(commit: Dict[str, Any]) -> str:- if commit["author"].get("user"):+def get_commit_author_name(commit: WildValue) -> str:+ if "user" in commit["author"]:return get_user_info(commit["author"]["user"])- return commit["author"]["raw"].split()[0]+ return commit["author"]["raw"].tame(check_string).split()[0]-def get_normal_push_body(payload: Dict[str, Any], change: Dict[str, Any]) -> str:+def get_normal_push_body(payload: WildValue, change: WildValue) -> str:commits_data = [{"name": get_commit_author_name(commit),- "sha": commit.get("hash"),- "url": commit.get("links").get("html").get("href"),- "message": commit.get("message"),+ "sha": commit["hash"].tame(check_string),+ "url": commit["links"]["html"]["href"].tame(check_string),+ "message": commit["message"].tame(check_string),}for commit in change["commits"]]return get_push_commits_event_message(get_actor_info(payload),- change["links"]["html"]["href"],- change["new"]["name"],+ change["links"]["html"]["href"].tame(check_string),+ change["new"]["name"].tame(check_string),commits_data,- is_truncated=change["truncated"],+ is_truncated=change["truncated"].tame(check_bool),)-def get_fork_body(payload: Dict[str, Any], include_title: bool) -> str:+def get_fork_body(payload: WildValue, include_title: bool) -> str:return BITBUCKET_FORK_BODY.format(actor=get_user_info(payload["actor"]),fork_name=get_repository_full_name(payload["fork"]),@@ -276,20 +276,20 @@ def get_fork_body(payload: Dict[str, Any], include_title: bool) -> str:)-def get_commit_comment_body(payload: Dict[str, Any], include_title: bool) -> str:+def get_commit_comment_body(payload: WildValue, include_title: bool) -> str:comment = payload["comment"]- action = "[commented]({})".format(comment["links"]["html"]["href"])+ action = "[commented]({})".format(comment["links"]["html"]["href"].tame(check_string))return get_commits_comment_action_message(get_actor_info(payload),action,- comment["commit"]["links"]["html"]["href"],- comment["commit"]["hash"],- comment["content"]["raw"],+ comment["commit"]["links"]["html"]["href"].tame(check_string),+ comment["commit"]["hash"].tame(check_string),+ comment["content"]["raw"].tame(check_string),)-def get_commit_status_changed_body(payload: Dict[str, Any], include_title: bool) -> str:- commit_api_url = payload["commit_status"]["links"]["commit"]["href"]+def get_commit_status_changed_body(payload: WildValue, include_title: bool) -> str:+ commit_api_url = payload["commit_status"]["links"]["commit"]["href"].tame(check_string)commit_id = commit_api_url.split("/")[-1]commit_info = "[{short_commit_id}]({repo_url}/commits/{commit_id})".format(@@ -299,89 +299,95 @@ def get_commit_status_changed_body(payload: Dict[str, Any], include_title: bool))return BITBUCKET_COMMIT_STATUS_CHANGED_BODY.format(- key=payload["commit_status"]["key"],- system_url=payload["commit_status"]["url"],+ key=payload["commit_status"]["key"].tame(check_string),+ system_url=payload["commit_status"]["url"].tame(check_string),commit_info=commit_info,- status=payload["commit_status"]["state"],+ status=payload["commit_status"]["state"].tame(check_string),)-def get_issue_commented_body(payload: Dict[str, Any], include_title: bool) -> str:- action = "[commented]({}) on".format(payload["comment"]["links"]["html"]["href"])+def get_issue_commented_body(payload: WildValue, include_title: bool) -> str:+ action = "[commented]({}) on".format(+ payload["comment"]["links"]["html"]["href"].tame(check_string)+ )return get_issue_action_body(payload, action, include_title)-def get_issue_action_body(payload: Dict[str, Any], action: str, include_title: bool) -> str:+def get_issue_action_body(payload: WildValue, action: str, include_title: bool) -> str:issue = payload["issue"]assignee = Nonemessage = Noneif action == "created":if issue["assignee"]:assignee = get_user_info(issue["assignee"])- message = issue["content"]["raw"]+ message = issue["content"]["raw"].tame(check_string)return get_issue_event_message(get_actor_info(payload),action,- issue["links"]["html"]["href"],- issue["id"],+ issue["links"]["html"]["href"].tame(check_string),+ issue["id"].tame(check_int),message,assignee,- title=issue["title"] if include_title else None,+ title=issue["title"].tame(check_string) if include_title else None,)-def get_pull_request_action_body(payload: Dict[str, Any], action: str, include_title: bool) -> str:+def get_pull_request_action_body(payload: WildValue, action: str, include_title: bool) -> str:pull_request = payload["pullrequest"]return get_pull_request_event_message(get_actor_info(payload),action,get_pull_request_url(pull_request),- pull_request.get("id"),- title=pull_request["title"] if include_title else None,+ pull_request["id"].tame(check_int),+ title=pull_request["title"].tame(check_string) if include_title else None,)def get_pull_request_created_or_updated_body(- payload: Dict[str, Any], action: str, include_title: bool+ payload: WildValue, action: str, include_title: bool) -> str:pull_request = payload["pullrequest"]assignee = None- if pull_request.get("reviewers"):- assignee = get_user_info(pull_request.get("reviewers")[0])+ if pull_request["reviewers"]:+ assignee = get_user_info(pull_request["reviewers"][0])return get_pull_request_event_message(get_actor_info(payload),action,get_pull_request_url(pull_request),- pull_request.get("id"),- target_branch=pull_request["source"]["branch"]["name"],- base_branch=pull_request["destination"]["branch"]["name"],- message=pull_request["description"],+ pull_request["id"].tame(check_int),+ target_branch=pull_request["source"]["branch"]["name"].tame(check_string),+ base_branch=pull_request["destination"]["branch"]["name"].tame(check_string),+ message=pull_request["description"].tame(check_string),assignee=assignee,- title=pull_request["title"] if include_title else None,+ title=pull_request["title"].tame(check_string) if include_title else None,)def get_pull_request_comment_created_action_body(- payload: Dict[str, Any],+ payload: WildValue,include_title: bool,) -> str:- action = "[commented]({})".format(payload["comment"]["links"]["html"]["href"])+ action = "[commented]({})".format(+ payload["comment"]["links"]["html"]["href"].tame(check_string)+ )return get_pull_request_comment_action_body(payload, action, include_title)def get_pull_request_deleted_or_updated_comment_action_body(- payload: Dict[str, Any],+ payload: WildValue,action: str,include_title: bool,) -> str:- action = "{} a [comment]({})".format(action, payload["comment"]["links"]["html"]["href"])+ action = "{} a [comment]({})".format(+ action, payload["comment"]["links"]["html"]["href"].tame(check_string)+ )return get_pull_request_comment_action_body(payload, action, include_title)def get_pull_request_comment_action_body(- payload: Dict[str, Any],+ payload: WildValue,action: str,include_title: bool,) -> str:@@ -389,14 +395,14 @@ def get_pull_request_comment_action_body(return get_pull_request_event_message(get_actor_info(payload),action,- payload["pullrequest"]["links"]["html"]["href"],- payload["pullrequest"]["id"],- message=payload["comment"]["content"]["raw"],- title=payload["pullrequest"]["title"] if include_title else None,+ payload["pullrequest"]["links"]["html"]["href"].tame(check_string),+ payload["pullrequest"]["id"].tame(check_int),+ message=payload["comment"]["content"]["raw"].tame(check_string),+ title=payload["pullrequest"]["title"].tame(check_string) if include_title else None,)-def get_push_tag_body(payload: Dict[str, Any], change: Dict[str, Any]) -> str:+def get_push_tag_body(payload: WildValue, change: WildValue) -> str:if change.get("new"):tag = change["new"]action = "pushed"@@ -406,8 +412,8 @@ def get_push_tag_body(payload: Dict[str, Any], change: Dict[str, Any]) -> str:return get_push_tag_event_message(get_actor_info(payload),- tag.get("name"),- tag_url=tag["links"]["html"].get("href"),+ tag["name"].tame(check_string),+ tag_url=tag["links"]["html"]["href"].tame(check_string),action=action,)@@ -419,10 +425,10 @@ def append_punctuation(title: str, message: str) -> str:return message-def get_repo_updated_body(payload: Dict[str, Any], include_title: bool) -> str:+def get_repo_updated_body(payload: WildValue, include_title: bool) -> str:changes = ["website", "name", "links", "language", "full_name", "description"]body = ""- repo_name = payload["repository"]["name"]+ repo_name = payload["repository"]["name"].tame(check_string)actor = get_actor_info(payload)for change in changes:@@ -435,49 +441,49 @@ def get_repo_updated_body(payload: Dict[str, Any], include_title: bool) -> str:actor=actor,change=change,repo_name=repo_name,- old=old,- new=new,+ old=str(old.value),+ new=str(new.value),)- message = append_punctuation(str(new), message) + "\n"+ message = append_punctuation(str(new.value), message) + "\n"body += messageelif new and not old:message = BITBUCKET_REPO_UPDATED_ADDED.format(actor=actor,change=change,repo_name=repo_name,- new=new,+ new=str(new.value),)- message = append_punctuation(str(new), message) + "\n"+ message = append_punctuation(str(new.value), message) + "\n"body += messagereturn body-def get_pull_request_url(pullrequest_payload: Dict[str, Any]) -> str:- return pullrequest_payload["links"]["html"]["href"]+def get_pull_request_url(pullrequest_payload: WildValue) -> str:+ return pullrequest_payload["links"]["html"]["href"].tame(check_string)-def get_repository_url(repository_payload: Dict[str, Any]) -> str:- return repository_payload["links"]["html"]["href"]+def get_repository_url(repository_payload: WildValue) -> str:+ return repository_payload["links"]["html"]["href"].tame(check_string)-def get_repository_name(repository_payload: Dict[str, Any]) -> str:- return repository_payload["name"]+def get_repository_name(repository_payload: WildValue) -> str:+ return repository_payload["name"].tame(check_string)-def get_repository_full_name(repository_payload: Dict[str, Any]) -> str:- return repository_payload["full_name"]+def get_repository_full_name(repository_payload: WildValue) -> str:+ return repository_payload["full_name"].tame(check_string)-def get_user_info(dct: Dict[str, Any]) -> str:+def get_user_info(dct: WildValue) -> str:# See https://developer.atlassian.com/cloud/bitbucket/bitbucket-api-changes-gdpr/# Since GDPR, we don't get username; instead, we either get display_name# or nickname.if "display_name" in dct:- return dct["display_name"]+ return dct["display_name"].tame(check_string)if "nickname" in dct:- return dct["nickname"]+ return dct["nickname"].tame(check_string)# We call this an unsupported_event, even though we# are technically still sending a message.@@ -488,18 +494,18 @@ def get_user_info(dct: Dict[str, Any]) -> str:return "Unknown user"-def get_actor_info(payload: Dict[str, Any]) -> str:+def get_actor_info(payload: WildValue) -> str:actor = payload["actor"]return get_user_info(actor)-def get_branch_name_for_push_event(payload: Dict[str, Any]) -> Optional[str]:+def get_branch_name_for_push_event(payload: WildValue) -> Optional[str]:change = payload["push"]["changes"][-1]- potential_tag = (change["new"] or change["old"] or {}).get("type")+ potential_tag = (change["new"] or change["old"])["type"].tame(check_string)if potential_tag == "tag":return Noneelse:- return (change["new"] or change["old"]).get("name")+ return (change["new"] or change["old"])["name"].tame(check_string)GET_SINGLE_MESSAGE_BODY_DEPENDING_ON_TYPE_MAPPER: Dict[str, BodyGetter] = {