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

Implement MSC3231: Token authenticated registration #10142

Merged
merged 54 commits into from
Aug 21, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
54 commits
Select commit Hold shift + click to select a range
5856f81
Hard-coded token authenticated registration
govynnus Jun 3, 2021
5f21580
Create registration_tokens table
govynnus Jun 10, 2021
2b8726c
Check in database to validate registration token
govynnus Jun 11, 2021
5b1ec0b
Increment `completed` when registration token used
govynnus Jun 14, 2021
15e5769
Rename total_uses to uses_allowed
govynnus Jun 14, 2021
9c502b0
Improve unit tests
govynnus Jun 14, 2021
e7754a9
Increment pending while registration in progress
govynnus Jun 14, 2021
ef05a6d
Add unit test for registration token expiry
govynnus Jun 16, 2021
53f0e05
Fix config file related bits
govynnus Jun 16, 2021
7883191
Run connected database ops in same transaction
govynnus Jun 16, 2021
1debc22
Fix some formatting problems
govynnus Jun 17, 2021
6ac376d
Test `completed` is empty when auth should fail
govynnus Jun 17, 2021
dfa8fec
Override type of simple_select_one_txn
govynnus Jun 17, 2021
c89d786
Raise error if token changes during UIA
govynnus Jun 17, 2021
e7bd00a
Add validity checking endpoint
govynnus Jun 18, 2021
d6704fd
Use AuthHandler methods for accessing UIA session
govynnus Jun 20, 2021
003e67d
Rate limit validity checking endpoint
govynnus Jun 29, 2021
3c51680
Use LoginError rather than SynapseError in checker
govynnus Jun 29, 2021
af90be7
Add fallback
govynnus Jun 30, 2021
1552b70
Docs for currently non-existent admin API
govynnus Jul 6, 2021
4df4a6e
Implement admin API
govynnus Jul 10, 2021
6901eee
Move admin api docs to correct location
govynnus Jul 19, 2021
93f752d
Include general API shape in docstrings
govynnus Jul 20, 2021
b2bf3ac
More input validation when creating and updating
govynnus Jul 20, 2021
5d5bdef
Add space to SQL query
govynnus Jul 20, 2021
b61c7f6
Fix SQL query for invalid tokens
govynnus Jul 20, 2021
e7495e6
Decrease pending when UIA session expires
govynnus Jul 22, 2021
39d24d2
Add type to test argument
govynnus Jul 23, 2021
70cc9d2
Add test for session expiry with deleted token
govynnus Jul 23, 2021
09f6572
Use f-strings rather than str.format()
govynnus Jul 27, 2021
36adec4
Update docs/usage/administration/admin_api/registration_tokens.md
govynnus Jul 27, 2021
7e539f5
Use more descriptive name
govynnus Jul 27, 2021
1cf29c9
Return 200 when nothing to update
govynnus Jul 27, 2021
7f9efcd
Remove unneeded else and add missing f
govynnus Jul 27, 2021
e9435f8
Run linter
govynnus Jul 27, 2021
f6e4831
Add uses_allowed to updating example in docstring
govynnus Aug 12, 2021
7208760
Add return values to docstring
govynnus Aug 12, 2021
47b8837
Add docstring to validity checking endpoint
govynnus Aug 12, 2021
b76099e
Move functions into RegistrationWorkerStore
govynnus Aug 12, 2021
86bbc24
Merge branch 'develop' into token-registration
govynnus Aug 19, 2021
c6cb80b
Add link to admin API docs in config file
govynnus Aug 19, 2021
ba22ffd
Move table creation SQL to latest delta
govynnus Aug 19, 2021
c775dce
Add changelog entry
govynnus Aug 19, 2021
f327b29
Regenerate sample config
govynnus Aug 19, 2021
c6bcae2
Move table creation sql to actual newest delta
govynnus Aug 20, 2021
01a74da
Avoid integrity error when creating tokens
govynnus Aug 20, 2021
5bfc707
Fix docs, comments and variable names
govynnus Aug 20, 2021
b5608c3
Try again if generated token already exists
govynnus Aug 20, 2021
bf28876
Let validity checking endpoint be used by workers
govynnus Aug 20, 2021
2e59dda
Document usage of `null` when updating tokens
govynnus Aug 20, 2021
df0077d
Merge remote-tracking branch 'upstream/develop' into token-registration
govynnus Aug 20, 2021
54867ef
Simplify retrying of token generation
govynnus Aug 21, 2021
20b566c
Small additions to admin api documentation
govynnus Aug 21, 2021
04b237a
Update synapse/storage/databases/main/registration.py
anoadragon453 Aug 21, 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
28 changes: 4 additions & 24 deletions synapse/rest/admin/registration_tokens.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
# limitations under the License.

import logging
import random
import string
from typing import TYPE_CHECKING, Tuple

Expand Down Expand Up @@ -153,7 +152,9 @@ async def on_POST(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
)

# Generate token
token = "".join(random.choices(self.allowed_chars, k=length))
token = await self.store.generate_registration_token(
length, self.allowed_chars
)

uses_allowed = body.get("uses_allowed", None)
if not (
Expand All @@ -179,28 +180,7 @@ async def on_POST(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
created = await self.store.create_registration_token(
token, uses_allowed, expiry_time
)

if "token" not in body:
# The token was generated. If it could not be created because
# that token already exists, then try a few more times before
# reporting a failure.
i = 0
while not created and i < 3:
token = "".join(random.choices(self.allowed_chars, k=length))
created = await self.store.create_registration_token(
token, uses_allowed, expiry_time
)
i += 1
if not created:
raise SynapseError(
500,
"The generated token already exists. Try again with a greater length.",
Codes.UNKNOWN,
)

elif not created:
# The token was specified in the request, but it already exists
# so could not be created.
if not created:
raise SynapseError(
400, f"Token already exists: {token}", Codes.INVALID_PARAM
)
Expand Down
41 changes: 41 additions & 0 deletions synapse/storage/databases/main/registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -1326,6 +1326,47 @@ async def get_one_registration_token(self, token: str) -> Optional[Dict[str, Any
desc="get_one_registration_token",
)

async def generate_registration_token(
self, length: int, chars: str
) -> Optional[str]:
"""Generate a random registration token. Used by the admin API.

Args:
length: The length of the token to generate.
chars: A string of the characters allowed in the generated token.

Returns:
The generated token.

Raises:
SynapseError if a unique registration token could still not be
generated after a few tries.
"""
# Make a few attempts at generating a unique token of the required
# length before failing.
for _i in range(3):
# Generate token
token = "".join(random.choices(chars, k=length))

# Check if the token already exists
existing_token = await self.db_pool.simple_select_one_onecol(
"registration_tokens",
keyvalues={"token": token},
retcol="token",
allow_none=True,
desc="check_if_registration_token_exists",
)

if existing_token is None:
# The generated token doesn't exist yet, return it
return token

raise SynapseError(
500,
"Unable to generate a registration token. Try again with a greater length",
anoadragon453 marked this conversation as resolved.
Show resolved Hide resolved
Codes.UNKNOWN,
)

async def create_registration_token(
self, token: str, uses_allowed: Optional[int], expiry_time: Optional[int]
) -> bool:
Expand Down
31 changes: 31 additions & 0 deletions tests/rest/admin/test_registration_tokens.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,37 @@ def test_create_token_already_exists(self):
self.assertEqual(400, int(channel2.result["code"]), msg=channel2.result["body"])
self.assertEqual(channel2.json_body["errcode"], Codes.INVALID_PARAM)

def test_create_unable_to_generate_token(self):
"""Check right error is raised when server can't generate unique token."""
# Create all possible single character tokens
tokens = []
for c in string.ascii_letters + string.digits + "-_":
tokens.append(
{
"token": c,
"uses_allowed": None,
"pending": 0,
"completed": 0,
"expiry_time": None,
}
)
self.get_success(
self.store.db_pool.simple_insert_many(
"registration_tokens",
tokens,
"create_all_registration_tokens",
)
)

# Check creating a single character token fails with a 500 status code
channel = self.make_request(
"POST",
self.url + "/new",
{"length": 1},
access_token=self.admin_user_tok,
)
self.assertEqual(500, int(channel.result["code"]), msg=channel.result["body"])

def test_create_uses_allowed(self):
"""Check you can only create a token with good values for uses_allowed."""
# Should work with 0 (token is invalid from the start)
Expand Down