Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/rest-api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,9 @@ You can either provide:

Webhook fields:
- ``webhook_url`` (string, optional): A single webhook URL to be notified.
It must be an absolute ``http(s)`` URL. Any other value is ignored: the
project is created without that webhook and a warning message is added to
the project.
- ``webhooks`` (list, optional): A list of webhook configurations.
- ``target_url`` (string, required): The URL to which the webhook will send a
``POST`` request.
Expand Down
33 changes: 32 additions & 1 deletion scanpipe/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
# ScanCode.io is a free software code scanning tool from nexB Inc. and others.
# Visit https://github.com/aboutcode-org/scancode.io for support and download.

from urllib.parse import urlparse

from django.apps import apps

from rest_framework import serializers
Expand Down Expand Up @@ -154,6 +156,24 @@ class Meta:
]


def is_absolute_http_url(url):
"""
Return True if the `url` has an http(s) scheme and a host, and no whitespace.

Django's URLValidator is not used here as it rejects single-label hosts,
such as ``http://dejacode:8000/``, which are common in container networks.
"""
try:
parsed = urlparse(url)
has_scheme_and_host = parsed.scheme in ("http", "https") and bool(
parsed.hostname
)
except ValueError:
return False
# urlparse drops tabs and newlines and keeps spaces: none belong in a URL.
return has_scheme_and_host and not any(char.isspace() for char in url)


class WebhookSubscriptionSerializer(serializers.ModelSerializer):
class Meta:
model = WebhookSubscription
Expand Down Expand Up @@ -334,7 +354,18 @@ def create(self, validated_data):
project.add_pipeline(pipeline_name, execute_now, selected_groups=groups)

if webhook_url:
project.add_webhook_subscription(target_url=webhook_url)
if is_absolute_http_url(webhook_url):
project.add_webhook_subscription(target_url=webhook_url)
else:
# The project is still created: a client that ignores the response
# would otherwise lose its scan along with the notification.
project.add_warning(
description=(
f'Webhook subscription not created: "{webhook_url}" is not '
f"an absolute http(s) URL."
),
model=WebhookSubscription,
)

for webhook_data in webhooks:
project.add_webhook_subscription(**webhook_data)
Expand Down
55 changes: 55 additions & 0 deletions scanpipe/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
from scanpipe.api.serializers import ProjectSerializer
from scanpipe.api.serializers import get_model_serializer
from scanpipe.api.serializers import get_serializer_fields
from scanpipe.api.serializers import is_absolute_http_url
from scanpipe.models import APIToken
from scanpipe.models import CodebaseRelation
from scanpipe.models import CodebaseResource
Expand Down Expand Up @@ -577,6 +578,60 @@ def test_scanpipe_api_project_create_pipeline_groups(self):
self.assertEqual(["Java", "JavaScript"], runs[0].selected_groups)
self.assertEqual(["StaticResolver"], runs[1].selected_groups)

def test_scanpipe_api_project_create_webhook_url(self):
webhook_url = "http://server:8000/notifications/IjEi:1sZEvv:_br-G/"
data = {"name": "Project1", "webhook_url": webhook_url}
response = self.csrf_client.post(self.project_list_url, data)
self.assertEqual(status.HTTP_201_CREATED, response.status_code)

project = Project.objects.get(name=data["name"])
webhook_subscription = project.webhooksubscriptions.get()
self.assertEqual(webhook_url, webhook_subscription.target_url)
self.assertEqual(0, project.projectmessages.count())

def test_scanpipe_api_project_create_webhook_url_not_absolute(self):
# A sender with an empty base URL setting ends up providing only the path.
# The ":" in the path makes `requests` fail with "No connection adapters".
webhook_url = "/notifications/send_scan_notification/IjEi:1sZEvv:_br-G/"
data = {"name": "Project1", "webhook_url": webhook_url}
response = self.csrf_client.post(self.project_list_url, data)
self.assertEqual(status.HTTP_201_CREATED, response.status_code)

project = Project.objects.get(name=data["name"])
self.assertEqual(0, project.webhooksubscriptions.count())
message = project.projectmessages.get()
self.assertEqual("warning", message.severity)
self.assertEqual("WebhookSubscription", message.model)
expected = (
f'Webhook subscription not created: "{webhook_url}" is not an absolute '
f"http(s) URL."
)
self.assertEqual(expected, message.description)

def test_scanpipe_api_is_absolute_http_url(self):
valid = [
"https://example.com/webhook",
"http://dejacode:8000/notifications/key/",
"http://127.0.0.1:8000/",
"http://[::1]:8000/hook",
]
for url in valid:
self.assertTrue(is_absolute_http_url(url), msg=url)

invalid = [
"/notifications/send_scan_notification/IjEi:1sZEvv:_br-G/",
"notifications/key/",
"example.com/webhook",
"//example.com/webhook",
"ftp://example.com/webhook",
"http:///webhook",
"http://[::1/webhook",
"http://exa mple.com/webhook",
"http://example\t.com/webhook",
]
for url in invalid:
self.assertFalse(is_absolute_http_url(url), msg=url)

def test_scanpipe_api_project_create_webhooks(self):
data = {
"name": "Project1",
Expand Down