Skip to content

Commit 2b62394

Browse files
authored
Support shorter tokens used with authentication (#3)
This adds a new send_links configuration option which defines whether to send links for the user to click in renewal emails, and defaults to true. If set to false, only the renewal token is sent, which is expected to be copied by the user into a compatible client, which would then send it to the homeserver in an authenticated request (which means we don't need to ensure these shorter tokens are unique across all of the users).
1 parent 2096daa commit 2b62394

File tree

9 files changed

+332
-66
lines changed

9 files changed

+332
-66
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,12 @@ modules:
3333
period: 6w
3434
# How long before an account expires should Synapse send it a renewal email.
3535
renew_at: 1w
36+
# Whether to include a link to click in the emails sent to users. If false, only a
37+
# renewal token is sent, in which case a shorter token is used, and the
38+
# user will need to copy it into a compatible client that will send an
39+
# authenticated request to the server.
40+
# Defaults to true.
41+
send_links: true
3642
```
3743
3844
The syntax for durations is the same as in the rest of Synapse's configuration file.

email_account_validity/_base.py

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

1616
import logging
17+
import os
1718
import time
1819
from typing import Optional, Tuple
1920

@@ -24,7 +25,13 @@
2425

2526
from email_account_validity._config import EmailAccountValidityConfig
2627
from email_account_validity._store import EmailAccountValidityStore
27-
from email_account_validity._utils import random_string
28+
from email_account_validity._utils import (
29+
LONG_TOKEN_REGEX,
30+
SHORT_TOKEN_REGEX,
31+
random_digit_string,
32+
random_string,
33+
TokenFormat,
34+
)
2835

2936
logger = logging.getLogger(__name__)
3037

@@ -40,9 +47,11 @@ def __init__(
4047
self._store = store
4148

4249
self._period = config.period
50+
self._send_links = config.send_links
4351

4452
(self._template_html, self._template_text,) = api.read_templates(
4553
["notice_expiry.html", "notice_expiry.txt"],
54+
os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates"),
4655
)
4756

4857
if config.renew_email_subject is not None:
@@ -53,7 +62,7 @@ def __init__(
5362
try:
5463
app_name = self._api.email_app_name
5564
self._renew_email_subject = renew_email_subject % {"app": app_name}
56-
except Exception:
65+
except (KeyError, TypeError):
5766
# If substitution failed, fall back to the bare strings.
5867
self._renew_email_subject = renew_email_subject
5968

@@ -110,35 +119,68 @@ async def send_renewal_email(self, user_id: str, expiration_ts: int):
110119
except SynapseError:
111120
display_name = user_id
112121

113-
renewal_token = await self.generate_renewal_token(user_id)
122+
# If the user isn't expected to click on a link, but instead to copy the token
123+
# into their client, we generate a different kind of token, simpler and shorter,
124+
# because a) we don't need it to be unique to the whole table and b) we want the
125+
# user to be able to be easily type it back into their client.
126+
if self._send_links:
127+
renewal_token = await self.generate_unauthenticated_renewal_token(user_id)
114128

115-
url = "%s_synapse/client/email_account_validity/renew?token=%s" % (
116-
self._api.public_baseurl,
117-
renewal_token,
118-
)
129+
url = "%s_synapse/client/email_account_validity/renew?token=%s" % (
130+
self._api.public_baseurl,
131+
renewal_token,
132+
)
133+
else:
134+
renewal_token = await self.generate_authenticated_renewal_token(user_id)
135+
url = None
119136

120137
template_vars = {
138+
"app_name": self._api.email_app_name,
121139
"display_name": display_name,
122140
"expiration_ts": expiration_ts,
123141
"url": url,
142+
"renewal_token": renewal_token,
124143
}
125144

126145
html_text = self._template_html.render(**template_vars)
127146
plain_text = self._template_text.render(**template_vars)
128147

129148
for address in addresses:
130149
await self._api.send_mail(
131-
address,
132-
self._renew_email_subject,
133-
html_text,
134-
plain_text,
150+
recipient=address,
151+
subject=self._renew_email_subject,
152+
html=html_text,
153+
text=plain_text,
135154
)
136155

137156
await self._store.set_renewal_mail_status(user_id=user_id, email_sent=True)
138157

139-
async def generate_renewal_token(self, user_id: str) -> str:
140-
"""Generates a 32-byte long random string that will be inserted into the
141-
user's renewal email's unique link, then saves it into the database.
158+
async def generate_authenticated_renewal_token(self, user_id: str) -> str:
159+
"""Generates a 8-digit long random string then saves it into the database.
160+
161+
This token is to be sent to the user over email so that the user can copy it into
162+
their client to renew their account.
163+
164+
Args:
165+
user_id: ID of the user to generate a string for.
166+
167+
Returns:
168+
The generated string.
169+
170+
Raises:
171+
SynapseError(500): Couldn't generate a unique string after 5 attempts.
172+
"""
173+
renewal_token = random_digit_string(8)
174+
await self._store.set_renewal_token_for_user(
175+
user_id, renewal_token, TokenFormat.SHORT,
176+
)
177+
return renewal_token
178+
179+
async def generate_unauthenticated_renewal_token(self, user_id: str) -> str:
180+
"""Generates a 32-letter long random string then saves it into the database.
181+
182+
This token is to be sent to the user over email in a link that the user will then
183+
click to renew their account.
142184
143185
Args:
144186
user_id: ID of the user to generate a string for.
@@ -153,13 +195,19 @@ async def generate_renewal_token(self, user_id: str) -> str:
153195
while attempts < 5:
154196
try:
155197
renewal_token = random_string(32)
156-
await self._store.set_renewal_token_for_user(user_id, renewal_token)
198+
await self._store.set_renewal_token_for_user(
199+
user_id, renewal_token, TokenFormat.LONG,
200+
)
157201
return renewal_token
158202
except SynapseError:
159203
attempts += 1
160204
raise SynapseError(500, "Couldn't generate a unique string as refresh string.")
161205

162-
async def renew_account(self, renewal_token: str) -> Tuple[bool, bool, int]:
206+
async def renew_account(
207+
self,
208+
renewal_token: str,
209+
user_id: Optional[str] = None,
210+
) -> Tuple[bool, bool, int]:
163211
"""Renews the account attached to a given renewal token by pushing back the
164212
expiration date by the current validity period in the server's configuration.
165213
@@ -169,19 +217,42 @@ async def renew_account(self, renewal_token: str) -> Tuple[bool, bool, int]:
169217
170218
Args:
171219
renewal_token: Token sent with the renewal request.
220+
user_id: The Matrix ID of the user to renew, if the renewal request was
221+
authenticated.
222+
172223
Returns:
173224
A tuple containing:
174225
* A bool representing whether the token is valid and unused.
175226
* A bool which is `True` if the token is valid, but stale.
176227
* An int representing the user's expiry timestamp as milliseconds since the
177228
epoch, or 0 if the token was invalid.
178229
"""
230+
# Try to match the token against a known format.
231+
if LONG_TOKEN_REGEX.match(renewal_token):
232+
token_format = TokenFormat.LONG
233+
elif SHORT_TOKEN_REGEX.match(renewal_token):
234+
token_format = TokenFormat.SHORT
235+
else:
236+
# If we can't figure out what format the renewal token is, consider it
237+
# invalid.
238+
return False, False, 0
239+
240+
# If we were not able to authenticate the user requesting a renewal, and the
241+
# token needs authentication, consider the token neither valid nor stale.
242+
if user_id is None and token_format == TokenFormat.SHORT:
243+
return False, False, 0
244+
245+
# Verify if the token, or the (token, user_id) tuple, exists.
179246
try:
180247
(
181248
user_id,
182249
current_expiration_ts,
183250
token_used_ts,
184-
) = await self._store.get_user_from_renewal_token(renewal_token)
251+
) = await self._store.validate_renewal_token(
252+
renewal_token,
253+
token_format,
254+
user_id,
255+
)
185256
except SynapseError:
186257
return False, False, 0
187258

@@ -238,6 +309,7 @@ async def renew_account_for_user(
238309
user_id=user_id,
239310
expiration_ts=expiration_ts,
240311
email_sent=email_sent,
312+
token_format=TokenFormat.LONG if self._send_links else TokenFormat.SHORT,
241313
renewal_token=renewal_token,
242314
token_used_ts=now,
243315
)

email_account_validity/_config.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,4 @@ class EmailAccountValidityConfig:
2222
period: int
2323
renew_at: int
2424
renew_email_subject: Optional[str] = None
25+
send_links: bool = True

email_account_validity/_servlets.py

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,19 @@
1212
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1313
# See the License for the specific language governing permissions and
1414
# limitations under the License.
15+
import os
1516

1617
from synapse.module_api import (
1718
DirectServeHtmlResource,
1819
DirectServeJsonResource,
1920
ModuleApi,
2021
respond_with_html,
2122
)
22-
from synapse.module_api.errors import ConfigError, SynapseError
23+
from synapse.module_api.errors import (
24+
ConfigError,
25+
InvalidClientCredentialsError,
26+
SynapseError,
27+
)
2328
from twisted.web.resource import Resource
2429

2530
from email_account_validity._base import EmailAccountValidityBase
@@ -64,7 +69,8 @@ def __init__(
6469
"account_renewed.html",
6570
"account_previously_renewed.html",
6671
"invalid_token.html",
67-
]
72+
],
73+
os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates"),
6874
)
6975

7076
async def _async_render_GET(self, request):
@@ -76,11 +82,17 @@ async def _async_render_GET(self, request):
7682

7783
renewal_token = request.args[b"token"][0].decode("utf-8")
7884

85+
try:
86+
requester = await self._api.get_user_by_req(request, allow_expired=True)
87+
user_id = requester.user.to_string()
88+
except InvalidClientCredentialsError:
89+
user_id = None
90+
7991
(
8092
token_valid,
8193
token_stale,
8294
expiration_ts,
83-
) = await self.renew_account(renewal_token)
95+
) = await self.renew_account(renewal_token, user_id)
8496

8597
if token_valid:
8698
status_code = 200
@@ -93,7 +105,7 @@ async def _async_render_GET(self, request):
93105
expiration_ts=expiration_ts
94106
)
95107
else:
96-
status_code = 404
108+
status_code = 400
97109
response = self._invalid_token_template.render()
98110

99111
respond_with_html(request, status_code, response)
@@ -130,15 +142,6 @@ class EmailAccountValidityAdminServlet(
130142
EmailAccountValidityBase,
131143
DirectServeJsonResource,
132144
):
133-
def __init__(
134-
self,
135-
config: EmailAccountValidityConfig,
136-
api: ModuleApi,
137-
store: EmailAccountValidityStore,
138-
):
139-
EmailAccountValidityBase.__init__(self, config, api, store)
140-
DirectServeJsonResource.__init__(self)
141-
142145
async def _async_render_POST(self, request):
143146
"""On POST requests on /admin, update the given user with the given account
144147
validity state, if the requester is a server admin.

0 commit comments

Comments
 (0)