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

Commit b43d085

Browse files
author
Sean Quah
committed
Convert strings in synapse.api.constants to enums or Final
This change makes mypy type the constants as `Literal`s instead of `str`s, allowing code of the following form to pass mypy: ```py def do_something( membership: Literal[Membership.JOIN, Membership.LEAVE], ... ): ... do_something(Membership.JOIN, ...) ```
1 parent ab89c60 commit b43d085

File tree

12 files changed

+173
-135
lines changed

12 files changed

+173
-135
lines changed

changelog.d/11356.misc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
Add `Final` annotation to string constants in `synapse.api.constants` so that they get typed as `Literal`s.
1+
Convert most string constants in `synapse.api.constants` into enums, so that they are usable as `Literal`s, and make the rest `Final`.

synapse/api/auth.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
from synapse.http.site import SynapseRequest
3535
from synapse.logging import opentracing as opentracing
3636
from synapse.storage.databases.main.registration import TokenLookupResult
37-
from synapse.types import Requester, StateMap, UserID, create_requester
37+
from synapse.types import MutableStateMap, Requester, StateMap, UserID, create_requester
3838
from synapse.util.caches.lrucache import LruCache
3939
from synapse.util.macaroons import get_value_from_macaroon, satisfy_expiry
4040

@@ -511,7 +511,7 @@ async def check_can_change_room_list(self, room_id: str, user: UserID) -> bool:
511511
room_id, EventTypes.PowerLevels, ""
512512
)
513513

514-
auth_events = {}
514+
auth_events: MutableStateMap[EventBase] = {}
515515
if power_level_event:
516516
auth_events[(EventTypes.PowerLevels, "")] = power_level_event
517517

synapse/api/constants.py

Lines changed: 117 additions & 118 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919

2020
from typing_extensions import Final
2121

22+
from synapse.util.enum import StrEnum
23+
2224
# the max size of a (canonical-json-encoded) event
2325
MAX_PDU_SIZE = 65536
2426

@@ -37,221 +39,218 @@
3739
MAX_GROUP_ROLEID_LENGTH = 255
3840

3941

40-
class Membership:
41-
42+
class Membership(StrEnum):
4243
"""Represents the membership states of a user in a room."""
4344

44-
INVITE: Final = "invite"
45-
JOIN: Final = "join"
46-
KNOCK: Final = "knock"
47-
LEAVE: Final = "leave"
48-
BAN: Final = "ban"
49-
LIST: Final = (INVITE, JOIN, KNOCK, LEAVE, BAN)
45+
INVITE = "invite"
46+
JOIN = "join"
47+
KNOCK = "knock"
48+
LEAVE = "leave"
49+
BAN = "ban"
5050

5151

52-
class PresenceState:
52+
class PresenceState(StrEnum):
5353
"""Represents the presence state of a user."""
5454

55-
OFFLINE: Final = "offline"
56-
UNAVAILABLE: Final = "unavailable"
57-
ONLINE: Final = "online"
58-
BUSY: Final = "org.matrix.msc3026.busy"
55+
OFFLINE = "offline"
56+
UNAVAILABLE = "unavailable"
57+
ONLINE = "online"
58+
BUSY = "org.matrix.msc3026.busy"
5959

6060

61-
class JoinRules:
62-
PUBLIC: Final = "public"
63-
KNOCK: Final = "knock"
64-
INVITE: Final = "invite"
65-
PRIVATE: Final = "private"
61+
class JoinRules(StrEnum):
62+
PUBLIC = "public"
63+
KNOCK = "knock"
64+
INVITE = "invite"
65+
PRIVATE = "private"
6666
# As defined for MSC3083.
67-
RESTRICTED: Final = "restricted"
67+
RESTRICTED = "restricted"
6868

6969

70-
class RestrictedJoinRuleTypes:
70+
class RestrictedJoinRuleTypes(StrEnum):
7171
"""Understood types for the allow rules in restricted join rules."""
7272

73-
ROOM_MEMBERSHIP: Final = "m.room_membership"
73+
ROOM_MEMBERSHIP = "m.room_membership"
7474

7575

76-
class LoginType:
77-
PASSWORD: Final = "m.login.password"
78-
EMAIL_IDENTITY: Final = "m.login.email.identity"
79-
MSISDN: Final = "m.login.msisdn"
80-
RECAPTCHA: Final = "m.login.recaptcha"
81-
TERMS: Final = "m.login.terms"
82-
SSO: Final = "m.login.sso"
83-
DUMMY: Final = "m.login.dummy"
84-
REGISTRATION_TOKEN: Final = "org.matrix.msc3231.login.registration_token"
76+
class LoginType(StrEnum):
77+
PASSWORD = "m.login.password"
78+
EMAIL_IDENTITY = "m.login.email.identity"
79+
MSISDN = "m.login.msisdn"
80+
RECAPTCHA = "m.login.recaptcha"
81+
TERMS = "m.login.terms"
82+
SSO = "m.login.sso"
83+
DUMMY = "m.login.dummy"
84+
REGISTRATION_TOKEN = "org.matrix.msc3231.login.registration_token"
8585

8686

8787
# This is used in the `type` parameter for /register when called by
8888
# an appservice to register a new user.
8989
APP_SERVICE_REGISTRATION_TYPE: Final = "m.login.application_service"
9090

9191

92-
class EventTypes:
93-
Member: Final = "m.room.member"
94-
Create: Final = "m.room.create"
95-
Tombstone: Final = "m.room.tombstone"
96-
JoinRules: Final = "m.room.join_rules"
97-
PowerLevels: Final = "m.room.power_levels"
98-
Aliases: Final = "m.room.aliases"
99-
Redaction: Final = "m.room.redaction"
100-
ThirdPartyInvite: Final = "m.room.third_party_invite"
101-
RelatedGroups: Final = "m.room.related_groups"
102-
103-
RoomHistoryVisibility: Final = "m.room.history_visibility"
104-
CanonicalAlias: Final = "m.room.canonical_alias"
105-
Encrypted: Final = "m.room.encrypted"
106-
RoomAvatar: Final = "m.room.avatar"
107-
RoomEncryption: Final = "m.room.encryption"
108-
GuestAccess: Final = "m.room.guest_access"
92+
class EventTypes(StrEnum):
93+
Member = "m.room.member"
94+
Create = "m.room.create"
95+
Tombstone = "m.room.tombstone"
96+
JoinRules = "m.room.join_rules"
97+
PowerLevels = "m.room.power_levels"
98+
Aliases = "m.room.aliases"
99+
Redaction = "m.room.redaction"
100+
ThirdPartyInvite = "m.room.third_party_invite"
101+
RelatedGroups = "m.room.related_groups"
102+
103+
RoomHistoryVisibility = "m.room.history_visibility"
104+
CanonicalAlias = "m.room.canonical_alias"
105+
Encrypted = "m.room.encrypted"
106+
RoomAvatar = "m.room.avatar"
107+
RoomEncryption = "m.room.encryption"
108+
GuestAccess = "m.room.guest_access"
109109

110110
# These are used for validation
111-
Message: Final = "m.room.message"
112-
Topic: Final = "m.room.topic"
113-
Name: Final = "m.room.name"
111+
Message = "m.room.message"
112+
Topic = "m.room.topic"
113+
Name = "m.room.name"
114114

115-
ServerACL: Final = "m.room.server_acl"
116-
Pinned: Final = "m.room.pinned_events"
115+
ServerACL = "m.room.server_acl"
116+
Pinned = "m.room.pinned_events"
117117

118-
Retention: Final = "m.room.retention"
118+
Retention = "m.room.retention"
119119

120-
Dummy: Final = "org.matrix.dummy_event"
120+
Dummy = "org.matrix.dummy_event"
121121

122-
SpaceChild: Final = "m.space.child"
123-
SpaceParent: Final = "m.space.parent"
122+
SpaceChild = "m.space.child"
123+
SpaceParent = "m.space.parent"
124124

125-
MSC2716_INSERTION: Final = "org.matrix.msc2716.insertion"
126-
MSC2716_BATCH: Final = "org.matrix.msc2716.batch"
127-
MSC2716_MARKER: Final = "org.matrix.msc2716.marker"
125+
MSC2716_INSERTION = "org.matrix.msc2716.insertion"
126+
MSC2716_BATCH = "org.matrix.msc2716.batch"
127+
MSC2716_MARKER = "org.matrix.msc2716.marker"
128128

129129

130-
class ToDeviceEventTypes:
131-
RoomKeyRequest: Final = "m.room_key_request"
130+
class ToDeviceEventTypes(StrEnum):
131+
RoomKeyRequest = "m.room_key_request"
132132

133133

134-
class DeviceKeyAlgorithms:
134+
class DeviceKeyAlgorithms(StrEnum):
135135
"""Spec'd algorithms for the generation of per-device keys"""
136136

137-
ED25519: Final = "ed25519"
138-
CURVE25519: Final = "curve25519"
139-
SIGNED_CURVE25519: Final = "signed_curve25519"
137+
ED25519 = "ed25519"
138+
CURVE25519 = "curve25519"
139+
SIGNED_CURVE25519 = "signed_curve25519"
140140

141141

142-
class EduTypes:
143-
Presence: Final = "m.presence"
142+
class EduTypes(StrEnum):
143+
Presence = "m.presence"
144144

145145

146-
class RejectedReason:
147-
AUTH_ERROR: Final = "auth_error"
146+
class RejectedReason(StrEnum):
147+
AUTH_ERROR = "auth_error"
148148

149149

150-
class RoomCreationPreset:
151-
PRIVATE_CHAT: Final = "private_chat"
152-
PUBLIC_CHAT: Final = "public_chat"
153-
TRUSTED_PRIVATE_CHAT: Final = "trusted_private_chat"
150+
class RoomCreationPreset(StrEnum):
151+
PRIVATE_CHAT = "private_chat"
152+
PUBLIC_CHAT = "public_chat"
153+
TRUSTED_PRIVATE_CHAT = "trusted_private_chat"
154154

155155

156-
class ThirdPartyEntityKind:
157-
USER: Final = "user"
158-
LOCATION: Final = "location"
156+
class ThirdPartyEntityKind(StrEnum):
157+
USER = "user"
158+
LOCATION = "location"
159159

160160

161161
ServerNoticeMsgType: Final = "m.server_notice"
162162
ServerNoticeLimitReached: Final = "m.server_notice.usage_limit_reached"
163163

164164

165-
class UserTypes:
165+
class UserTypes(StrEnum):
166166
"""Allows for user type specific behaviour. With the benefit of hindsight
167167
'admin' and 'guest' users should also be UserTypes. Normal users are type None
168168
"""
169169

170-
SUPPORT: Final = "support"
171-
BOT: Final = "bot"
172-
ALL_USER_TYPES: Final = (SUPPORT, BOT)
170+
SUPPORT = "support"
171+
BOT = "bot"
173172

174173

175-
class RelationTypes:
174+
class RelationTypes(StrEnum):
176175
"""The types of relations known to this server."""
177176

178-
ANNOTATION: Final = "m.annotation"
179-
REPLACE: Final = "m.replace"
180-
REFERENCE: Final = "m.reference"
181-
THREAD: Final = "io.element.thread"
177+
ANNOTATION = "m.annotation"
178+
REPLACE = "m.replace"
179+
REFERENCE = "m.reference"
180+
THREAD = "io.element.thread"
182181

183182

184-
class LimitBlockingTypes:
183+
class LimitBlockingTypes(StrEnum):
185184
"""Reasons that a server may be blocked"""
186185

187-
MONTHLY_ACTIVE_USER: Final = "monthly_active_user"
188-
HS_DISABLED: Final = "hs_disabled"
186+
MONTHLY_ACTIVE_USER = "monthly_active_user"
187+
HS_DISABLED = "hs_disabled"
189188

190189

191-
class EventContentFields:
190+
class EventContentFields(StrEnum):
192191
"""Fields found in events' content, regardless of type."""
193192

194193
# Labels for the event, cf https://github.com/matrix-org/matrix-doc/pull/2326
195-
LABELS: Final = "org.matrix.labels"
194+
LABELS = "org.matrix.labels"
196195

197196
# Timestamp to delete the event after
198197
# cf https://github.com/matrix-org/matrix-doc/pull/2228
199-
SELF_DESTRUCT_AFTER: Final = "org.matrix.self_destruct_after"
198+
SELF_DESTRUCT_AFTER = "org.matrix.self_destruct_after"
200199

201200
# cf https://github.com/matrix-org/matrix-doc/pull/1772
202-
ROOM_TYPE: Final = "type"
201+
ROOM_TYPE = "type"
203202

204203
# Whether a room can federate.
205-
FEDERATE: Final = "m.federate"
204+
FEDERATE = "m.federate"
206205

207206
# The creator of the room, as used in `m.room.create` events.
208-
ROOM_CREATOR: Final = "creator"
207+
ROOM_CREATOR = "creator"
209208

210209
# Used in m.room.guest_access events.
211-
GUEST_ACCESS: Final = "guest_access"
210+
GUEST_ACCESS = "guest_access"
212211

213212
# Used on normal messages to indicate they were historically imported after the fact
214-
MSC2716_HISTORICAL: Final = "org.matrix.msc2716.historical"
213+
MSC2716_HISTORICAL = "org.matrix.msc2716.historical"
215214
# For "insertion" events to indicate what the next batch ID should be in
216215
# order to connect to it
217-
MSC2716_NEXT_BATCH_ID: Final = "org.matrix.msc2716.next_batch_id"
216+
MSC2716_NEXT_BATCH_ID = "org.matrix.msc2716.next_batch_id"
218217
# Used on "batch" events to indicate which insertion event it connects to
219-
MSC2716_BATCH_ID: Final = "org.matrix.msc2716.batch_id"
218+
MSC2716_BATCH_ID = "org.matrix.msc2716.batch_id"
220219
# For "marker" events
221-
MSC2716_MARKER_INSERTION: Final = "org.matrix.msc2716.marker.insertion"
220+
MSC2716_MARKER_INSERTION = "org.matrix.msc2716.marker.insertion"
222221

223222
# The authorising user for joining a restricted room.
224-
AUTHORISING_USER: Final = "join_authorised_via_users_server"
223+
AUTHORISING_USER = "join_authorised_via_users_server"
225224

226225

227-
class RoomTypes:
226+
class RoomTypes(StrEnum):
228227
"""Understood values of the room_type field of m.room.create events."""
229228

230-
SPACE: Final = "m.space"
229+
SPACE = "m.space"
231230

232231

233-
class RoomEncryptionAlgorithms:
234-
MEGOLM_V1_AES_SHA2: Final = "m.megolm.v1.aes-sha2"
235-
DEFAULT: Final = MEGOLM_V1_AES_SHA2
232+
class RoomEncryptionAlgorithms(StrEnum):
233+
MEGOLM_V1_AES_SHA2 = "m.megolm.v1.aes-sha2"
234+
DEFAULT = MEGOLM_V1_AES_SHA2
236235

237236

238-
class AccountDataTypes:
239-
DIRECT: Final = "m.direct"
240-
IGNORED_USER_LIST: Final = "m.ignored_user_list"
237+
class AccountDataTypes(StrEnum):
238+
DIRECT = "m.direct"
239+
IGNORED_USER_LIST = "m.ignored_user_list"
241240

242241

243-
class HistoryVisibility:
244-
INVITED: Final = "invited"
245-
JOINED: Final = "joined"
246-
SHARED: Final = "shared"
247-
WORLD_READABLE: Final = "world_readable"
242+
class HistoryVisibility(StrEnum):
243+
INVITED = "invited"
244+
JOINED = "joined"
245+
SHARED = "shared"
246+
WORLD_READABLE = "world_readable"
248247

249248

250-
class GuestAccess:
251-
CAN_JOIN: Final = "can_join"
249+
class GuestAccess(StrEnum):
250+
CAN_JOIN = "can_join"
252251
# anything that is not "can_join" is considered "forbidden", but for completeness:
253-
FORBIDDEN: Final = "forbidden"
252+
FORBIDDEN = "forbidden"
254253

255254

256-
class ReadReceiptEventFields:
257-
MSC2285_HIDDEN: Final = "org.matrix.msc2285.hidden"
255+
class ReadReceiptEventFields(StrEnum):
256+
MSC2285_HIDDEN = "org.matrix.msc2285.hidden"

synapse/event_auth.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -840,7 +840,7 @@ def get_public_keys(invite_event: EventBase) -> List[Dict[str, Any]]:
840840

841841
def auth_types_for_event(
842842
room_version: RoomVersion, event: Union[EventBase, EventBuilder]
843-
) -> Set[Tuple[str, str]]:
843+
) -> Set[Tuple[EventTypes, str]]:
844844
"""Given an event, return a list of (EventType, StateKey) that may be
845845
needed to auth the event. The returned list may be a superset of what
846846
would actually be required depending on the full state of the room.

synapse/events/validator.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,9 @@ def validate_builder(self, event: Union[EventBase, EventBuilder]) -> None:
189189
if "membership" not in event.content:
190190
raise SynapseError(400, "Content has not membership key")
191191

192-
if event.content["membership"] not in Membership.LIST:
192+
try:
193+
Membership(event.content["membership"])
194+
except ValueError:
193195
raise SynapseError(400, "Invalid membership key")
194196

195197
self._ensure_state_event(event)

0 commit comments

Comments
 (0)