diff --git a/changelog.d/367.misc b/changelog.d/367.misc new file mode 100644 index 00000000..f524361b --- /dev/null +++ b/changelog.d/367.misc @@ -0,0 +1 @@ +Remove redundant type hints from docstrings. \ No newline at end of file diff --git a/sydent/db/accounts.py b/sydent/db/accounts.py index 03b4dea0..d93c1bf3 100644 --- a/sydent/db/accounts.py +++ b/sydent/db/accounts.py @@ -29,10 +29,8 @@ def getAccountByToken(self, token: str) -> Optional[Account]: Select the account matching the given token, if any. :param token: The token to identify the account, if any. - :type token: unicode :return: The account matching the token, or None if no account matched. - :rtype: Account or None """ cur = self.sydent.db.cursor() res = cur.execute( @@ -54,12 +52,9 @@ def storeAccount( Stores an account for the given user ID. :param user_id: The Matrix user ID to create an account for. - :type user_id: unicode :param creation_ts: The timestamp in milliseconds. - :type creation_ts: int :param consent_version: The version of the terms of services that the user last accepted. - :type consent_version: str or None """ cur = self.sydent.db.cursor() cur.execute( @@ -75,9 +70,7 @@ def setConsentVersion(self, user_id: str, consent_version: Optional[str]) -> Non given version. :param user_id: The Matrix ID of the user that has agreed to the terms. - :type user_id: str :param consent_version: The version of the document the user has agreed to. - :type consent_version: unicode or None """ cur = self.sydent.db.cursor() cur.execute( @@ -91,9 +84,7 @@ def addToken(self, user_id: str, token: str) -> None: Stores the authentication token for a given user. :param user_id: The Matrix user ID to save the given token for. - :type user_id: unicode :param token: The token to store for that user ID. - :type token: unicode """ cur = self.sydent.db.cursor() cur.execute( @@ -107,7 +98,6 @@ def delToken(self, token: str) -> int: Deletes an authentication token from the database. :param token: The token to delete from the database. - :type token: unicode """ cur = self.sydent.db.cursor() cur.execute( diff --git a/sydent/db/hashing_metadata.py b/sydent/db/hashing_metadata.py index 7459e5f8..cbe72a01 100644 --- a/sydent/db/hashing_metadata.py +++ b/sydent/db/hashing_metadata.py @@ -30,7 +30,6 @@ def get_lookup_pepper(self) -> Optional[str]: :return: A pepper if it exists in the database, or None if one does not exist - :rtype: unicode or None """ cur = self.sydent.db.cursor() res = cur.execute("select lookup_pepper from hashing_metadata") @@ -53,10 +52,8 @@ def store_lookup_pepper( """Stores a new lookup pepper in the hashing_metadata db table and rehashes all 3PIDs :param hashing_function: A function with single input and output strings - :type hashing_function func(str) -> str :param pepper: The pepper to store in the database - :type pepper: str """ cur = self.sydent.db.cursor() diff --git a/sydent/db/invite_tokens.py b/sydent/db/invite_tokens.py index 08c0b52f..782b6dc3 100644 --- a/sydent/db/invite_tokens.py +++ b/sydent/db/invite_tokens.py @@ -29,15 +29,10 @@ def storeToken( Store a new invite token and its metadata. :param medium: The medium of the 3PID the token is associated to. - :type medium: unicode :param address: The address of the 3PID the token is associated to. - :type address: unicode :param roomId: The ID of the room the 3PID is invited in. - :type roomId: unicode :param sender: The MXID of the user that sent the invite. - :type sender: unicode :param token: The token to store. - :type token: unicode """ cur = self.sydent.db.cursor() @@ -57,13 +52,10 @@ def getTokens( yet. :param medium: The medium of the 3PID to get tokens for. - :type medium: unicode :param address: The address of the 3PID to get tokens for. - :type address: unicode :return: A list of dicts, each containing a pending token and its metadata for this 3PID. - :rtype: list[dict[str, unicode or dict[str, unicode]] """ cur = self.sydent.db.cursor() @@ -112,9 +104,7 @@ def markTokensAsSent(self, medium: str, address: str) -> None: delivered to a homeserver so they're not delivered again in the future. :param medium: The medium of the 3PID to update tokens for. - :type medium: unicode :param address: The address of the 3PID to update tokens for. - :type address: unicode """ cur = self.sydent.db.cursor() @@ -133,7 +123,6 @@ def storeEphemeralPublicKey(self, publicKey: str) -> None: Saves the provided ephemeral public key. :param publicKey: The key to store. - :type publicKey: unicode """ cur = self.sydent.db.cursor() cur.execute( @@ -150,10 +139,8 @@ def validateEphemeralPublicKey(self, publicKey: str) -> bool: verification count. :param publicKey: The public key to validate. - :type publicKey: unicode :return: Whether the key is valid. - :rtype: bool """ cur = self.sydent.db.cursor() cur.execute( @@ -170,11 +157,9 @@ def getSenderForToken(self, token: str) -> Optional[str]: Retrieves the MXID of the user that sent the invite the provided token is for. :param token: The token to retrieve the sender of. - :type token: unicode :return: The invite's sender, or None if the token doesn't match an existing invite. - :rtype: unicode or None """ cur = self.sydent.db.cursor() res = cur.execute("SELECT sender FROM invite_tokens WHERE token = ?", (token,)) @@ -188,9 +173,7 @@ def deleteTokens(self, medium: str, address: str) -> None: Deletes every token for a given 3PID. :param medium: The medium of the 3PID to delete tokens for. - :type medium: unicode :param address: The address of the 3PID to delete tokens for. - :type address: unicode """ cur = self.sydent.db.cursor() diff --git a/sydent/db/peers.py b/sydent/db/peers.py index 3f8c53fd..ba5451f8 100644 --- a/sydent/db/peers.py +++ b/sydent/db/peers.py @@ -29,10 +29,8 @@ def getPeerByName(self, name: str) -> Optional[RemotePeer]: Retrieves a remote peer using it's server name. :param name: The server name of the peer. - :type name: unicode :return: The retrieved peer. - :rtype: RemotePeer """ cur = self.sydent.db.cursor() res = cur.execute( @@ -64,7 +62,6 @@ def getAllPeers(self) -> List[RemotePeer]: Retrieve all of the remote peers from the database. :return: A list of the remote peers this server knows about. - :rtype: list[RemotePeer] """ cur = self.sydent.db.cursor() res = cur.execute( @@ -104,12 +101,9 @@ def setLastSentVersionAndPokeSucceeded( last successful request sent to that peer. :param peerName: The server name of the peer. - :type peerName: unicode :param lastSentVersion: The ID of the last association sent to that peer. - :type lastSentVersion: int :param lastPokeSucceeded: The timestamp in milliseconds of the last successful request sent to that peer. - :type lastPokeSucceeded: int """ cur = self.sydent.db.cursor() cur.execute( diff --git a/sydent/db/terms.py b/sydent/db/terms.py index d1a38e52..6b85ab4b 100644 --- a/sydent/db/terms.py +++ b/sydent/db/terms.py @@ -27,10 +27,8 @@ def getAgreedUrls(self, user_id: str) -> List[str]: Retrieves the URLs of the terms the given user has agreed to. :param user_id: Matrix user ID to fetch the URLs for. - :type user_id: str :return: A list of the URLs of the terms accepted by the user. - :rtype: list[unicode] """ cur = self.sydent.db.cursor() res = cur.execute( @@ -53,9 +51,7 @@ def addAgreedUrls(self, user_id: str, urls: List[str]) -> None: Saves that the given user has accepted the terms at the given URLs. :param user_id: The Matrix user ID that has accepted the terms. - :type user_id: str :param urls: The list of URLs. - :type urls: list[unicode] """ cur = self.sydent.db.cursor() cur.executemany( diff --git a/sydent/db/threepid_associations.py b/sydent/db/threepid_associations.py index c4560c3a..276d1d2f 100644 --- a/sydent/db/threepid_associations.py +++ b/sydent/db/threepid_associations.py @@ -35,7 +35,6 @@ def addOrUpdateAssociation(self, assoc: ThreepidAssociation) -> None: Updates an association, or creates one if none exists with these parameters. :param assoc: The association to create or update. - :type assoc: ThreepidAssociation """ cur = self.sydent.db.cursor() @@ -63,14 +62,11 @@ def getAssociationsAfterId( Retrieves every association after the given ID. :param afterId: The ID after which to retrieve associations. - :type afterId: int :param limit: The maximum number of associations to retrieve, or None if no limit. - :type limit: int or None :return: The retrieved associations (in a dict[id, assoc]), and the highest ID retrieved (or None if no ID thus no association was retrieved). - :rtype: tuple[dict[int, ThreepidAssociation] or int or None] """ cur = self.sydent.db.cursor() @@ -107,16 +103,13 @@ def getSignedAssociationsAfterId( """Get associations after a given ID, and sign them before returning :param afterId: The ID to return results after (not inclusive) - :type afterId: int :param limit: The maximum amount of signed associations to return. None for no limit. - :type limit: int|None :return: A tuple consisting of a dictionary containing the signed associations (id: assoc dict) and an int representing the maximum ID (which is None if there was no association to retrieve). - :rtype: tuple[dict[int, dict[str, any]] or int or None] """ assocs = {} @@ -136,9 +129,7 @@ def removeAssociation(self, threepid: Dict[str, str], mxid: str) -> None: association doesn't exist, log and do nothing. :param threepid: The 3PID of the binding to remove. - :type threepid: dict[unicode, unicode] :param mxid: The MXID of the binding to remove. - :type mxid: unicode """ cur = self.sydent.db.cursor() @@ -193,13 +184,10 @@ def signedAssociationStringForThreepid( if one exists. :param medium: The medium of the 3PID. - :type medium: unicode :param address: The address of the 3PID. - :type address: unicode :return: The signed association, or None if no association was found for this 3PID. - :rtype: unicode or None """ cur = self.sydent.db.cursor() # We treat address as case-insensitive because that's true for all the @@ -227,12 +215,9 @@ def getMxid(self, medium: str, address: str) -> Optional[str]: Retrieves the MXID associated with a 3PID. :param medium: The medium of the 3PID. - :type medium: unicode :param address: The address of the 3PID. - :type address: unicode :return: The associated MXID, or None if no MXID is associated with this 3PID. - :rtype: unicode or None """ cur = self.sydent.db.cursor() res = cur.execute( @@ -257,10 +242,8 @@ def getMxids( database for. Output is ordered by medium, address, timestamp DESC :param threepid_tuples: List containing (medium, address) tuples - :type threepid_tuples: list[tuple[unicode]] :return: a list of (medium, address, mxid) tuples - :rtype: list[tuple[unicode]] """ cur = self.sydent.db.cursor() @@ -317,17 +300,12 @@ def addAssociation( Saves an association received through either a replication push or a local push. :param assoc: The association to add as a high level object. - :type assoc: sydent.threepid.ThreepidAssociation :param rawSgAssoc: The original raw bytes of the signed association. - :type rawSgAssoc: dict[str, any] :param originServer: The name of the server the association was created on. - :type originServer: str :param originId: The ID of the association on the server the association was created on. - :type originId: int :param commit: Whether to commit the database transaction after inserting the association. - :type commit: bool """ cur = self.sydent.db.cursor() cur.execute( @@ -355,11 +333,9 @@ def lastIdFromServer(self, server: str) -> Optional[int]: Retrieves the ID of the last association received from the given peer. :param server: - :type server: str :return: The the ID of the last association received from the peer, or None if no association has ever been received from that peer. - :rtype: int or None """ cur = self.sydent.db.cursor() res = cur.execute( @@ -379,9 +355,7 @@ def removeAssociation(self, medium: str, address: str) -> None: Removes any association stored for the provided 3PID. :param medium: The medium for the 3PID. - :type medium: unicode :param address: The address for the 3PID. - :type address: unicode """ cur = self.sydent.db.cursor() cur.execute( @@ -401,10 +375,8 @@ def retrieveMxidsForHashes(self, addresses: List[str]) -> Dict[str, str]: """Returns a mapping from hash: mxid from a list of given lookup_hash values :param addresses: An array of lookup_hash values to check against the db - :type addresses: list[unicode] :returns a dictionary of lookup_hash values to mxids of all discovered matches - :rtype: dict[unicode, unicode] """ cur = self.sydent.db.cursor() diff --git a/sydent/db/valsession.py b/sydent/db/valsession.py index 20df870a..87d0d2cb 100644 --- a/sydent/db/valsession.py +++ b/sydent/db/valsession.py @@ -42,15 +42,11 @@ def getOrCreateTokenSession( or creates one if none was found. :param medium: The medium to use when looking up or creating the session. - :type medium: unicode :param address: The address to use when looking up or creating the session. - :type address: unicode :param clientSecret: The client secret to use when looking up or creating the session. - :type clientSecret: unicode :return: The session that was retrieved or created. - :rtype: ValidationSession """ cur = self.sydent.db.cursor() @@ -97,20 +93,14 @@ def addValSession( Creates a validation session with the given parameters. :param medium: The medium to create the session for. - :type medium: unicode :param address: The address to create the session for. - :type address: unicode :param clientSecret: The client secret to use when looking up or creating the session. - :type clientSecret: unicode :param mtime: The current time in milliseconds. - :type mtime: int :param commit: Whether to commit the transaction after executing the insert statement. - :type commit: bool :return: The ID of the created session. - :rtype: int """ cur = self.sydent.db.cursor() @@ -132,9 +122,7 @@ def setSendAttemptNumber(self, sid: int, attemptNo: int) -> None: Updates the send attempt number for the session with the given ID. :param sid: The ID of the session to update - :type sid: int :param attemptNo: The send attempt number to update the session with. - :type attemptNo: int """ cur = self.sydent.db.cursor() @@ -149,9 +137,7 @@ def setValidated(self, sid: int, validated: bool) -> None: Updates a session to set the validated flag to the given value. :param sid: The ID of the session to update. - :type sid: int :param validated: The value to set the validated flag. - :type validated: bool """ cur = self.sydent.db.cursor() @@ -166,9 +152,7 @@ def setMtime(self, sid: int, mtime: int) -> None: Set the time of the last send attempt for the session with the given ID :param sid: The ID of the session to update. - :type sid: int :param mtime: The time of the last send attempt for that session. - :type mtime: int """ cur = self.sydent.db.cursor() @@ -183,11 +167,9 @@ def getSessionById(self, sid: int) -> Optional[ValidationSession]: Retrieves the session matching the given sid. :param sid: The ID of the session to retrieve. - :type sid: int :return: The retrieved session, or None if no session could be found with that sid. - :rtype: ValidationSession or None """ cur = self.sydent.db.cursor() @@ -210,10 +192,8 @@ def getTokenSessionById(self, sid: int) -> Optional[ValidationSession]: Retrieves a validation session using the session's ID. :param sid: The ID of the session to retrieve. - :type sid: int :return: The validation session, or None if no session was found with that ID. - :rtype: ValidationSession or None """ cur = self.sydent.db.cursor() @@ -239,13 +219,10 @@ def getValidatedSession(self, sid: int, clientSecret: str) -> ValidationSession: one passed in. :param sid: The ID of the session to retrieve. - :type sid: int :param clientSecret: A client secret to check against the one retrieved from the database. - :type clientSecret: unicode :return: The retrieved session. - :rtype: ValidationSession :raise InvalidSessionIdException: No session could be found with this ID. :raise IncorrectClientSecretException: The session's client secret doesn't diff --git a/sydent/hs_federation/verifier.py b/sydent/hs_federation/verifier.py index 47ee6fde..43cec1fa 100644 --- a/sydent/hs_federation/verifier.py +++ b/sydent/hs_federation/verifier.py @@ -68,7 +68,6 @@ def _getKeysForServer(self, server_name: str) -> Generator: """Get the signing key data from a homeserver. :param server_name: The name of the server to request the keys from. - :type server_name: unicode :return: The verification keys returned by the server. :rtype: twisted.internet.defer.Deferred[dict[unicode, dict[unicode, unicode]]] @@ -122,7 +121,6 @@ def verifyServerSignedJson( :param acceptable_server_names: If provided and not None, only signatures from servers in this list will be accepted. - :type acceptable_server_names: list[unicode] or None :return a tuple of the server name and key name that was successfully verified. @@ -175,9 +173,7 @@ def authenticate_request( XXX: Copied largely from synapse :param request: The request object to authenticate - :type request: twisted.web.server.Request :param content: The content of the request, if any - :type content: bytes or None :return: The origin of the server whose signature was validated :rtype: twisted.internet.defer.Deferred[unicode] @@ -200,10 +196,8 @@ def parse_auth_header(header_str: str) -> Tuple[str, str, str]: authentication header. :param header_str: The content of the header - :type header_str: unicode :return: The server name, the signing key, and the payload signature. - :rtype: tuple[unicode] """ try: params = header_str.split(" ")[1].split(",") diff --git a/sydent/http/auth.py b/sydent/http/auth.py index 8ad7904e..ad4a4f87 100644 --- a/sydent/http/auth.py +++ b/sydent/http/auth.py @@ -32,10 +32,8 @@ def tokenFromRequest(request: "Request") -> Optional[str]: """Extract token from header of query parameter. :param request: The request to look for an access token in. - :type request: twisted.web.server.Request :return: The token or None if not found - :rtype: unicode or None """ token = None # check for Authorization header first @@ -63,9 +61,7 @@ def authV2( """For v2 APIs check that the request has a valid access token associated with it :param sydent: The Sydent instance to use. - :type sydent: sydent.sydent.Sydent :param request: The request to look for an access token in. - :type request: twisted.web.server.Request :param requireTermsAgreed: Whether to deny authentication if the user hasn't accepted the terms of service. diff --git a/sydent/http/httpclient.py b/sydent/http/httpclient.py index d69ed5e2..a8ddce8e 100644 --- a/sydent/http/httpclient.py +++ b/sydent/http/httpclient.py @@ -46,10 +46,8 @@ def get_json(self, uri: str, max_size: Optional[int] = None) -> Generator: """Make a GET request to an endpoint returning JSON and parse result :param uri: The URI to make a GET request to. - :type uri: unicode :param max_size: The maximum size (in bytes) to allow as a response. - :type max_size: int :return: A deferred containing JSON parsed into a Python object. :rtype: twisted.internet.defer.Deferred[dict[any, any]] @@ -76,15 +74,12 @@ def post_json_get_nothing( """Make a POST request to an endpoint returning JSON and parse result :param uri: The URI to make a POST request to. - :type uri: unicode :param post_json: A Python object that will be converted to a JSON string and POSTed to the given URI. - :type post_json: dict[any, any] :param opts: A dictionary of request options. Currently only opts.headers is supported. - :type opts: dict[str,any] :return: a response from the remote server. :rtype: twisted.internet.defer.Deferred[twisted.web.iweb.IResponse] diff --git a/sydent/http/httpsclient.py b/sydent/http/httpsclient.py index 0edaf1ca..68e9ac99 100644 --- a/sydent/http/httpsclient.py +++ b/sydent/http/httpsclient.py @@ -54,9 +54,7 @@ def postJson(self, uri: str, jsonObject: Dict[Any, Any]) -> Optional[Deferred]: Sends an POST request over HTTPS. :param uri: The URI to send the request to. - :type uri: unicode :param jsonObject: The request's body. - :type jsonObject: dict[any, any] :return: The request's response. :rtype: twisted.internet.defer.Deferred[twisted.web.iweb.IResponse] diff --git a/sydent/http/matrixfederationagent.py b/sydent/http/matrixfederationagent.py index 114b0e90..8051697a 100644 --- a/sydent/http/matrixfederationagent.py +++ b/sydent/http/matrixfederationagent.py @@ -124,20 +124,16 @@ def request( ) -> Generator: """ :param method: HTTP method (GET/POST/etc). - :type method: bytes :param uri: Absolute URI to be retrieved. - :type uri: bytes :param headers: HTTP headers to send with the request, or None to send no extra headers. - :type headers: twisted.web.http_headers.Headers, None :param bodyProducer: An object which can generate bytes to make up the body of this request (for example, the properly encoded contents of a file for a file upload). Or None if the request is to have no body. - :type bodyProducer: twisted.web.iweb.IBodyProducer, None :returns a deferred that fires when the header of the response has been received (regardless of the response status code). Fails if @@ -195,10 +191,8 @@ def _route_matrix_uri( :param parsed_uri: uri to route. Note that it should be parsed with URI.fromBytes(uri, defaultPort=-1) to set the `port` to -1 if there is no explicit port given. - :type parsed_uri: twisted.web.client.URI :param lookup_well_known: True if we should look up the .well-known file if there is no SRV record. - :type lookup_well_known: bool :returns a routing result. :rtype: Deferred[_RoutingResult] @@ -302,7 +296,6 @@ def _get_well_known(self, server_name: bytes) -> Generator: """Attempt to fetch and parse a .well-known file for the given server :param server_name: Name of the server, from the requested url. - :type server_name: bytes :returns either the new server name, from the .well-known, or None if there was no .well-known file. @@ -325,7 +318,6 @@ def _do_get_well_known(self, server_name: bytes) -> Generator: """Actually fetch and parse a .well-known, without checking the cache :param server_name: Name of the server, from the requested url - :type server_name: bytes :returns a tuple of (result, cache period), where result is one of: - the new server name from the .well-known (as a `bytes`) diff --git a/sydent/http/servlets/__init__.py b/sydent/http/servlets/__init__.py index 39b4891f..3ecfff69 100644 --- a/sydent/http/servlets/__init__.py +++ b/sydent/http/servlets/__init__.py @@ -54,19 +54,15 @@ def get_args( parameters passed. :param request: The request received by the servlet. - :type request: twisted.web.server.Request :param args: The args to look for in the request's parameters. - :type args: Iterable[str] :param required: Whether to raise a MatrixRestError with 400 M_MISSING_PARAMS if an argument is not found. - :type required: bool :raises: MatrixRestError if required is True and a given parameter was not found in the request's query parameters. :return: A dict containing the requested args and their values. String values are of type unicode. - :rtype: dict[unicode, any] """ assert request.path is not None v1_path = request.path.startswith(b"/_matrix/identity/api/v1") @@ -141,12 +137,10 @@ def inner(self, request: Request, *args, **kwargs) -> bytes: :param self: The current object. :param request: The request to process. - :type request: twisted.web.server.Request :param args: The arguments to pass to the function. :param kwargs: The keyword arguments to pass to the function. :return: The JSON payload to send as a response to the request. - :rtype bytes """ try: request.setHeader("Content-Type", "application/json") @@ -175,9 +169,7 @@ def reqDone(resp: Dict[str, Any], request: Request) -> None: writes it as the response to the given request with the right headers. :param resp: The response content to convert to JSON and encode. - :type resp: dict[str, any] :param request: The request to respond to. - :type request: twisted.web.server.Request """ request.setHeader("Content-Type", "application/json") request.write(dict_to_json_bytes(resp)) @@ -189,9 +181,7 @@ def reqErr(failure: Failure, request: Request) -> None: using the info it contains, otherwise responds with 500 Internal Server Error. :param failure: The failure to process. - :type failure: twisted.python.failure.Failure :param request: The request to respond to. - :type request: twisted.web.server.Request """ request.setHeader("Content-Type", "application/json") if failure.check(MatrixRestError) is not None: @@ -223,7 +213,6 @@ def inner(*args, **kwargs) -> int: :return: A special code to tell the servlet that the response isn't ready yet and will come later. - :rtype: int """ request = args[1] @@ -245,10 +234,6 @@ def dict_to_json_bytes(content: JsonDict) -> bytes: """ Converts a dict into JSON and encodes it to bytes. - :param content: - :type content: dict[any, any] - :return: The JSON bytes. - :rtype: bytes """ return json.dumps(content).encode("UTF-8") diff --git a/sydent/http/servlets/emailservlet.py b/sydent/http/servlets/emailservlet.py index 3d397ccd..9b8abe8a 100644 --- a/sydent/http/servlets/emailservlet.py +++ b/sydent/http/servlets/emailservlet.py @@ -147,12 +147,10 @@ def do_validate_request(self, request: Request) -> JsonDict: attempts to validate that session. :param request: The request to extract information about the session from. - :type request: twisted.web.server.Request :return: A dict with a "success" key which value indicates whether the validation succeeded. If the validation failed, this dict also includes a "errcode" and a "error" keys which include information about the failure. - :rtype: dict[str, bool or str] """ args = get_args(request, ("token", "sid", "client_secret")) diff --git a/sydent/http/servlets/msisdnservlet.py b/sydent/http/servlets/msisdnservlet.py index 216b69b9..3a21a1c9 100644 --- a/sydent/http/servlets/msisdnservlet.py +++ b/sydent/http/servlets/msisdnservlet.py @@ -168,12 +168,10 @@ def do_validate_request(self, request: Request) -> JsonDict: attempts to validate that session. :param request: The request to extract information about the session from. - :type request: twisted.web.server.Request :return: A dict with a "success" key which value indicates whether the validation succeeded. If the validation failed, this dict also includes a "errcode" and a "error" keys which include information about the failure. - :rtype: dict[str, bool or str] """ args = get_args(request, ("token", "sid", "client_secret")) diff --git a/sydent/http/servlets/store_invite_servlet.py b/sydent/http/servlets/store_invite_servlet.py index 8d3aa806..9f05affa 100644 --- a/sydent/http/servlets/store_invite_servlet.py +++ b/sydent/http/servlets/store_invite_servlet.py @@ -188,10 +188,8 @@ def redact_email_address(self, address: str) -> str: domain independently. :param address: The address to redact. - :type address: unicode :return: The redacted address. - :rtype: unicode """ # Extract strings from the address username, domain = address.split("@", 1) @@ -210,14 +208,11 @@ def _redact(self, s: str, characters_to_reveal: int) -> str: If the string is shorter than the given threshold, redact it based on length. :param s: The string to redact. - :type s: unicode :param characters_to_reveal: How many characters of the string to leave before the '...' - :type characters_to_reveal: int :return: The redacted string. - :rtype: unicode """ # If the string is shorter than the defined threshold, redact based on length if len(s) <= characters_to_reveal: @@ -235,9 +230,7 @@ def _randomString(self, length: int) -> str: Generate a random string of the given length. :param length: The length of the string to generate. - :type length: int :return: The generated string. - :rtype: unicode """ return "".join(self.random.choice(string.ascii_letters) for _ in range(length)) diff --git a/sydent/http/srvresolver.py b/sydent/http/srvresolver.py index 691773bc..4df59bac 100644 --- a/sydent/http/srvresolver.py +++ b/sydent/http/srvresolver.py @@ -53,10 +53,8 @@ def pick_server_from_list(server_list: List[Server]) -> Tuple[bytes, int]: """Randomly choose a server from the server list. :param server_list: List of candidate servers. - :type server_list: list[Server] :returns a (host, port) pair for the chosen server. - :rtype: Tuple[bytes, int] """ if not server_list: raise RuntimeError("pick_server_from_list called with empty list") @@ -87,13 +85,10 @@ class SrvResolver: but the cache never gets populated), so we add our own caching layer here. :param dns_client: Twisted resolver impl - :type dns_client: twisted.internet.interfaces.IResolver :param cache: cache object - :type cache: Dict :param get_time: Clock implementation. Should return seconds since the epoch. - :type get_time: callable """ def __init__( @@ -110,10 +105,9 @@ async def resolve_service(self, service_name: bytes) -> List["Server"]: """Look up a SRV record :param service_name: The record to look up. - :type service_name: bytes + :returns a list of the SRV records, or an empty list if none found. - :rtype: Deferred[list[Server]] """ now = int(self._get_time()) diff --git a/sydent/replication/peer.py b/sydent/replication/peer.py index 529b6093..cf7e98d6 100644 --- a/sydent/replication/peer.py +++ b/sydent/replication/peer.py @@ -52,7 +52,6 @@ def pushUpdates(self, sgAssocs) -> "Deferred": """ :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 @@ -77,10 +76,8 @@ def pushUpdates(self, sgAssocs: Dict[int, Dict[str, Any]]) -> "Deferred": association if its ID is greater than the last seen ID. :param sgAssocs: The associations to save. - :type sgAssocs: dict[int, dict[str, any]] :return: True - :rtype: twisted.internet.defer.Deferred[bool] """ globalAssocStore = GlobalAssociationStore(self.sydent) for localId in sgAssocs: @@ -126,15 +123,10 @@ def __init__( ) -> None: """ :param sydent: The current Sydent instance. - :type sydent: sydent.sydent.Sydent :param server_name: The peer's server name. - :type server_name: unicode :param port: The peer's port. - :type port: int :param pubkeys: The peer's public keys in a dict[key_id, key_b64] - :type pubkeys: dict[unicode, unicode] :param lastSentVersion: The ID of the last association sent to the peer. - :type lastSentVersion: int """ super().__init__(server_name, pubkeys) self.sydent = sydent @@ -195,7 +187,6 @@ def verifySignedAssociation(self, assoc: Dict[Any, Any]) -> None: signature is incorrect or couldn't be verified. :param assoc: A signed association. - :type assoc: dict[any, any] """ if "signatures" not in assoc: raise NoSignaturesException() @@ -219,10 +210,8 @@ def pushUpdates(self, sgAssocs: Dict[int, Dict[str, Any]]) -> "Deferred": Pushes the given associations to the peer. :param sgAssocs: The associations to push. - :type sgAssocs: dict[int, dict[str, any]] :return: A deferred which results in the response to the push request. - :rtype: twisted.internet.defer.Deferred[twisted.web.iweb.IResponse] """ body = {"sgAssocs": sgAssocs} @@ -252,10 +241,8 @@ def _pushSuccess( that's not a success, consider it a failure :param result: The HTTP response. - :type result: twisted.web.iweb.IResponse :param updateDeferred: The deferred to make either succeed or fail depending on the status code. - :type updateDeferred: twisted.internet.defer.Deferred """ if result.code >= 200 and result.code < 300: updateDeferred.callback(result) @@ -270,9 +257,7 @@ def _failedPushBodyRead(self, body: bytes, updateDeferred: "Deferred") -> None: callback of the provided deferred. :param body: The response body. - :type body: bytes :param updateDeferred: The deferred to call the error callback of. - :type updateDeferred: twisted.internet.defer.Deferred """ errObj = json_decoder.decode(body.decode("utf8")) e = RemotePeerError() @@ -291,7 +276,6 @@ def _pushFailed( :param failure: The failure to process. :type failure: twisted.python.failure.Failure :param updateDeferred: The deferred to call the error callback of. - :type updateDeferred: twisted.internet.defer.Deferred """ updateDeferred.errback(failure) return None diff --git a/sydent/replication/pusher.py b/sydent/replication/pusher.py index 06900ac5..0242cb9e 100644 --- a/sydent/replication/pusher.py +++ b/sydent/replication/pusher.py @@ -84,7 +84,6 @@ async def _push_to_peer(self, p: "RemotePeer") -> None: sends them. :param p: The peer to send associations to. - :type p: sydent.replication.peer.RemotePeer """ logger.debug("Looking for updates to push to %s", p.servername) diff --git a/sydent/sms/openmarket.py b/sydent/sms/openmarket.py index 7eb22fab..55bad951 100644 --- a/sydent/sms/openmarket.py +++ b/sydent/sms/openmarket.py @@ -61,18 +61,15 @@ def __init__(self, sydent: "Sydent") -> None: self.http_cli = SimpleHttpClient(sydent) async def sendTextSMS( - self, body: Dict, dest: str, source: Optional[Dict[str, str]] = None + self, body: str, dest: str, source: Optional[Dict[str, str]] = None ) -> None: """ Sends a text message with the given body to the given MSISDN. :param body: The message to send. - :type body: str :param dest: The destination MSISDN to send the text message to. - :type dest: unicode - :type source: dict[str, str] or None """ - body = { + send_body = { "mobileTerminate": { "message": {"content": body, "type": "text"}, "destination": { @@ -81,7 +78,7 @@ async def sendTextSMS( }, } if source: - body["mobileTerminate"]["source"] = { + send_body["mobileTerminate"]["source"] = { "ton": tonFromType(source["type"]), "address": source["text"], } @@ -100,7 +97,7 @@ async def sendTextSMS( ) resp = await self.http_cli.post_json_get_nothing( - API_BASE_URL, body, {"headers": req_headers} + API_BASE_URL, send_body, {"headers": req_headers} ) headers = dict(resp.headers.getAllRawHeaders()) diff --git a/sydent/terms/terms.py b/sydent/terms/terms.py index 2777780b..58bf83f1 100644 --- a/sydent/terms/terms.py +++ b/sydent/terms/terms.py @@ -24,7 +24,6 @@ class Terms: def __init__(self, yamlObj: Optional[Dict[str, Any]]) -> None: """ :param yamlObj: The parsed YAML. - :type yamlObj: dict[str, any] or None """ self._rawTerms = yamlObj @@ -32,7 +31,6 @@ def getMasterVersion(self) -> Optional[str]: """ :return: The global (master) version of the terms, or None if there are no terms of service for this server. - :rtype: unicode or None """ version = None if self._rawTerms is None else self._rawTerms["master_version"] @@ -46,7 +44,6 @@ def getForClient(self) -> Dict[str, dict]: """ :return: A dict which value for the "policies" key is a dict which contains the "docs" part of the terms' YAML. That nested dict is empty if no terms. - :rtype: dict[str, dict] """ policies = {} if self._rawTerms is not None: @@ -60,7 +57,6 @@ def getForClient(self) -> Dict[str, dict]: def getUrlSet(self) -> Set[str]: """ :return: All the URLs for the terms in a set. Empty set if no terms. - :rtype: set[unicode] """ urls = set() if self._rawTerms is not None: @@ -81,11 +77,9 @@ def urlListIsSufficient(self, urls: List[str]) -> bool: accepted by the user) is enough to allow the creation of the user's account. :param urls: The list of URLs of terms the user has accepted. - :type urls: list[unicode] :return: Whether the list is sufficient to allow the creation of the user's account. - :rtype: bool """ agreed = set() urlset = set(urls) diff --git a/sydent/threepid/bind.py b/sydent/threepid/bind.py index 7172536c..36609ba2 100644 --- a/sydent/threepid/bind.py +++ b/sydent/threepid/bind.py @@ -53,14 +53,10 @@ def addBinding(self, medium: str, address: str, mxid: str) -> Dict[str, Any]: the given 3pid :param medium: The medium of the 3PID to bind. - :type medium: unicode :param address: The address of the 3PID to bind. - :type address: unicode :param mxid: The MXID to bind the 3PID to. - :type mxid: unicode :return: The signed association. - :rtype: dict[str, any] """ localAssocStore = LocalAssociationStore(self.sydent) @@ -118,9 +114,7 @@ def removeBinding(self, threepid: Dict[str, str], mxid: str) -> None: Removes the binding between a given 3PID and a given MXID. :param threepid: The 3PID of the binding to remove. - :type threepid: dict[unicode, unicode] :param mxid: The MXID of the binding to remove. - :type mxid: unicode """ localAssocStore = LocalAssociationStore(self.sydent) localAssocStore.removeAssociation(threepid, mxid) @@ -133,9 +127,7 @@ def _notify(self, assoc: Dict[str, Any], attempt: int) -> Generator: to the associated MXID's homeserver. :param assoc: The association to send down to the homeserver. - :type assoc: dict[str, any] :param attempt: The number of previous attempts to send this association. - :type attempt: int """ mxid = assoc["mxid"] mxid_parts = mxid.split(":", 1) @@ -202,11 +194,8 @@ def _notifyErrback( logging the error and scheduling a new attempt. :param assoc: The association to send down to the homeserver. - :type assoc: dict[str, any] :param attempt: The number of previous attempts to send this association. - :type attempt: int :param error: The error that was raised when trying to send the association. - :type error: Exception """ logger.warning( "Error notifying on bind for %s: %s - rescheduling", assoc["mxid"], error diff --git a/sydent/threepid/signer.py b/sydent/threepid/signer.py index d49962ff..4cc37913 100644 --- a/sydent/threepid/signer.py +++ b/sydent/threepid/signer.py @@ -30,10 +30,8 @@ def signedThreePidAssociation(self, assoc: "ThreepidAssociation") -> Dict[str, A Signs a 3PID association. :param assoc: The association to sign. - :type assoc: sydent.threepid.ThreepidAssociation :return: A signed representation of the association. - :rtype: dict[str, any] """ sgassoc = { "medium": assoc.medium, diff --git a/sydent/users/accounts.py b/sydent/users/accounts.py index d565cf4d..18f3fda8 100644 --- a/sydent/users/accounts.py +++ b/sydent/users/accounts.py @@ -17,9 +17,7 @@ class Account: def __init__(self, user_id: str, creation_ts: int, consent_version: str) -> None: """ :param user_id: The Matrix user ID for the account. - :type user_id: str :param creation_ts: The timestamp in milliseconds of the account's creation. - :type creation_ts: int :param consent_version: The version of the terms of services that the user last accepted. """ diff --git a/sydent/users/tokens.py b/sydent/users/tokens.py index a2f02929..c8e427a7 100644 --- a/sydent/users/tokens.py +++ b/sydent/users/tokens.py @@ -32,12 +32,9 @@ def issueToken(sydent: "Sydent", user_id: str) -> str: an access token for that account. :param sydent: The Sydent instance to use for storing the token. - :type sydent: sydent.sydent.Sydent :param user_id: The Matrix user ID to issue a token for. - :type user_id: unicode :return: The access token for that account. - :rtype: unicode """ accountStore = AccountStore(sydent) accountStore.storeAccount(user_id, int(time.time() * 1000), None) diff --git a/sydent/util/emailutils.py b/sydent/util/emailutils.py index 315bc58c..e9de0ac6 100644 --- a/sydent/util/emailutils.py +++ b/sydent/util/emailutils.py @@ -41,14 +41,10 @@ def sendEmail( :param sydent: The Sydent instance to use when building the configuration to send the email with. - :type sydent: sydent.sydent.Sydent :param templateFile: The filename of the template to use when building the body of the email. - :type templateFile: str :param mailTo: The email address to send the email to. - :type mailTo: unicode :param substitutions: The substitutions to use with the template. - :type substitutions: dict[str, str] """ mailFrom = sydent.cfg.get("email", "email.from") diff --git a/sydent/util/hash.py b/sydent/util/hash.py index 38dea6db..3bf04ca1 100644 --- a/sydent/util/hash.py +++ b/sydent/util/hash.py @@ -22,10 +22,8 @@ def sha256_and_url_safe_base64(input_text: str) -> str: return :param input_text: string to hash - :type input_text: unicode :returns a sha256 hashed and url-safe base64 encoded digest - :rtype: bytes """ digest = hashlib.sha256(input_text.encode()).digest() return unpaddedbase64.encode_base64(digest, urlsafe=True) diff --git a/sydent/util/stringutils.py b/sydent/util/stringutils.py index d66737fd..d757da88 100644 --- a/sydent/util/stringutils.py +++ b/sydent/util/stringutils.py @@ -40,10 +40,8 @@ def is_valid_client_secret(client_secret: str) -> bool: """Validate that a given string matches the client_secret regex defined by the spec :param client_secret: The client_secret to validate - :type client_secret: str :return: Whether the client_secret is valid - :rtype: bool """ return ( 0 < len(client_secret) <= 255 @@ -58,10 +56,8 @@ def is_valid_hostname(string: str) -> bool: instance, it doesn't check that the TLD is valid). :param string: The string to validate - :type string: str :return: Whether the input is a valid hostname - :rtype: bool """ return hostname_regex.match(string) is not None @@ -114,10 +110,8 @@ def is_valid_matrix_server_name(string: str) -> bool: c. A valid hostname :param string: The string to validate - :type string: str :return: Whether the input is a valid Matrix server name - :rtype: bool """ try: diff --git a/sydent/util/tokenutils.py b/sydent/util/tokenutils.py index ef607a96..d7e7b932 100644 --- a/sydent/util/tokenutils.py +++ b/sydent/util/tokenutils.py @@ -24,10 +24,8 @@ def generateTokenForMedium(medium: str) -> str: alphanumeric one if the medium is email, a 6 characters numeric one otherwise. :param medium: The medium to generate a token for. - :type medium: unicode :return: The generated token. - :rtype: unicode """ if medium == "email": return generateAlphanumericTokenOfLength(32) @@ -40,10 +38,8 @@ def generateNumericTokenOfLength(length: int) -> str: Generates a token of the given length with the character set [0-9]. :param length: The length of the token to generate. - :type length: int :return: The generated token. - :rtype: unicode """ return "".join([r.choice(string.digits) for _ in range(length)]) @@ -53,10 +49,8 @@ def generateAlphanumericTokenOfLength(length: int) -> str: Generates a token of the given length with the character set [a-zA-Z0-9]. :param length: The length of the token to generate. - :type length: int :return: The generated token. - :rtype: unicode """ return "".join( [ diff --git a/sydent/validators/common.py b/sydent/validators/common.py index 72ad368a..8a049555 100644 --- a/sydent/validators/common.py +++ b/sydent/validators/common.py @@ -26,15 +26,11 @@ def validateSessionWithToken( prevent attempts to guess the token for a sid. :param sid: The ID of the session to validate. - :type sid: int :param clientSecret: The client secret to validate. - :type clientSecret: unicode :param token: The token to validate. - :type token: unicode :return: A dict with a "success" key which is True if the session was successfully validated, False otherwise. - :rtype: dict[str, bool] :raise IncorrectClientSecretException: The provided client_secret is incorrect. :raise SessionExpiredException: The session has expired. diff --git a/sydent/validators/emailvalidator.py b/sydent/validators/emailvalidator.py index 987bbbad..a34b3099 100644 --- a/sydent/validators/emailvalidator.py +++ b/sydent/validators/emailvalidator.py @@ -46,21 +46,14 @@ def requestToken( email address with a token to use to verify the association. :param emailAddress: The email address to send the email to. - :type emailAddress: unicode :param clientSecret: The client secret to use. - :type clientSecret: unicode :param sendAttempt: The current send attempt. - :type sendAttempt: int :param nextLink: The link to redirect the user to once they have completed the validation. - :type nextLink: unicode :param ipaddress: The requester's IP address. - :type ipaddress: str or None :param brand: A hint at a brand from the request. - :type brand: str or None :return: The ID of the session created (or of the existing one if any) - :rtype: int """ valSessionStore = ThreePidValSessionStore(self.sydent) @@ -110,15 +103,11 @@ def makeValidateLink( Creates a validation link that can be sent via email to the user. :param valSession: The current validation session. - :type valSession: sydent.validators.ValidationSession :param clientSecret: The client secret to include in the link. - :type clientSecret: unicode :param nextLink: The link to redirect the user to once they have completed the validation. - :type nextLink: unicode :return: The validation link. - :rtype: unicode """ base = self.sydent.cfg.get("http", "client_http_base") link = "%s/_matrix/identity/api/v1/validate/email/submitToken?token=%s&client_secret=%s&sid=%d" % ( @@ -147,14 +136,10 @@ def validateSessionWithToken( Validates the session with the given ID. :param sid: The ID of the session to validate. - :type sid: int :param clientSecret: The client secret to validate. - :type clientSecret: unicode :param token: The token to validate. - :type token: unicode :return: A dict with a "success" key which is True if the session was successfully validated, False otherwise. - :rtype: dict[str, bool] """ return common.validateSessionWithToken(self.sydent, sid, clientSecret, token) diff --git a/sydent/validators/msisdnvalidator.py b/sydent/validators/msisdnvalidator.py index 33f5d6ee..2561d731 100644 --- a/sydent/validators/msisdnvalidator.py +++ b/sydent/validators/msisdnvalidator.py @@ -84,16 +84,11 @@ def requestToken( corresponding phone number address with a token to use to verify the association. :param phoneNumber: The phone number to send the email to. - :type phoneNumber: phonenumbers.PhoneNumber :param clientSecret: The client secret to use. - :type clientSecret: unicode :param sendAttempt: The current send attempt. - :type sendAttempt: int :param brand: A hint at a brand from the request. - :type brand: str or None :return: The ID of the session created (or of the existing one if any) - :rtype: int """ if str(phoneNumber.country_code) in self.smsRules: action = self.smsRules[str(phoneNumber.country_code)] @@ -146,10 +141,8 @@ def getOriginator( Gets an originator for a given phone number. :param destPhoneNumber: The phone number to find the originator for. - :type destPhoneNumber: phonenumbers.PhoneNumber :return: The originator (a dict with a "type" key and a "text" key). - :rtype: dict[str, str] """ countryCode = str(destPhoneNumber.country_code) @@ -181,14 +174,10 @@ def validateSessionWithToken( Validates the session with the given ID. :param sid: The ID of the session to validate. - :type sid: int :param clientSecret: The client secret to validate. - :type clientSecret: unicode :param token: The token to validate. - :type token: unicode :return: A dict with a "success" key which is True if the session was successfully validated, False otherwise. - :rtype: dict[str, bool] """ return common.validateSessionWithToken(self.sydent, sid, clientSecret, token)