123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155 |
- # -*- coding: utf-8 -*-
- # Copyright 2014 OpenMarket Ltd
- #
- # Licensed under the Apache License, Version 2.0 (the "License");
- # you may not use this file except in compliance with the License.
- # You may obtain a copy of the License at
- #
- # http://www.apache.org/licenses/LICENSE-2.0
- #
- # Unless required by applicable law or agreed to in writing, software
- # distributed under the License is distributed on an "AS IS" BASIS,
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- # See the License for the specific language governing permissions and
- # limitations under the License.
- from sydent.db.threepid_associations import GlobalAssociationStore
- from sydent.threepid import threePidAssocFromDict
- import signedjson.sign
- import logging
- import json
- import twisted.internet.reactor
- from twisted.internet import defer
- from twisted.web.client import readBody
- logger = logging.getLogger(__name__)
- class Peer(object):
- def __init__(self, servername, pubkeys):
- self.servername = servername
- self.pubkeys = pubkeys
- def pushUpdates(self, sgAssocs):
- """
- :param sgAssocs: Sequence of (originId, sgAssoc) tuples where originId is the id on the creating server and
- sgAssoc is the json object of the signed association
- :return a deferred
- """
- pass
- class LocalPeer(Peer):
- """
- The local peer (ourselves: essentially copying from the local associations table to the global one)
- """
- def __init__(self, sydent):
- super(LocalPeer, self).__init__(sydent.server_name, {})
- self.sydent = sydent
- globalAssocStore = GlobalAssociationStore(self.sydent)
- self.lastId = globalAssocStore.lastIdFromServer(self.servername)
- if self.lastId is None:
- self.lastId = -1
- def pushUpdates(self, sgAssocs):
- globalAssocStore = GlobalAssociationStore(self.sydent)
- for localId in sgAssocs:
- if localId > self.lastId:
- assocObj = threePidAssocFromDict(sgAssocs[localId])
- if assocObj.mxid is not None:
- # We can probably skip verification for the local peer (although it could be good as a sanity check)
- globalAssocStore.addAssociation(assocObj, json.dumps(sgAssocs[localId]),
- self.sydent.server_name, localId)
- else:
- globalAssocStore.removeAssociation(assocObj.medium, assocObj.address)
- d = twisted.internet.defer.succeed(True)
- return d
- class RemotePeer(Peer):
- def __init__(self, sydent, server_name, pubkeys):
- super(RemotePeer, self).__init__(server_name, pubkeys)
- self.sydent = sydent
- self.port = 1001
- def verifyMessage(self, jsonMessage):
- if not 'signatures' in jsonMessage:
- raise NoSignaturesException()
- alg = 'ed25519'
- key_ids = signedjson.sign.signature_ids(jsonMessage, self.servername)
- if not key_ids or len(key_ids) == 0 or not key_ids[0].startswith(alg + ":"):
- e = NoMatchingSignatureException()
- e.foundSigs = jsonMessage['signatures'].keys()
- e.requiredServername = self.servername
- raise e
- # Get verify key from signing key
- signing_key = signedjson.key.decode_signing_key_base64(alg, "0", self.pubkeys[alg])
- verify_key = signing_key.verify_key
- # Attach metadata
- verify_key.alg = alg
- verify_key.version = 0
- # Verify the JSON
- signedjson.sign.verify_signed_json(jsonMessage, self.servername, verify_key)
- def pushUpdates(self, sgAssocs):
- body = {'sgAssocs': sgAssocs}
- reqDeferred = self.sydent.replicationHttpsClient.postJson(self.servername,
- self.port,
- '/_matrix/identity/replicate/v1/push',
- body)
- # XXX: We'll also need to prune the deleted associations out of the
- # local associations table once they've been replicated to all peers
- # (ie. remove the record we kept in order to propagate the deletion to
- # other peers).
- updateDeferred = twisted.internet.defer.Deferred()
- reqDeferred.addCallback(self._pushSuccess, updateDeferred=updateDeferred)
- reqDeferred.addErrback(self._pushFailed, updateDeferred=updateDeferred)
- return updateDeferred
- def _pushSuccess(self, result, updateDeferred):
- if result.code >= 200 and result.code < 300:
- updateDeferred.callback(result)
- else:
- d = readBody(result)
- d.addCallback(self._failedPushBodyRead, updateDeferred=updateDeferred)
- d.addErrback(self._pushFailed, updateDeferred=updateDeferred)
- def _failedPushBodyRead(self, body, updateDeferred):
- errObj = json.loads(body)
- e = RemotePeerError()
- e.errorDict = errObj
- updateDeferred.errback(e)
- def _pushFailed(self, failure, updateDeferred):
- updateDeferred.errback(failure)
- return None
- class NoSignaturesException(Exception):
- pass
- class NoMatchingSignatureException(Exception):
- def __str__(self):
- return "Found signatures: %s, required server name: %s" % (self.foundSigs, self.requiredServername)
- class RemotePeerError(Exception):
- def __str__(self):
- return repr(self.errorDict)
|