Пример #1
0
    def test_hostgroup_request(self, m_get, m_delete):

        m_get.return_value = MockResponse(
            '{\
            "name": "Testgroup", \
            "id": 999\
        }', 200)

        self._host_dn = "cn=Testgroup,ou=groups,dc=example,dc=net"

        payload_data = {
            "event": "after_create",
            "object": "Testgroup",
            "data": {
                "hostgroup": {
                    "hostgroup": {
                        "id": 999,
                        "name": "Testgroup"
                    }
                }
            }
        }
        headers, payload = self._create_request(payload_data)
        AsyncHTTPTestCase.fetch(self,
                                "/hooks/",
                                method="POST",
                                headers=headers,
                                body=payload)

        # check if the host has been updated
        device = ObjectProxy(self._host_dn)
        assert device.cn == "Testgroup"
        assert device.foremanGroupId == "999"

        # delete the host
        payload_data = {
            "event": "after_destroy",
            "object": "Testgroup",
            "data": {
                "hostgroup": {
                    "hostgroup": {
                        "id": 999,
                        "name": "Testgroup"
                    }
                }
            }
        }
        headers, payload = self._create_request(payload_data)
        AsyncHTTPTestCase.fetch(self,
                                "/hooks/",
                                method="POST",
                                headers=headers,
                                body=payload)

        with pytest.raises(ProxyException):
            ObjectProxy(self._host_dn)

        self._host_dn = None
Пример #2
0
    def test_request(self, m_get):

        m_get.return_value = MockResponse(
            '{\
            "status": 0,\
            "status_label": "Build"\
        }', 200)

        token = bytes(self.token, 'ascii')
        payload = bytes(
            dumps({
                "action": "create",
                "hostname": "new-foreman-host",
                "parameters": {}
            }), 'utf-8')
        signature_hash = hmac.new(token, msg=payload, digestmod="sha512")
        signature = 'sha1=' + signature_hash.hexdigest()
        headers = {
            'Content-Type': 'application/vnd.foreman.hostevent+json',
            'HTTP_X_HUB_SENDER': 'test-webhook',
            'HTTP_X_HUB_SIGNATURE': signature
        }
        response = AsyncHTTPTestCase.fetch(self,
                                           "/hooks/",
                                           method="POST",
                                           headers=headers,
                                           body=payload)

        otp_response = loads(response.body.decode("utf-8"))
        assert "randompassword" in otp_response
        assert otp_response["randompassword"] is not None

        # check if the host has been created
        device = ObjectProxy(
            "cn=new-foreman-host,ou=incoming,dc=example,dc=net")
        assert device.cn == "new-foreman-host"

        # delete the host
        payload = bytes(
            dumps({
                "action": "delete",
                "hostname": "new-foreman-host",
                "parameters": {}
            }), 'utf-8')
        signature_hash = hmac.new(token, msg=payload, digestmod="sha512")
        signature = 'sha1=' + signature_hash.hexdigest()
        headers['HTTP_X_HUB_SIGNATURE'] = signature
        AsyncHTTPTestCase.fetch(self,
                                "/hooks/",
                                method="POST",
                                headers=headers,
                                body=payload)

        with pytest.raises(ProxyException):
            ObjectProxy("cn=new-foreman-host,ou=incoming,dc=example,dc=net")
Пример #3
0
    def fetch(self, *args, **kwargs):
        assert ' ' not in args[0], 'Unescaped space in URL'

        # having to manually open and close a db connection when writing tests would be a pain
        # but the controllers manage their own connection and they're called from the same process
        # so we go through the trouble of overwriting this method to manage the connection automatically
        model.peewee_db.close()

        # network_interface gets passed through and eventually mapped directly to remote_ip on the request object
        # but there are also some fallback headers that would achieve the same thing, e.g. X-Forwarded-For
        headers = kwargs.pop('headers', HEADERS.copy())
        if hasattr(self, 'cookies'):
            headers['Cookie'] = '; '.join(
                [key + '=' + value for key, value in self.cookies.items()])
        kwargs['headers'] = headers

        # split up redirects here to capture the cookie after the first one
        response = AsyncHTTPTestCase.fetch(self,
                                           *args,
                                           network_interface='127.0.0.1',
                                           follow_redirects=False,
                                           **kwargs)
        self.setCookie(response)
        redirect = response.headers.get('Location')

        if redirect:
            # cookie might have been updated since last request in setCookie call above
            if hasattr(self, 'cookies'):
                headers['Cookie'] = '; '.join(
                    [key + '=' + value for key, value in self.cookies.items()])
            kwargs['headers'] = headers

            # never POSTing twice in a row
            kwargs['method'] = 'GET'
            kwargs['body'] = None

            response = AsyncHTTPTestCase.fetch(self,
                                               redirect,
                                               network_interface='127.0.0.1',
                                               follow_redirects=True,
                                               **kwargs)

        model.peewee_db.connect()
        response.body_string = response.body.decode()  # for convenience
        return response
Пример #4
0
    def test_registering(self):
        registry = PluginRegistry.getInstance("WebhookRegistry")
        hook = TestWebhook()
        registry.register_handler("application/vnd.gosa.test+plain", hook)
        url, token = registry.registerWebhook("admin", "test-webhook", "application/vnd.gosa.test+plain")

        token = bytes(token, 'ascii')
        signature_hash = hmac.new(token, msg=b"Test", digestmod="sha512")
        signature = 'sha1=' + signature_hash.hexdigest()
        headers = {
            'Content-Type': 'application/vnd.gosa.test+plain',
            'HTTP_X_HUB_SENDER': 'test-webhook',
            'HTTP_X_HUB_SIGNATURE': signature
        }
        with mock.patch.object(hook, "content") as m_content:
            AsyncHTTPTestCase.fetch(self, "/hooks/", method="POST", headers=headers, body=b"Test")
            m_content.assert_called_with(b"Test")
            m_content.reset_mock()

            registry.unregisterWebhook("admin", "test-webhook", "application/vnd.gosa.test+plain")
            AsyncHTTPTestCase.fetch(self, url, method="POST", headers=headers, body=b"Test")
            assert not m_content.called
Пример #5
0
 def fetch(self, url, **kw):
     headers = kw.pop('headers', {})
     if self.__cookies != '':
         headers['Cookie'] = self.__cookies
     if self._xsrf:
         headers['X-XSRFToken'] = self._xsrf
         if len(headers['Cookie'])>0 and '_xsrf' not in headers['Cookie']:
             headers['Cookie'] = "%s;%s=%s" % (headers['Cookie'], '_xsrf', self._xsrf)
     # if 'body' in kw:
     #     print("URL: {}, Body: {}, Headers: {}".format(url, kw['body'] , headers))
     # else:
     #     print("URL: {}, Headers: {}".format(url, headers))
     resp = AsyncHTTPTestCase.fetch(self, url, headers=headers, **kw)
     self._update_cookies(resp.headers)
     return resp
Пример #6
0
 def fetch(self, url, **kw):
     headers = kw.pop('headers', {})
     if self.__cookies != '':
         headers['Cookie'] = self.__cookies
     if self._xsrf:
         headers['X-XSRFToken'] = self._xsrf
         if len(headers['Cookie']) > 0 and '_xsrf' not in headers['Cookie']:
             headers['Cookie'] = "%s;%s=%s" % (headers['Cookie'], '_xsrf',
                                               self._xsrf)
     # if 'body' in kw:
     #     print("URL: {}, Body: {}, Headers: {}".format(url, kw['body'] , headers))
     # else:
     #     print("URL: {}, Headers: {}".format(url, headers))
     resp = AsyncHTTPTestCase.fetch(self, url, headers=headers, **kw)
     self._update_cookies(resp.headers)
     return resp
Пример #7
0
    def test_post(self):

        # create webhook post
        e = EventMaker()
        update = e.Event(
            e.BackendChange(
                e.DN("cn=Test,ou=people,dc=example,dc=net"),
                e.ModificationTime(datetime.now().strftime("%Y%m%d%H%M%SZ")),
                e.ChangeType("update")
            )
        )
        payload = etree.tostring(update)

        token = bytes(Environment.getInstance().config.get("webhooks.ldap_monitor_token"), 'ascii')
        signature_hash = hmac.new(token, msg=payload, digestmod="sha512")
        signature = 'sha1=' + signature_hash.hexdigest()

        headers = {
            'Content-Type': 'application/vnd.gosa.event+xml',
            'HTTP_X_HUB_SENDER': 'backend-monitor',
            'HTTP_X_HUB_SIGNATURE': signature
        }
        with mock.patch("gosa.backend.plugins.webhook.registry.zope.event.notify") as m_notify:
            AsyncHTTPTestCase.fetch(self, "/hooks/", method="POST", headers=headers, body=payload)
            assert m_notify.called
            m_notify.reset_mock()

            # unregistered sender
            headers['HTTP_X_HUB_SENDER'] = 'unknown'
            resp = AsyncHTTPTestCase.fetch(self, "/hooks/", method="POST", headers=headers, body=payload)
            assert resp.code == 401
            assert not m_notify.called

            # wrong signature
            headers['HTTP_X_HUB_SENDER'] = 'backend-monitor'
            headers['HTTP_X_HUB_SIGNATURE'] = 'sha1=823rjadfkjlasasddfdgasdfgasd'
            resp = AsyncHTTPTestCase.fetch(self, "/hooks/", method="POST", headers=headers, body=payload)
            assert resp.code == 401
            assert not m_notify.called

            # no signature
            del headers['HTTP_X_HUB_SIGNATURE']
            resp = AsyncHTTPTestCase.fetch(self, "/hooks/", method="POST", headers=headers, body=payload)
            assert resp.code == 401
            assert not m_notify.called

            # no handler for content type
            headers['HTTP_X_HUB_SIGNATURE'] = signature
            headers['Content-Type'] = 'application/vnd.gosa.unknown+xml'
            resp = AsyncHTTPTestCase.fetch(self, "/hooks/", method="POST", headers=headers, body=payload)
            assert resp.code == 401
            assert not m_notify.called
Пример #8
0
    def test_host_request(self, m_get):

        m_get.return_value = MockResponse(
            '{\
            "build_status": 0\
        }', 200)

        host_dn = "cn=new-foreman-host,ou=incoming,dc=example,dc=net"
        self._host_cn = "new-foreman-host"
        # create new host to update
        foreman = ForemanPlugin()
        foreman.serve()
        foreman.add_host("new-foreman-host")

        payload_data = {
            "event": "after_commit",
            "object": "new-foreman-host",
            "data": {
                "host": {
                    "host": {
                        "name": "new-foreman-host",
                        "ip": "127.0.0.1",
                        "mac": "00:00:00:00:00:01",
                    }
                }
            }
        }

        headers, payload = self._create_request(payload_data)
        AsyncHTTPTestCase.fetch(self,
                                "/hooks/",
                                method="POST",
                                headers=headers,
                                body=payload)

        # check if the host has been updated
        device = ObjectProxy(host_dn)
        assert device.cn == "new-foreman-host"
        assert device.ipHostNumber == payload_data["data"]["host"]["host"][
            "ip"]
        assert device.macAddress == payload_data["data"]["host"]["host"]["mac"]

        # delete the host
        payload_data = {
            "event": "after_destroy",
            "object": "new-foreman-host",
            "data": {
                "host": {
                    "host": {
                        "name": "new-foreman-host"
                    }
                }
            }
        }
        headers, payload = self._create_request(payload_data)
        AsyncHTTPTestCase.fetch(self,
                                "/hooks/",
                                method="POST",
                                headers=headers,
                                body=payload)

        with pytest.raises(ProxyException):
            ObjectProxy("cn=new-foreman-host,ou=incoming,dc=example,dc=net")

        self._host_cn = None
Пример #9
0
 def fetch(self, path, **kwargs):
     response = AsyncHTTPTestCase.fetch(self, path, **kwargs)
     if response.body is not None:
         response.value = response.body.decode('utf-8')
     return response