Skip to content

Commit

Permalink
Add command to create webhook with random secret
Browse files Browse the repository at this point in the history
  • Loading branch information
tulir committed Jun 12, 2021
1 parent 811a083 commit 19fda9e
Show file tree
Hide file tree
Showing 6 changed files with 38 additions and 19 deletions.
1 change: 0 additions & 1 deletion base-config.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
path: "/webhooks"
secret: "passwd"
base_command: "gitlab"
send_as_notice: true
Expand Down
4 changes: 3 additions & 1 deletion gitlab_matrix/commands/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@
from .alias import CommandAlias
from .server import CommandServer
from .commit import CommandCommit
from .webhook import CommandWebhook


class GitlabCommands(CommandRoom, CommandIssue, CommandAlias, CommandServer, CommandCommit):
class GitlabCommands(CommandRoom, CommandIssue, CommandAlias, CommandServer, CommandCommit,
CommandWebhook):
pass


Expand Down
18 changes: 18 additions & 0 deletions gitlab_matrix/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,13 @@ class MatrixMessage(Base):
event_id: EventID = Column(String(255), nullable=False)


class WebhookToken(Base):
__tablename__ = "webhook_token"

room_id: RoomID = Column(Text, nullable=False)
secret: str = Column(Text, primary_key=True)


class Database:
db: Engine

Expand Down Expand Up @@ -199,3 +206,14 @@ def change_default(self, mxid: UserID, url: str) -> None:
default = s.query(Default).get((mxid,))
default.gitlab_server = url
s.commit()

def get_webhook_room(self, secret: str) -> Optional[RoomID]:
s = self.Session()
webhook_token = s.query(WebhookToken).get((secret,))
return webhook_token.room_id if webhook_token else None

def add_webhook_room(self, secret: str, room_id: RoomID) -> None:
s = self.Session()
webhook_token = WebhookToken(secret=secret, room_id=room_id)
s.add(webhook_token)
s.commit()
16 changes: 8 additions & 8 deletions gitlab_matrix/util/arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from maubot.handlers.command import Argument

if TYPE_CHECKING:
from ..bot import GitlabBot
from ..commands import Command


class OptUrlAliasArgument(Argument):
Expand All @@ -30,26 +30,26 @@ def __init__(self, name: str, label: str = None,
super().__init__(name, label=label, required=required, pass_raw=True)
self.arg_num = arg_num

def match(self, val: str, evt: MessageEvent, instance: 'GitlabBot', **kwargs
def match(self, val: str, evt: MessageEvent, instance: 'Command', **kwargs
) -> Tuple[str, Any]:
vals = val.split(" ")

if (len(vals) > self.arg_num
and (vals[0] in instance.db.get_servers(evt.sender)
or vals[0] in instance.db.get_aliases(evt.sender))):
return " ".join(vals[1:]), instance.db.get_login(evt.sender, url_alias=val[0])
return val, instance.db.get_login(evt.sender)
and (vals[0] in instance.bot.db.get_servers(evt.sender)
or vals[0] in instance.bot.db.get_aliases(evt.sender))):
return " ".join(vals[1:]), instance.bot.db.get_login(evt.sender, url_alias=val[0])
return val, instance.bot.db.get_login(evt.sender)


class OptRepoArgument(Argument):
def __init__(self, name: str, label: str = None, required: bool = False) -> None:
super().__init__(name, label=label, required=required)

def match(self, val: str, evt: MessageEvent, instance: 'GitlabBot', **kwargs
def match(self, val: str, evt: MessageEvent, instance: 'Command', **kwargs
) -> Tuple[str, Any]:
repo = re.split(r"\s", val, 1)[0]

default_repo = instance.db.get_default_repo(evt.room_id)
default_repo = instance.bot.db.get_default_repo(evt.room_id)
if not default_repo or re.fullmatch(r"\w+/[\w/]+", repo):
return val[len(repo):], repo
return val, default_repo
Expand Down
1 change: 0 additions & 1 deletion gitlab_matrix/util/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@

class Config(BaseProxyConfig):
def do_update(self, helper: ConfigUpdateHelper) -> None:
helper.copy("path")
helper.copy("secret")
helper.copy("base_command")
helper.copy("send_as_notice")
Expand Down
17 changes: 9 additions & 8 deletions gitlab_matrix/webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,16 @@ async def post_handler(self, request: Request) -> Response:
except KeyError:
return Response(text="401: Unauthorized\n"
"Missing auth token header\n", status=401)
if token == self.bot.config["secret"]:
try:
room_id = RoomID(request.query["room"])
except KeyError:
return Response(text="400: Bad request\nNo room specified. "
"Did you forget the ?room query parameter?\n",
status=400)
else:
if token != self.bot.config["secret"]:
room_id = self.bot.db.get_webhook_room(token)
if not room_id:
return Response(text="401: Unauthorized\n", status=401)

try:
Expand All @@ -79,13 +87,6 @@ async def post_handler(self, request: Request) -> Response:
return Response(text="400: Bad request\n"
"Event type not specified\n", status=400)

try:
room_id = RoomID(request.query["room"])
except KeyError:
return Response(text="400: Bad request\n"
"No room specified. Did you forget the ?room query parameter?\n",
status=400)

if not request.can_read_body:
return Response(status=400, text="400: Bad request\n"
"Missing request body\n")
Expand Down

0 comments on commit 19fda9e

Please sign in to comment.