Skip to content

Commit d803d98

Browse files
committed
Make Webhook views CSRF exempt
This way, these webhook can be called from a command line and authenticate them via session (user/password)
1 parent 4d91f61 commit d803d98

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

readthedocs/restapi/authentication.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# -*- coding: utf-8 -*-
2+
from rest_framework.authentication import SessionAuthentication
3+
4+
5+
class CsrfExemptSessionAuthentication(SessionAuthentication):
6+
"""
7+
Session authentication class exempt of CSRF.
8+
9+
DRF by default when using a ``SessionAuthentication`` it enforces CSRF.
10+
11+
See: https://github.com/encode/django-rest-framework/blob/3.9.0/rest_framework/authentication.py#L134-L144
12+
"""
13+
14+
def enforce_csrf(self, request):
15+
return

readthedocs/restapi/views/integrations.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
# -*- coding: utf-8 -*-
2-
31
"""Endpoints integrating with Github, Bitbucket, and other webhooks."""
42

53
import json
@@ -23,6 +21,8 @@
2321
from readthedocs.integrations.utils import normalize_request_payload
2422
from readthedocs.projects.models import Project
2523

24+
from ..authentication import CsrfExemptSessionAuthentication
25+
2626

2727
log = logging.getLogger(__name__)
2828

@@ -349,7 +349,7 @@ class IsAuthenticatedOrHasToken(permissions.IsAuthenticated):
349349
"""
350350

351351
def has_permission(self, request, view):
352-
has_perm = (super().has_permission(request, view))
352+
has_perm = super().has_permission(request, view)
353353
return has_perm or 'token' in request.data
354354

355355

@@ -422,6 +422,11 @@ class WebhookView(APIView):
422422
be.
423423
"""
424424

425+
# We want to avoid CSRF checking when authenticating by user/password on
426+
# this API endpoint so we can make a request like:
427+
# curl -X POST -d "branches=branch" -u user:pass -e URL /api/v2/webhook/test-builds/{pk}/
428+
authentication_classes = [CsrfExemptSessionAuthentication]
429+
425430
VIEW_MAP = {
426431
Integration.GITHUB_WEBHOOK: GitHubWebhookView,
427432
Integration.GITLAB_WEBHOOK: GitLabWebhookView,

0 commit comments

Comments
 (0)