|
| 1 | +import hashlib |
| 2 | +import hmac |
| 3 | +import os.path |
| 4 | +from urllib.parse import urljoin |
| 5 | + |
| 6 | +from django.conf import settings |
| 7 | +from django.core.management.base import BaseCommand, CommandError |
| 8 | +from django.urls import reverse |
| 9 | +from django.utils.encoding import force_bytes |
| 10 | + |
| 11 | +import requests |
| 12 | + |
| 13 | + |
| 14 | +class Command(BaseCommand): |
| 15 | + help = 'Send fake webhook request to local abuse response API like Cinder would.' |
| 16 | + |
| 17 | + def add_arguments(self, parser): |
| 18 | + parser.add_argument( |
| 19 | + '--payload', |
| 20 | + dest='payload_filename', |
| 21 | + default=os.path.join(settings.ROOT, 'tmp/payload.json'), |
| 22 | + help='Path to filename containing payload (default: %(default)s)', |
| 23 | + ) |
| 24 | + |
| 25 | + def handle(self, *args, **options): |
| 26 | + if settings.ENV != 'local': |
| 27 | + raise CommandError('Only works in local environments') |
| 28 | + try: |
| 29 | + body = open(options['payload_filename'], 'rb').read() |
| 30 | + except FileNotFoundError as exc: |
| 31 | + raise CommandError( |
| 32 | + 'Cannot find payload file. Try using --payload=<path>.' |
| 33 | + ) from exc |
| 34 | + signature = hmac.new( |
| 35 | + force_bytes(settings.CINDER_WEBHOOK_TOKEN), |
| 36 | + msg=body, |
| 37 | + digestmod=hashlib.sha256, |
| 38 | + ).hexdigest() |
| 39 | + url = urljoin('http://nginx', reverse('v5:cinder-webhook')) |
| 40 | + response = requests.post( |
| 41 | + url, |
| 42 | + data=body, |
| 43 | + headers={ |
| 44 | + 'X-Cinder-Signature': signature, |
| 45 | + 'Content-Type': 'application/json', |
| 46 | + }, |
| 47 | + ) |
| 48 | + self.stdout.write(f'{response.status_code}\n') |
| 49 | + self.stdout.write(f'{response.content}\n') |
0 commit comments