Files

171 lines
6.1 KiB
Python

# Copyright 2024-2025 New Vector Ltd
# Copyright 2025-2026 Element Creations Ltd
#
# SPDX-License-Identifier: AGPL-3.0-only
import hashlib
import hmac
from ssl import SSLContext
import aiohttp
import pytest
from lightkube import AsyncClient
from .utils import aiohttp_client, aiohttp_get_json, aiohttp_post_json, async_retry_with_timeout
async def get_nonce(synapse_fqdn: str, ssl_context) -> str:
"""
Call Synapse for a nonce.
"""
response = await aiohttp_get_json(f"https://{synapse_fqdn}/_synapse/admin/v1/register", {}, ssl_context)
return response.get("nonce", "")
def generate_mac(username: str, password: str, admin: bool, registration_shared_secret: str, nonce: str) -> str:
"""
Generate a MAC for using in registering the user.
"""
# From: https://github.com/element-hq/synapse/blob/master/docs/admin_api/register_api.md
mac = hmac.new(
key=registration_shared_secret.encode("utf8"),
digestmod=hashlib.sha1,
)
mac.update(nonce.encode("utf8"))
mac.update(b"\x00")
mac.update(username.encode("utf8"))
mac.update(b"\x00")
mac.update(password.encode("utf8"))
mac.update(b"\x00")
mac.update(b"admin" if admin else b"notadmin")
return mac.hexdigest()
async def create_synapse_user(
synapse_fqdn: str,
username: str,
password: str,
admin: bool,
registration_shared_secret: str,
ssl_context: SSLContext,
pytestconfig: pytest.Config,
) -> str:
"""
Create the user and return access_token
"""
cached_user_token = pytestconfig.cache.get(f"ess-helm/cached-tokens/{username}", None)
if cached_user_token:
# Locally the cached token may be from a previous run but we don't know whether it is with the same DB or not
# We still want the caching in-case we request this for the same user multiple times in the same run
try:
headers = {"Authorization": f"Bearer {cached_user_token}"}
response = await aiohttp_get_json(
f"https://{synapse_fqdn}/_matrix/client/v3/account/whoami", headers=headers, ssl_context=ssl_context
)
if response["user_id"].split(":")[0] == f"@{username}":
return cached_user_token
except aiohttp.ClientResponseError:
pass
pytestconfig.cache.set(f"ess-helm/cached-tokens/{username}", None)
# The below is going to fail if this is a subsequent run against the same DB (as the user ID will exist) but
# the access token wasn't valid/for the correct user. Unsure how we could ever get into this state, but at
# least now we're succeeding in the case that this is a run against a new DB. `pytest --cache-clear` would
# be helpful in this scenario.
async def _register_user():
nonce = await get_nonce(synapse_fqdn, ssl_context)
mac = generate_mac(username, password, admin, registration_shared_secret, nonce)
data = {
"nonce": nonce,
"username": username,
"password": password,
"admin": admin,
"mac": mac,
}
return await aiohttp_post_json(f"https://{synapse_fqdn}/_synapse/admin/v1/register", data, {}, ssl_context)
response = await async_retry_with_timeout(
_register_user, should_retry=lambda e: type(e) is aiohttp.ClientResponseError and e.status == 400
)
pytestconfig.cache.set(f"ess-helm/cached-tokens/{username}", response["access_token"])
return response["access_token"]
async def upload_media(
synapse_fqdn: str,
user_access_token: str,
payload: aiohttp.payload.AsyncIterablePayload,
filename: str,
ssl_context: SSLContext,
):
headers = {}
headers["Authorization"] = f"Bearer {user_access_token}"
headers["Host"] = synapse_fqdn
params = {"filename": filename}
# A plain session is used: the RetryClient would re-send the same payload object on a retry,
# and a stream can only be read once. The caller retries with a fresh payload.
async with (
aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=ssl_context)) as client,
client.post(
"https://127.0.0.1/_matrix/media/v3/upload",
server_hostname=synapse_fqdn,
headers=headers,
params=params,
data=payload,
) as response,
):
response.raise_for_status()
response_json = await response.json()
assert response_json["content_uri"].startswith("mxc://")
return response_json
async def download_media(
server_name: str, synapse_fqdn: str, user_access_token, content_upload_json: dict, ssl_context: SSLContext
):
headers = {}
headers["Authorization"] = f"Bearer {user_access_token}"
headers["Host"] = synapse_fqdn
content_id = content_upload_json["content_uri"].replace(f"mxc://{server_name}/", "")
# Initialize SHA-256 hasher
sha256_hash = hashlib.sha256()
async with (
aiohttp_client(ssl_context) as client,
client.get(
f"https://127.0.0.1/_matrix/client/v1/media/download/{server_name}/{content_id}",
headers=headers,
server_hostname=synapse_fqdn,
) as response,
):
# Process the stream in chunks
while True:
chunk = await response.content.read(8192) # 8KB chunks
if not chunk:
break
sha256_hash.update(chunk)
return sha256_hash.hexdigest()
async def assert_downloaded_content(
kube_client: AsyncClient, media_pod, namespace, source_sha256, content_id, content_download_sha256
):
assert source_sha256 == content_download_sha256.split(" ")[0]
# Look in Synapse's short-term disk storage for the file
path = f"local_content/{content_id[0:2]}/{content_id[2:4]}/{content_id[4:]}"
local_path = f"/media/media_store/{path}"
response = await kube_client.exec(
media_pod, namespace=namespace, command=["sha256sum", local_path], stdout=True, raise_on_error=True
)
# The exec call captures and decodes stdout as a string
assert isinstance(response.stdout, str)
local_media_sha256 = response.stdout
assert source_sha256 == local_media_sha256.split(" ")[0]