-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #7 from lukany/feature/dynamic-secret
Feature/dynamic secret
- Loading branch information
Showing
12 changed files
with
309 additions
and
195 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,26 +1,75 @@ | ||
import re | ||
import secrets | ||
from typing import Tuple | ||
|
||
from flask import Blueprint, current_app, request | ||
|
||
from ggci.google_chat import send_message | ||
from ggci.gitlab import MergeRequestEvent, UnsupportedEvent | ||
from ggci.google_chat import GoogleChatError, send_message | ||
from ggci.gitlab import MergeRequestEvent, InvalidFormat, UnsupportedEvent | ||
|
||
_GITLAB_TOKEN_REGEX_PATTERN = 'GGCI-SECRET=(.*);GOOGLE-CHAT-URL=(.*)' | ||
_GOOGLE_CHAT_REGEX_PATTERN = 'https://chat.googleapis.com/v1/spaces/.*' | ||
_UNAUTHORIZED_RESPONSE = ('Unauthorized', 401) | ||
|
||
bp = Blueprint('forwarder', __name__) | ||
|
||
|
||
def _get_gitlab_token(): | ||
return current_app.config['GGCI_GITLAB_TOKEN'] | ||
class IncorrectTokenFormat(Exception): | ||
pass | ||
|
||
|
||
class Unauthorized(Exception): | ||
pass | ||
|
||
|
||
def _parse_gitlab_token(gitlab_token: str) -> Tuple[str, str]: | ||
if not isinstance(gitlab_token, str): | ||
raise IncorrectTokenFormat() | ||
match = re.match(_GITLAB_TOKEN_REGEX_PATTERN, gitlab_token) | ||
if match is None: | ||
raise IncorrectTokenFormat() | ||
ggci_secret, google_chat_url = match.groups() | ||
return ggci_secret, google_chat_url | ||
|
||
|
||
def _authorize(ggci_secret: str) -> None: | ||
if not secrets.compare_digest( | ||
ggci_secret, current_app.config['GGCI_SECRET'] | ||
): | ||
raise Unauthorized() | ||
|
||
|
||
@bp.route('/', methods=['POST']) | ||
def forward(): | ||
|
||
if request.headers.get('X-Gitlab-Token') != _get_gitlab_token(): | ||
return '', 401 | ||
try: | ||
ggci_secret, google_chat_url = _parse_gitlab_token( | ||
gitlab_token=request.headers.get('X-Gitlab-Token'), | ||
) | ||
except IncorrectTokenFormat: | ||
return _UNAUTHORIZED_RESPONSE | ||
|
||
try: | ||
_authorize(ggci_secret=ggci_secret) | ||
except Unauthorized: | ||
return _UNAUTHORIZED_RESPONSE | ||
|
||
if re.fullmatch(_GOOGLE_CHAT_REGEX_PATTERN, google_chat_url) is None: | ||
return ( | ||
f'Google Chat URL does not match the following regex pattern:' | ||
f' {_GOOGLE_CHAT_REGEX_PATTERN}' | ||
), 400 | ||
|
||
try: | ||
mr_event = MergeRequestEvent.from_dict(request.json) | ||
except InvalidFormat as exc: | ||
return str(exc), 400 | ||
except UnsupportedEvent as exc: | ||
return str(exc), 501 | ||
|
||
send_message(message=mr_event.create_message()) | ||
try: | ||
send_message(url=google_chat_url, message=mr_event.create_message()) | ||
except GoogleChatError as exc: | ||
return str(exc), 500 | ||
|
||
return 'Success', 200 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,32 +1,37 @@ | ||
import logging | ||
from typing import Optional | ||
|
||
import requests | ||
from flask import current_app | ||
|
||
import tenacity | ||
|
||
from ggci.commons import Message | ||
|
||
_LOGGER = logging.getLogger(__name__) | ||
|
||
|
||
def _get_google_chat_url() -> Optional[str]: | ||
return current_app.config.get('GGCI_GOOGLE_CHAT_URL') | ||
class GoogleChatError(Exception): | ||
def __init__(self, error): | ||
|
||
if isinstance(error, tenacity.Future): | ||
# Tenacity initiates `retry_error_cls` with tenacity.Future. | ||
# containing more information along with the exception itself | ||
error = error.exception() | ||
|
||
def send_message(message: Message) -> None: | ||
super().__init__(error) | ||
|
||
url = _get_google_chat_url() | ||
|
||
if not isinstance(url, str): | ||
raise TypeError(f'Google Chat URL must be str, got: {type(url)}') | ||
if not url: | ||
raise ValueError('Google Chat URL must not be empty') | ||
@tenacity.retry( | ||
retry=tenacity.retry_if_exception_type(requests.exceptions.HTTPError), | ||
stop=tenacity.stop_after_attempt(5), | ||
wait=tenacity.wait.wait_random(min=0.05, max=0.2), | ||
retry_error_cls=GoogleChatError, | ||
) | ||
def send_message(url: str, message: Message) -> None: | ||
|
||
_LOGGER.info('Sending message...') | ||
_LOGGER.debug('Message: %s', message) | ||
|
||
if message.thread_key is not None: | ||
url += f'&threadKey=GGCI_{message.thread_key}' | ||
|
||
requests.post(url=url, json={'text': message.text}) | ||
response = requests.post(url=url, json={'text': message.text}) | ||
response.raise_for_status() |
Oops, something went wrong.