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

Implement MSC3852: Expose last_seen_user_agent to users for their own devices; also expose to Admin API #13549

Merged
merged 7 commits into from
Aug 19, 2022
Merged
1 change: 1 addition & 0 deletions changelog.d/13549.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add an experimental implementation for [MSC3852](https://github.com/matrix-org/matrix-spec-proposals/pull/3852).
1 change: 1 addition & 0 deletions changelog.d/13549.misc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Allow specifying additional request fields when using the `HomeServerTestCase.login` helper method.
7 changes: 7 additions & 0 deletions docs/admin_api/user_admin_api.md
Original file line number Diff line number Diff line change
Expand Up @@ -753,13 +753,15 @@ A response body like the following is returned:
"device_id": "QBUAZIFURK",
"display_name": "android",
"last_seen_ip": "1.2.3.4",
"last_seen_user_agent": "Mozilla/5.0 (X11; Linux x86_64; rv:103.0) Gecko/20100101 Firefox/103.0",
"last_seen_ts": 1474491775024,
"user_id": "<user_id>"
},
{
"device_id": "AUIECTSRND",
"display_name": "ios",
"last_seen_ip": "1.2.3.5",
"last_seen_user_agent": "Mozilla/5.0 (X11; Linux x86_64; rv:103.0) Gecko/20100101 Firefox/103.0",
"last_seen_ts": 1474491775025,
"user_id": "<user_id>"
}
Expand All @@ -786,6 +788,8 @@ The following fields are returned in the JSON response body:
Absent if no name has been set.
- `last_seen_ip` - The IP address where this device was last seen.
(May be a few minutes out of date, for efficiency reasons).
- `last_seen_user_agent` - The user agent of the device when it was last seen.
(May be a few minutes out of date, for efficiency reasons).
- `last_seen_ts` - The timestamp (in milliseconds since the unix epoch) when this
devices was last seen. (May be a few minutes out of date, for efficiency reasons).
- `user_id` - Owner of device.
Expand Down Expand Up @@ -837,6 +841,7 @@ A response body like the following is returned:
"device_id": "<device_id>",
"display_name": "android",
"last_seen_ip": "1.2.3.4",
"last_seen_user_agent": "Mozilla/5.0 (X11; Linux x86_64; rv:103.0) Gecko/20100101 Firefox/103.0",
"last_seen_ts": 1474491775024,
"user_id": "<user_id>"
}
Expand All @@ -858,6 +863,8 @@ The following fields are returned in the JSON response body:
Absent if no name has been set.
- `last_seen_ip` - The IP address where this device was last seen.
(May be a few minutes out of date, for efficiency reasons).
- `last_seen_user_agent` - The user agent of the device when it was last seen.
(May be a few minutes out of date, for efficiency reasons).
- `last_seen_ts` - The timestamp (in milliseconds since the unix epoch) when this
devices was last seen. (May be a few minutes out of date, for efficiency reasons).
- `user_id` - Owner of device.
Expand Down
3 changes: 3 additions & 0 deletions synapse/config/experimental.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,6 @@ def read_config(self, config: JsonDict, **kwargs: Any) -> None:

# MSC3848: Introduce errcodes for specific event sending failures
self.msc3848_enabled: bool = experimental.get("msc3848_enabled", False)

# MSC3852: Expose last seen user agent field on /_matrix/client/v3/devices.
self.msc3852_enabled: bool = experimental.get("msc3852_enabled", False)
9 changes: 8 additions & 1 deletion synapse/handlers/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ def __init__(self, hs: "HomeServer"):
self._state_storage = hs.get_storage_controllers().state
self._auth_handler = hs.get_auth_handler()
self.server_name = hs.hostname
self._msc3852_enabled = hs.config.experimental.msc3852_enabled

@trace
async def get_devices_by_user(self, user_id: str) -> List[JsonDict]:
Expand Down Expand Up @@ -747,7 +748,13 @@ def _update_device_from_client_ips(
device: JsonDict, client_ips: Mapping[Tuple[str, str], Mapping[str, Any]]
) -> None:
ip = client_ips.get((device["user_id"], device["device_id"]), {})
device.update({"last_seen_ts": ip.get("last_seen"), "last_seen_ip": ip.get("ip")})
device.update(
{
"last_seen_user_agent": ip.get("user_agent"),
"last_seen_ts": ip.get("last_seen"),
"last_seen_ip": ip.get("ip"),
}
)


class DeviceListUpdater:
Expand Down
27 changes: 27 additions & 0 deletions synapse/rest/client/devices.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,26 @@ def __init__(self, hs: "HomeServer"):
self.hs = hs
self.auth = hs.get_auth()
self.device_handler = hs.get_device_handler()
self._msc3852_enabled = hs.config.experimental.msc3852_enabled

async def on_GET(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
requester = await self.auth.get_user_by_req(request, allow_guest=True)
devices = await self.device_handler.get_devices_by_user(
requester.user.to_string()
)

# If MSC3852 is disabled, then the "last_seen_user_agent" field will be
# removed from each device. If it is enabled, then the field name will
# be replaced by the unstable identifier.
#
# When MSC3852 is accepted, this block of code can just be removed to
# expose "last_seen_user_agent" to clients.
for device in devices:
last_seen_user_agent = device["last_seen_user_agent"]
del device["last_seen_user_agent"]
if self._msc3852_enabled:
device["org.matrix.msc3852.last_seen_user_agent"] = last_seen_user_agent

return 200, {"devices": devices}


Expand Down Expand Up @@ -108,6 +122,7 @@ def __init__(self, hs: "HomeServer"):
self.auth = hs.get_auth()
self.device_handler = hs.get_device_handler()
self.auth_handler = hs.get_auth_handler()
self._msc3852_enabled = hs.config.experimental.msc3852_enabled

async def on_GET(
self, request: SynapseRequest, device_id: str
Expand All @@ -118,6 +133,18 @@ async def on_GET(
)
if device is None:
raise NotFoundError("No device found")

# If MSC3852 is disabled, then the "last_seen_user_agent" field will be
# removed from each device. If it is enabled, then the field name will
# be replaced by the unstable identifier.
#
# When MSC3852 is accepted, this block of code can just be removed to
# expose "last_seen_user_agent" to clients.
last_seen_user_agent = device["last_seen_user_agent"]
del device["last_seen_user_agent"]
if self._msc3852_enabled:
device["org.matrix.msc3852.last_seen_user_agent"] = last_seen_user_agent

return 200, device

@interactive_auth_handler
Expand Down
92 changes: 91 additions & 1 deletion tests/rest/admin/test_user.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Copyright 2018-2021 The Matrix.org Foundation C.I.C.
# Copyright 2018-2022 The Matrix.org Foundation C.I.C.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -904,6 +904,96 @@ def _create_users(self, number_users: int) -> None:
)


class UserDevicesTestCase(unittest.HomeserverTestCase):
"""
Tests user device management-related Admin APIs.
"""

servlets = [
synapse.rest.admin.register_servlets,
login.register_servlets,
sync.register_servlets,
]

def prepare(
self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer
) -> None:
# Set up an Admin user to query the Admin API with.
self.admin_user_id = self.register_user("admin", "pass", admin=True)
self.admin_user_token = self.login("admin", "pass")

# Set up a test user to query the devices of.
self.other_user_device_id = "TESTDEVICEID"
self.other_user_device_display_name = "My Test Device"
self.other_user_client_ip = "1.2.3.4"
self.other_user_user_agent = "EquestriaTechnology/123.0"

self.other_user_id = self.register_user("user", "pass", displayname="User1")
self.other_user_token = self.login(
"user",
"pass",
device_id=self.other_user_device_id,
additional_request_fields={
"initial_device_display_name": self.other_user_device_display_name,
},
)

# Have the "other user" make a request so that the "last_seen_*" fields are
# populated in the tests below.
channel = self.make_request(
"GET",
"/_matrix/client/v3/sync",
access_token=self.other_user_token,
client_ip=self.other_user_client_ip,
custom_headers=[
("User-Agent", self.other_user_user_agent),
],
)
self.assertEqual(200, channel.code, msg=channel.json_body)

def test_list_user_devices(self) -> None:
"""
Tests that a user's devices and attributes are listed correctly via the Admin API.
"""
# Request all devices of "other user"
channel = self.make_request(
"GET",
f"/_synapse/admin/v2/users/{self.other_user_id}/devices",
access_token=self.admin_user_token,
)
self.assertEqual(200, channel.code, msg=channel.json_body)

# Double-check we got the single device expected
user_devices = channel.json_body["devices"]
self.assertEqual(len(user_devices), 1)
self.assertEqual(channel.json_body["total"], 1)

# Check that all the attributes of the device reported are as expected.
self._validate_attributes_of_device_response(user_devices[0])

# Request just a single device for "other user" by its ID
channel = self.make_request(
"GET",
f"/_synapse/admin/v2/users/{self.other_user_id}/devices/"
f"{self.other_user_device_id}",
access_token=self.admin_user_token,
)
self.assertEqual(200, channel.code, msg=channel.json_body)

# Check that all the attributes of the device reported are as expected.
self._validate_attributes_of_device_response(channel.json_body)

def _validate_attributes_of_device_response(self, response: JsonDict) -> None:
# Check that all device expected attributes are present
self.assertEqual(response["user_id"], self.other_user_id)
self.assertEqual(response["device_id"], self.other_user_device_id)
self.assertEqual(response["display_name"], self.other_user_device_display_name)
self.assertEqual(response["last_seen_ip"], self.other_user_client_ip)
self.assertEqual(response["last_seen_user_agent"], self.other_user_user_agent)
self.assertIsInstance(response["last_seen_ts"], int)
self.assertGreater(response["last_seen_ts"], 0)


class DeactivateAccountTestCase(unittest.HomeserverTestCase):

servlets = [
Expand Down
15 changes: 15 additions & 0 deletions tests/unittest.py
Original file line number Diff line number Diff line change
Expand Up @@ -677,14 +677,29 @@ def login(
username: str,
password: str,
device_id: Optional[str] = None,
additional_request_fields: Optional[Dict[str, str]] = None,
custom_headers: Optional[Iterable[CustomHeaderType]] = None,
) -> str:
"""
Log in a user, and get an access token. Requires the Login API be registered.

Args:
username: The localpart to assign to the new user.
password: The password to assign to the new user.
device_id: An optional device ID to assign to the new device created during
login.
additional_request_fields: A dictionary containing any additional /login
request fields and their values.
custom_headers: Custom HTTP headers and values to add to the /login request.

Returns:
The newly registered user's Matrix ID.
"""
body = {"type": "m.login.password", "user": username, "password": password}
if device_id:
body["device_id"] = device_id
if additional_request_fields:
body.update(additional_request_fields)

channel = self.make_request(
"POST",
Expand Down