diff --git a/api_v2/tests.py b/api_v2/tests.py index fd8088e..6727bff 100644 --- a/api_v2/tests.py +++ b/api_v2/tests.py @@ -1,13 +1,16 @@ import json +from datetime import timedelta from unittest.mock import patch from django.test import TestCase, override_settings +from django.utils import timezone from api_v2.models import ApiKey +from vpn_invite.models import InviteSettings, PeerInvite from cluster.models import ClusterSettings, Worker from cluster.tests import create_instance from dns.models import DNSSettings, StaticHost -from wireguard.models import WireGuardInstance +from wireguard.models import Peer, WireGuardInstance class ApiV2ManageDnsRecordTests(TestCase): @@ -291,3 +294,121 @@ class ApiV2ManageClusterTests(TestCase): self.assertEqual(response.status_code, 405) response = self.client.put(self.status_url, HTTP_TOKEN=str(self.api_key.token)) self.assertEqual(response.status_code, 405) + + +class ApiV2PeerInviteTests(TestCase): + url = "/api/v2/peer_invite/" + + def setUp(self): + self.instance = create_instance(0) + self.other_instance = create_instance(1) + self.api_key = ApiKey.objects.create(name="invite-test-key", enabled=True) + self.api_key.allowed_instances.add(self.instance) + self.peer = Peer.objects.create( + wireguard_instance=self.instance, name="Test Peer", public_key="peer-public", private_key="peer-private", + ) + self.invite_settings = InviteSettings.objects.create( + name="default_settings", invite_url="https://vpn.example.com/invite/", invite_expiration=30, + ) + + def request(self, payload, api_key=None): + return self.client.post( + self.url, data=json.dumps(payload), content_type="application/json", + HTTP_TOKEN=str((api_key or self.api_key).token), + ) + + def test_creates_invite(self): + response = self.request({"instance": "wg0", "peer_uuid": str(self.peer.uuid)}) + self.assertEqual(response.status_code, 200) + body = response.json() + self.assertEqual(body["message"], "Invite created.") + invite = PeerInvite.objects.get(peer=self.peer) + self.assertEqual(body["invite_data"]["uuid"], str(invite.uuid)) + self.assertEqual(body["invite_data"]["url"], f"https://vpn.example.com/invite/?token={invite.uuid}&") + self.assertEqual(body["invite_data"]["password"], invite.invite_password) + + def test_selects_peer_by_public_key(self): + response = self.request({"instance": "wg0", "peer_public_key": "peer-public"}) + self.assertEqual(response.status_code, 200) + self.assertTrue(PeerInvite.objects.filter(peer=self.peer).exists()) + + def test_existing_invite_is_renewed(self): + self.request({"instance": "wg0", "peer_uuid": str(self.peer.uuid)}) + invite = PeerInvite.objects.get(peer=self.peer) + PeerInvite.objects.filter(pk=invite.pk).update( + invite_expiration=invite.invite_expiration - timedelta(minutes=20) + ) + response = self.request({"instance": "wg0", "peer_uuid": str(self.peer.uuid)}) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()["message"], "Existing invite renewed.") + renewed = PeerInvite.objects.get(peer=self.peer) + self.assertEqual(renewed.uuid, invite.uuid) + self.assertGreater(renewed.invite_expiration, timezone.now() + timedelta(minutes=25)) + + def test_missing_peer_selector(self): + response = self.request({"instance": "wg0"}) + self.assertEqual(response.status_code, 400) + self.assertEqual(response.json()["error_message"], "Missing peer selector (peer_uuid or peer_public_key).") + + def test_unknown_peer(self): + for peer_uuid in ("00000000-0000-0000-0000-000000000000", "not-a-uuid"): + response = self.request({"instance": "wg0", "peer_uuid": peer_uuid}) + self.assertEqual(response.status_code, 404) + self.assertEqual(response.json()["error_message"], "Peer not found.") + + def test_invalid_instance(self): + response = self.request({"instance": "wg999", "peer_uuid": str(self.peer.uuid)}) + self.assertEqual(response.status_code, 400) + self.assertEqual(response.json()["error_message"], "Invalid or missing WireGuard instance.") + + def test_peer_of_another_instance_is_not_found(self): + unrestricted_key = ApiKey.objects.create(name="unrestricted-key", enabled=True) + response = self.request({"instance": "wg1", "peer_uuid": str(self.peer.uuid)}, api_key=unrestricted_key) + self.assertEqual(response.status_code, 404) + self.assertFalse(PeerInvite.objects.exists()) + + def test_api_key_without_access_to_the_instance(self): + other_peer = Peer.objects.create( + wireguard_instance=self.other_instance, name="Other Peer", public_key="other-public", private_key="other-private", + ) + response = self.request({"instance": "wg1", "peer_uuid": str(other_peer.uuid)}) + self.assertEqual(response.status_code, 403) + self.assertFalse(PeerInvite.objects.exists()) + + def test_peer_with_endpoint_is_refused(self): + Peer.objects.filter(pk=self.peer.pk).update(endpoint="remote.example.com:51820") + response = self.request({"instance": "wg0", "peer_uuid": str(self.peer.uuid)}) + self.assertEqual(response.status_code, 400) + self.assertEqual(response.json()["error_message"], "Peers with an endpoint have no client configuration to share.") + self.assertFalse(PeerInvite.objects.exists()) + + @patch("api_v2.views_api.send_email") + def test_email_disabled_in_invite_settings(self, mock_send_email): + InviteSettings.objects.filter(pk=self.invite_settings.pk).update(invite_email_enabled=False) + response = self.request({"instance": "wg0", "peer_uuid": str(self.peer.uuid), "email": "user@example.com"}) + self.assertEqual(response.status_code, 400) + self.assertEqual(response.json()["error_message"], "Email invites are disabled in the VPN invite settings.") + self.assertFalse(PeerInvite.objects.exists()) + mock_send_email.assert_not_called() + + @patch("api_v2.views_api.send_email") + def test_sends_invite_by_email(self, mock_send_email): + mock_send_email.return_value = ("success", "Email sent successfully.") + response = self.request({"instance": "wg0", "peer_uuid": str(self.peer.uuid), "email": "user@example.com"}) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()["message"], "Invite created. Email sent to user@example.com.") + invite_data = response.json()["invite_data"] + mock_send_email.assert_called_once_with("user@example.com", invite_data["email_subject"], invite_data["email_body"]) + + @patch("api_v2.views_api.send_email") + def test_email_failure_keeps_the_invite(self, mock_send_email): + mock_send_email.return_value = ("error", "SMTP server not available") + response = self.request({"instance": "wg0", "peer_uuid": str(self.peer.uuid), "email": "user@example.com"}) + self.assertEqual(response.status_code, 500) + body = response.json() + self.assertEqual(body["error_message"], "Invite created, but the email could not be sent: SMTP server not available") + self.assertEqual(body["invite_data"]["uuid"], str(PeerInvite.objects.get(peer=self.peer).uuid)) + + def test_other_methods_are_not_allowed(self): + response = self.client.get(self.url, HTTP_TOKEN=str(self.api_key.token)) + self.assertEqual(response.status_code, 405) diff --git a/api_v2/urls_api.py b/api_v2/urls_api.py index 197c2e8..3e8bf03 100644 --- a/api_v2/urls_api.py +++ b/api_v2/urls_api.py @@ -6,6 +6,7 @@ from .views_api import ( api_v2_manage_dns_record, api_v2_manage_peer, api_v2_peer_detail, + api_v2_peer_invite, api_v2_peer_list, api_v2_wireguard_status, ) @@ -15,6 +16,7 @@ urlpatterns = [ path('manage_dns_record/', api_v2_manage_dns_record, name='api_v2_manage_dns_record'), path('peer_list/', api_v2_peer_list, name='api_v2_peer_list'), path('peer_detail/', api_v2_peer_detail, name='api_v2_peer_detail'), + path('peer_invite/', api_v2_peer_invite, name='api_v2_peer_invite'), path('wireguard_status/', api_v2_wireguard_status, name='api_v2_wireguard_status'), path('manage_cluster/status/', api_v2_manage_cluster_status, name='api_v2_manage_cluster_status'), path('manage_cluster/manage_status/', api_v2_manage_cluster_manage_status, name='api_v2_manage_cluster_manage_status'), diff --git a/api_v2/views_api.py b/api_v2/views_api.py index a83f951..dfa09c9 100644 --- a/api_v2/views_api.py +++ b/api_v2/views_api.py @@ -1,6 +1,7 @@ import ipaddress import json import re +from datetime import timedelta from functools import wraps from typing import List, Optional, Tuple @@ -9,6 +10,7 @@ from django.conf import settings as django_settings from django.core.exceptions import ValidationError from django.db import transaction from django.http import JsonResponse +from django.utils import timezone from django.views.decorators.csrf import csrf_exempt from api.views import func_get_wireguard_status @@ -25,6 +27,8 @@ from wireguard_peer.functions import find_network_in_other_instance, func_create from wireguard_tools.functions import ( func_reload_wireguard_interface, running_wireguard_interfaces, start_primary_interfaces, stop_primary_interfaces, ) +from vpn_invite.models import InviteSettings, PeerInvite +from wgwadmlibrary.tools import create_peer_invite, get_peer_invite_data, send_email from wireguard_tools.views import export_wireguard_configuration from .models import ApiKey @@ -884,6 +888,126 @@ def api_v2_peer_detail(request): return JsonResponse({"status": "success", "peer": peer_data}, status=200) +@csrf_exempt +@api_doc( + summary="Create a VPN invite for a peer and optionally send it by email", + auth="Header token: ", + methods=["POST"], + params=[ + {"name": "instance", "in": "json", "type": "string", "required": True, "example": "wg0", + "description": "Required. Target instance name in the format wg{instance_id} (e.g. wg0, wg1)."}, + {"name": "peer_uuid", "in": "json", "type": "string", "required": False, + "description": "Peer UUID selector."}, + {"name": "peer_public_key", "in": "json", "type": "string", "required": False, + "description": "Peer public key selector."}, + {"name": "email", "in": "json", "type": "string", "required": False, + "description": "Optional. Sends the invite to this address. Requires email invites to be enabled in the VPN invite settings."}, + ], + returns=[ + {"status": 200, "body": {"status": "success", "message": "Invite created.", "invite_data": {"url": "...", "password": "...", "expiration": "...", "email_subject": "...", "email_body": "...", "whatsapp_body": "...", "text_body": "...", "uuid": "..."}}}, + {"status": 400, "body": {"status": "error", "error_message": "Peers with an endpoint have no client configuration to share."}}, + {"status": 403, "body": {"status": "error", "error_message": "Invalid API key."}}, + {"status": 404, "body": {"status": "error", "error_message": "Peer not found."}}, + {"status": 500, "body": {"status": "error", "error_message": "Invite created, but the email could not be sent: ...", "invite_data": {"url": "..."}}}, + ], + examples={ + "create_invite": {"method": "POST", "json": {"instance": "wg0", "peer_uuid": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"}}, + "create_and_send_invite": {"method": "POST", "json": {"instance": "wg0", "peer_uuid": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "email": "user@example.com"}}, + } +) +def api_v2_peer_invite(request): + if request.method != "POST": + return JsonResponse({"status": "error", "error_message": "Method not allowed."}, status=405) + + try: + payload = json.loads(request.body.decode("utf-8")) if request.body else {} + except Exception: + return JsonResponse({"status": "error", "error_message": "Invalid JSON body."}, status=400) + if not isinstance(payload, dict): + return JsonResponse({"status": "error", "error_message": "Invalid JSON body."}, status=400) + + try: + wireguard_instance = WireGuardInstance.objects.get( + instance_id=int(str(payload.get("instance")).replace("wg", "")) + ) + except Exception: + wireguard_instance = None + + if not wireguard_instance: + return JsonResponse({"status": "error", "error_message": "Invalid or missing WireGuard instance."}, status=400) + + api_key, api_error = validate_api_key(request, wireguard_instance=wireguard_instance) + if not api_key: + return JsonResponse({"status": "error", "error_message": api_error}, status=403) + + selector_peer_uuid = payload.get("peer_uuid") + selector_peer_public_key = payload.get("peer_public_key") + if not selector_peer_uuid and not selector_peer_public_key: + return JsonResponse( + {"status": "error", "error_message": "Missing peer selector (peer_uuid or peer_public_key)."}, + status=400, + ) + + peers = Peer.objects.filter(wireguard_instance=wireguard_instance) + try: + if selector_peer_uuid: + peer = peers.filter(uuid=selector_peer_uuid).first() + else: + peer = peers.filter(public_key=selector_peer_public_key).first() + except ValidationError: + peer = None + if not peer: + return JsonResponse({"status": "error", "error_message": "Peer not found."}, status=404) + + if peer.endpoint: + return JsonResponse( + {"status": "error", "error_message": "Peers with an endpoint have no client configuration to share."}, + status=400, + ) + + invite_settings = InviteSettings.objects.filter(name='default_settings').first() + if not invite_settings: + return JsonResponse({"status": "error", "error_message": "VPN invite is not configured."}, status=400) + + email = payload.get("email") + if email: + if not isinstance(email, str): + return JsonResponse({"status": "error", "error_message": "Invalid email address."}, status=400) + if not invite_settings.invite_email_enabled: + return JsonResponse( + {"status": "error", "error_message": "Email invites are disabled in the VPN invite settings."}, + status=400, + ) + + PeerInvite.objects.filter(invite_expiration__lt=timezone.now()).delete() + peer_invite = PeerInvite.objects.filter(peer=peer).first() + if peer_invite: + # An existing invite is renewed, so the returned link is valid for the whole expiration period + peer_invite.invite_expiration = timezone.now() + timedelta(minutes=invite_settings.invite_expiration) + peer_invite.save() + message = "Existing invite renewed." + else: + peer_invite = create_peer_invite(peer, invite_settings) + message = "Invite created." + + invite_data = get_peer_invite_data(peer_invite, invite_settings) + + if email: + email_status, email_message = send_email(email, invite_data['email_subject'], invite_data['email_body']) + if email_status != 'success': + return JsonResponse( + { + "status": "error", + "error_message": f"Invite created, but the email could not be sent: {email_message}", + "invite_data": invite_data, + }, + status=500, + ) + message = f"{message} Email sent to {email}." + + return JsonResponse({"status": "success", "message": message, "invite_data": invite_data}, status=200) + + @csrf_exempt @api_doc( summary="Get WireGuard status (dump) for all interfaces/peers", diff --git a/wgwadmlibrary/tools.py b/wgwadmlibrary/tools.py index ce8e857..7d151a2 100644 --- a/wgwadmlibrary/tools.py +++ b/wgwadmlibrary/tools.py @@ -149,7 +149,7 @@ def replace_message_variables(message: str, peer_invite: PeerInvite, invite_sett def get_peer_invite_data(peer_invite: PeerInvite, invite_settings: InviteSettings): data = { # The & at the end is to prevent the token from being concatenated with any other template text. - 'url': f'{invite_settings.invite_url}?token{peer_invite.uuid}&', + 'url': f'{invite_settings.invite_url}?token={peer_invite.uuid}&', 'password': peer_invite.invite_password, 'expiration': peer_invite.invite_expiration.isoformat(), 'email_subject': replace_message_variables(invite_settings.invite_email_subject, peer_invite, invite_settings),