Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Commit aaf7d1a

Browse files
authored
Correct type hints for synapse.event_auth. (#10253)
1 parent 329ef5c commit aaf7d1a

File tree

6 files changed

+51
-38
lines changed

6 files changed

+51
-38
lines changed

changelog.d/10253.misc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix type hints for computing auth events.

synapse/api/auth.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414
import logging
15-
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
15+
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
1616

1717
import pymacaroons
1818
from netaddr import IPAddress
@@ -31,6 +31,7 @@
3131
from synapse.api.room_versions import KNOWN_ROOM_VERSIONS
3232
from synapse.appservice import ApplicationService
3333
from synapse.events import EventBase
34+
from synapse.events.builder import EventBuilder
3435
from synapse.http import get_request_user_agent
3536
from synapse.http.site import SynapseRequest
3637
from synapse.logging import opentracing as opentracing
@@ -490,7 +491,7 @@ async def is_server_admin(self, user: UserID) -> bool:
490491

491492
def compute_auth_events(
492493
self,
493-
event,
494+
event: Union[EventBase, EventBuilder],
494495
current_state_ids: StateMap[str],
495496
for_verification: bool = False,
496497
) -> List[str]:

synapse/event_auth.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
# limitations under the License.
1515

1616
import logging
17-
from typing import Any, Dict, List, Optional, Set, Tuple
17+
from typing import Any, Dict, List, Optional, Set, Tuple, Union
1818

1919
from canonicaljson import encode_canonical_json
2020
from signedjson.key import decode_verify_key_bytes
@@ -29,6 +29,7 @@
2929
RoomVersion,
3030
)
3131
from synapse.events import EventBase
32+
from synapse.events.builder import EventBuilder
3233
from synapse.types import StateMap, UserID, get_domain_from_id
3334

3435
logger = logging.getLogger(__name__)
@@ -724,7 +725,7 @@ def get_public_keys(invite_event: EventBase) -> List[Dict[str, Any]]:
724725
return public_keys
725726

726727

727-
def auth_types_for_event(event: EventBase) -> Set[Tuple[str, str]]:
728+
def auth_types_for_event(event: Union[EventBase, EventBuilder]) -> Set[Tuple[str, str]]:
728729
"""Given an event, return a list of (EventType, StateKey) that may be
729730
needed to auth the event. The returned list may be a superset of what
730731
would actually be required depending on the full state of the room.

synapse/events/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ def __init__(self, internal_metadata_dict: JsonDict):
118118
proactively_send = DictProperty("proactively_send") # type: bool
119119
redacted = DictProperty("redacted") # type: bool
120120
txn_id = DictProperty("txn_id") # type: str
121-
token_id = DictProperty("token_id") # type: str
121+
token_id = DictProperty("token_id") # type: int
122122
historical = DictProperty("historical") # type: bool
123123

124124
# XXX: These are set by StreamWorkerStore._set_before_and_after.

synapse/events/builder.py

Lines changed: 36 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,11 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414
import logging
15-
from typing import Any, Dict, List, Optional, Tuple, Union
15+
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
1616

1717
import attr
1818
from nacl.signing import SigningKey
1919

20-
from synapse.api.auth import Auth
2120
from synapse.api.constants import MAX_DEPTH
2221
from synapse.api.errors import UnsupportedRoomVersionError
2322
from synapse.api.room_versions import (
@@ -34,10 +33,14 @@
3433
from synapse.util import Clock
3534
from synapse.util.stringutils import random_string
3635

36+
if TYPE_CHECKING:
37+
from synapse.api.auth import Auth
38+
from synapse.server import HomeServer
39+
3740
logger = logging.getLogger(__name__)
3841

3942

40-
@attr.s(slots=True, cmp=False, frozen=True)
43+
@attr.s(slots=True, cmp=False, frozen=True, auto_attribs=True)
4144
class EventBuilder:
4245
"""A format independent event builder used to build up the event content
4346
before signing the event.
@@ -62,31 +65,30 @@ class EventBuilder:
6265
_signing_key: The signing key to use to sign the event as the server
6366
"""
6467

65-
_state = attr.ib(type=StateHandler)
66-
_auth = attr.ib(type=Auth)
67-
_store = attr.ib(type=DataStore)
68-
_clock = attr.ib(type=Clock)
69-
_hostname = attr.ib(type=str)
70-
_signing_key = attr.ib(type=SigningKey)
68+
_state: StateHandler
69+
_auth: "Auth"
70+
_store: DataStore
71+
_clock: Clock
72+
_hostname: str
73+
_signing_key: SigningKey
7174

72-
room_version = attr.ib(type=RoomVersion)
75+
room_version: RoomVersion
7376

74-
room_id = attr.ib(type=str)
75-
type = attr.ib(type=str)
76-
sender = attr.ib(type=str)
77+
room_id: str
78+
type: str
79+
sender: str
7780

78-
content = attr.ib(default=attr.Factory(dict), type=JsonDict)
79-
unsigned = attr.ib(default=attr.Factory(dict), type=JsonDict)
81+
content: JsonDict = attr.Factory(dict)
82+
unsigned: JsonDict = attr.Factory(dict)
8083

8184
# These only exist on a subset of events, so they raise AttributeError if
8285
# someone tries to get them when they don't exist.
83-
_state_key = attr.ib(default=None, type=Optional[str])
84-
_redacts = attr.ib(default=None, type=Optional[str])
85-
_origin_server_ts = attr.ib(default=None, type=Optional[int])
86+
_state_key: Optional[str] = None
87+
_redacts: Optional[str] = None
88+
_origin_server_ts: Optional[int] = None
8689

87-
internal_metadata = attr.ib(
88-
default=attr.Factory(lambda: _EventInternalMetadata({})),
89-
type=_EventInternalMetadata,
90+
internal_metadata: _EventInternalMetadata = attr.Factory(
91+
lambda: _EventInternalMetadata({})
9092
)
9193

9294
@property
@@ -184,7 +186,7 @@ async def build(
184186

185187

186188
class EventBuilderFactory:
187-
def __init__(self, hs):
189+
def __init__(self, hs: "HomeServer"):
188190
self.clock = hs.get_clock()
189191
self.hostname = hs.hostname
190192
self.signing_key = hs.signing_key
@@ -193,15 +195,14 @@ def __init__(self, hs):
193195
self.state = hs.get_state_handler()
194196
self.auth = hs.get_auth()
195197

196-
def new(self, room_version, key_values):
198+
def new(self, room_version: str, key_values: dict) -> EventBuilder:
197199
"""Generate an event builder appropriate for the given room version
198200
199201
Deprecated: use for_room_version with a RoomVersion object instead
200202
201203
Args:
202-
room_version (str): Version of the room that we're creating an event builder
203-
for
204-
key_values (dict): Fields used as the basis of the new event
204+
room_version: Version of the room that we're creating an event builder for
205+
key_values: Fields used as the basis of the new event
205206
206207
Returns:
207208
EventBuilder
@@ -212,13 +213,15 @@ def new(self, room_version, key_values):
212213
raise UnsupportedRoomVersionError()
213214
return self.for_room_version(v, key_values)
214215

215-
def for_room_version(self, room_version, key_values):
216+
def for_room_version(
217+
self, room_version: RoomVersion, key_values: dict
218+
) -> EventBuilder:
216219
"""Generate an event builder appropriate for the given room version
217220
218221
Args:
219-
room_version (synapse.api.room_versions.RoomVersion):
222+
room_version:
220223
Version of the room that we're creating an event builder for
221-
key_values (dict): Fields used as the basis of the new event
224+
key_values: Fields used as the basis of the new event
222225
223226
Returns:
224227
EventBuilder
@@ -286,15 +289,15 @@ def create_local_event_from_event_dict(
286289
_event_id_counter = 0
287290

288291

289-
def _create_event_id(clock, hostname):
292+
def _create_event_id(clock: Clock, hostname: str) -> str:
290293
"""Create a new event ID
291294
292295
Args:
293-
clock (Clock)
294-
hostname (str): The server name for the event ID
296+
clock
297+
hostname: The server name for the event ID
295298
296299
Returns:
297-
str
300+
The new event ID
298301
"""
299302

300303
global _event_id_counter

synapse/handlers/message.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -509,6 +509,8 @@ async def create_event(
509509
Should normally be left as None, which will cause them to be calculated
510510
based on the room state at the prev_events.
511511
512+
If non-None, prev_event_ids must also be provided.
513+
512514
require_consent: Whether to check if the requester has
513515
consented to the privacy policy.
514516
@@ -581,6 +583,9 @@ async def create_event(
581583
# Strip down the auth_event_ids to only what we need to auth the event.
582584
# For example, we don't need extra m.room.member that don't match event.sender
583585
if auth_event_ids is not None:
586+
# If auth events are provided, prev events must be also.
587+
assert prev_event_ids is not None
588+
584589
temp_event = await builder.build(
585590
prev_event_ids=prev_event_ids,
586591
auth_event_ids=auth_event_ids,
@@ -784,6 +789,8 @@ async def create_and_send_nonmember_event(
784789
The event ids to use as the auth_events for the new event.
785790
Should normally be left as None, which will cause them to be calculated
786791
based on the room state at the prev_events.
792+
793+
If non-None, prev_event_ids must also be provided.
787794
ratelimit: Whether to rate limit this send.
788795
txn_id: The transaction ID.
789796
ignore_shadow_ban: True if shadow-banned users should be allowed to

0 commit comments

Comments
 (0)