Example #1
0
 def test_passes_gracefully_for_non_matrix_request(self):
     assert not identify_request(RequestType(body='foo'))
     assert not identify_request(RequestType(body='<xml></<xml>'))
     assert not identify_request(RequestType(body=b'<xml></<xml>'))
     assert not identify_request(
         RequestType(body=json.dumps('{"@context": "foo"}')))
     assert not identify_request(
         RequestType(
             body=json.dumps('{"@context": "foo"}').encode('utf-8')))
Example #2
0
def retrieve_and_parse_content(
        id: str, guid: str, handle: str, entity_type: str, sender_key_fetcher: Callable[[str], str]=None,
):
    """Retrieve remote content and return an Entity class instance.

    This is basically the inverse of receiving an entity. Instead, we fetch it, then call "handle_receive".

    :param sender_key_fetcher: Function to use to fetch sender public key. If not given, network will be used
        to fetch the profile and the key. Function must take handle as only parameter and return a public key.
    :returns: Entity object instance or ``None``
    """
    if not validate_handle(handle):
        return
    _username, domain = handle.split("@")
    url = get_fetch_content_endpoint(domain, entity_type.lower(), guid)
    document, status_code, error = fetch_document(url)
    if status_code == 200:
        request = RequestType(body=document)
        _sender, _protocol, entities = handle_receive(request, sender_key_fetcher=sender_key_fetcher)
        if len(entities) > 1:
            logger.warning("retrieve_and_parse_content - more than one entity parsed from remote even though we"
                           "expected only one! ID %s", guid)
        if entities:
            return entities[0]
        return
    elif status_code == 404:
        logger.warning("retrieve_and_parse_content - remote content %s not found", guid)
        return
    if error:
        raise error
    raise Exception("retrieve_and_parse_content - unknown problem when fetching document: %s, %s, %s" % (
        document, status_code, error,
    ))
Example #3
0
 def test_receive_unencrypted_returns_sender_and_content(self):
     protocol = self.init_protocol()
     user = self.get_mock_user()
     protocol.get_message_content = self.mock_get_message_content
     sender, content = protocol.receive(RequestType(body=DIASPORA_PUBLIC_PAYLOAD), user, mock_get_contact_key,
                                        skip_author_verification=True)
     assert sender == "*****@*****.**"
     assert content == "<content />"
Example #4
0
 def test_handle_receive_routes_to_identified_protocol(self):
     payload = RequestType(body=DIASPORA_PUBLIC_PAYLOAD)
     with patch.object(
                 Protocol,
                 'receive',
                 return_value=("*****@*****.**", "<foobar></foobar>")) as mock_receive,\
             patch(
                 "federation.entities.diaspora.mappers.message_to_objects",
                 return_value=[]) as mock_message_to_objects:
         handle_receive(payload)
         assert mock_receive.called
Example #5
0
 def test_calls_handle_receive(self, mock_handle, mock_get, mock_fetch):
     entity = retrieve_and_parse_content(
         id="eggs",
         guid="eggs",
         handle="*****@*****.**",
         entity_type="spam",
         sender_key_fetcher=sum,
     )
     mock_handle.assert_called_once_with(
         RequestType(body=DIASPORA_PUBLIC_PAYLOAD), sender_key_fetcher=sum)
     assert entity == "entity"
Example #6
0
def queue_payload(request: HttpRequest, uuid: str = None):
    """
    Queue payload for processing.
    """
    from socialhome.federate.tasks import receive_task  # Circulars
    try:
        # Create a simpler request object we can push to RQ
        headers = {}
        for key, value in request.META.items():
            key = key.replace('HTTP_', '').lower().replace('_',
                                                           '-').capitalize()
            try:
                pickle.dumps(value)
            except Exception:
                pass
            else:
                headers[key] = value
                # Include also a lowercase version for compatibility with signature verification module
                headers[key.lower()] = value
        _request = RequestType(
            body=request.body,
            headers=headers,
            method=request.method,
            url=request.build_absolute_uri(),
        )
        preferences = global_preferences_registry.manager()
        if preferences["admin__log_all_receive_payloads"]:
            logger.debug("queue_payload - Request: %s", _request)

        if not uuid:
            # Check if profile path has an uuid
            match = re.match(r"^/p/([0-9a-z-]+)/inbox/$", request.path)
            if match:
                uuid = match.groups()[0]

        django_rq.enqueue(receive_task, _request, uuid=uuid)
        return True
    except Exception:
        logger.exception('Failed to enqueue payload')
        return False
Example #7
0
 def test_receive_creates_and_verifies_magic_envelope_instance(self, mock_fetch, mock_env):
     protocol = self.init_protocol()
     user = self.get_mock_user()
     protocol.receive(RequestType(body=DIASPORA_PUBLIC_PAYLOAD), user)
     mock_env.assert_called_once_with(doc=protocol.doc, public_key="key", verify=True)
Example #8
0
 def test_identifies_matrix_request(self):
     assert identify_request(RequestType(body=json.dumps('{"events": []}')))
     assert identify_request(
         RequestType(body=json.dumps('{"events": []}').encode('utf-8')))
Example #9
0
 def test_handle_receive_raises_on_unidentified_protocol(self):
     payload = RequestType(body="foobar")
     with pytest.raises(NoSuitableProtocolFoundError):
         handle_receive(payload)
Example #10
0
 def test_identify_payload_with_diaspora_encrypted_payload(self):
     assert identify_request(RequestType(body=DIASPORA_ENCRYPTED_PAYLOAD)) is True
Example #11
0
 def test_identify_payload_with_diaspora_public_payload(self):
     assert identify_request(RequestType(body=DIASPORA_PUBLIC_PAYLOAD)) is True
     assert identify_request(RequestType(body=bytes(DIASPORA_PUBLIC_PAYLOAD, encoding="utf-8"))) is True
Example #12
0
 def test_receive_raises_on_signature_verification_failure(self, mock_fetch):
     mock_fetch.return_value = PUBKEY
     protocol = self.init_protocol()
     user = self.get_mock_user()
     with pytest.raises(SignatureVerificationError):
         protocol.receive(RequestType(body=DIASPORA_PUBLIC_PAYLOAD), user)
Example #13
0
 def test_identifies_activitypub_request(self):
     assert identify_request(
         RequestType(body=json.dumps('{"@context": "foo"}')))
     assert identify_request(
         RequestType(
             body=json.dumps('{"@context": "foo"}').encode('utf-8')))
Example #14
0
 def test_receive_calls_fetch_public_key_if_key_fetcher_not_given(self, mock_fetch):
     protocol = self.init_protocol()
     user = self.get_mock_user()
     with pytest.raises(NoSenderKeyFoundError):
         protocol.receive(RequestType(body=DIASPORA_PUBLIC_PAYLOAD), user)
     mock_fetch.assert_called_once_with("*****@*****.**")
Example #15
0
 def test_receive_raises_if_sender_key_cannot_be_found(self, mock_fetch):
     protocol = self.init_protocol()
     user = self.get_mock_user()
     with pytest.raises(NoSenderKeyFoundError):
         protocol.receive(RequestType(body=DIASPORA_PUBLIC_PAYLOAD), user, mock_not_found_get_contact_key)
     assert not mock_fetch.called
Example #16
0
 def test_identify_payload_with_reshare(self):
     assert identify_request(RequestType(body=DIASPORA_RESHARE_PAYLOAD)) is True
Example #17
0
 def test_identify_payload_with_other_payload(self):
     assert identify_request(RequestType(body="foobar not a diaspora protocol")) is False
Example #18
0
 def test_passes_gracefully_for_non_activitypub_request(self):
     assert not identify_request(RequestType(body='foo'))
     assert not identify_request(RequestType(body='<xml></<xml>'))
     assert not identify_request(RequestType(body=b'<xml></<xml>'))