Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support shorter tokens used with authentication #3

Merged
merged 33 commits into from
Aug 17, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
0d75d6a
Support renewing an authenticated token
babolivier May 4, 2021
4b04f89
Generate and send shorter authenticated tokens if configured to do so
babolivier May 5, 2021
28a8d4a
Document send_link and templates in the README.md
babolivier May 5, 2021
c1c0b48
Add test for authenticated tokens
babolivier May 5, 2021
83852bf
Actually error when trying to reuse a unique renewal token
babolivier May 5, 2021
ff9433b
Merge branch 'master' into babolivier/token
babolivier May 5, 2021
a1b5743
call_args.kwargs was only introduced in Python 3.8
babolivier May 5, 2021
04ed67b
Use the right assertion method
babolivier May 5, 2021
083668c
Import from Synapse's module API
babolivier May 14, 2021
caa23ff
Look for templates in the module; globalise config
babolivier May 20, 2021
56e4841
Fix test infra
babolivier May 20, 2021
c02b930
Incorporate review
babolivier May 20, 2021
0efb472
Fix test
babolivier May 20, 2021
5663b3f
Fix is_user_expired to match expected API
babolivier May 24, 2021
d42ee31
Fix tests
babolivier May 24, 2021
6978508
Move to the new module system
babolivier Jul 1, 2021
605337c
Use indexes to check unicity on tokens
babolivier Jul 2, 2021
41eaf8f
Fix tests
babolivier Jul 2, 2021
5377864
Update docs
babolivier Jul 2, 2021
ccc9a81
Migrate to new module interface
babolivier Jul 19, 2021
29b5634
Merge branch 'main' into babolivier/new_api
babolivier Jul 19, 2021
de0470e
Merge branch 'main' into babolivier/token
babolivier Jul 19, 2021
f086863
Fix tests
babolivier Jul 19, 2021
7b8624c
Merge branch 'babolivier/new_api' into babolivier/token
babolivier Jul 19, 2021
ddc2640
Update README too
babolivier Jul 19, 2021
a90ba0a
Update minimal required synapse version (for real this time)
babolivier Jul 19, 2021
74bd1f5
Update minimal required synapse version (for real this time)
babolivier Jul 19, 2021
c28e129
Merge branch 'babolivier/new_api' into babolivier/token
babolivier Jul 19, 2021
d8da9eb
Merge branch 'main' into babolivier/token
babolivier Aug 11, 2021
ccb68a6
Incorporate review
babolivier Aug 16, 2021
f9e2c0f
Update README.md
babolivier Aug 16, 2021
ee8ee76
Validate short tokens
babolivier Aug 16, 2021
efd23fd
Merge branch 'babolivier/token' of github.com:matrix-org/synapse-emai…
babolivier Aug 16, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ modules:
period: 6w
# How long before an account expires should Synapse send it a renewal email.
renew_at: 1w
# Whether to include a link to click in the emails sent to users. If false, only a
# renewal token is sent, in which case a shorter token is used, and the
# user will need to copy it into a compatible client that will send an
# authenticated request to the server.
# Defaults to true.
send_links: true
```

The syntax for durations is the same as in the rest of Synapse's configuration file.
Expand Down
106 changes: 89 additions & 17 deletions email_account_validity/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
# limitations under the License.

import logging
import os
import time
from typing import Optional, Tuple

Expand All @@ -24,7 +25,13 @@

from email_account_validity._config import EmailAccountValidityConfig
from email_account_validity._store import EmailAccountValidityStore
from email_account_validity._utils import random_string
from email_account_validity._utils import (
LONG_TOKEN_REGEX,
SHORT_TOKEN_REGEX,
random_digit_string,
random_string,
TokenFormat,
)

logger = logging.getLogger(__name__)

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

self._period = config.period
self._send_links = config.send_links

(self._template_html, self._template_text,) = api.read_templates(
["notice_expiry.html", "notice_expiry.txt"],
os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates"),
)
babolivier marked this conversation as resolved.
Show resolved Hide resolved

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

Expand Down Expand Up @@ -110,35 +119,68 @@ async def send_renewal_email(self, user_id: str, expiration_ts: int):
except SynapseError:
display_name = user_id

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

url = "%s_synapse/client/email_account_validity/renew?token=%s" % (
self._api.public_baseurl,
renewal_token,
)
url = "%s_synapse/client/email_account_validity/renew?token=%s" % (
self._api.public_baseurl,
renewal_token,
)
else:
renewal_token = await self.generate_authenticated_renewal_token(user_id)
url = None

template_vars = {
"app_name": self._api.email_app_name,
"display_name": display_name,
"expiration_ts": expiration_ts,
"url": url,
"renewal_token": renewal_token,
}

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

for address in addresses:
await self._api.send_mail(
address,
self._renew_email_subject,
html_text,
plain_text,
recipient=address,
subject=self._renew_email_subject,
html=html_text,
text=plain_text,
)

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

async def generate_renewal_token(self, user_id: str) -> str:
"""Generates a 32-byte long random string that will be inserted into the
user's renewal email's unique link, then saves it into the database.
async def generate_authenticated_renewal_token(self, user_id: str) -> str:
"""Generates a 8-digit long random string then saves it into the database.

This token is to be sent to the user over email so that the user can copy it into
their client to renew their account.

Args:
user_id: ID of the user to generate a string for.

Returns:
The generated string.

Raises:
SynapseError(500): Couldn't generate a unique string after 5 attempts.
babolivier marked this conversation as resolved.
Show resolved Hide resolved
"""
renewal_token = random_digit_string(8)
await self._store.set_renewal_token_for_user(
user_id, renewal_token, TokenFormat.SHORT,
)
return renewal_token

async def generate_unauthenticated_renewal_token(self, user_id: str) -> str:
"""Generates a 32-letter long random string then saves it into the database.

This token is to be sent to the user over email in a link that the user will then
click to renew their account.

Args:
user_id: ID of the user to generate a string for.
Expand All @@ -153,13 +195,19 @@ async def generate_renewal_token(self, user_id: str) -> str:
while attempts < 5:
try:
renewal_token = random_string(32)
await self._store.set_renewal_token_for_user(user_id, renewal_token)
await self._store.set_renewal_token_for_user(
user_id, renewal_token, TokenFormat.LONG,
)
return renewal_token
except SynapseError:
attempts += 1
raise SynapseError(500, "Couldn't generate a unique string as refresh string.")

async def renew_account(self, renewal_token: str) -> Tuple[bool, bool, int]:
async def renew_account(
self,
renewal_token: str,
user_id: Optional[str] = None,
) -> Tuple[bool, bool, int]:
"""Renews the account attached to a given renewal token by pushing back the
expiration date by the current validity period in the server's configuration.

Expand All @@ -169,19 +217,42 @@ async def renew_account(self, renewal_token: str) -> Tuple[bool, bool, int]:

Args:
renewal_token: Token sent with the renewal request.
user_id: The Matrix ID of the user to renew, if the renewal request was
authenticated.

Returns:
A tuple containing:
* A bool representing whether the token is valid and unused.
* A bool which is `True` if the token is valid, but stale.
* An int representing the user's expiry timestamp as milliseconds since the
epoch, or 0 if the token was invalid.
"""
# Try to match the token against a known format.
if LONG_TOKEN_REGEX.match(renewal_token):
token_format = TokenFormat.LONG
elif SHORT_TOKEN_REGEX.match(renewal_token):
token_format = TokenFormat.SHORT
else:
# If we can't figure out what format the renewal token is, consider it
# invalid.
return False, False, 0

# If we were not able to authenticate the user requesting a renewal, and the
# token needs authentication, consider the token neither valid nor stale.
if user_id is None and token_format == TokenFormat.SHORT:
return False, False, 0

# Verify if the token, or the (token, user_id) tuple, exists.
try:
(
user_id,
current_expiration_ts,
token_used_ts,
) = await self._store.get_user_from_renewal_token(renewal_token)
) = await self._store.validate_renewal_token(
renewal_token,
token_format,
user_id,
)
except SynapseError:
return False, False, 0

Expand Down Expand Up @@ -238,6 +309,7 @@ async def renew_account_for_user(
user_id=user_id,
expiration_ts=expiration_ts,
email_sent=email_sent,
token_format=TokenFormat.LONG if self._send_links else TokenFormat.SHORT,
renewal_token=renewal_token,
token_used_ts=now,
)
Expand Down
1 change: 1 addition & 0 deletions email_account_validity/_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,4 @@ class EmailAccountValidityConfig:
period: int
renew_at: int
renew_email_subject: Optional[str] = None
send_links: bool = True
29 changes: 16 additions & 13 deletions email_account_validity/_servlets.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,19 @@
# 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.
import os

from synapse.module_api import (
DirectServeHtmlResource,
DirectServeJsonResource,
ModuleApi,
respond_with_html,
)
from synapse.module_api.errors import ConfigError, SynapseError
from synapse.module_api.errors import (
ConfigError,
InvalidClientCredentialsError,
SynapseError,
)
from twisted.web.resource import Resource

from email_account_validity._base import EmailAccountValidityBase
Expand Down Expand Up @@ -64,7 +69,8 @@ def __init__(
"account_renewed.html",
"account_previously_renewed.html",
"invalid_token.html",
]
],
os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates"),
babolivier marked this conversation as resolved.
Show resolved Hide resolved
)

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

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

try:
requester = await self._api.get_user_by_req(request, allow_expired=True)
user_id = requester.user.to_string()
except InvalidClientCredentialsError:
user_id = None

(
token_valid,
token_stale,
expiration_ts,
) = await self.renew_account(renewal_token)
) = await self.renew_account(renewal_token, user_id)

if token_valid:
status_code = 200
Expand All @@ -93,7 +105,7 @@ async def _async_render_GET(self, request):
expiration_ts=expiration_ts
)
else:
status_code = 404
status_code = 400
response = self._invalid_token_template.render()

respond_with_html(request, status_code, response)
Expand Down Expand Up @@ -130,15 +142,6 @@ class EmailAccountValidityAdminServlet(
EmailAccountValidityBase,
DirectServeJsonResource,
):
def __init__(
self,
config: EmailAccountValidityConfig,
api: ModuleApi,
store: EmailAccountValidityStore,
):
EmailAccountValidityBase.__init__(self, config, api, store)
DirectServeJsonResource.__init__(self)

async def _async_render_POST(self, request):
"""On POST requests on /admin, update the given user with the given account
validity state, if the requester is a server admin.
Expand Down
Loading