mirror of
https://github.com/suitenumerique/meet.git
synced 2026-11-11 13:03:42 +00:00
Compare commits
63 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d3ddb58ee9 | |||
| b4b776e5e5 | |||
| 82c61f97de | |||
| 9b11526d85 | |||
| 9ede799cb9 | |||
| cc4275c23c | |||
| d1489f8a61 | |||
| c6beb8ed3e | |||
| 505c55d3b9 | |||
| 72d964656c | |||
| 58bf9a7d82 | |||
| 72af9d629e | |||
| 3cd2cb5591 | |||
| fcd37b0f26 | |||
| b6a8ae7d35 | |||
| 68848c0d6f | |||
| 2ea5c85436 | |||
| 57a4446710 | |||
| df723e6a0e | |||
| 900ebd3edd | |||
| c4fbfdd302 | |||
| 6f1b9ddba7 | |||
| e412dec76f | |||
| 6af43ebf1d | |||
| 4e953da226 | |||
| f45628d881 | |||
| 6fb698a63d | |||
| 5887795858 | |||
| 21b9b42cb1 | |||
| 2b9eba72a6 | |||
| 327f405559 | |||
| 35c3491ab2 | |||
| 41f3d1def4 | |||
| 22a93947d5 | |||
| b9748983ac | |||
| f7c3f392ef | |||
| 0c357c8b46 | |||
| cae6c19da8 | |||
| 455daf1e8f | |||
| 73b182b34a | |||
| 6a1622cd50 | |||
| 56b5a34ec5 | |||
| 815baa73e8 | |||
| 85670a02d5 | |||
| 21121e8bc1 | |||
| 1717c65f2b | |||
| fa20d52248 | |||
| 75df71733a | |||
| bae6affcba | |||
| 708f0d332e | |||
| bc1849cb1f | |||
| ce29593929 | |||
| 3bedae346c | |||
| c03440b92f | |||
| 1913330ae6 | |||
| adf9c22a9f | |||
| 480be6da6b | |||
| 8659182f41 | |||
| d3302c8644 | |||
| da3ebc3564 | |||
| 5e2fde5792 | |||
| 5c371e8ad8 | |||
| 6711d791cf |
+17
-8
@@ -2,19 +2,28 @@
|
||||
# Review regularly and remove entries once Debian ships a fix.
|
||||
|
||||
# util-linux
|
||||
CVE-2026-76642
|
||||
CVE-2026-78408
|
||||
CVE-2026-78409
|
||||
CVE-2026-78410
|
||||
CVE-2026-76642 exp:2026-12-05
|
||||
CVE-2026-78408 exp:2026-12-05
|
||||
CVE-2026-78409 exp:2026-12-05
|
||||
CVE-2026-78410 exp:2026-12-05
|
||||
|
||||
# acl
|
||||
CVE-2026-54369
|
||||
CVE-2026-54369 exp:2026-12-05
|
||||
|
||||
# ncurses
|
||||
CVE-2025-69720
|
||||
CVE-2025-69720 exp:2026-12-05
|
||||
|
||||
# systemd
|
||||
CVE-2026-16742
|
||||
CVE-2026-16742 exp:2026-12-05
|
||||
|
||||
# perl-base (fix deferred by Debian)
|
||||
CVE-2026-9538
|
||||
CVE-2026-9538 exp:2026-12-05
|
||||
|
||||
# libsqlite3-0 (fixed in sid 3.54.1-1; trixie marked no-dsa / minor)
|
||||
CVE-2026-119373 exp:2026-12-05
|
||||
CVE-2026-119374 exp:2026-12-05
|
||||
CVE-2026-119379 exp:2026-12-05
|
||||
|
||||
# zlib (fixed in sid 1:1.3.dfsg+really1.3.2-4; trixie still vulnerable)
|
||||
CVE-2026-76844 exp:2026-12-05
|
||||
CVE-2026-85091 exp:2026-12-05
|
||||
|
||||
@@ -215,7 +215,7 @@ jobs:
|
||||
- name: Install Node.js
|
||||
uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0
|
||||
with:
|
||||
node-version: "24"
|
||||
node-version: "24.22.1"
|
||||
|
||||
- name: Install dependencies
|
||||
run: cd src/frontend/ && npm ci --ignore-scripts
|
||||
|
||||
@@ -89,3 +89,4 @@ docker/livekit/rootCA.pem
|
||||
|
||||
# NixOS
|
||||
.devenv
|
||||
.pre-commit-config.yaml
|
||||
|
||||
+88
-1
@@ -10,6 +10,87 @@ and this project adheres to
|
||||
|
||||
### Added
|
||||
|
||||
- ✨(frontend) add jittered exponential backoff to LiveKit reconnections
|
||||
- ✨(frontend) tell participants when a recording is interrupted
|
||||
- ✨(backend) show the last login of users in the admin
|
||||
- ✨(backend) filter users sharing an email in the admin
|
||||
|
||||
### Changed
|
||||
|
||||
- ⬆️(frontend) upgrade livekit-client to 2.23.0
|
||||
- ✨(backend) expose LiveKit reconnection settings in the config
|
||||
- ✨(backend) keep recordings cut short by LiveKit egress
|
||||
- ⬆️(dev) upgrade LiveKit server to v1.13.11 and egress to v1.15.0
|
||||
- ⬆️(backend) update python dependencies
|
||||
- ⬆️(agents) update python dependencies
|
||||
- ⬆️(summary) update python dependencies
|
||||
- 🔒️(backend) issue room access tokens via POST rooms/{id}/join/ only
|
||||
- 🔒️(frontend) send the display name in the join request body
|
||||
- 🔥(backend) drop is_administrable from unregistered room payloads
|
||||
- ♻️(backend) match emails in a single normalized form
|
||||
- ⚡️(backend) index user emails for exact lookups
|
||||
|
||||
### Fixed
|
||||
|
||||
- 📌(summary) pin kombu to keep celery workers compatible with redis 5
|
||||
- 🐛(frontend) show a page when the connection ends unexpectedly
|
||||
- 🐛(frontend) show the transcript mic hint when every mic is muted
|
||||
- 🐛(frontend) show join errors instead of silently waiting in the lobby
|
||||
- 🐛(frontend) send users who cannot enter directly back to the lobby
|
||||
- 🔒️(backend) refuse unregistered rooms whose slug is a UUID
|
||||
- 🔒️(agents) upgrade python to 3.14.10 to fix CVE-2026-109518
|
||||
- 🔒️(docker) upgrade musl-utils to 1.2.6-r3 to fix CVE-2026-107891
|
||||
- ♿️(frontend) close the invite dialog with the Escape key #1916
|
||||
|
||||
## [1.37.0] - 2026-11-01
|
||||
|
||||
### Changed
|
||||
|
||||
- ⬆️(summary) update ffmpeg to 8.1.3-r0
|
||||
- ✨(frontend) replace the Crisp chat with the La Suite support form
|
||||
- 🔒️(frontend) keep rooms out of search engine and AI indexes
|
||||
- ⬆️(backend) upgrade django-lasuite to v1.0.0
|
||||
- ⚡️(docker) build frontend assets natively for arm64 images
|
||||
|
||||
### Fixed
|
||||
|
||||
- 🔒️(summary) protect signed URLs in models, source logs and analytics metadata
|
||||
- 🔒️(summary) mask secret validation inputs and sanitize upstream and task errors
|
||||
- 🔒️(summary) scrub sensitive Sentry event and breadcrumb content while retaining
|
||||
redacted frame locals and application DEBUG diagnostics
|
||||
|
||||
## [1.36.3] - 2026-10-23
|
||||
|
||||
### Fixed
|
||||
|
||||
- 🔒️(backend) upgrade brotli to 1.2.1 to fix CVE-2026-111497
|
||||
- 🔒️(frontend) upgrade nginx to 1.30.6 to fix CVE-2026-15176
|
||||
- 🔒️(docker) upgrade brotli-libs to 1.2.1 to fix CVE-2026-111497
|
||||
- 🔒️(frontend) build the Outlook add-in on Node 22.23.4
|
||||
- 🔒️(backend) upgrade djangorestframework to 3.18.2 to fix CVE-2026-114136,
|
||||
CVE-2026-114137 and CVE-2026-114138
|
||||
|
||||
## [1.36.2] - 2026-10-21
|
||||
|
||||
### Fixed
|
||||
|
||||
- 🔒️(frontend) upgrade Node to 22.23.4 and 24.22.1 security releases
|
||||
|
||||
## [1.36.1] - 2026-10-21
|
||||
|
||||
### Changed
|
||||
|
||||
- 🔖(helm) release chart 0.0.28
|
||||
|
||||
### Fixed
|
||||
|
||||
- 🔒️(docker) distrust compromised eMudhra emSign G3 CA roots
|
||||
- 🔒️(backend) upgrade pillow to 13.0.0 to fix CVE-2026-112403
|
||||
|
||||
## [1.36.0] - 2026-10-20
|
||||
|
||||
### Added
|
||||
|
||||
- ⚡️(backend) add UPPER(email) index for case-insensitive user lookups
|
||||
- ✨(backend) add room soft-deletion to the external API
|
||||
- ✨(all) allow any authenticated user to start a recording
|
||||
@@ -19,6 +100,11 @@ and this project adheres to
|
||||
### Fixed
|
||||
|
||||
- 🔒️(frontend) upgrade libx11 to fix CVE-2026-88806
|
||||
- 🔒️(backend) throttle the start recording endpoint
|
||||
- 🐛(backend) put a timeout on every LiveKit API call
|
||||
- 🔒️(backend) upgrade aiohttp to 3.14.5 to fix CVE-2026-111064
|
||||
- ♿️(frontend) announce the microphone turning off on shortcut #1816
|
||||
- 🐛(release) use env bash in prepare-release script for NixOS
|
||||
|
||||
## [1.35.0] - 2026-10-13
|
||||
|
||||
@@ -28,6 +114,7 @@ and this project adheres to
|
||||
- ✨(backend) introduce a token exchange endpoint for iframe embeds
|
||||
- ⚡️(backend) send recording notification emails from a Celery task
|
||||
- ✨(backend) allow static feature flags without an analytics backend #1809
|
||||
- ⚡️(backend) add an opt-in psycopg connection pool
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -142,7 +229,7 @@ and this project adheres to
|
||||
|
||||
### Fixed
|
||||
|
||||
- 🐛(helm) probe liveness on __lbheartbeat__ and readiness on __heartbeat__
|
||||
- 🐛(helm) probe liveness on `__lbheartbeat__` and readiness on `__heartbeat__`
|
||||
- 🐛(helm) render periodSeconds and failureThreshold on probes
|
||||
- 🐛(backend) report the app release to Sentry instead of "NA"
|
||||
- 🐛(frontend) play the waiting room notification sound on every arrival
|
||||
|
||||
+12
-6
@@ -1,14 +1,17 @@
|
||||
# Django Meet
|
||||
|
||||
# ---- base image to inherit from ----
|
||||
FROM python:3.13.15-alpine3.24 AS base
|
||||
FROM python:3.13.16-alpine3.24 AS base
|
||||
|
||||
# Upgrade pip to its latest release to speed up dependencies installation
|
||||
RUN python -m pip install --upgrade pip
|
||||
|
||||
# Upgrade system packages to install security updates
|
||||
RUN apk update && \
|
||||
apk upgrade
|
||||
apk upgrade && \
|
||||
apk add --no-cache --upgrade 'ca-certificates>=20261020-r0' \
|
||||
'musl-utils>=1.2.6-r3' && \
|
||||
update-ca-certificates
|
||||
|
||||
# ---- Back-end builder image ----
|
||||
FROM base AS back-builder
|
||||
@@ -23,7 +26,7 @@ ENV UV_LINK_MODE=copy
|
||||
ENV UV_PYTHON_DOWNLOADS=0
|
||||
|
||||
# install uv
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.10.9 /uv /uvx /bin/
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.13.4 /uv /uvx /bin/
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
@@ -37,7 +40,9 @@ RUN --mount=type=cache,target=/root/.cache/uv \
|
||||
uv sync --locked --no-dev
|
||||
|
||||
# ---- mails ----
|
||||
FROM node:22-alpine AS mail-builder
|
||||
FROM node:22.23.4-alpine AS mail-builder
|
||||
|
||||
RUN apk upgrade --no-cache ca-certificates
|
||||
|
||||
COPY ./src/mail /mail/app
|
||||
|
||||
@@ -83,7 +88,8 @@ RUN apk --no-cache add \
|
||||
libffi-dev \
|
||||
pango \
|
||||
libmagic \
|
||||
shared-mime-info
|
||||
shared-mime-info \
|
||||
'brotli-libs>=1.2.1-r0'
|
||||
|
||||
|
||||
# Copy entrypoint
|
||||
@@ -120,7 +126,7 @@ USER root:root
|
||||
RUN apk add postgresql-client
|
||||
|
||||
# Install development dependencies
|
||||
RUN --mount=from=ghcr.io/astral-sh/uv:0.10.9,source=/uv,target=/bin/uv \
|
||||
RUN --mount=from=ghcr.io/astral-sh/uv:0.13.4,source=/uv,target=/bin/uv \
|
||||
uv sync --all-extras --locked
|
||||
|
||||
# Restore the un-privileged user running the application
|
||||
|
||||
+65
@@ -16,6 +16,71 @@ the following command inside your docker container:
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
|
||||
### Room access tokens moved to POST /join/
|
||||
|
||||
LiveKit access tokens are no longer returned when reading a room. They are henceforth issued by a dedicated `POST
|
||||
/api/v1.0/rooms/{id}/join/` endpoint, which receives the display name in its JSON body. Display names therefore no
|
||||
longer appear in URLs and token retrieval by logged-in users is now protected against CSRF.
|
||||
|
||||
- `GET /api/v1.0/rooms/{id}/` no longer returns the `livekit` block, and neither do the list, create and update
|
||||
responses
|
||||
- The `username` field of `POST /api/v1.0/rooms/{id}/request-entry/` is now limited to 255 characters
|
||||
- When the caller may enter the room directly, the response contains the room data plus a `livekit` block
|
||||
- When the caller must go through the lobby, the response has no `livekit` block
|
||||
- Session-authenticated callers must send the CSRF token (`X-CSRFToken` header and `csrftoken` cookie)
|
||||
- Every join returning a `livekit` block mints a new token, valid for 6 hours, and anonymous callers get a new
|
||||
participant identity each time.
|
||||
- Joining again returns no `livekit` block to callers admitted through the lobby.
|
||||
- Unregistered rooms are always entered directly: joining one always returns a `livekit` block.
|
||||
- Unregistered rooms are no longer described with an `is_administrable` field,
|
||||
|
||||
### Unregistered rooms can no longer be named after a UUID
|
||||
|
||||
When `ALLOW_UNREGISTERED_ROOMS` is enabled, reading or joining a room whose identifier normalizes to an empty slug or to
|
||||
a UUID now returns a 404 instead of describing or letting callers join the unregistered room.
|
||||
|
||||
This closes a lobby bypass since a registered LiveKit room is named after its room id. An identifier crafted to not
|
||||
parse as a UUID, yet to normalize to an existing room's id, matched no registered room and was treated as an
|
||||
unregistered one. The token minted for that unregistered room was valid for the registered room: anyone could join a
|
||||
trusted or restricted room without being admitted through the lobby.
|
||||
|
||||
### User emails matched in a single normalized form
|
||||
|
||||
User emails are now stored stripped, with their ASCII letters lowercased, and compared exactly. A migration normalizes
|
||||
the stored emails and stores blank ones as NULL. Other letters keep their case.
|
||||
|
||||
- With `OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION` disabled (the default), a new `sub` whose email is already used by
|
||||
another user is now refused, by the OIDC login and by the external API, instead of getting a second account. To keep
|
||||
creating user with a duplicate mail, set the new `OIDC_ALLOW_DUPLICATE_EMAILS=True`.
|
||||
- Known limitation: provisional users still have a unique constraint comparing lowercased emails,
|
||||
non-ASCII letters included. Provisioning an email that differs from another provisional user's only by the case of a
|
||||
non-ASCII letter (e.g. `É` and `é`) returns a 409.
|
||||
|
||||
## v1.37.0
|
||||
|
||||
### Crisp support chat replaced by the La Suite support form
|
||||
|
||||
The Crisp chat is gone, the support button, now open the La Suite support form. They are hidden unless these `FRONTEND_SUPPORT` keys are all set.
|
||||
The former help links for recording/transcription are now redirecting to the adhoc page in the official documentation
|
||||
|
||||
### Pages hidden from search engines
|
||||
|
||||
Every page except `/` now carries a `noindex` tag and, with the provided nginx configurations, an `X-Robots-Tag` header to stay out of search indexes.
|
||||
A new `robots.txt` also blocks the main AI crawlers. If you maintain your own nginx configuration, copy the `location = /` and `location = /home.html` blocks from `src/frontend/default.conf`, and the `X-Robots-Tag` header from its `location /`.
|
||||
|
||||
### LiveKit server v1.13.11 and egress v1.15.0
|
||||
|
||||
The development stack now runs LiveKit server v1.13.11 and LiveKit Egress v1.15.0. When upgrading your own deployment:
|
||||
|
||||
- Deploy this release of Meet first, then upgrade egress, then the server. Older Meet releases discard the partial recordings described below.
|
||||
- Transcripts no longer go through Chrome. Since egress v1.13, audio-only recordings always use the egress SDK pipeline.
|
||||
- A transcript now waits for actual audio: it stays "starting", and participants are asked to turn on their microphone, while every microphone is muted.
|
||||
- Recordings cut short are now kept. Since egress v1.14, a transcript that lost the room, or any recording drained because its egress host ran out of CPU, still uploads what it recorded, even though egress may report it as failed. Meet saves and processes it as usual, and tells participants the recording was interrupted. A screen recording that loses the room is still reported as complete, and saved without a warning.
|
||||
- Telephony: since server v1.13.8, a call that matches no dispatch rule, for example while no room is active, is rejected with a SIP 404 instead of being silently dropped.
|
||||
|
||||
## [v1.35.0]
|
||||
|
||||
### Purging deleted rooms
|
||||
|
||||
Deleting a room now only soft deletes it: it is hidden but keeps its slug and PIN code. The `purge_inactive_rooms` command also permanently deletes soft-deleted rooms. See [the room purge documentation](docs/features/room-purge.md).
|
||||
|
||||
+45
-48
@@ -1,6 +1,6 @@
|
||||
#!/bin/bash
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -e # Exit on error
|
||||
set -e # Exit on error
|
||||
|
||||
# Colors for output
|
||||
RED='\033[0;31m'
|
||||
@@ -10,60 +10,59 @@ NC='\033[0m' # No Color
|
||||
|
||||
# Function to print colored output
|
||||
print_info() {
|
||||
echo -e "${GREEN}[INFO]${NC} $1"
|
||||
echo -e "${GREEN}[INFO]${NC} $1"
|
||||
}
|
||||
|
||||
print_error() {
|
||||
echo -e "${RED}[ERROR]${NC} $1"
|
||||
echo -e "${RED}[ERROR]${NC} $1"
|
||||
}
|
||||
|
||||
print_warning() {
|
||||
echo -e "${YELLOW}[WARNING]${NC} $1"
|
||||
echo -e "${YELLOW}[WARNING]${NC} $1"
|
||||
}
|
||||
|
||||
|
||||
# Function to update npm package version
|
||||
update_npm_version() {
|
||||
local component=$1
|
||||
print_info "Updating $component version..."
|
||||
cd "src/$component"
|
||||
npm version "$VERSION" --no-git-tag-version
|
||||
cd -
|
||||
local component=$1
|
||||
print_info "Updating $component version..."
|
||||
cd "src/$component"
|
||||
npm version "$VERSION" --no-git-tag-version
|
||||
cd -
|
||||
}
|
||||
|
||||
# Function to update Python project version in pyproject.toml
|
||||
update_python_version() {
|
||||
local component=$1
|
||||
print_info "Updating $component version..."
|
||||
cd "src/$component"
|
||||
local component=$1
|
||||
print_info "Updating $component version..."
|
||||
cd "src/$component"
|
||||
|
||||
if [ ! -f "pyproject.toml" ]; then
|
||||
print_error "pyproject.toml not found in src/$component!"
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -f "pyproject.toml" ]; then
|
||||
print_error "pyproject.toml not found in src/$component!"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if grep -q '^version = "' pyproject.toml; then
|
||||
sed -i.bak "s/^version = \".*\"/version = \"$VERSION\"/" pyproject.toml
|
||||
rm pyproject.toml.bak
|
||||
print_info "Updated pyproject.toml version to $VERSION"
|
||||
else
|
||||
print_error "Could not find version line in pyproject.toml"
|
||||
exit 1
|
||||
fi
|
||||
if grep -q '^version = "' pyproject.toml; then
|
||||
sed -i.bak "s/^version = \".*\"/version = \"$VERSION\"/" pyproject.toml
|
||||
rm pyproject.toml.bak
|
||||
print_info "Updated pyproject.toml version to $VERSION"
|
||||
else
|
||||
print_error "Could not find version line in pyproject.toml"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cd -
|
||||
cd -
|
||||
}
|
||||
|
||||
# Check if we're in a git repository
|
||||
if ! git rev-parse --git-dir > /dev/null 2>&1; then
|
||||
print_error "Not a git repository. Please run this script from the root of your project."
|
||||
exit 1
|
||||
if ! git rev-parse --git-dir >/dev/null 2>&1; then
|
||||
print_error "Not a git repository. Please run this script from the root of your project."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check if working directory is clean
|
||||
if ! git diff-index --quiet HEAD --; then
|
||||
print_error "Working directory is not clean. Please commit or stash your changes first."
|
||||
exit 1
|
||||
print_error "Working directory is not clean. Please commit or stash your changes first."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Ask user for release version number
|
||||
@@ -72,8 +71,8 @@ read -r -p "Enter release version number (e.g., 1.2.3): " VERSION
|
||||
|
||||
# Validate version format (basic semver check)
|
||||
if ! [[ $VERSION =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
print_error "Invalid version format. Please use semantic versioning (e.g., 1.2.3)"
|
||||
exit 1
|
||||
print_error "Invalid version format. Please use semantic versioning (e.g., 1.2.3)"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
print_info "Release version: $VERSION"
|
||||
@@ -81,8 +80,8 @@ print_info "Release version: $VERSION"
|
||||
# Check if branch already exists
|
||||
BRANCH_NAME="release/$VERSION"
|
||||
if git show-ref --verify --quiet "refs/heads/$BRANCH_NAME"; then
|
||||
print_error "Branch $BRANCH_NAME already exists!"
|
||||
exit 1
|
||||
print_error "Branch $BRANCH_NAME already exists!"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Create and checkout new branch
|
||||
@@ -129,8 +128,8 @@ cd -
|
||||
print_info "Updating CHANGELOG..."
|
||||
|
||||
if [ ! -f "CHANGELOG.md" ]; then
|
||||
print_error "CHANGELOG.md not found in project root!"
|
||||
exit 1
|
||||
print_error "CHANGELOG.md not found in project root!"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Get current date in YYYY-MM-DD format
|
||||
@@ -138,23 +137,21 @@ CURRENT_DATE=$(date +%Y-%m-%d)
|
||||
|
||||
# Replace [Unreleased] with [version number] - YYYY-MM-DD
|
||||
if grep -q '\[Unreleased\]' CHANGELOG.md; then
|
||||
sed -i.bak "s/\[Unreleased\]/[$VERSION] - $CURRENT_DATE/" CHANGELOG.md
|
||||
sed -i.bak "s/\[Unreleased\]/[$VERSION] - $CURRENT_DATE/" CHANGELOG.md
|
||||
|
||||
# Add new [Unreleased] section after the header
|
||||
# This adds it after the line containing "Semantic Versioning"
|
||||
sed -i.bak "/Semantic Versioning/a\\
|
||||
# Add new [Unreleased] section after the header
|
||||
# This adds it after the line containing "Semantic Versioning"
|
||||
sed -i.bak "/Semantic Versioning/a\\
|
||||
\\
|
||||
## [Unreleased]
|
||||
" CHANGELOG.md
|
||||
|
||||
rm CHANGELOG.md.bak
|
||||
print_info "Updated CHANGELOG.md"
|
||||
rm CHANGELOG.md.bak
|
||||
print_info "Updated CHANGELOG.md"
|
||||
else
|
||||
print_warning "Could not find [Unreleased] section in CHANGELOG.md"
|
||||
print_warning "Could not find [Unreleased] section in CHANGELOG.md"
|
||||
fi
|
||||
|
||||
|
||||
|
||||
# Summary
|
||||
echo ""
|
||||
print_info "Release preparation complete!"
|
||||
@@ -178,4 +175,4 @@ print_warning "Next steps:"
|
||||
echo " 1. Review the changes: git status"
|
||||
echo " 2. Commit the changes: git add . && git commit -m 'Release $VERSION'"
|
||||
echo " 3. Push the branch: git push origin $BRANCH_NAME"
|
||||
echo ""
|
||||
echo ""
|
||||
|
||||
+3
-3
@@ -175,7 +175,7 @@ services:
|
||||
working_dir: /app
|
||||
|
||||
node:
|
||||
image: node:22-alpine
|
||||
image: node:22.23.4-alpine
|
||||
user: "${DOCKER_USER:-1000}"
|
||||
environment:
|
||||
HOME: /tmp
|
||||
@@ -218,7 +218,7 @@ services:
|
||||
- kc_postgresql
|
||||
|
||||
livekit:
|
||||
image: livekit/livekit-server:v1.13.6
|
||||
image: livekit/livekit-server:v1.13.11
|
||||
entrypoint: /livekit-server --dev --bind 0.0.0.0 --config ./config.yaml
|
||||
ports:
|
||||
- "7880:7880"
|
||||
@@ -233,7 +233,7 @@ services:
|
||||
- livekit-egress
|
||||
|
||||
livekit-egress:
|
||||
image: livekit/egress:v1.11.0
|
||||
image: livekit/egress:v1.15.0
|
||||
environment:
|
||||
EGRESS_CONFIG_FILE: ./livekit-egress.yaml
|
||||
volumes:
|
||||
|
||||
@@ -38,6 +38,17 @@ server {
|
||||
add_header Cache-Control "public, max-age=2592000";
|
||||
}
|
||||
|
||||
location = / {
|
||||
try_files /home.html /index.html;
|
||||
add_header Cache-Control "no-cache, no-store, must-revalidate";
|
||||
add_header Pragma "no-cache";
|
||||
add_header Expires 0;
|
||||
}
|
||||
|
||||
location = /home.html {
|
||||
internal;
|
||||
}
|
||||
|
||||
# Serve static files
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
@@ -45,6 +56,7 @@ server {
|
||||
add_header Cache-Control "no-cache, no-store, must-revalidate";
|
||||
add_header Pragma "no-cache"; # HTTP 1.0 header for backward compatibility
|
||||
add_header Expires 0;
|
||||
add_header X-Robots-Tag "noindex, nofollow" always;
|
||||
}
|
||||
|
||||
# Optionally, handle 404 errors by redirecting to index.html
|
||||
|
||||
+42
-3
@@ -18,12 +18,50 @@
|
||||
"url": "https://github.com/cachix/devenv"
|
||||
}
|
||||
},
|
||||
"flake-compat": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1767039857,
|
||||
"narHash": "sha256-vNpUSpF5Nuw8xvDLj2KCwwksIbjua2LZCqhV1LNRDns=",
|
||||
"owner": "NixOS",
|
||||
"repo": "flake-compat",
|
||||
"rev": "5edf11c44bc78a0d334f6334cdaf7d60d732daab",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"repo": "flake-compat",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"git-hooks": {
|
||||
"inputs": {
|
||||
"flake-compat": "flake-compat",
|
||||
"nixpkgs": [
|
||||
"nixpkgs"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1791909798,
|
||||
"narHash": "sha256-VAhpCOmrun/KXimYfR8NM88bciKCui7CqHHhThSzgag=",
|
||||
"ref": "refs/heads/master",
|
||||
"rev": "1ba1dbfe28738c9a71c266be6efa5b89e75491a9",
|
||||
"shallow": true,
|
||||
"type": "git",
|
||||
"url": "https://github.com/cachix/git-hooks.nix"
|
||||
},
|
||||
"original": {
|
||||
"shallow": true,
|
||||
"type": "git",
|
||||
"url": "https://github.com/cachix/git-hooks.nix"
|
||||
}
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1789542786,
|
||||
"narHash": "sha256-ajQuqcxnj6RYnwCjA/9FTCnrdR2+BDzstE8UembXf60=",
|
||||
"lastModified": 1792295010,
|
||||
"narHash": "sha256-F7meJtbqGttmUoMmYjRRgkVs42sn7bh7vvRvLPlUN98=",
|
||||
"ref": "nixos-26.05",
|
||||
"rev": "4c7870105e7f1fdf9c48688c8d7efc21abf0688a",
|
||||
"rev": "8ce73368d1efd4d657e9064d29b144a52046b4e8",
|
||||
"shallow": true,
|
||||
"type": "git",
|
||||
"url": "https://github.com/NixOS/nixpkgs"
|
||||
@@ -38,6 +76,7 @@
|
||||
"root": {
|
||||
"inputs": {
|
||||
"devenv": "devenv",
|
||||
"git-hooks": "git-hooks",
|
||||
"nixpkgs": "nixpkgs"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,6 +101,8 @@ in
|
||||
languages.typescript.enable = false;
|
||||
languages.nix.enable = true;
|
||||
|
||||
git-hooks.hooks.gitlint.enable = true;
|
||||
|
||||
packages =
|
||||
with pkgs;
|
||||
[
|
||||
|
||||
@@ -3,3 +3,8 @@ inputs:
|
||||
url: git+https://github.com/NixOS/nixpkgs?ref=nixos-26.05&shallow=1
|
||||
devenv:
|
||||
url: git+https://github.com/cachix/devenv?ref=refs/tags/v2.1.2&dir=src/modules
|
||||
git-hooks:
|
||||
url: git+https://github.com/cachix/git-hooks.nix?shallow=1
|
||||
inputs:
|
||||
nixpkgs:
|
||||
follows: nixpkgs
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# ---- Front-end image ----
|
||||
FROM node:22-alpine AS frontend-deps
|
||||
FROM --platform=$BUILDPLATFORM node:22.23.4-alpine AS frontend-deps
|
||||
|
||||
RUN apk upgrade --no-cache ca-certificates
|
||||
|
||||
WORKDIR /home/frontend/
|
||||
|
||||
@@ -39,7 +41,9 @@ COPY ./docker/dinum-frontend/fonts/ \
|
||||
./dist/assets/fonts/
|
||||
|
||||
# ---- Addons builder image ----
|
||||
FROM node:20-alpine AS addons-builder
|
||||
FROM --platform=$BUILDPLATFORM node:22.23.4-alpine AS addons-builder
|
||||
|
||||
RUN apk upgrade --no-cache ca-certificates
|
||||
|
||||
WORKDIR /home/addons/outlook
|
||||
|
||||
@@ -54,13 +58,15 @@ RUN npx webpack --mode production
|
||||
|
||||
|
||||
# ---- Front-end image ----
|
||||
FROM nginxinc/nginx-unprivileged:1.30.4-alpine3.24 AS frontend-production
|
||||
FROM nginxinc/nginx-unprivileged:1.30.6-alpine3.24 AS frontend-production
|
||||
|
||||
USER root
|
||||
RUN apk upgrade --no-cache libexpat && \
|
||||
apk add --no-cache --upgrade 'pcre2>=10.49-r0' 'tiff>=4.7.2-r0' \
|
||||
'libx11>=1.8.14-r0' && \
|
||||
apk del curl
|
||||
'libx11>=1.8.14-r0' 'ca-certificates>=20261020-r0' \
|
||||
'brotli-libs>=1.2.1-r0' 'musl-utils>=1.2.6-r3' && \
|
||||
apk del curl && \
|
||||
rm -f /usr/share/nginx/html/50x.html
|
||||
USER nginx
|
||||
|
||||
USER nginx
|
||||
|
||||
@@ -43,6 +43,7 @@ server {
|
||||
add_header Cache-Control "no-cache, no-store, must-revalidate";
|
||||
add_header Pragma "no-cache" always;
|
||||
add_header Expires 0 always;
|
||||
add_header X-Robots-Tag "noindex, nofollow" always;
|
||||
|
||||
set $ms_domains "https://*.live.com https://*.office.com https://*.microsoft.com https://*.office365.com https://*.sharepoint.com";
|
||||
|
||||
@@ -76,6 +77,17 @@ server {
|
||||
add_header Cache-Control "public, max-age=2592000";
|
||||
}
|
||||
|
||||
location = / {
|
||||
try_files /home.html /index.html;
|
||||
add_header Cache-Control "no-cache, no-store, must-revalidate";
|
||||
add_header Pragma "no-cache";
|
||||
add_header Expires 0;
|
||||
}
|
||||
|
||||
location = /home.html {
|
||||
internal;
|
||||
}
|
||||
|
||||
# Serve static files
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
@@ -83,6 +95,7 @@ server {
|
||||
add_header Cache-Control "no-cache, no-store, must-revalidate";
|
||||
add_header Pragma "no-cache"; # HTTP 1.0 header for backward compatibility
|
||||
add_header Expires 0;
|
||||
add_header X-Robots-Tag "noindex, nofollow" always;
|
||||
}
|
||||
|
||||
# Optionally, handle 404 errors by redirecting to index.html
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM livekit/livekit-server:v1.13.6
|
||||
FROM livekit/livekit-server:v1.13.11
|
||||
|
||||
# We inject the nip.io certificate manually because the livekit chart doesn't support volume mounting
|
||||
COPY rootCA.pem /etc/ssl/certs/
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
log_level: debug
|
||||
logging:
|
||||
level: debug
|
||||
api_key: devkey
|
||||
api_secret: secret
|
||||
ws_url: "ws://livekit:7880"
|
||||
|
||||
@@ -37,7 +37,7 @@ $ make help
|
||||
---
|
||||
|
||||
## Need Help?
|
||||
If you need any assistance or have questions while getting started, feel free to reach out to @lebaudantoine anytime! Antoine is available to help you onboard and guide you through the process. Chat with him @antoine.lebaud:matrix.org, or from the [support hotline](https://go.crisp.chat/chat/embed/?website_id=58ea6697-8eba-4492-bc59-ad6562585041).
|
||||
If you need any assistance or have questions while getting started, feel free to reach out to @lebaudantoine anytime! Antoine is available to help you onboard and guide you through the process. Chat with him @antoine.lebaud:matrix.org, or by email at [support-visio@numerique.gouv.fr](mailto:support-visio@numerique.gouv.fr).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -16,7 +16,8 @@ Authentication relies on [django-lasuite](https://github.com/suitenumerique/djan
|
||||
| OIDC_VERIFY_SSL | Verify SSL certificates when contacting the OIDC provider | `true` |
|
||||
| OIDC_USE_NONCE | Use `nonce` to prevent replay attacks | `true` |
|
||||
| OIDC_STORE_ID_TOKEN | Store the ID token returned by the OIDC provider (useful for backend validation) | `true` |
|
||||
| OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION | Fallback to identifying users by email if `sub` claim does not match. Enable only if emails are unique. | `false` |
|
||||
| OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION | Fallback to identifying users by email if `sub` claim does not match. Cannot be enabled together with `OIDC_ALLOW_DUPLICATE_EMAILS`. | `false` |
|
||||
| OIDC_ALLOW_DUPLICATE_EMAILS | When the email fallback is disabled, create a new user for an unknown `sub` even if its email is already used by another user. Otherwise, the login is refused. Emails are compared once stripped, with their ASCII letters lowercased. | `false` |
|
||||
| **Endpoints** | | |
|
||||
| OIDC_OP_JWKS_ENDPOINT | URL to retrieve JSON Web Key Sets (for token verification) | — |
|
||||
| OIDC_OP_AUTHORIZATION_ENDPOINT | URL for authorization requests | — |
|
||||
|
||||
@@ -11,14 +11,23 @@ We do not cover internal signaling behavior. For full reference, see the [LiveKi
|
||||
> [!IMPORTANT]
|
||||
> The WebSocket is the backbone of LiveKit signaling. All signaling messages rely on it, and without it, ICE candidate exchange and peer connection setup cannot occur. If the WebSocket connection is lost, the client automatically attempts to resume the RTC session once connectivity is restored.
|
||||
|
||||
## Reconnection
|
||||
|
||||
When the WebSocket drops, for instance after a LiveKit node crash or during a Redis outage, every client in every room loses it at the same time. To keep them from all reconnecting at once, each client waits a random delay before every attempt. The first delay is at most `LIVEKIT_RECONNECT_BASE_DELAY_MS`. That ceiling then doubles after each failed attempt, capped at `LIVEKIT_RECONNECT_MAX_DELAY_MS`, and each later delay falls between half the ceiling and the ceiling. The first attempt always starts within 5 seconds of the drop.
|
||||
|
||||
A client gives up once its reconnection has lasted longer than `LIVEKIT_RECONNECT_GIVE_UP_AFTER_MS`, and then shows a "connection lost" page. While only signaling is down and its media still flows, it keeps trying instead. A client that loses the connection again less than `LIVEKIT_RECONNECT_BACKOFF_RESET_MS` after reconnecting resumes the backoff one step above where it stopped.
|
||||
|
||||
## Environment Variables
|
||||
|
||||
| Variable | Type | Default | Purpose |
|
||||
| ----------------------------------------- | ------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `LIVEKIT_FORCE_WSS_PROTOCOL` | Boolean | `True` | Forces the WebSocket URL to use `wss://`. Required for legacy browsers (Firefox <124, Chrome <125, Edge <125) where HTTPS URLs in `WebSocket()` may fail. |
|
||||
| `LIVEKIT_ENABLE_FIREFOX_PROXY_WORKAROUND` | Boolean | `True` | Workaround for Firefox clients behind proxies that fail to establish WebSocket connections. Pre-establishes a dummy connection to “prime” the WebSocket. |
|
||||
| Variable | Type | Default | Purpose |
|
||||
| ----------------------------------------- | ------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `LIVEKIT_FORCE_WSS_PROTOCOL` | Boolean | `False` | Forces the WebSocket URL to use `wss://`. Required for legacy browsers (Firefox <124, Chrome <125, Edge <125) where HTTPS URLs in `WebSocket()` may fail. |
|
||||
| `LIVEKIT_ENABLE_FIREFOX_PROXY_WORKAROUND` | Boolean | `False` | Workaround for Firefox clients behind proxies that fail to establish WebSocket connections. Pre-establishes a dummy connection to “prime” the WebSocket. |
|
||||
| `LIVEKIT_RECONNECT_BACKOFF_ENABLED` | Boolean | `True` | Enables the reconnection backoff described above. When `False`, clients use LiveKit's default reconnection policy. |
|
||||
| `LIVEKIT_RECONNECT_BASE_DELAY_MS` | Integer | `1000` | Longest wait before the first reconnection attempt, in milliseconds. It doubles after each failed attempt. Must be greater than 0. |
|
||||
| `LIVEKIT_RECONNECT_MAX_DELAY_MS` | Integer | `10000` | Longest wait between two reconnection attempts, in milliseconds. Must be greater than 0. |
|
||||
| `LIVEKIT_RECONNECT_GIVE_UP_AFTER_MS` | Integer | `180000` | How long a client keeps trying to reconnect, in milliseconds. Not applied while its media still flows. Must be greater than 0. |
|
||||
| `LIVEKIT_RECONNECT_BACKOFF_RESET_MS` | Integer | `120000` | How long a connection must stay up, in milliseconds, for the next reconnection to start from the shortest delay again. With `0`, every reconnection does. |
|
||||
|
||||
> [!NOTE]
|
||||
> Questions? Open an issue on [GitHub](https://github.com/suitenumerique/meet/issues/new?assignees=&labels=bug&template=Bug_report.md) or join our [Matrix community](https://matrix.to/#/#meet-official:matrix.org).
|
||||
|
||||
@@ -318,12 +318,17 @@ These are the environmental options available on meet backend.
|
||||
| DJANGO_SECRET_KEY | Secret key used for Django security | |
|
||||
| DJANGO_SILENCED_SYSTEM_CHECKS | Silence Django system checks | [] |
|
||||
| DJANGO_ALLOW_UNSECURE_USER_LISTING | Allow unsecure user listing | false |
|
||||
| DB_ENGINE | Database engine used | django.db.backends.postgresql_psycopg2 |
|
||||
| DB_ENGINE | Database engine used | django.db.backends.postgresql |
|
||||
| DB_NAME | Name of the database | meet |
|
||||
| DB_USER | User used to connect to database | dinum |
|
||||
| DB_PASSWORD | Password used to connect to the database | pass |
|
||||
| DB_HOST | Hostname of the database | localhost |
|
||||
| DB_PORT | Port to connect to database | 5432 |
|
||||
| DB_PSYCOPG_POOL_ENABLED | Enable the psycopg connection pool | false |
|
||||
| DB_PSYCOPG_POOL_MIN_SIZE | Connections each pool keeps open | 1 |
|
||||
| DB_PSYCOPG_POOL_MAX_SIZE | Maximum connections per pool | 3 |
|
||||
| DB_PSYCOPG_POOL_TIMEOUT | Seconds a request waits for a free pool connection before failing | 30 |
|
||||
| DB_PSYCOPG_POOL_MAX_IDLE | Seconds an idle connection above the minimum stays open | 600 |
|
||||
| STORAGES_STATICFILES_BACKEND | Static file serving engine | whitenoise.storage.CompressedManifestStaticFilesStorage |
|
||||
| AWS_S3_ENDPOINT_URL | S3 host endpoint | |
|
||||
| AWS_S3_ACCESS_KEY_ID | S3 access key | |
|
||||
@@ -335,13 +340,15 @@ These are the environmental options available on meet backend.
|
||||
| SESSION_COOKIE_AGE | Session cookie expiration in seconds | 43200 (12 hours) |
|
||||
| ROOM_CREATION_THROTTLE_RATES | Room creation throttle rate per authenticated user | 50/minute | 50/minute |
|
||||
| ROOM_CREATION_DAILY_THROTTLE_RATES | Daily room creation cap per authenticated user | 1000/day |
|
||||
| START_RECORDING_THROTTLE_RATES | Recording start throttle rate per authenticated user | 10/minute |
|
||||
| START_RECORDING_DAILY_THROTTLE_RATES | Daily recording start cap per authenticated user | 100/day |
|
||||
| REQUEST_ENTRY_THROTTLE_RATES | Entry request throttle rates | 150/minute |
|
||||
| CREATION_CALLBACK_THROTTLE_RATES | Creation callback throttle rates | 600/minute |
|
||||
| SPECTACULAR_SETTINGS_ENABLE_DJANGO_DEPLOY_CHECK | Enable Django deploy check | false |
|
||||
| CSRF_TRUSTED_ORIGINS | CSRF trusted origins list | [] |
|
||||
| FRONTEND_CUSTOM_CSS_URL | URL of an additional CSS file to load in the frontend app. If set, a `<link>` tag with this URL as href is added to the `<head>` of the frontend app | |
|
||||
| FRONTEND_ANALYTICS | Analytics information | {} |
|
||||
| FRONTEND_SUPPORT | Crisp frontend support configuration, also you can pass help articles, with `help_article_transcript`, `help_article_recording`, `help_article_more_tools` | {} |
|
||||
| FRONTEND_SUPPORT | La Suite support form (`widget_script_url`, `widget_api_url`, `widget_channel`) and help articles (`help_article_*`) | {} |
|
||||
| FRONTEND_MANIFEST_LINK | Link to the "Learn more" button on the homepage | {} |
|
||||
| FRONTEND_SILENCE_LIVEKIT_DEBUG | Silence LiveKit debug logs | false |
|
||||
| FRONTEND_IS_SILENT_LOGIN_ENABLED | Enable silent login feature | true |
|
||||
@@ -372,7 +379,8 @@ These are the environmental options available on meet backend.
|
||||
| DJANGO_CELERY_BROKER_TRANSPORT_OPTIONS | Celery broker options | {} |
|
||||
| OIDC_CREATE_USER | Create OIDC user if not exists | true |
|
||||
| OIDC_VERIFY_SSL | Verify SSL for OIDC | true |
|
||||
| OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION | Fallback to email for identification | false |
|
||||
| OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION | Fallback to email for identification, cannot be enabled with OIDC_ALLOW_DUPLICATE_EMAILS | false |
|
||||
| OIDC_ALLOW_DUPLICATE_EMAILS | Without the email fallback, create a user for a new sub whose email is already used | false |
|
||||
| OIDC_RP_SIGN_ALGO | Token verification algorithm used by OIDC | RS256 |
|
||||
| OIDC_RP_CLIENT_ID | OIDC client ID | meet |
|
||||
| OIDC_RP_CLIENT_SECRET | OIDC client secret | |
|
||||
@@ -403,8 +411,14 @@ These are the environmental options available on meet backend.
|
||||
| LIVEKIT_API_SECRET | LiveKit API secret | |
|
||||
| LIVEKIT_API_URL | LiveKit API URL | |
|
||||
| LIVEKIT_VERIFY_SSL | Verify SSL for LiveKit connections | true |
|
||||
| LIVEKIT_API_TIMEOUT_SECONDS | Seconds before a call to the LiveKit API gives up | 10 |
|
||||
| LIVEKIT_FORCE_WSS_PROTOCOL | Enables WSS protocol conversion for legacy browser compatibility (Firefox <124, Chrome <125, Edge <125) where HTTPS URLs fail in WebSocket() constructor. | false |
|
||||
| LIVEKIT_ENABLE_FIREFOX_PROXY_WORKAROUND | Firefox-only connection warmup: pre-calls WebSocket endpoint (expecting 401) to initialize cache, resolving proxy/network connectivity issues. | false |
|
||||
| LIVEKIT_RECONNECT_BACKOFF_ENABLED | Spread client reconnections with a random exponential backoff. When false, clients use LiveKit's default reconnection policy | true |
|
||||
| LIVEKIT_RECONNECT_BASE_DELAY_MS | Longest wait before the first reconnection attempt, in milliseconds. It doubles after each failed attempt. Must be greater than 0 | 1000 |
|
||||
| LIVEKIT_RECONNECT_MAX_DELAY_MS | Longest wait between two reconnection attempts, in milliseconds. Must be greater than 0 | 10000 |
|
||||
| LIVEKIT_RECONNECT_GIVE_UP_AFTER_MS | How long a client keeps trying to reconnect, in milliseconds. Not applied while its media still flows. Must be greater than 0 | 180000 |
|
||||
| LIVEKIT_RECONNECT_BACKOFF_RESET_MS | How long a connection must stay up, in milliseconds, for the next reconnection to start from the shortest delay again. With 0, every reconnection does | 120000 |
|
||||
| RESOURCE_DEFAULT_ACCESS_LEVEL | Default resource access level for rooms | public |
|
||||
| ALLOW_UNREGISTERED_ROOMS | Allow usage of unregistered rooms | true |
|
||||
| ROOM_INACTIVITY_DELETION_DAYS | Days without being started after which a room is purged. Unset to never purge | |
|
||||
|
||||
@@ -8,4 +8,5 @@ DB_HOST=postgresql
|
||||
DB_NAME=meet
|
||||
DB_USER=dinum
|
||||
DB_PASSWORD=pass
|
||||
DB_PORT=5432
|
||||
DB_PORT=5432
|
||||
DB_PSYCOPG_POOL_ENABLED=True
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="robots" content="noindex, nofollow" />
|
||||
<title data-app-name></title>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
|
||||
<script nonce="NONCE_PLACEHOLDER" src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js"></script>
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="robots" content="noindex, nofollow" />
|
||||
<title data-app-name></title>
|
||||
<link rel="stylesheet" href="../styles/spinner.css" />
|
||||
<script nonce="NONCE_PLACEHOLDER" src="/addons/outlook/config.js"></script>
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="robots" content="noindex, nofollow" />
|
||||
<title data-app-name></title>
|
||||
<link rel="stylesheet" href="taskpane.css" />
|
||||
<script nonce="NONCE_PLACEHOLDER" src="/addons/outlook/config.js"></script>
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="robots" content="noindex, nofollow" />
|
||||
<title data-app-name></title>
|
||||
<link rel="stylesheet" href="../styles/spinner.css" />
|
||||
<script nonce="NONCE_PLACEHOLDER" src="/addons/outlook/config.js"></script>
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
FROM python:3.14.7-slim AS base
|
||||
FROM python:3.14.10-slim AS base
|
||||
|
||||
# Install system dependencies required by LiveKit, fetching packages over HTTPS only for Bureautix proxy
|
||||
RUN sed -i "s|^URIs: http://|URIs: https://|" /etc/apt/sources.list.d/debian.sources \
|
||||
&& apt-get update && apt-get install -y --no-install-recommends \
|
||||
ca-certificates \
|
||||
libglib2.0-0 \
|
||||
libgobject-2.0-0 \
|
||||
libpcre2-8-0 \
|
||||
@@ -18,7 +19,7 @@ ENV UV_COMPILE_BYTECODE=1 \
|
||||
UV_PYTHON_DOWNLOADS=0
|
||||
|
||||
# Install uv
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.10.9 /uv /uvx /bin/
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.13.4 /uv /uvx /bin/
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
@@ -41,7 +42,7 @@ ENV UV_COMPILE_BYTECODE=1 \
|
||||
UV_LINK_MODE=copy \
|
||||
UV_PYTHON_DOWNLOADS=0
|
||||
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.10.9 /uv /uvx /bin/
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.13.4 /uv /uvx /bin/
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
|
||||
+10
-10
@@ -1,24 +1,24 @@
|
||||
|
||||
[project]
|
||||
name = "agents"
|
||||
version = "1.35.0"
|
||||
version = "1.37.0"
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"livekit-agents==1.7.0",
|
||||
"livekit-plugins-deepgram==1.7.0",
|
||||
"livekit-plugins-silero==1.7.0",
|
||||
"livekit-agents==1.8.9",
|
||||
"livekit-plugins-deepgram==1.8.9",
|
||||
"livekit-plugins-silero==1.8.9",
|
||||
"livekit-plugins-kyutai-lasuite==0.0.6",
|
||||
"boto3==1.43.56",
|
||||
"python-dotenv==1.2.3",
|
||||
"protobuf==7.36.0",
|
||||
"sentry-sdk==2.68.1",
|
||||
"websockets==17.1",
|
||||
"boto3==1.43.118",
|
||||
"python-dotenv==1.2.4",
|
||||
"protobuf==7.36.2",
|
||||
"sentry-sdk==2.73.0",
|
||||
"websockets==17.3",
|
||||
"httpx==0.28.1",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = [
|
||||
"ruff==0.16.4",
|
||||
"ruff==0.17.2",
|
||||
]
|
||||
|
||||
[tool.uv]
|
||||
|
||||
Generated
+435
-329
File diff suppressed because it is too large
Load Diff
@@ -4,6 +4,7 @@ from django import forms
|
||||
from django.contrib import admin, messages
|
||||
from django.contrib.auth import admin as auth_admin
|
||||
from django.db import transaction
|
||||
from django.db.models import Exists, OuterRef
|
||||
from django.utils.html import format_html
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
@@ -46,6 +47,26 @@ class FileInline(admin.TabularInline):
|
||||
return super().get_queryset(request).filter(hard_deleted_at__isnull=True)
|
||||
|
||||
|
||||
class DuplicateEmailFilter(admin.SimpleListFilter):
|
||||
"""Filter the users whose stored email is shared with another user."""
|
||||
|
||||
title = _("duplicate email")
|
||||
parameter_name = "duplicate_email"
|
||||
|
||||
def lookups(self, request, model_admin):
|
||||
"""Return the filter options."""
|
||||
return [("yes", _("Yes"))]
|
||||
|
||||
def queryset(self, request, queryset):
|
||||
"""Keep the users sharing their email with another user."""
|
||||
if self.value() != "yes":
|
||||
return queryset
|
||||
others = models.User.objects.filter(email=OuterRef("email")).exclude(
|
||||
pk=OuterRef("pk")
|
||||
)
|
||||
return queryset.filter(Exists(others))
|
||||
|
||||
|
||||
@admin.register(models.User)
|
||||
class UserAdmin(auth_admin.UserAdmin):
|
||||
"""Admin class for the User model"""
|
||||
@@ -89,7 +110,10 @@ class UserAdmin(auth_admin.UserAdmin):
|
||||
),
|
||||
},
|
||||
),
|
||||
(_("Important dates"), {"fields": ("created_at", "updated_at")}),
|
||||
(
|
||||
_("Important dates"),
|
||||
{"fields": ("created_at", "updated_at", "last_login")},
|
||||
),
|
||||
)
|
||||
add_fieldsets = (
|
||||
(
|
||||
@@ -112,9 +136,16 @@ class UserAdmin(auth_admin.UserAdmin):
|
||||
"is_superuser",
|
||||
"is_device",
|
||||
"created_at",
|
||||
"last_login",
|
||||
"updated_at",
|
||||
)
|
||||
list_filter = ("is_staff", "is_superuser", "is_device", "is_active")
|
||||
list_filter = (
|
||||
"is_staff",
|
||||
"is_superuser",
|
||||
"is_device",
|
||||
"is_active",
|
||||
DuplicateEmailFilter,
|
||||
)
|
||||
ordering = (
|
||||
"is_active",
|
||||
"-is_superuser",
|
||||
@@ -131,9 +162,16 @@ class UserAdmin(auth_admin.UserAdmin):
|
||||
"short_name",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
"last_login",
|
||||
)
|
||||
search_fields = ("id", "sub", "admin_email", "email", "full_name")
|
||||
|
||||
def get_ordering(self, request):
|
||||
"""Group the users sharing an email when filtering on duplicates."""
|
||||
if DuplicateEmailFilter.parameter_name in request.GET:
|
||||
return ("email", "created_at")
|
||||
return super().get_ordering(request)
|
||||
|
||||
|
||||
@admin.register(models.File)
|
||||
class FileAdmin(admin.ModelAdmin):
|
||||
|
||||
@@ -86,6 +86,13 @@ def get_frontend_configuration(request):
|
||||
"enable_firefox_proxy_workaround": settings.LIVEKIT_ENABLE_FIREFOX_PROXY_WORKAROUND,
|
||||
"default_sources": settings.LIVEKIT_DEFAULT_SOURCES,
|
||||
"default_video_codec": settings.LIVEKIT_DEFAULT_VIDEO_CODEC,
|
||||
"reconnect": {
|
||||
"backoff_enabled": settings.LIVEKIT_RECONNECT_BACKOFF_ENABLED,
|
||||
"base_delay_ms": settings.LIVEKIT_RECONNECT_BASE_DELAY_MS,
|
||||
"max_delay_ms": settings.LIVEKIT_RECONNECT_MAX_DELAY_MS,
|
||||
"give_up_after_ms": settings.LIVEKIT_RECONNECT_GIVE_UP_AFTER_MS,
|
||||
"backoff_reset_ms": settings.LIVEKIT_RECONNECT_BACKOFF_RESET_MS,
|
||||
},
|
||||
},
|
||||
"allow_unregistered_rooms": settings.ALLOW_UNREGISTERED_ROOMS,
|
||||
"authenticated_users_can_edit_display_name": (
|
||||
|
||||
@@ -27,9 +27,12 @@ from timezone_field.rest_framework import TimeZoneSerializerField
|
||||
|
||||
from core import models, utils
|
||||
from core.api.exceptions import ensure_room_not_deleted
|
||||
from core.services.lobby import LobbyService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DISPLAY_NAME_MAX_LENGTH = 255
|
||||
|
||||
|
||||
class UserSerializer(serializers.ModelSerializer):
|
||||
"""Serialize users."""
|
||||
@@ -170,17 +173,18 @@ class RoomSerializer(serializers.ModelSerializer):
|
||||
return value
|
||||
|
||||
def to_representation(self, instance):
|
||||
"""
|
||||
Add users only for administrator users.
|
||||
Add LiveKit credentials for public instance or related users/groups
|
||||
"""
|
||||
"""Add accesses only for administrator and owner users."""
|
||||
output = super().to_representation(instance)
|
||||
request = self.context.get("request")
|
||||
|
||||
if not request:
|
||||
return output
|
||||
|
||||
role = instance.get_role(request.user)
|
||||
if "role" in self.context:
|
||||
role = self.context["role"]
|
||||
else:
|
||||
role = instance.get_role(request.user)
|
||||
|
||||
is_admin_or_owner = models.RoleChoices.check_administrator_role(
|
||||
role
|
||||
) or models.RoleChoices.check_owner_role(role)
|
||||
@@ -193,26 +197,9 @@ class RoomSerializer(serializers.ModelSerializer):
|
||||
)
|
||||
output["accesses"] = access_serializer.data
|
||||
|
||||
should_access_room = (
|
||||
(
|
||||
instance.access_level == models.RoomAccessLevel.TRUSTED
|
||||
and request.user.is_authenticated
|
||||
)
|
||||
or role is not None
|
||||
or instance.is_public
|
||||
)
|
||||
|
||||
if should_access_room:
|
||||
room_id = f"{instance.id!s}"
|
||||
username = request.query_params.get("username", None)
|
||||
output["livekit"] = utils.generate_livekit_config(
|
||||
room_id=room_id,
|
||||
user=request.user,
|
||||
username=username,
|
||||
configuration=output["configuration"],
|
||||
role=role,
|
||||
)
|
||||
else:
|
||||
if not LobbyService.can_bypass_lobby(
|
||||
room=instance, user=request.user, role=role
|
||||
):
|
||||
del output["pin_code"]
|
||||
|
||||
return output
|
||||
@@ -355,10 +342,23 @@ class StartRecordingSerializer(BaseValidationOnlySerializer):
|
||||
return value
|
||||
|
||||
|
||||
class JoinRoomSerializer(BaseValidationOnlySerializer):
|
||||
"""Validate the data sent to join a room."""
|
||||
|
||||
username = serializers.CharField(
|
||||
required=False,
|
||||
allow_blank=True,
|
||||
allow_null=True,
|
||||
max_length=DISPLAY_NAME_MAX_LENGTH,
|
||||
help_text="Display name in the room. The default name is used when it "
|
||||
"is missing, null or blank.",
|
||||
)
|
||||
|
||||
|
||||
class RequestEntrySerializer(BaseValidationOnlySerializer):
|
||||
"""Validate request entry data."""
|
||||
|
||||
username = serializers.CharField(required=True)
|
||||
username = serializers.CharField(required=True, max_length=DISPLAY_NAME_MAX_LENGTH)
|
||||
participant_id = serializers.CharField(
|
||||
required=False, allow_null=True, max_length=128
|
||||
)
|
||||
@@ -675,7 +675,9 @@ class RaiseHandSerializer(BaseValidationOnlySerializer):
|
||||
class RenameParticipantSerializer(BaseValidationOnlySerializer):
|
||||
"""Serializer for renaming a participant in a room."""
|
||||
|
||||
name = serializers.CharField(min_length=1, max_length=255, allow_blank=False)
|
||||
name = serializers.CharField(
|
||||
min_length=1, max_length=DISPLAY_NAME_MAX_LENGTH, allow_blank=False
|
||||
)
|
||||
|
||||
|
||||
class ExternalProcessEventSerializer(BaseValidationOnlySerializer):
|
||||
|
||||
@@ -47,6 +47,18 @@ class RoomCreationDailyUserRateThrottle(RoomCreationUserRateThrottle):
|
||||
scope = "room_creation_daily"
|
||||
|
||||
|
||||
class StartRecordingUserRateThrottle(MonitoredUserRateThrottle):
|
||||
"""Throttle recording starts per authenticated user."""
|
||||
|
||||
scope = "start_recording"
|
||||
|
||||
|
||||
class StartRecordingDailyUserRateThrottle(StartRecordingUserRateThrottle):
|
||||
"""Cap recording starts per authenticated user over a day."""
|
||||
|
||||
scope = "start_recording_daily"
|
||||
|
||||
|
||||
class RequestEntryAuthenticatedUserRateThrottle(MonitoredUserRateThrottle):
|
||||
"""Throttle authenticated user requesting room entry"""
|
||||
|
||||
|
||||
@@ -309,35 +309,35 @@ class RoomViewSet( # pylint: disable=too-many-public-methods
|
||||
ensure_room_not_deleted(obj)
|
||||
return obj
|
||||
|
||||
def _get_object_or_unregistered_slug(self):
|
||||
"""Return the requested room, or the slug of an unregistered room."""
|
||||
try:
|
||||
return self.get_object(), None
|
||||
except Http404:
|
||||
slug = slugify(self.kwargs["pk"])
|
||||
if not settings.ALLOW_UNREGISTERED_ROOMS or not slug or utils.is_uuid(slug):
|
||||
raise
|
||||
return None, slug
|
||||
|
||||
@staticmethod
|
||||
def _get_unregistered_room_data(slug):
|
||||
"""Describe an unregistered room, which only exists by its slug."""
|
||||
return {
|
||||
"id": None,
|
||||
"slug": slug,
|
||||
"access_level": RoomAccessLevel.PUBLIC,
|
||||
}
|
||||
|
||||
def retrieve(self, request, *args, **kwargs):
|
||||
"""
|
||||
Allow unregistered rooms when activated.
|
||||
For unregistered rooms we only return a null id and the livekit room and token.
|
||||
LiveKit credentials are never returned: they are obtained by joining.
|
||||
"""
|
||||
try:
|
||||
instance = self.get_object()
|
||||
except Http404:
|
||||
if not settings.ALLOW_UNREGISTERED_ROOMS:
|
||||
raise
|
||||
slug = slugify(self.kwargs["pk"])
|
||||
username = request.query_params.get("username", None)
|
||||
data = {
|
||||
"id": None,
|
||||
"slug": slug,
|
||||
"is_administrable": False,
|
||||
"access_level": RoomAccessLevel.PUBLIC,
|
||||
"livekit": {
|
||||
"url": settings.LIVEKIT_CONFIGURATION["url"],
|
||||
"room": slug,
|
||||
"token": utils.generate_token(
|
||||
room=slug, user=request.user, username=username
|
||||
),
|
||||
},
|
||||
}
|
||||
else:
|
||||
data = self.get_serializer(instance).data
|
||||
room, slug = self._get_object_or_unregistered_slug()
|
||||
if room is None:
|
||||
return drf_response.Response(self._get_unregistered_room_data(slug))
|
||||
|
||||
return drf_response.Response(data)
|
||||
return drf_response.Response(self.get_serializer(room).data)
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
"""Limit listed rooms to the ones related to the authenticated user."""
|
||||
@@ -452,6 +452,10 @@ class RoomViewSet( # pylint: disable=too-many-public-methods
|
||||
permissions.CanManageRecording,
|
||||
],
|
||||
audit_action=auditing.RECORDING_START,
|
||||
throttle_classes=[
|
||||
throttling.StartRecordingUserRateThrottle,
|
||||
throttling.StartRecordingDailyUserRateThrottle,
|
||||
],
|
||||
)
|
||||
@FeatureFlag.require("recording")
|
||||
def start_room_recording(self, request, pk=None): # pylint: disable=unused-argument
|
||||
@@ -568,6 +572,55 @@ class RoomViewSet( # pylint: disable=too-many-public-methods
|
||||
{"message": f"Recording stopped for room {room.slug}."}
|
||||
)
|
||||
|
||||
@decorators.action(
|
||||
detail=True,
|
||||
methods=["post"],
|
||||
url_path="join",
|
||||
permission_classes=[],
|
||||
)
|
||||
def join(self, request, pk=None): # pylint: disable=unused-argument
|
||||
"""
|
||||
Join a room, getting LiveKit credentials when allowed to enter directly.
|
||||
|
||||
The response contains the room with a livekit object holding the url,
|
||||
room and token to connect with when the requester may enter without
|
||||
going through the lobby. Otherwise, it has no livekit object and the
|
||||
client should request entry through the lobby.
|
||||
|
||||
Unregistered rooms, when allowed, are always joined directly.
|
||||
"""
|
||||
|
||||
serializer = serializers.JoinRoomSerializer(data=request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
username = serializer.validated_data.get("username") or None
|
||||
|
||||
room, slug = self._get_object_or_unregistered_slug()
|
||||
if room is None:
|
||||
return drf_response.Response(
|
||||
{
|
||||
**self._get_unregistered_room_data(slug),
|
||||
"livekit": utils.generate_livekit_config(
|
||||
room_id=slug, user=request.user, username=username
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
role = room.get_role(request.user)
|
||||
data = self.get_serializer(
|
||||
room, context={**self.get_serializer_context(), "role": role}
|
||||
).data
|
||||
|
||||
if LobbyService.can_bypass_lobby(room=room, user=request.user, role=role):
|
||||
data["livekit"] = utils.generate_livekit_config(
|
||||
room_id=str(room.id),
|
||||
user=request.user,
|
||||
username=username,
|
||||
configuration=data["configuration"],
|
||||
role=role,
|
||||
)
|
||||
|
||||
return drf_response.Response(data)
|
||||
|
||||
@decorators.action(
|
||||
detail=True,
|
||||
methods=["post"],
|
||||
|
||||
@@ -13,7 +13,7 @@ from lasuite.oidc_login.backends import (
|
||||
)
|
||||
from rest_framework.authentication import SessionAuthentication
|
||||
|
||||
from core.models import User
|
||||
from core.models import DuplicateEmailError, User
|
||||
from core.validators import sub_validator
|
||||
|
||||
|
||||
@@ -83,18 +83,9 @@ class OIDCAuthenticationBackend(LaSuiteOIDCAuthenticationBackend):
|
||||
) from err
|
||||
|
||||
try:
|
||||
return User.objects.get(sub=sub)
|
||||
except User.DoesNotExist:
|
||||
if email and settings.OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION:
|
||||
try:
|
||||
return User.objects.get(email__iexact=email)
|
||||
except User.DoesNotExist:
|
||||
pass
|
||||
except User.MultipleObjectsReturned as e:
|
||||
raise SuspiciousOperation(
|
||||
"Multiple user accounts share a common email."
|
||||
) from e
|
||||
return None
|
||||
return User.objects.get_user_by_sub_or_email(sub, email)
|
||||
except DuplicateEmailError as err:
|
||||
raise SuspiciousOperation(err.message) from err
|
||||
|
||||
|
||||
class SessionAuthenticationWith401(SessionAuthentication):
|
||||
|
||||
@@ -20,6 +20,7 @@ from rest_framework import authentication, exceptions
|
||||
from core import audit, auditing
|
||||
from core.models import Application, ApplicationScope
|
||||
from core.services import jwt_token
|
||||
from core.utils import normalize_email
|
||||
from core.validators import sub_validator
|
||||
|
||||
User = get_user_model()
|
||||
@@ -63,6 +64,10 @@ def get_or_create_user_by_sub(sub, email=None, *, auth_method, client_id=None):
|
||||
Shared by the resource server backends, so that tokens introspected with the
|
||||
OIDC provider or with Menshen resolve users the same way.
|
||||
|
||||
Users are never identified by email here, but a user to create is refused
|
||||
when its normalized email is already stored, unless
|
||||
OIDC_ALLOW_DUPLICATE_EMAILS is set.
|
||||
|
||||
Args:
|
||||
sub: Subject identifier from the introspected token
|
||||
email: Email to store on a newly created user
|
||||
@@ -90,12 +95,10 @@ def get_or_create_user_by_sub(sub, email=None, *, auth_method, client_id=None):
|
||||
if not settings.OIDC_CREATE_USER:
|
||||
return None
|
||||
|
||||
# Users are never identified by email here. But a second account with the
|
||||
# same email (e.g. provisionnal account) would break the lookups by email:
|
||||
# refuse it.
|
||||
normalized_email = normalize_email(email)
|
||||
existing_user = (
|
||||
User.objects.filter(email__iexact=email).first()
|
||||
if settings.OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION and email
|
||||
User.objects.filter(email=normalized_email).first()
|
||||
if normalized_email and not settings.OIDC_ALLOW_DUPLICATE_EMAILS
|
||||
else None
|
||||
)
|
||||
if existing_user is not None:
|
||||
|
||||
@@ -6,7 +6,6 @@ from django.contrib.auth import get_user_model
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
from django.db import transaction
|
||||
from django.db.models import Count
|
||||
from django.db.models.functions import Lower
|
||||
|
||||
from core.models import File, RecordingAccess, ResourceAccess, RoleChoices
|
||||
|
||||
@@ -21,14 +20,15 @@ ROLE_PRIORITY = {
|
||||
|
||||
class Command(BaseCommand):
|
||||
"""
|
||||
Merge duplicate users sharing the same email (case-insensitive) into the
|
||||
most recently created one.
|
||||
Merge duplicate users sharing the same email into the most recently
|
||||
created one.
|
||||
|
||||
Emails are compared case-insensitively, so 'John@Example.com' and
|
||||
'john@example.com' are treated as duplicates. The KEPT user is the most
|
||||
recently created. All room memberships, recording accesses and files are
|
||||
transferred to it. When a conflict exists, the higher-privilege role wins.
|
||||
Stale users are then deleted.
|
||||
Emails are stored normalized (stripped, ASCII letters lowercased) and are
|
||||
compared exactly, so 'John@Example.com' and 'john@example.com' are both
|
||||
stored as 'john@example.com' and treated as duplicates. The KEPT user is
|
||||
the most recently created. All room memberships, recording accesses and
|
||||
files are transferred to it. When a conflict exists, the higher-privilege
|
||||
role wins. Stale users are then deleted.
|
||||
Each email group is processed inside a single database transaction.
|
||||
"""
|
||||
|
||||
@@ -60,16 +60,13 @@ class Command(BaseCommand):
|
||||
users_qs = users_qs.filter(email__icontains=email_filter)
|
||||
self.stdout.write(f"[INFO] Filtering emails containing '{email_filter}'.\n")
|
||||
|
||||
# Group emails case-insensitively so 'John@X.com' and 'john@x.com'
|
||||
# are detected as duplicates of each other.
|
||||
duplicate_emails = (
|
||||
users_qs.exclude(email__isnull=True)
|
||||
.exclude(email="")
|
||||
.annotate(email_lower=Lower("email"))
|
||||
.values("email_lower")
|
||||
.values("email")
|
||||
.annotate(cnt=Count("id"))
|
||||
.filter(cnt__gt=1)
|
||||
.values_list("email_lower", flat=True)
|
||||
.values_list("email", flat=True)
|
||||
)
|
||||
|
||||
if not duplicate_emails:
|
||||
@@ -85,12 +82,9 @@ class Command(BaseCommand):
|
||||
failed_emails = []
|
||||
|
||||
for email in duplicate_emails:
|
||||
# Case-insensitive lookup to fetch every casing variant of the email.
|
||||
# Secondary sort by id ensures a stable, deterministic order when
|
||||
# created_at timestamps are equal (common in tests and bulk imports).
|
||||
users = list(
|
||||
User.objects.filter(email__iexact=email).order_by("created_at", "id")
|
||||
)
|
||||
users = list(User.objects.filter(email=email).order_by("created_at", "id"))
|
||||
kept_user = users[-1]
|
||||
stale_users = users[:-1]
|
||||
|
||||
@@ -130,10 +124,6 @@ class Command(BaseCommand):
|
||||
failed_emails.append(email)
|
||||
self.stderr.write(f"[ERROR] Failed to merge '{email}': {exc}")
|
||||
|
||||
if not kept_user.email.islower():
|
||||
kept_user.email = kept_user.email.lower()
|
||||
kept_user.save(update_fields=["email"])
|
||||
|
||||
if failed_emails:
|
||||
raise CommandError(
|
||||
f"Failed to merge {len(failed_emails)} email group(s): {', '.join(failed_emails)}"
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 5.2.17 on 2026-10-21 20:49
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('core', '0028_room_deleted_at'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='application',
|
||||
name='client_secret_sha256',
|
||||
field=models.CharField(blank=True, editable=False, max_length=255, null=True),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Store user emails stripped and ASCII-lowercased, and blank ones as NULL."""
|
||||
|
||||
import string
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
BATCH_SIZE = 500
|
||||
|
||||
_ASCII_LOWERCASE_TABLE = str.maketrans(string.ascii_uppercase, string.ascii_lowercase)
|
||||
|
||||
|
||||
def normalize_email(email):
|
||||
"""Strip an email and lowercase its ASCII letters only."""
|
||||
return (email or "").strip().translate(_ASCII_LOWERCASE_TABLE)
|
||||
|
||||
|
||||
def forwards(apps, schema_editor):
|
||||
"""Normalize the user emails, writing the changed rows in batches."""
|
||||
User = apps.get_model("core", "User")
|
||||
batch = []
|
||||
for user_id, email in User.objects.values_list("id", "email").iterator(
|
||||
chunk_size=BATCH_SIZE
|
||||
):
|
||||
normalized = normalize_email(email) or None
|
||||
if normalized == email:
|
||||
continue
|
||||
batch.append(User(id=user_id, email=normalized))
|
||||
if len(batch) == BATCH_SIZE:
|
||||
User.objects.bulk_update(batch, ["email"])
|
||||
batch = []
|
||||
if batch:
|
||||
User.objects.bulk_update(batch, ["email"])
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
atomic = False
|
||||
|
||||
dependencies = [
|
||||
("core", "0029_alter_application_client_secret_sha256"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RunPython(forwards, migrations.RunPython.noop, elidable=True),
|
||||
]
|
||||
@@ -0,0 +1,20 @@
|
||||
# Generated by Django 5.2.17 on 2026-11-10 16:28
|
||||
|
||||
import core.models
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('core', '0030_normalize_user_emails'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterModelManagers(
|
||||
name='user',
|
||||
managers=[
|
||||
('objects', core.models.UserManager()),
|
||||
],
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,26 @@
|
||||
# Generated by Django 5.2.17 on 2026-11-10 17:00
|
||||
|
||||
from django.contrib.postgres.operations import (
|
||||
AddIndexConcurrently,
|
||||
RemoveIndexConcurrently,
|
||||
)
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
atomic = False
|
||||
|
||||
dependencies = [
|
||||
('core', '0031_alter_user_managers'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
AddIndexConcurrently(
|
||||
model_name="user",
|
||||
index=models.Index(fields=["email"], name="user_email_idx"),
|
||||
),
|
||||
RemoveIndexConcurrently(
|
||||
model_name="user",
|
||||
name="user_email_upper_idx",
|
||||
),
|
||||
]
|
||||
@@ -115,6 +115,16 @@ class RoomAccessLevel(models.TextChoices):
|
||||
RESTRICTED = "restricted", _("Restricted Access")
|
||||
|
||||
|
||||
class DuplicateEmailError(Exception):
|
||||
"""Raised when an email is already associated with a pre-existing user."""
|
||||
|
||||
def __init__(self, message=None, email=None):
|
||||
"""Set message and email to describe the exception."""
|
||||
self.message = message
|
||||
self.email = email
|
||||
super().__init__(self.message)
|
||||
|
||||
|
||||
class BaseModel(models.Model):
|
||||
"""
|
||||
Serves as an abstract base model for other models, ensuring that records are validated
|
||||
@@ -152,6 +162,36 @@ class BaseModel(models.Model):
|
||||
super().save(*args, **kwargs)
|
||||
|
||||
|
||||
class UserManager(auth_models.UserManager):
|
||||
"""Custom manager for User model with additional methods."""
|
||||
|
||||
def get_user_by_sub_or_email(self, sub, email):
|
||||
"""Fetch existing user by sub or email."""
|
||||
try:
|
||||
return self.get(sub=sub)
|
||||
except self.model.DoesNotExist as err:
|
||||
if not email:
|
||||
return None
|
||||
|
||||
normalized_email = utils.normalize_email(email)
|
||||
if settings.OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION:
|
||||
users = self.filter(email=normalized_email).order_by("-is_active")[:2]
|
||||
if len(users) == 2 and users[1].is_active:
|
||||
raise DuplicateEmailError(
|
||||
"Several active users are associated with this email."
|
||||
) from err
|
||||
return users[0] if users else None
|
||||
if (
|
||||
not settings.OIDC_ALLOW_DUPLICATE_EMAILS
|
||||
and self.filter(email=normalized_email).exists()
|
||||
):
|
||||
raise DuplicateEmailError(
|
||||
"We couldn't find a user with this sub but the email is already "
|
||||
"associated with a registered user."
|
||||
) from err
|
||||
return None
|
||||
|
||||
|
||||
class User(AbstractBaseUser, BaseModel, auth_models.PermissionsMixin):
|
||||
"""User model to work with OIDC only authentication."""
|
||||
|
||||
@@ -229,7 +269,7 @@ class User(AbstractBaseUser, BaseModel, auth_models.PermissionsMixin):
|
||||
),
|
||||
)
|
||||
|
||||
objects = auth_models.UserManager()
|
||||
objects = UserManager()
|
||||
|
||||
USERNAME_FIELD = "admin_email"
|
||||
REQUIRED_FIELDS = []
|
||||
@@ -247,12 +287,21 @@ class User(AbstractBaseUser, BaseModel, auth_models.PermissionsMixin):
|
||||
)
|
||||
]
|
||||
indexes = [
|
||||
models.Index(models.functions.Upper("email"), name="user_email_upper_idx"),
|
||||
models.Index(fields=["email"], name="user_email_idx"),
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
return self.email or self.admin_email or str(self.id)
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
"""Store the email normalized, and a blank one as NULL, even on a partial save."""
|
||||
email = utils.normalize_email(self.email) or None
|
||||
update_fields = kwargs.get("update_fields")
|
||||
if update_fields is not None and email != self.email:
|
||||
kwargs["update_fields"] = {*update_fields, "email"}
|
||||
self.email = email
|
||||
super().save(*args, **kwargs)
|
||||
|
||||
def email_user(self, subject, message, from_email=None, **kwargs):
|
||||
"""Email this user."""
|
||||
if not self.email:
|
||||
|
||||
@@ -27,6 +27,9 @@ class RecordingWorkerEvent(Enum):
|
||||
COMPLETED = "completed"
|
||||
# The recording ended on its configured limit, its media file is available.
|
||||
LIMIT_REACHED = "limit reached"
|
||||
# The recording ended early without being stopped, its partial media file
|
||||
# is available.
|
||||
INTERRUPTED = "interrupted"
|
||||
# The worker stopped before it ever started recording, there is no media file.
|
||||
ABORTED = "aborted"
|
||||
# The worker hit a runtime error once recording had started; its media file
|
||||
@@ -44,6 +47,7 @@ SUCCESSFUL_EVENTS = frozenset(
|
||||
{
|
||||
RecordingWorkerEvent.COMPLETED,
|
||||
RecordingWorkerEvent.LIMIT_REACHED,
|
||||
RecordingWorkerEvent.INTERRUPTED,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ from django.conf import settings
|
||||
from django.utils.translation import get_language, gettext, gettext_noop, override
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
import aiohttp
|
||||
import requests
|
||||
from asgiref.sync import async_to_sync
|
||||
from celery.exceptions import OperationalError as CeleryOperationalError
|
||||
@@ -138,11 +137,7 @@ class NotificationService:
|
||||
if not worker_id:
|
||||
return None, None
|
||||
|
||||
custom_configuration = {
|
||||
**settings.LIVEKIT_CONFIGURATION,
|
||||
"timeout": aiohttp.ClientTimeout(total=10),
|
||||
}
|
||||
lkapi = utils.create_livekit_client(custom_configuration=custom_configuration)
|
||||
lkapi = utils.create_livekit_client()
|
||||
try:
|
||||
egress_list = await lkapi.egress.list_egress(
|
||||
livekit_api.ListEgressRequest(egress_id=worker_id) # pylint: disable=no-member
|
||||
|
||||
@@ -33,6 +33,7 @@ NOTIFICATION_PREFIXES = {
|
||||
}
|
||||
NOTIFICATION_SUFFIXES = {
|
||||
RecordingWorkerEvent.LIMIT_REACHED: "LimitReached",
|
||||
RecordingWorkerEvent.INTERRUPTED: "Interrupted",
|
||||
RecordingWorkerEvent.FAILED: "Failed",
|
||||
RecordingWorkerEvent.ABORTED: "Aborted",
|
||||
}
|
||||
@@ -61,24 +62,29 @@ class RecordingEventsService:
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def log_worker_error(recording, event, error=None, error_code=None):
|
||||
"""Log FAILED at error level and expected ABORTED outcomes at info level."""
|
||||
def log_worker_error(recording, event, error=None, error_code=None, details=None):
|
||||
"""Log FAILED at error level, INTERRUPTED at warning level and expected
|
||||
ABORTED outcomes at info level."""
|
||||
|
||||
if event == RecordingWorkerEvent.FAILED:
|
||||
log = logger.error
|
||||
elif event == RecordingWorkerEvent.INTERRUPTED:
|
||||
log = logger.warning
|
||||
elif event == RecordingWorkerEvent.ABORTED:
|
||||
log = logger.info
|
||||
else:
|
||||
return
|
||||
|
||||
log(
|
||||
"Recording worker reported %s for recording %s (room=%s, mode=%s): %s (error_code=%s)",
|
||||
"Recording worker reported %s for recording %s (room=%s, mode=%s): %s "
|
||||
"(error_code=%s, details=%s)",
|
||||
event.value,
|
||||
recording.id,
|
||||
recording.room.id,
|
||||
recording.mode,
|
||||
error or "no error reported",
|
||||
error_code or "no error_code reported",
|
||||
details or "no details reported",
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -196,6 +202,13 @@ class RecordingEventsService:
|
||||
):
|
||||
self._apply_outcome(recording, event, self._handle_limit_reached)
|
||||
|
||||
# Interrupted
|
||||
if (
|
||||
event == RecordingWorkerEvent.INTERRUPTED
|
||||
and recording.status == models.RecordingStatusChoices.ACTIVE
|
||||
):
|
||||
self._apply_outcome(recording, event, self._handle_interrupted)
|
||||
|
||||
try:
|
||||
self._handle_successful(recording)
|
||||
except RecordingNotSavableError:
|
||||
@@ -224,6 +237,20 @@ class RecordingEventsService:
|
||||
|
||||
cls._notify_participants(recording, RecordingWorkerEvent.LIMIT_REACHED)
|
||||
|
||||
@classmethod
|
||||
def _handle_interrupted(cls, recording: Recording):
|
||||
"""Stop recording and notify participants that only part of it is saved.
|
||||
|
||||
INTERRUPTED: used when the worker ended the recording early on its own
|
||||
because it lost the room or ran out of resources but kept what it had
|
||||
recorded so far
|
||||
"""
|
||||
|
||||
recording.status = models.RecordingStatusChoices.STOPPED
|
||||
recording.save()
|
||||
|
||||
cls._notify_participants(recording, RecordingWorkerEvent.INTERRUPTED)
|
||||
|
||||
@classmethod
|
||||
def _handle_failed(cls, recording: Recording):
|
||||
"""Set recording status to failed, matching the worker event, and notify participants.
|
||||
|
||||
@@ -96,6 +96,9 @@ EGRESS_STATUS_TO_RECORDING_EVENT = {
|
||||
api.EgressStatus.EGRESS_FAILED: RecordingWorkerEvent.FAILED,
|
||||
}
|
||||
|
||||
EGRESS_ROOM_CONNECTION_FAILED_ERROR = "recording ended early: connection to room failed"
|
||||
EGRESS_CPU_EXHAUSTED_DETAILS = "End reason: CPU exhausted"
|
||||
|
||||
|
||||
def to_recording_event(egress_status):
|
||||
"""Translate a LiveKit egress status into a recording worker event."""
|
||||
@@ -109,6 +112,34 @@ def to_recording_event(egress_status):
|
||||
return event
|
||||
|
||||
|
||||
def to_ended_recording_event(egress_info):
|
||||
"""Translate an ended LiveKit egress into a recording worker event.
|
||||
|
||||
This handles partial media file upload where an egress was interrupted
|
||||
which can happen when:
|
||||
- an transcription egress that lost its room connection uploads an audio file, then ends
|
||||
FAILED with the EGRESS_ROOM_CONNECTION_FAILED_ERROR
|
||||
- an egress drained because its host ran out of CPU which can transition to COMPLETE state
|
||||
with EGRESS_CPU_EXHAUSTED_DETAILS or FAILED state if the drain outlasted its grace period
|
||||
and the egress got killed, possibly before the upload.
|
||||
"""
|
||||
|
||||
status = egress_info.status
|
||||
is_cut_short = (
|
||||
egress_info.error == EGRESS_ROOM_CONNECTION_FAILED_ERROR
|
||||
or egress_info.details == EGRESS_CPU_EXHAUSTED_DETAILS
|
||||
)
|
||||
has_uploaded_file = any(file.location for file in egress_info.file_results)
|
||||
|
||||
if is_cut_short and (
|
||||
status == api.EgressStatus.EGRESS_COMPLETE
|
||||
or (status == api.EgressStatus.EGRESS_FAILED and has_uploaded_file)
|
||||
):
|
||||
return RecordingWorkerEvent.INTERRUPTED
|
||||
|
||||
return to_recording_event(status)
|
||||
|
||||
|
||||
class LiveKitEventsService:
|
||||
"""Service for processing and handling LiveKit webhook events and notifications."""
|
||||
|
||||
@@ -221,7 +252,7 @@ class LiveKitEventsService:
|
||||
f"Recording with worker ID {data.egress_info.egress_id} does not exist"
|
||||
) from err
|
||||
|
||||
event = to_recording_event(data.egress_info.status)
|
||||
event = to_ended_recording_event(data.egress_info)
|
||||
self._audit_recording_end(recording, event, data.egress_info.error_code)
|
||||
|
||||
# Log if/why the recording failed
|
||||
@@ -230,6 +261,7 @@ class LiveKitEventsService:
|
||||
event,
|
||||
error=data.egress_info.error,
|
||||
error_code=data.egress_info.error_code,
|
||||
details=data.egress_info.details,
|
||||
)
|
||||
|
||||
# Update room
|
||||
|
||||
@@ -13,6 +13,7 @@ from livekit.api import (
|
||||
MuteRoomTrackRequest,
|
||||
RoomParticipantIdentity,
|
||||
TwirpError,
|
||||
TwirpErrorCode,
|
||||
UpdateParticipantRequest,
|
||||
)
|
||||
from livekit.protocol.models import ParticipantInfo
|
||||
@@ -52,8 +53,8 @@ class ParticipantsManagement:
|
||||
)
|
||||
)
|
||||
|
||||
except TwirpError as e:
|
||||
if e.code == "not_found":
|
||||
except (TwirpError, TimeoutError) as e:
|
||||
if isinstance(e, TwirpError) and e.code == TwirpErrorCode.NOT_FOUND:
|
||||
logger.warning(
|
||||
"Participant %s not found in room %s, skipping muting",
|
||||
identity,
|
||||
@@ -95,8 +96,8 @@ class ParticipantsManagement:
|
||||
await lkapi.room.remove_participant(
|
||||
RoomParticipantIdentity(room=room_name, identity=identity)
|
||||
)
|
||||
except TwirpError as e:
|
||||
if e.code == "not_found":
|
||||
except (TwirpError, TimeoutError) as e:
|
||||
if isinstance(e, TwirpError) and e.code == TwirpErrorCode.NOT_FOUND:
|
||||
logger.warning(
|
||||
"Participant %s not found in room %s, skipping removing",
|
||||
identity,
|
||||
@@ -140,8 +141,8 @@ class ParticipantsManagement:
|
||||
)
|
||||
)
|
||||
|
||||
except TwirpError as e:
|
||||
if e.code == "not_found":
|
||||
except (TwirpError, TimeoutError) as e:
|
||||
if isinstance(e, TwirpError) and e.code == TwirpErrorCode.NOT_FOUND:
|
||||
logger.warning(
|
||||
"Participant %s not found in room %s, skipping update",
|
||||
identity,
|
||||
@@ -203,8 +204,8 @@ class ParticipantsManagement:
|
||||
identity=identity,
|
||||
)
|
||||
)
|
||||
except TwirpError as e:
|
||||
if e.code == "not_found":
|
||||
except (TwirpError, TimeoutError) as e:
|
||||
if isinstance(e, TwirpError) and e.code == TwirpErrorCode.NOT_FOUND:
|
||||
raise ParticipantNotFoundException("Participant does not exist") from e
|
||||
|
||||
logger.exception(
|
||||
|
||||
@@ -5,6 +5,7 @@ from django.core.exceptions import SuspiciousOperation, ValidationError
|
||||
from django.db import IntegrityError
|
||||
|
||||
from core import audit, auditing, models
|
||||
from core.utils import normalize_email
|
||||
|
||||
|
||||
class ProvisionalUserError(Exception):
|
||||
@@ -42,7 +43,7 @@ class ProvisionalUserService:
|
||||
def _get_by_email(self, email: str) -> models.User | None:
|
||||
"""Return the user with this email, or None if not found."""
|
||||
try:
|
||||
return models.User.objects.get(email__iexact=email)
|
||||
return models.User.objects.get(email=normalize_email(email))
|
||||
except models.User.DoesNotExist:
|
||||
return None
|
||||
except models.User.MultipleObjectsReturned as e:
|
||||
|
||||
@@ -14,6 +14,7 @@ from livekit.api import (
|
||||
DeleteRoomRequest,
|
||||
ListRoomsRequest,
|
||||
TwirpError,
|
||||
TwirpErrorCode,
|
||||
UpdateRoomMetadataRequest,
|
||||
)
|
||||
|
||||
@@ -80,8 +81,8 @@ class RoomManagement:
|
||||
)
|
||||
)
|
||||
|
||||
except TwirpError as e:
|
||||
if e.code == "not_found":
|
||||
except (TwirpError, TimeoutError) as e:
|
||||
if isinstance(e, TwirpError) and e.code == TwirpErrorCode.NOT_FOUND:
|
||||
raise RoomNotFoundException("Room does not exist") from e
|
||||
|
||||
logger.exception(
|
||||
@@ -108,8 +109,8 @@ class RoomManagement:
|
||||
try:
|
||||
await lkapi.room.delete_room(DeleteRoomRequest(room=room_name))
|
||||
logger.info("Deleted LiveKit room %s", room_name)
|
||||
except TwirpError as e:
|
||||
if e.code == "not_found":
|
||||
except (TwirpError, TimeoutError) as e:
|
||||
if isinstance(e, TwirpError) and e.code == TwirpErrorCode.NOT_FOUND:
|
||||
logger.warning(
|
||||
"Room %s not found in LiveKit, skipping deletion",
|
||||
room_name,
|
||||
|
||||
@@ -54,8 +54,8 @@ class SIPManagement:
|
||||
|
||||
try:
|
||||
await lkapi.sip.create_sip_dispatch_rule(create=request)
|
||||
except TwirpError as e:
|
||||
if e.code == TwirpErrorCode.ALREADY_EXISTS:
|
||||
except (TwirpError, TimeoutError) as e:
|
||||
if isinstance(e, TwirpError) and e.code == TwirpErrorCode.ALREADY_EXISTS:
|
||||
raise DispatchRuleConflictError("Dispatch rule already exists") from e
|
||||
logger.exception(
|
||||
"Unexpected error creating dispatch rule for room %s", room.id
|
||||
@@ -83,7 +83,7 @@ class SIPManagement:
|
||||
existing_rules = await lkapi.sip.list_sip_dispatch_rule(
|
||||
list=ListSIPDispatchRuleRequest()
|
||||
)
|
||||
except TwirpError as e:
|
||||
except (TwirpError, TimeoutError) as e:
|
||||
logger.exception("Failed to list dispatch rules for room %s", room_id)
|
||||
raise SIPException("Could not list dispatch rules") from e
|
||||
finally:
|
||||
@@ -155,7 +155,7 @@ class SIPManagement:
|
||||
|
||||
return True
|
||||
|
||||
except TwirpError as e:
|
||||
except (TwirpError, TimeoutError) as e:
|
||||
logger.exception("Failed to delete dispatch rules for room %s", room_id)
|
||||
raise SIPException("Could not delete dispatch rules") from e
|
||||
|
||||
|
||||
@@ -296,17 +296,26 @@ def test_finds_user_by_sub(django_assert_num_queries):
|
||||
|
||||
|
||||
def test_finds_user_when_email_fallback_disabled(django_assert_num_queries, settings):
|
||||
"""Should not return a user when not found by sub, and email fallback is disabled."""
|
||||
"""Should refuse a sub that is not found when its email is already used, and email
|
||||
fallback is disabled."""
|
||||
|
||||
settings.OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION = False
|
||||
settings.OIDC_ALLOW_DUPLICATE_EMAILS = False
|
||||
|
||||
klass = OIDCAuthenticationBackend()
|
||||
db_user = UserFactory(email="foo@mail.com")
|
||||
|
||||
with django_assert_num_queries(1):
|
||||
user = klass.get_existing_user("wrong-sub", db_user.email)
|
||||
|
||||
assert user is None
|
||||
with (
|
||||
django_assert_num_queries(2),
|
||||
pytest.raises(
|
||||
SuspiciousOperation,
|
||||
match=(
|
||||
"We couldn't find a user with this sub but the email is already "
|
||||
"associated with a registered user."
|
||||
),
|
||||
),
|
||||
):
|
||||
klass.get_existing_user("wrong-sub", db_user.email)
|
||||
|
||||
|
||||
def test_finds_user_when_email_is_none(django_assert_num_queries, settings):
|
||||
@@ -340,7 +349,7 @@ def test_finds_user_by_email(django_assert_num_queries, settings):
|
||||
|
||||
|
||||
def test_finds_user_case_insensitive_email(django_assert_num_queries, settings):
|
||||
"""Should match email case-insensitively when falling back to email."""
|
||||
"""Should match email ignoring ASCII case when falling back to email."""
|
||||
settings.OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION = True
|
||||
|
||||
klass = OIDCAuthenticationBackend()
|
||||
@@ -353,7 +362,7 @@ def test_finds_user_case_insensitive_email(django_assert_num_queries, settings):
|
||||
|
||||
|
||||
def test_finds_user_multiple_users_same_email(django_assert_num_queries, settings):
|
||||
"""Should handle multiple users with same email appropriately."""
|
||||
"""Should refuse to pick one of several active users sharing the email."""
|
||||
|
||||
settings.OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION = True
|
||||
|
||||
@@ -366,25 +375,178 @@ def test_finds_user_multiple_users_same_email(django_assert_num_queries, setting
|
||||
django_assert_num_queries(2),
|
||||
pytest.raises(
|
||||
SuspiciousOperation,
|
||||
match="Multiple user accounts share a common email.",
|
||||
match="Several active users are associated with this email.",
|
||||
),
|
||||
):
|
||||
klass.get_existing_user("wrong-sub", email)
|
||||
|
||||
|
||||
def test_finds_user_whitespace_email(django_assert_num_queries, settings):
|
||||
"""Should not match emails with whitespace."""
|
||||
"""Should match emails with surrounding whitespace once stripped."""
|
||||
|
||||
settings.OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION = True
|
||||
settings.OIDC_CREATE_USER = False
|
||||
|
||||
klass = OIDCAuthenticationBackend()
|
||||
UserFactory(email="foo@mail.com")
|
||||
db_user = UserFactory(email="foo@mail.com")
|
||||
|
||||
with django_assert_num_queries(2):
|
||||
user = klass.get_existing_user("wrong-sub", " foo@mail.com ")
|
||||
|
||||
assert user is None
|
||||
assert user == db_user
|
||||
|
||||
|
||||
def test_authentication_getter_existing_user_via_email_case_insensitive(
|
||||
monkeypatch, settings
|
||||
):
|
||||
"""
|
||||
If an existing user doesn't match the sub but matches the email with another
|
||||
ASCII case, the user should be returned and its email should stay normalized.
|
||||
"""
|
||||
|
||||
settings.OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION = True
|
||||
|
||||
klass = OIDCAuthenticationBackend()
|
||||
db_user = UserFactory(email="john.doe@example.com")
|
||||
|
||||
def get_userinfo_mocked(*args):
|
||||
return {"sub": "123", "email": "JOHN.DOE@EXAMPLE.COM"}
|
||||
|
||||
monkeypatch.setattr(OIDCAuthenticationBackend, "get_userinfo", get_userinfo_mocked)
|
||||
|
||||
user = klass.get_or_create_user(
|
||||
access_token="test-token", id_token=None, payload=None
|
||||
)
|
||||
|
||||
assert user == db_user
|
||||
db_user.refresh_from_db()
|
||||
assert db_user.email == "john.doe@example.com"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"email",
|
||||
[
|
||||
"dısk@example.com",
|
||||
"diſk@example.com",
|
||||
"disK@example.com",
|
||||
],
|
||||
ids=["dotless-i", "long-s", "kelvin-sign"],
|
||||
)
|
||||
@pytest.mark.parametrize("fallback", [True, False])
|
||||
def test_authentication_getter_existing_user_via_email_non_ascii(
|
||||
monkeypatch, settings, fallback, email
|
||||
):
|
||||
"""
|
||||
If an existing user doesn't match the sub and the email only matches its email
|
||||
through Unicode case folding, a new user should be created and the existing user
|
||||
should be left untouched.
|
||||
"""
|
||||
|
||||
settings.OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION = fallback
|
||||
settings.OIDC_ALLOW_DUPLICATE_EMAILS = False
|
||||
|
||||
klass = OIDCAuthenticationBackend()
|
||||
db_user = UserFactory(email="disk@example.com")
|
||||
db_sub = db_user.sub
|
||||
|
||||
def get_userinfo_mocked(*args):
|
||||
return {"sub": "other-sub", "email": email}
|
||||
|
||||
monkeypatch.setattr(OIDCAuthenticationBackend, "get_userinfo", get_userinfo_mocked)
|
||||
|
||||
user = klass.get_or_create_user(
|
||||
access_token="test-token", id_token=None, payload=None
|
||||
)
|
||||
|
||||
assert user != db_user
|
||||
assert user.sub == "other-sub"
|
||||
assert user.email == email
|
||||
assert models.User.objects.count() == 2
|
||||
db_user.refresh_from_db()
|
||||
assert db_user.sub == db_sub
|
||||
assert db_user.email == "disk@example.com"
|
||||
|
||||
|
||||
def test_authentication_getter_existing_inactive_user_via_email(monkeypatch, settings):
|
||||
"""
|
||||
If the only user matching the email is inactive, the login should be refused
|
||||
instead of creating another user.
|
||||
"""
|
||||
|
||||
settings.OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION = True
|
||||
|
||||
klass = OIDCAuthenticationBackend()
|
||||
UserFactory(email="john.doe@example.com", is_active=False)
|
||||
|
||||
def get_userinfo_mocked(*args):
|
||||
return {"sub": "123", "email": "John.Doe@example.com"}
|
||||
|
||||
monkeypatch.setattr(OIDCAuthenticationBackend, "get_userinfo", get_userinfo_mocked)
|
||||
|
||||
with pytest.raises(SuspiciousOperation, match="User account is disabled"):
|
||||
klass.get_or_create_user(access_token="test-token", id_token=None, payload=None)
|
||||
|
||||
assert models.User.objects.count() == 1
|
||||
|
||||
|
||||
def test_authentication_getter_no_fallback_to_email_no_duplicate(monkeypatch, settings):
|
||||
"""
|
||||
When the email fallback is disabled, an unknown sub whose email is already used,
|
||||
in another ASCII case, should be refused instead of creating a second user.
|
||||
"""
|
||||
|
||||
settings.OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION = False
|
||||
settings.OIDC_ALLOW_DUPLICATE_EMAILS = False
|
||||
|
||||
klass = OIDCAuthenticationBackend()
|
||||
db_user = UserFactory(email="john.doe@example.com")
|
||||
|
||||
def get_userinfo_mocked(*args):
|
||||
return {"sub": "123", "email": "JOHN.DOE@EXAMPLE.COM"}
|
||||
|
||||
monkeypatch.setattr(OIDCAuthenticationBackend, "get_userinfo", get_userinfo_mocked)
|
||||
|
||||
with pytest.raises(
|
||||
SuspiciousOperation,
|
||||
match=(
|
||||
"We couldn't find a user with this sub but the email is already "
|
||||
"associated with a registered user."
|
||||
),
|
||||
):
|
||||
klass.get_or_create_user(access_token="test-token", id_token=None, payload=None)
|
||||
|
||||
assert models.User.objects.count() == 1
|
||||
db_user.refresh_from_db()
|
||||
assert db_user.sub != "123"
|
||||
|
||||
|
||||
def test_authentication_getter_no_fallback_to_email_allow_duplicate(
|
||||
monkeypatch, settings
|
||||
):
|
||||
"""
|
||||
When the email fallback is disabled and duplicate emails are allowed, an unknown
|
||||
sub whose email is already used should get a new user.
|
||||
"""
|
||||
|
||||
settings.OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION = False
|
||||
settings.OIDC_ALLOW_DUPLICATE_EMAILS = True
|
||||
|
||||
klass = OIDCAuthenticationBackend()
|
||||
db_user = UserFactory(email="john.doe@example.com")
|
||||
|
||||
def get_userinfo_mocked(*args):
|
||||
return {"sub": "123", "email": "JOHN.DOE@EXAMPLE.COM"}
|
||||
|
||||
monkeypatch.setattr(OIDCAuthenticationBackend, "get_userinfo", get_userinfo_mocked)
|
||||
|
||||
user = klass.get_or_create_user(
|
||||
access_token="test-token", id_token=None, payload=None
|
||||
)
|
||||
|
||||
assert user != db_user
|
||||
assert user.sub == "123"
|
||||
assert user.email == "john.doe@example.com"
|
||||
assert models.User.objects.count() == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
|
||||
@@ -6,6 +6,7 @@ from concurrent.futures import ThreadPoolExecutor
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
from uuid import uuid4
|
||||
|
||||
from django.db import connection
|
||||
from django.utils import timezone
|
||||
|
||||
import pytest
|
||||
@@ -361,18 +362,21 @@ def test_api_files_create_file_race_condition():
|
||||
"""
|
||||
|
||||
def create_item(title):
|
||||
user = factories.UserFactory()
|
||||
client = APIClient()
|
||||
client.force_login(user)
|
||||
return client.post(
|
||||
"/api/v1.0/files/",
|
||||
{
|
||||
"title": title,
|
||||
"type": FileTypeChoices.BACKGROUND_IMAGE,
|
||||
"filename": "my_file.png",
|
||||
},
|
||||
format="json",
|
||||
)
|
||||
try:
|
||||
user = factories.UserFactory()
|
||||
client = APIClient()
|
||||
client.force_login(user)
|
||||
return client.post(
|
||||
"/api/v1.0/files/",
|
||||
{
|
||||
"title": title,
|
||||
"type": FileTypeChoices.BACKGROUND_IMAGE,
|
||||
"filename": "my_file.png",
|
||||
},
|
||||
format="json",
|
||||
)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
future1 = executor.submit(create_item, "my item 1")
|
||||
|
||||
@@ -5,6 +5,7 @@ from concurrent.futures import ThreadPoolExecutor
|
||||
from io import BytesIO
|
||||
|
||||
from django.core.files.storage import default_storage
|
||||
from django.db import connection
|
||||
|
||||
import pytest
|
||||
from rest_framework.test import APIClient
|
||||
@@ -295,9 +296,12 @@ def test_api_file_upload_ended_concurrent_calls_are_serialized(settings):
|
||||
default_storage.save(file.temporary_file_key, BytesIO(b"my prose"))
|
||||
|
||||
def call_upload_ended():
|
||||
client = APIClient()
|
||||
client.force_login(user)
|
||||
return client.post(f"/api/v1.0/files/{file.id!s}/upload-ended/")
|
||||
try:
|
||||
client = APIClient()
|
||||
client.force_login(user)
|
||||
return client.post(f"/api/v1.0/files/{file.id!s}/upload-ended/")
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
futures = [
|
||||
|
||||
@@ -19,6 +19,13 @@ pytestmark = pytest.mark.django_db
|
||||
# pylint: disable=W0613
|
||||
|
||||
|
||||
def _user_with_stored_email(email):
|
||||
"""Create a user storing the email as is, like the rows predating the normalization."""
|
||||
user = UserFactory()
|
||||
User.objects.filter(pk=user.pk).update(email=email)
|
||||
return user
|
||||
|
||||
|
||||
def test_merge_no_duplicates_does_nothing():
|
||||
"""Command should do nothing when no duplicate users exist."""
|
||||
user = UserFactory(email="unique@example.com")
|
||||
@@ -36,24 +43,30 @@ def test_merge_keeps_most_recently_created_user():
|
||||
assert User.objects.filter(id=user2.id).exists()
|
||||
|
||||
|
||||
def test_merge_user_case_insensitive():
|
||||
"""Emails differing only by case should be treated as duplicates and merged,
|
||||
keeping the most recently created user."""
|
||||
user1 = UserFactory(email="Dup@example.com")
|
||||
user2 = UserFactory(email="dup@example.com")
|
||||
@pytest.mark.parametrize(
|
||||
"lookalike_email",
|
||||
[
|
||||
"dısk@example.com",
|
||||
"diſk@example.com",
|
||||
"disK@example.com",
|
||||
],
|
||||
ids=["dotless-i", "long-s", "kelvin-sign"],
|
||||
)
|
||||
def test_merge_does_not_merge_lookalike_emails(lookalike_email):
|
||||
"""A user whose email only matches the duplicates' email through Unicode case
|
||||
folding should not be merged with them, even when created last."""
|
||||
user1 = UserFactory(email="disk@example.com")
|
||||
user2 = UserFactory(email="disk@example.com")
|
||||
ra = UserResourceAccessFactory(user=user1)
|
||||
lookalike = UserFactory(email=lookalike_email)
|
||||
call_command("merge_duplicate_users")
|
||||
|
||||
assert not User.objects.filter(id=user1.id).exists()
|
||||
assert User.objects.filter(id=user2.id).exists()
|
||||
|
||||
user3 = UserFactory(email="joe@example.com")
|
||||
user4 = UserFactory(email="Joe@example.com")
|
||||
call_command("merge_duplicate_users")
|
||||
assert not User.objects.filter(id=user3.id).exists()
|
||||
assert User.objects.filter(id=user4.id).exists()
|
||||
|
||||
user4.refresh_from_db()
|
||||
assert user4.email.islower()
|
||||
ra.refresh_from_db()
|
||||
assert ra.user == user2
|
||||
lookalike.refresh_from_db()
|
||||
assert lookalike.email == lookalike_email
|
||||
assert not ResourceAccess.objects.filter(user=lookalike).exists()
|
||||
|
||||
|
||||
def test_merge_deletes_all_stale_users():
|
||||
@@ -409,10 +422,11 @@ def test_merge_does_not_merge_users_with_null_email():
|
||||
assert User.objects.filter(id=user2.id).exists()
|
||||
|
||||
|
||||
def test_merge_does_not_merge_users_with_blank_email():
|
||||
"""Users with empty-string email must never be merged together, even if multiple exist."""
|
||||
user1 = UserFactory(email="")
|
||||
user2 = UserFactory(email="")
|
||||
def test_merge_does_not_merge_users_with_legacy_blank_email():
|
||||
"""Users with a legacy empty-string email must never be merged together, even if
|
||||
multiple exist."""
|
||||
user1 = _user_with_stored_email("")
|
||||
user2 = _user_with_stored_email("")
|
||||
call_command("merge_duplicate_users")
|
||||
assert User.objects.filter(id=user1.id).exists()
|
||||
assert User.objects.filter(id=user2.id).exists()
|
||||
@@ -474,7 +488,7 @@ def test_merge_email_filter_no_match_does_nothing():
|
||||
|
||||
def test_merge_email_filter_is_case_insensitive():
|
||||
"""Command should match emails case-insensitively when filtering."""
|
||||
UserFactory(email="user1@Example.com")
|
||||
UserFactory(email="user1@Example.com")
|
||||
call_command("merge_duplicate_users", email_filter="@example.com")
|
||||
UserFactory(email="user1@example.com")
|
||||
UserFactory(email="user1@example.com")
|
||||
call_command("merge_duplicate_users", email_filter="@Example.COM")
|
||||
assert User.objects.filter(email="user1@example.com").count() == 1
|
||||
|
||||
@@ -50,6 +50,26 @@ def test_handle_limit_reached_success(mock_notify, mode, notification_type, serv
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("mode", "notification_type"),
|
||||
(
|
||||
("screen_recording", "screenRecordingInterrupted"),
|
||||
("transcript", "transcriptionInterrupted"),
|
||||
),
|
||||
)
|
||||
@mock.patch("core.utils.notify_participants")
|
||||
def test_handle_interrupted_success(mock_notify, mode, notification_type, service):
|
||||
"""Test _handle_interrupted stops recording and notifies participants."""
|
||||
|
||||
recording = RecordingFactory(status="active", mode=mode)
|
||||
service._handle_interrupted(recording)
|
||||
|
||||
assert recording.status == "stopped"
|
||||
mock_notify.assert_called_once_with(
|
||||
room_name=str(recording.room.id), notification_data={"type": notification_type}
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("mode", "notification_type"),
|
||||
(
|
||||
@@ -222,6 +242,7 @@ def test_handle_update_syncs_room_metadata(
|
||||
RecordingWorkerEvent.STARTING,
|
||||
RecordingWorkerEvent.COMPLETED,
|
||||
RecordingWorkerEvent.LIMIT_REACHED,
|
||||
RecordingWorkerEvent.INTERRUPTED,
|
||||
RecordingWorkerEvent.ABORTED,
|
||||
RecordingWorkerEvent.FAILED,
|
||||
),
|
||||
@@ -244,6 +265,10 @@ def test_handle_update_ignores_events_without_a_metadata_status(
|
||||
(RecordingWorkerEvent.LIMIT_REACHED, "active", "saved", "LimitReached"),
|
||||
(RecordingWorkerEvent.LIMIT_REACHED, "stopped", "saved", None),
|
||||
(RecordingWorkerEvent.LIMIT_REACHED, "saved", "saved", None),
|
||||
(RecordingWorkerEvent.INTERRUPTED, "active", "saved", "Interrupted"),
|
||||
(RecordingWorkerEvent.INTERRUPTED, "stopped", "saved", None),
|
||||
(RecordingWorkerEvent.INTERRUPTED, "saved", "saved", None),
|
||||
(RecordingWorkerEvent.INTERRUPTED, "failed_to_stop", "failed_to_stop", None),
|
||||
(RecordingWorkerEvent.ABORTED, "active", "aborted", "Aborted"),
|
||||
(RecordingWorkerEvent.ABORTED, "failed_to_stop", "failed_to_stop", None),
|
||||
(RecordingWorkerEvent.FAILED, "active", "failed", "Failed"),
|
||||
@@ -321,6 +346,7 @@ def test_handle_terminal_event_ignores_non_terminal_events(
|
||||
("event", "expected_status"),
|
||||
(
|
||||
(RecordingWorkerEvent.LIMIT_REACHED, "saved"),
|
||||
(RecordingWorkerEvent.INTERRUPTED, "saved"),
|
||||
(RecordingWorkerEvent.ABORTED, "aborted"),
|
||||
(RecordingWorkerEvent.FAILED, "failed"),
|
||||
),
|
||||
@@ -407,6 +433,7 @@ def test_handle_update_survives_a_metadata_failure(
|
||||
("event", "expected_level"),
|
||||
(
|
||||
(RecordingWorkerEvent.ABORTED, logging.INFO),
|
||||
(RecordingWorkerEvent.INTERRUPTED, logging.WARNING),
|
||||
(RecordingWorkerEvent.FAILED, logging.ERROR),
|
||||
),
|
||||
)
|
||||
@@ -419,7 +446,11 @@ def test_log_worker_error_reports_an_unsuccessful_event(
|
||||
|
||||
with caplog.at_level(logging.INFO):
|
||||
service.log_worker_error(
|
||||
recording, event, error="could not connect to the room", error_code=500
|
||||
recording,
|
||||
event,
|
||||
error="could not connect to the room",
|
||||
error_code=500,
|
||||
details="End reason: Failure",
|
||||
)
|
||||
|
||||
assert (
|
||||
@@ -428,6 +459,7 @@ def test_log_worker_error_reports_an_unsuccessful_event(
|
||||
)
|
||||
assert "could not connect to the room" in caplog.text
|
||||
assert "error_code=500" in caplog.text
|
||||
assert "details=End reason: Failure" in caplog.text
|
||||
worker_logs = [
|
||||
record
|
||||
for record in caplog.records
|
||||
@@ -448,7 +480,7 @@ def test_log_worker_error_reports_an_unsuccessful_event(
|
||||
),
|
||||
)
|
||||
def test_log_worker_error_stays_quiet_on_anything_else(event, service, caplog):
|
||||
"""Test log_worker_error ignores events other than FAILED and ABORTED."""
|
||||
"""Test log_worker_error ignores events other than FAILED, INTERRUPTED and ABORTED."""
|
||||
|
||||
recording = RecordingFactory(status="active")
|
||||
|
||||
|
||||
@@ -66,6 +66,8 @@ def test_api_rooms_create_authenticated(reset_cache):
|
||||
assert room.name == "my room"
|
||||
assert room.slug == "my-room"
|
||||
assert room.accesses.filter(role="owner", user=user).exists() is True
|
||||
assert "livekit" not in response.json()
|
||||
assert response.json()["pin_code"] == room.pin_code
|
||||
|
||||
rooms_data = cache.keys("room-creation-callback_*")
|
||||
assert not rooms_data
|
||||
@@ -495,3 +497,4 @@ def test_api_rooms_create_authenticated_with_user_access_token():
|
||||
assert response.status_code == 201
|
||||
room = Room.objects.get()
|
||||
assert room.accesses.filter(role="owner", user=user).exists()
|
||||
assert "livekit" not in response.json()
|
||||
|
||||
@@ -0,0 +1,580 @@
|
||||
"""
|
||||
Test rooms API endpoints in the Meet core app: join.
|
||||
"""
|
||||
|
||||
# pylint: disable=redefined-outer-name
|
||||
|
||||
from unittest import mock
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.models import AnonymousUser
|
||||
from django.utils.crypto import get_random_string
|
||||
|
||||
import jwt
|
||||
import pytest
|
||||
from faker import Faker
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from ...factories import (
|
||||
RoomFactory,
|
||||
UserFactory,
|
||||
UserResourceAccessFactory,
|
||||
)
|
||||
from ...models import RoleChoices, RoomAccessLevel
|
||||
from ..utils import generate_user_access_token
|
||||
|
||||
fake = Faker()
|
||||
pytestmark = pytest.mark.django_db
|
||||
|
||||
livekit_token = fake.sha256()
|
||||
|
||||
ANONYMOUS = "anonymous"
|
||||
NO_ROLE = "no-role"
|
||||
|
||||
# Who may join a room directly, without going through the lobby
|
||||
# room.get_role(user) returns None both for an anonymous user and for an
|
||||
# authenticated user without access, hence the NO_ROLE
|
||||
ACCESS_MATRIX = [
|
||||
(RoomAccessLevel.PUBLIC, ANONYMOUS, True),
|
||||
(RoomAccessLevel.TRUSTED, ANONYMOUS, False),
|
||||
(RoomAccessLevel.RESTRICTED, ANONYMOUS, False),
|
||||
(RoomAccessLevel.PUBLIC, NO_ROLE, True),
|
||||
(RoomAccessLevel.TRUSTED, NO_ROLE, True),
|
||||
(RoomAccessLevel.RESTRICTED, NO_ROLE, False),
|
||||
*[
|
||||
(access_level, role, True)
|
||||
for access_level in RoomAccessLevel
|
||||
for role in RoleChoices
|
||||
],
|
||||
]
|
||||
|
||||
|
||||
def decode_token(token):
|
||||
"""Decode a LiveKit access token for inspection."""
|
||||
return jwt.decode(
|
||||
token,
|
||||
settings.LIVEKIT_CONFIGURATION["api_secret"],
|
||||
algorithms=["HS256"],
|
||||
)
|
||||
|
||||
|
||||
def join_url(room_id):
|
||||
"""Return the url to join a room."""
|
||||
return f"/api/v1.0/rooms/{room_id!s}/join/"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("access_level", "requester", "can_join_directly"), ACCESS_MATRIX
|
||||
)
|
||||
@mock.patch("core.utils.generate_token", return_value=livekit_token)
|
||||
def test_api_rooms_join_access(mock_token, access_level, requester, can_join_directly):
|
||||
"""
|
||||
Joining a room should return LiveKit credentials and the pin code only to
|
||||
users who may enter without going through the lobby, and the accesses
|
||||
only to the room's administrators and owners.
|
||||
"""
|
||||
room = RoomFactory(
|
||||
access_level=access_level,
|
||||
configuration={"can_publish_sources": ["camera"]},
|
||||
)
|
||||
client = APIClient()
|
||||
user = AnonymousUser()
|
||||
username = fake.user_name()
|
||||
|
||||
role = None
|
||||
if requester != ANONYMOUS:
|
||||
user = UserFactory()
|
||||
client.force_login(user)
|
||||
if requester != NO_ROLE:
|
||||
role = requester
|
||||
UserResourceAccessFactory(resource=room, user=user, role=role)
|
||||
|
||||
response = client.post(join_url(room.id), {"username": username}, format="json")
|
||||
|
||||
assert response.status_code == 200
|
||||
content = response.json()
|
||||
|
||||
accesses = content.pop("accesses", None)
|
||||
|
||||
if role in (RoleChoices.ADMIN, RoleChoices.OWNER):
|
||||
assert {access["id"] for access in accesses} == {
|
||||
str(access.id) for access in room.accesses.all()
|
||||
}
|
||||
else:
|
||||
assert accesses is None
|
||||
|
||||
expected = {
|
||||
"id": str(room.id),
|
||||
"name": room.name,
|
||||
"slug": room.slug,
|
||||
"configuration": {"can_publish_sources": ["camera"]},
|
||||
"access_level": str(access_level),
|
||||
}
|
||||
if can_join_directly:
|
||||
expected["pin_code"] = room.pin_code
|
||||
expected["livekit"] = {
|
||||
"url": settings.LIVEKIT_CONFIGURATION["url"],
|
||||
"room": str(room.id),
|
||||
"token": livekit_token,
|
||||
}
|
||||
assert content == expected
|
||||
|
||||
if can_join_directly:
|
||||
mock_token.assert_called_once_with(
|
||||
room=str(room.id),
|
||||
user=user,
|
||||
username=username,
|
||||
color=None,
|
||||
sources=["camera"],
|
||||
role=role,
|
||||
participant_id=None,
|
||||
)
|
||||
else:
|
||||
mock_token.assert_not_called()
|
||||
|
||||
|
||||
@mock.patch("core.utils.generate_token", return_value=livekit_token)
|
||||
def test_api_rooms_join_by_slug(mock_token):
|
||||
"""It should be possible to join a room by its slug, not normalized."""
|
||||
room = RoomFactory(name="Réunion", access_level=RoomAccessLevel.PUBLIC)
|
||||
|
||||
response = APIClient().post(join_url("Réunion"), {}, format="json")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["id"] == str(room.id)
|
||||
assert response.json()["livekit"]["room"] == str(room.id)
|
||||
mock_token.assert_called_once()
|
||||
|
||||
|
||||
@mock.patch("core.utils.generate_token", return_value=livekit_token)
|
||||
def test_api_rooms_join_members_num_queries(mock_token, django_assert_num_queries):
|
||||
"""The role of the requester should only be looked up once."""
|
||||
user = UserFactory()
|
||||
room = RoomFactory(access_level=RoomAccessLevel.RESTRICTED)
|
||||
UserResourceAccessFactory(resource=room, user=user, role=RoleChoices.MEMBER)
|
||||
client = APIClient()
|
||||
client.force_login(user)
|
||||
|
||||
with django_assert_num_queries(3):
|
||||
response = client.post(join_url(room.id), {}, format="json")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert "livekit" in response.json()
|
||||
assert mock_token.call_args.kwargs["role"] == RoleChoices.MEMBER
|
||||
|
||||
|
||||
@pytest.mark.parametrize("role", [RoleChoices.ADMIN, RoleChoices.OWNER])
|
||||
@mock.patch("core.utils.generate_token", return_value=livekit_token)
|
||||
def test_api_rooms_join_administrators_num_queries(
|
||||
mock_token, role, django_assert_num_queries
|
||||
):
|
||||
"""Only the accesses should be queried on top of the role for administrators."""
|
||||
user = UserFactory()
|
||||
room = RoomFactory(access_level=RoomAccessLevel.RESTRICTED)
|
||||
UserResourceAccessFactory(resource=room, user=user, role=role)
|
||||
client = APIClient()
|
||||
client.force_login(user)
|
||||
|
||||
with django_assert_num_queries(4):
|
||||
response = client.post(join_url(room.id), {}, format="json")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert "livekit" in response.json()
|
||||
assert "accesses" in response.json()
|
||||
assert mock_token.call_args.kwargs["role"] == role
|
||||
|
||||
|
||||
def test_api_rooms_join_get_not_allowed():
|
||||
"""Joining a room should only be possible with a POST request."""
|
||||
room = RoomFactory(access_level=RoomAccessLevel.PUBLIC)
|
||||
|
||||
response = APIClient().get(join_url(room.id))
|
||||
|
||||
assert response.status_code == 405
|
||||
|
||||
|
||||
@pytest.mark.parametrize("authenticated", [False, True])
|
||||
@mock.patch("core.utils.generate_token", return_value=livekit_token)
|
||||
def test_api_rooms_join_unregistered_allowed(mock_token, authenticated, settings):
|
||||
"""
|
||||
Joining an unregistered room should return LiveKit credentials for the
|
||||
room named after the slug, when unregistered rooms are allowed.
|
||||
"""
|
||||
settings.ALLOW_UNREGISTERED_ROOMS = True
|
||||
client = APIClient()
|
||||
user = AnonymousUser()
|
||||
username = fake.user_name()
|
||||
if authenticated:
|
||||
user = UserFactory()
|
||||
client.force_login(user)
|
||||
|
||||
response = client.post(
|
||||
join_url("unregistered-room"), {"username": username}, format="json"
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {
|
||||
"id": None,
|
||||
"slug": "unregistered-room",
|
||||
"access_level": "public",
|
||||
"livekit": {
|
||||
"url": settings.LIVEKIT_CONFIGURATION["url"],
|
||||
"room": "unregistered-room",
|
||||
"token": livekit_token,
|
||||
},
|
||||
}
|
||||
mock_token.assert_called_once_with(
|
||||
room="unregistered-room",
|
||||
user=user,
|
||||
username=username,
|
||||
color=None,
|
||||
sources=None,
|
||||
role=None,
|
||||
participant_id=None,
|
||||
)
|
||||
|
||||
|
||||
@mock.patch("core.utils.generate_token", return_value=livekit_token)
|
||||
def test_api_rooms_join_unregistered_allowed_not_normalized(mock_token, settings):
|
||||
"""
|
||||
Joining an unregistered room by a slug that is not normalized should use
|
||||
the LiveKit room named after the url-safe slug.
|
||||
"""
|
||||
settings.ALLOW_UNREGISTERED_ROOMS = True
|
||||
|
||||
response = APIClient().post(join_url("Réunion"), {}, format="json")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {
|
||||
"id": None,
|
||||
"slug": "reunion",
|
||||
"access_level": "public",
|
||||
"livekit": {
|
||||
"url": settings.LIVEKIT_CONFIGURATION["url"],
|
||||
"room": "reunion",
|
||||
"token": livekit_token,
|
||||
},
|
||||
}
|
||||
mock_token.assert_called_once_with(
|
||||
room="reunion",
|
||||
user=AnonymousUser(),
|
||||
username=None,
|
||||
color=None,
|
||||
sources=None,
|
||||
role=None,
|
||||
participant_id=None,
|
||||
)
|
||||
|
||||
|
||||
def test_api_rooms_join_unregistered_token_claims(settings):
|
||||
"""The token of an unregistered room should be scoped to it and carry the name."""
|
||||
settings.ALLOW_UNREGISTERED_ROOMS = True
|
||||
username = fake.user_name()
|
||||
|
||||
response = APIClient().post(
|
||||
join_url("unregistered-room"), {"username": username}, format="json"
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
claims = decode_token(response.json()["livekit"]["token"])
|
||||
assert claims["name"] == username
|
||||
assert claims["video"]["room"] == "unregistered-room"
|
||||
|
||||
|
||||
@mock.patch("core.utils.generate_token", return_value=livekit_token)
|
||||
def test_api_rooms_join_unregistered_not_allowed(mock_token, settings):
|
||||
"""
|
||||
Joining an unregistered room should return a 404 if unregistered rooms
|
||||
are not allowed.
|
||||
"""
|
||||
settings.ALLOW_UNREGISTERED_ROOMS = False
|
||||
|
||||
response = APIClient().post(join_url("unregistered-room"), {}, format="json")
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.json() == {"detail": "No Room matches the given query."}
|
||||
mock_token.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lookup", ["---", "!!!", "_"])
|
||||
@mock.patch("core.utils.generate_token", return_value=livekit_token)
|
||||
def test_api_rooms_join_unregistered_empty_slug(mock_token, lookup, settings):
|
||||
"""
|
||||
Joining an unregistered room whose slug is empty once normalized should
|
||||
return a 404 rather than credentials for a room with no name.
|
||||
"""
|
||||
settings.ALLOW_UNREGISTERED_ROOMS = True
|
||||
|
||||
response = APIClient().post(join_url(lookup), {}, format="json")
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.json() == {"detail": "No Room matches the given query."}
|
||||
mock_token.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("template", ["{}!", "_{}", "{}~", "{}!!"])
|
||||
@pytest.mark.parametrize(
|
||||
"access_level", [RoomAccessLevel.TRUSTED, RoomAccessLevel.RESTRICTED]
|
||||
)
|
||||
@mock.patch("core.utils.generate_token", return_value=livekit_token)
|
||||
def test_api_rooms_join_unregistered_uuid_slug(
|
||||
mock_token, access_level, template, settings
|
||||
):
|
||||
"""
|
||||
Joining an unregistered room whose slug is a UUID once normalized should
|
||||
return a 404 rather than credentials for the registered room with that id.
|
||||
"""
|
||||
settings.ALLOW_UNREGISTERED_ROOMS = True
|
||||
room = RoomFactory(access_level=access_level)
|
||||
|
||||
response = APIClient().post(
|
||||
join_url(template.format(str(room.id).upper())), {}, format="json"
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.json() == {"detail": "No Room matches the given query."}
|
||||
mock_token.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("allow_unregistered_rooms", [True, False])
|
||||
@pytest.mark.parametrize("lookup", ["id", "slug"])
|
||||
@mock.patch("core.utils.generate_token", return_value=livekit_token)
|
||||
def test_api_rooms_join_soft_deleted(
|
||||
mock_token, lookup, allow_unregistered_rooms, settings
|
||||
):
|
||||
"""
|
||||
Joining a soft-deleted room should return a 410, and never fall back
|
||||
to an unregistered room with the same slug.
|
||||
"""
|
||||
settings.ALLOW_UNREGISTERED_ROOMS = allow_unregistered_rooms
|
||||
room = RoomFactory(access_level=RoomAccessLevel.PUBLIC)
|
||||
room.soft_delete()
|
||||
|
||||
response = APIClient().post(join_url(getattr(room, lookup)), {}, format="json")
|
||||
|
||||
assert response.status_code == 410
|
||||
assert response.json() == {"detail": "This room has been deleted."}
|
||||
mock_token.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("payload", "expected_username"),
|
||||
[
|
||||
({"username": "Jean Bon"}, "Jean Bon"),
|
||||
({"username": " Jean Bon "}, "Jean Bon"),
|
||||
({"username": "x" * 255}, "x" * 255),
|
||||
({}, None),
|
||||
({"username": None}, None),
|
||||
({"username": ""}, None),
|
||||
({"username": " "}, None),
|
||||
],
|
||||
)
|
||||
@mock.patch("core.utils.generate_token", return_value=livekit_token)
|
||||
def test_api_rooms_join_username(mock_token, payload, expected_username):
|
||||
"""
|
||||
The trimmed display name should be passed on to the token, a missing or
|
||||
blank one leaving the default name to the token generation.
|
||||
"""
|
||||
room = RoomFactory(access_level=RoomAccessLevel.PUBLIC)
|
||||
|
||||
response = APIClient().post(join_url(room.id), payload, format="json")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["livekit"]["token"] == livekit_token
|
||||
assert mock_token.call_args.kwargs["username"] == expected_username
|
||||
|
||||
|
||||
@mock.patch("core.utils.generate_token", return_value=livekit_token)
|
||||
def test_api_rooms_join_username_too_long(mock_token):
|
||||
"""A display name exceeding 255 characters should be rejected."""
|
||||
room = RoomFactory(access_level=RoomAccessLevel.PUBLIC)
|
||||
|
||||
response = APIClient().post(
|
||||
join_url(room.id), {"username": "a" * 256}, format="json"
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json() == {
|
||||
"username": ["Ensure this field has no more than 255 characters."]
|
||||
}
|
||||
mock_token.assert_not_called()
|
||||
|
||||
|
||||
@mock.patch("core.utils.generate_token", return_value=livekit_token)
|
||||
def test_api_rooms_join_username_in_query_string_ignored(mock_token):
|
||||
"""The display name should only be read from the request body."""
|
||||
room = RoomFactory(access_level=RoomAccessLevel.PUBLIC)
|
||||
username = fake.user_name()
|
||||
|
||||
response = APIClient().post(
|
||||
f"{join_url(room.id)}?username={username}", {}, format="json"
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert mock_token.call_args.kwargs["username"] is None
|
||||
|
||||
|
||||
def test_api_rooms_join_token_claims_anonymous():
|
||||
"""The token should carry the submitted display name and be scoped to the room."""
|
||||
room = RoomFactory(access_level=RoomAccessLevel.PUBLIC)
|
||||
username = fake.user_name()
|
||||
|
||||
response = APIClient().post(
|
||||
join_url(room.id), {"username": username}, format="json"
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
claims = decode_token(response.json()["livekit"]["token"])
|
||||
assert claims["name"] == username
|
||||
assert claims["video"]["room"] == str(room.id)
|
||||
assert claims["video"]["roomAdmin"] is False
|
||||
|
||||
|
||||
def test_api_rooms_join_token_claims_anonymous_default_name():
|
||||
"""An anonymous user joining without a display name should get the default one."""
|
||||
room = RoomFactory(access_level=RoomAccessLevel.PUBLIC)
|
||||
|
||||
response = APIClient().post(join_url(room.id), {"username": ""}, format="json")
|
||||
|
||||
assert response.status_code == 200
|
||||
claims = decode_token(response.json()["livekit"]["token"])
|
||||
assert claims["name"] == "Anonymous"
|
||||
|
||||
|
||||
def test_api_rooms_join_token_claims_owner():
|
||||
"""The token of an owner should carry the submitted name and the room admin grant."""
|
||||
username = fake.user_name()
|
||||
user = UserFactory(full_name=fake.name())
|
||||
room = RoomFactory(access_level=RoomAccessLevel.RESTRICTED, users=[(user, "owner")])
|
||||
client = APIClient()
|
||||
client.force_login(user)
|
||||
|
||||
response = client.post(join_url(room.id), {"username": username}, format="json")
|
||||
|
||||
assert response.status_code == 200
|
||||
claims = decode_token(response.json()["livekit"]["token"])
|
||||
assert claims["name"] == username
|
||||
assert claims["sub"] == str(user.sub)
|
||||
assert claims["video"]["roomAdmin"] is True
|
||||
|
||||
|
||||
def test_api_rooms_join_display_name_edit_disabled(settings):
|
||||
"""
|
||||
An authenticated user should keep their account's name when display name
|
||||
edition is disabled, whatever name they submit.
|
||||
"""
|
||||
settings.AUTHENTICATED_PARTICIPANTS_CAN_EDIT_DISPLAY_NAME = False
|
||||
full_name = f"{fake.first_name()} {fake.last_name()}"
|
||||
user = UserFactory(full_name=full_name)
|
||||
room = RoomFactory(access_level=RoomAccessLevel.PUBLIC)
|
||||
client = APIClient()
|
||||
client.force_login(user)
|
||||
|
||||
response = client.post(join_url(room.id), {"username": "Impostor"}, format="json")
|
||||
|
||||
assert response.status_code == 200
|
||||
claims = decode_token(response.json()["livekit"]["token"])
|
||||
assert claims["name"] == full_name
|
||||
|
||||
|
||||
def test_api_rooms_join_display_name_edit_disabled_anonymous(settings):
|
||||
"""Anonymous users should still choose their display name when edition is disabled."""
|
||||
settings.AUTHENTICATED_PARTICIPANTS_CAN_EDIT_DISPLAY_NAME = False
|
||||
username = fake.user_name()
|
||||
room = RoomFactory(access_level=RoomAccessLevel.PUBLIC)
|
||||
|
||||
response = APIClient().post(
|
||||
join_url(room.id), {"username": username}, format="json"
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
claims = decode_token(response.json()["livekit"]["token"])
|
||||
assert claims["name"] == username
|
||||
|
||||
|
||||
def test_api_rooms_join_session_without_csrf_token():
|
||||
"""A session-authenticated request without a CSRF token should be rejected."""
|
||||
user = UserFactory()
|
||||
room = RoomFactory(access_level=RoomAccessLevel.PUBLIC)
|
||||
client = APIClient(enforce_csrf_checks=True)
|
||||
client.force_login(user)
|
||||
|
||||
response = client.post(join_url(room.id), {"username": "Jane"}, format="json")
|
||||
|
||||
assert response.status_code == 403
|
||||
assert response.json()["detail"].startswith("CSRF Failed")
|
||||
|
||||
|
||||
def test_api_rooms_join_session_with_csrf_token():
|
||||
"""A session-authenticated request with a valid CSRF token should be accepted."""
|
||||
user = UserFactory()
|
||||
room = RoomFactory(access_level=RoomAccessLevel.PUBLIC)
|
||||
client = APIClient(enforce_csrf_checks=True)
|
||||
client.force_login(user)
|
||||
csrf_secret = get_random_string(32)
|
||||
client.cookies[settings.CSRF_COOKIE_NAME] = csrf_secret
|
||||
|
||||
response = client.post(
|
||||
join_url(room.id),
|
||||
{"username": "Jane"},
|
||||
format="json",
|
||||
HTTP_X_CSRFTOKEN=csrf_secret,
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert "livekit" in response.json()
|
||||
|
||||
|
||||
def test_api_rooms_join_session_with_csrf_token_foreign_origin():
|
||||
"""A session-authenticated request from a foreign origin should be rejected."""
|
||||
user = UserFactory()
|
||||
room = RoomFactory(access_level=RoomAccessLevel.PUBLIC)
|
||||
client = APIClient(enforce_csrf_checks=True)
|
||||
client.force_login(user)
|
||||
csrf_secret = get_random_string(32)
|
||||
client.cookies[settings.CSRF_COOKIE_NAME] = csrf_secret
|
||||
|
||||
response = client.post(
|
||||
join_url(room.id),
|
||||
{"username": "Jane"},
|
||||
format="json",
|
||||
HTTP_X_CSRFTOKEN=csrf_secret,
|
||||
HTTP_ORIGIN="https://evil.example",
|
||||
)
|
||||
|
||||
assert response.status_code == 403
|
||||
assert response.json()["detail"].startswith("CSRF Failed: Origin checking failed")
|
||||
|
||||
|
||||
def test_api_rooms_join_anonymous_without_csrf_token():
|
||||
"""
|
||||
An anonymous request carries no ambient credential, so it should not be
|
||||
subject to CSRF checks.
|
||||
"""
|
||||
room = RoomFactory(access_level=RoomAccessLevel.PUBLIC)
|
||||
client = APIClient(enforce_csrf_checks=True)
|
||||
|
||||
response = client.post(join_url(room.id), {"username": "Anonymous"}, format="json")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert "livekit" in response.json()
|
||||
|
||||
|
||||
def test_api_rooms_join_user_access_token_without_csrf_token():
|
||||
"""
|
||||
A request authenticated with a user access token carries no ambient
|
||||
credential, so it should not be subject to CSRF checks.
|
||||
"""
|
||||
username = fake.user_name()
|
||||
user = UserFactory()
|
||||
room = RoomFactory(access_level=RoomAccessLevel.RESTRICTED, users=[(user, "owner")])
|
||||
client = APIClient(enforce_csrf_checks=True)
|
||||
client.credentials(HTTP_AUTHORIZATION=f"Bearer {generate_user_access_token(user)}")
|
||||
|
||||
response = client.post(join_url(room.id), {"username": username}, format="json")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["pin_code"] == room.pin_code
|
||||
assert "accesses" in response.json()
|
||||
claims = decode_token(response.json()["livekit"]["token"])
|
||||
assert claims["sub"] == str(user.sub)
|
||||
@@ -61,6 +61,7 @@ def test_api_rooms_list_authenticated():
|
||||
}
|
||||
results_id = {result["id"] for result in results}
|
||||
assert expected_ids == results_id
|
||||
assert all("livekit" not in result for result in results)
|
||||
|
||||
|
||||
@mock.patch.object(PageNumberPagination, "get_page_size", return_value=2)
|
||||
@@ -172,3 +173,4 @@ def test_api_rooms_list_authenticated_with_user_access_token():
|
||||
assert response.status_code == 200
|
||||
assert response.data["count"] == 1
|
||||
assert response.data["results"][0]["id"] == str(room.id)
|
||||
assert "livekit" not in response.data["results"][0]
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
Test rooms API endpoints in the Meet core app: lobby functionality.
|
||||
"""
|
||||
|
||||
# pylint: disable=W0621,W0613,W0212
|
||||
# pylint: disable=W0621,W0613,W0212,too-many-lines
|
||||
import uuid
|
||||
from unittest import mock
|
||||
|
||||
@@ -360,6 +360,40 @@ def test_request_entry_invalid_data():
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_request_entry_username_too_long():
|
||||
"""Should return 400 for a username exceeding 255 characters."""
|
||||
room = RoomFactory(access_level=RoomAccessLevel.RESTRICTED)
|
||||
client = APIClient()
|
||||
|
||||
with mock.patch.object(utils, "notify_participants") as mock_notify:
|
||||
response = client.post(
|
||||
f"/api/v1.0/rooms/{room.id}/request-entry/",
|
||||
{"username": "a" * 256},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json() == {
|
||||
"username": ["Ensure this field has no more than 255 characters."]
|
||||
}
|
||||
mock_notify.assert_not_called()
|
||||
assert not LobbyService()._index_members(room.id)
|
||||
|
||||
|
||||
def test_request_entry_username_at_max_length():
|
||||
"""Should accept a username of exactly 255 characters."""
|
||||
room = RoomFactory(access_level=RoomAccessLevel.RESTRICTED)
|
||||
client = APIClient()
|
||||
|
||||
with mock.patch.object(utils, "notify_participants", return_value=None):
|
||||
response = client.post(
|
||||
f"/api/v1.0/rooms/{room.id}/request-entry/",
|
||||
{"username": "a" * 255},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["username"] == "a" * 255
|
||||
|
||||
|
||||
def test_request_entry_room_not_found():
|
||||
"""Should return 404 for non-existent room."""
|
||||
client = APIClient()
|
||||
|
||||
@@ -782,7 +782,7 @@ def test_update_participant_invalid_permission():
|
||||
"loc": ["invalid-attributes"],
|
||||
"msg": "Extra inputs are not permitted",
|
||||
"input": "True",
|
||||
"url": "https://errors.pydantic.dev/2.13/v/extra_forbidden",
|
||||
"url": "https://errors.pydantic.dev/2.14/v/extra_forbidden",
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
@@ -366,6 +366,22 @@ def test_rename_participant_name_too_long(room, token):
|
||||
assert "name" in response.data
|
||||
|
||||
|
||||
def test_rename_participant_name_at_max_length(mock_livekit_client, room, token):
|
||||
"""Test rename accepts a name of exactly 255 characters."""
|
||||
client = APIClient()
|
||||
url = reverse("rooms-rename", kwargs={"pk": room.id})
|
||||
response = client.post(
|
||||
url,
|
||||
{"name": "a" * 255},
|
||||
format="json",
|
||||
HTTP_AUTHORIZATION=f"X-LiveKit-Token {token}",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
call_kwargs = mock_livekit_client.room.update_participant.call_args
|
||||
assert call_kwargs[0][0].name == "a" * 255
|
||||
|
||||
|
||||
def test_rename_participant_forbidden_without_token(room):
|
||||
"""Test rename returns 403 when no LiveKit token is provided."""
|
||||
client = APIClient()
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
"""
|
||||
Test rooms API endpoints in the Meet core app: retrieve.
|
||||
"""
|
||||
"""Test rooms API endpoints in the Meet core app: retrieve."""
|
||||
|
||||
import random
|
||||
from unittest import mock
|
||||
|
||||
from django.contrib.auth.models import AnonymousUser
|
||||
from django.test.utils import override_settings
|
||||
from django.utils import timezone as dj_timezone
|
||||
|
||||
@@ -112,18 +109,11 @@ def test_api_rooms_retrieve_anonymous_private_slug_not_normalized():
|
||||
|
||||
|
||||
@override_settings(ALLOW_UNREGISTERED_ROOMS=True)
|
||||
@override_settings(
|
||||
LIVEKIT_CONFIGURATION={
|
||||
"api_key": "key",
|
||||
"api_secret": "secret",
|
||||
"url": "test_url_value",
|
||||
}
|
||||
)
|
||||
@mock.patch("core.utils.generate_token", return_value="foo")
|
||||
def test_api_rooms_retrieve_anonymous_unregistered_allowed(mock_token):
|
||||
"""
|
||||
Retrieving an unregistered room should return a Livekit token
|
||||
if unregistered rooms are allowed.
|
||||
Retrieving an unregistered room should describe it if unregistered rooms
|
||||
are allowed, without any LiveKit token: those are obtained by joining.
|
||||
"""
|
||||
client = APIClient()
|
||||
response = client.get("/api/v1.0/rooms/unregistered-room/")
|
||||
@@ -133,32 +123,17 @@ def test_api_rooms_retrieve_anonymous_unregistered_allowed(mock_token):
|
||||
"id": None,
|
||||
"slug": "unregistered-room",
|
||||
"access_level": "public",
|
||||
"is_administrable": False,
|
||||
"livekit": {
|
||||
"url": "test_url_value",
|
||||
"room": "unregistered-room",
|
||||
"token": "foo",
|
||||
},
|
||||
}
|
||||
|
||||
mock_token.assert_called_once_with(
|
||||
room="unregistered-room", user=AnonymousUser(), username=None
|
||||
)
|
||||
mock_token.assert_not_called()
|
||||
|
||||
|
||||
@override_settings(ALLOW_UNREGISTERED_ROOMS=True)
|
||||
@override_settings(
|
||||
LIVEKIT_CONFIGURATION={
|
||||
"api_key": "key",
|
||||
"api_secret": "secret",
|
||||
"url": "test_url_value",
|
||||
}
|
||||
)
|
||||
@mock.patch("core.utils.generate_token", return_value="foo")
|
||||
def test_api_rooms_retrieve_anonymous_unregistered_allowed_not_normalized(mock_token):
|
||||
"""
|
||||
Getting an unregistered room by a slug that is not normalized should work
|
||||
and use the Livekit room on the url-safe name.
|
||||
and return the url-safe slug.
|
||||
"""
|
||||
client = APIClient()
|
||||
response = client.get("/api/v1.0/rooms/Réunion/")
|
||||
@@ -168,17 +143,9 @@ def test_api_rooms_retrieve_anonymous_unregistered_allowed_not_normalized(mock_t
|
||||
"id": None,
|
||||
"slug": "reunion",
|
||||
"access_level": "public",
|
||||
"is_administrable": False,
|
||||
"livekit": {
|
||||
"url": "test_url_value",
|
||||
"room": "reunion",
|
||||
"token": "foo",
|
||||
},
|
||||
}
|
||||
|
||||
mock_token.assert_called_once_with(
|
||||
room="reunion", user=AnonymousUser(), username=None
|
||||
)
|
||||
mock_token.assert_not_called()
|
||||
|
||||
|
||||
@override_settings(ALLOW_UNREGISTERED_ROOMS=False)
|
||||
@@ -193,6 +160,36 @@ def test_api_rooms_retrieve_anonymous_unregistered_not_allowed():
|
||||
assert response.json() == {"detail": "No Room matches the given query."}
|
||||
|
||||
|
||||
@override_settings(ALLOW_UNREGISTERED_ROOMS=True)
|
||||
@pytest.mark.parametrize("lookup", ["---", "!!!", "_"])
|
||||
def test_api_rooms_retrieve_anonymous_unregistered_empty_slug(lookup):
|
||||
"""
|
||||
Retrieving an unregistered room whose slug is empty once normalized should
|
||||
return a 404.
|
||||
"""
|
||||
client = APIClient()
|
||||
response = client.get(f"/api/v1.0/rooms/{lookup}/")
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.json() == {"detail": "No Room matches the given query."}
|
||||
|
||||
|
||||
@override_settings(ALLOW_UNREGISTERED_ROOMS=True)
|
||||
@pytest.mark.parametrize("template", ["{}!", "_{}", "{}~"])
|
||||
def test_api_rooms_retrieve_anonymous_unregistered_uuid_slug(template):
|
||||
"""
|
||||
Retrieving an unregistered room whose slug is a UUID once normalized should
|
||||
return a 404.
|
||||
"""
|
||||
room = RoomFactory(access_level=RoomAccessLevel.RESTRICTED)
|
||||
|
||||
client = APIClient()
|
||||
response = client.get(f"/api/v1.0/rooms/{template.format(room.id)}/")
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.json() == {"detail": "No Room matches the given query."}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("allow_unregistered_rooms", [True, False])
|
||||
@pytest.mark.parametrize("lookup", ["id", "slug"])
|
||||
@mock.patch("core.utils.generate_token", return_value="foo")
|
||||
@@ -216,52 +213,33 @@ def test_api_rooms_retrieve_soft_deleted(
|
||||
|
||||
|
||||
@mock.patch("core.utils.generate_token", return_value="foo")
|
||||
@override_settings(
|
||||
LIVEKIT_CONFIGURATION={
|
||||
"api_key": "key",
|
||||
"api_secret": "secret",
|
||||
"url": "test_url_value",
|
||||
}
|
||||
)
|
||||
def test_api_rooms_retrieve_anonymous_public(mock_token):
|
||||
"""
|
||||
Anonymous users should be able to retrieve a room with a token provided, if the room is public.
|
||||
Anonymous users should be able to retrieve a public room with its pin code,
|
||||
but should not be given any token: those are obtained by joining.
|
||||
"""
|
||||
room = RoomFactory(access_level=RoomAccessLevel.PUBLIC)
|
||||
client = APIClient()
|
||||
response = client.get(f"/api/v1.0/rooms/{room.id!s}/")
|
||||
|
||||
assert response.status_code == 200
|
||||
expected_name = f"{room.id!s}"
|
||||
assert response.json() == {
|
||||
"configuration": {},
|
||||
"access_level": str(room.access_level),
|
||||
"id": str(room.id),
|
||||
"livekit": {
|
||||
"url": "test_url_value",
|
||||
"room": expected_name,
|
||||
"token": "foo",
|
||||
},
|
||||
"name": room.name,
|
||||
"pin_code": room.pin_code,
|
||||
"slug": room.slug,
|
||||
}
|
||||
|
||||
mock_token.assert_called_once()
|
||||
mock_token.assert_not_called()
|
||||
|
||||
|
||||
@mock.patch("core.utils.generate_token", return_value="foo")
|
||||
@override_settings(
|
||||
LIVEKIT_CONFIGURATION={
|
||||
"api_key": "key",
|
||||
"api_secret": "secret",
|
||||
"url": "test_url_value",
|
||||
}
|
||||
)
|
||||
def test_api_rooms_retrieve_authenticated_public(mock_token):
|
||||
"""
|
||||
Authenticated users should be allowed to retrieve a room and get a token for a room to
|
||||
which they are not related, provided the room is public.
|
||||
Authenticated users should be allowed to retrieve a public room to which
|
||||
they are not related, with its pin code but without any token.
|
||||
They should not see related users.
|
||||
"""
|
||||
room = RoomFactory(
|
||||
@@ -278,44 +256,23 @@ def test_api_rooms_retrieve_authenticated_public(mock_token):
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
expected_name = f"{room.id!s}"
|
||||
assert response.json() == {
|
||||
"configuration": {"can_publish_sources": ["camera"]},
|
||||
"access_level": str(room.access_level),
|
||||
"id": str(room.id),
|
||||
"livekit": {
|
||||
"url": "test_url_value",
|
||||
"room": expected_name,
|
||||
"token": "foo",
|
||||
},
|
||||
"name": room.name,
|
||||
"pin_code": room.pin_code,
|
||||
"slug": room.slug,
|
||||
}
|
||||
|
||||
mock_token.assert_called_once_with(
|
||||
room=expected_name,
|
||||
user=user,
|
||||
username=None,
|
||||
color=None,
|
||||
sources=["camera"],
|
||||
role=None,
|
||||
participant_id=None,
|
||||
)
|
||||
mock_token.assert_not_called()
|
||||
|
||||
|
||||
@mock.patch("core.utils.generate_token", return_value="foo")
|
||||
@override_settings(
|
||||
LIVEKIT_CONFIGURATION={
|
||||
"api_key": "key",
|
||||
"api_secret": "secret",
|
||||
"url": "test_url_value",
|
||||
}
|
||||
)
|
||||
def test_api_rooms_retrieve_authenticated_trusted(mock_token):
|
||||
"""
|
||||
Authenticated users should be allowed to retrieve a room and get a token for a room to
|
||||
which they are not related, provided the room has a trusted access_level.
|
||||
Authenticated users should be allowed to retrieve a trusted room to which
|
||||
they are not related, with its pin code but without any token.
|
||||
They should not see related users.
|
||||
"""
|
||||
room = RoomFactory(access_level=RoomAccessLevel.TRUSTED)
|
||||
@@ -329,30 +286,16 @@ def test_api_rooms_retrieve_authenticated_trusted(mock_token):
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
expected_name = f"{room.id!s}"
|
||||
assert response.json() == {
|
||||
"configuration": {},
|
||||
"access_level": str(room.access_level),
|
||||
"id": str(room.id),
|
||||
"livekit": {
|
||||
"url": "test_url_value",
|
||||
"room": expected_name,
|
||||
"token": "foo",
|
||||
},
|
||||
"name": room.name,
|
||||
"pin_code": room.pin_code,
|
||||
"slug": room.slug,
|
||||
}
|
||||
|
||||
mock_token.assert_called_once_with(
|
||||
room=expected_name,
|
||||
user=user,
|
||||
username=None,
|
||||
color=None,
|
||||
sources=None,
|
||||
role=None,
|
||||
participant_id=None,
|
||||
)
|
||||
mock_token.assert_not_called()
|
||||
|
||||
|
||||
def test_api_rooms_retrieve_authenticated():
|
||||
@@ -381,13 +324,6 @@ def test_api_rooms_retrieve_authenticated():
|
||||
|
||||
|
||||
@mock.patch("core.utils.generate_token", return_value="foo")
|
||||
@override_settings(
|
||||
LIVEKIT_CONFIGURATION={
|
||||
"api_key": "key",
|
||||
"api_secret": "secret",
|
||||
"url": "test_url_value",
|
||||
}
|
||||
)
|
||||
def test_api_rooms_retrieve_members(mock_token, django_assert_num_queries, settings):
|
||||
"""
|
||||
Users who are members of a room should not be allowed to see related users.
|
||||
@@ -415,40 +351,19 @@ def test_api_rooms_retrieve_members(mock_token, django_assert_num_queries, setti
|
||||
|
||||
assert "accesses" not in content_dict
|
||||
|
||||
expected_name = str(room.id)
|
||||
assert content_dict == {
|
||||
"configuration": {"can_publish_sources": ["camera"]},
|
||||
"access_level": str(room.access_level),
|
||||
"id": str(room.id),
|
||||
"livekit": {
|
||||
"url": "test_url_value",
|
||||
"room": expected_name,
|
||||
"token": "foo",
|
||||
},
|
||||
"name": room.name,
|
||||
"pin_code": room.pin_code,
|
||||
"slug": room.slug,
|
||||
}
|
||||
|
||||
mock_token.assert_called_once_with(
|
||||
room=expected_name,
|
||||
user=user,
|
||||
username=None,
|
||||
color=None,
|
||||
sources=["camera"],
|
||||
role=str(RoleChoices.MEMBER),
|
||||
participant_id=None,
|
||||
)
|
||||
mock_token.assert_not_called()
|
||||
|
||||
|
||||
@mock.patch("core.utils.generate_token", return_value="foo")
|
||||
@override_settings(
|
||||
LIVEKIT_CONFIGURATION={
|
||||
"api_key": "key",
|
||||
"api_secret": "secret",
|
||||
"url": "test_url_value",
|
||||
}
|
||||
)
|
||||
def test_api_rooms_retrieve_administrators(
|
||||
mock_token, django_assert_num_queries, settings
|
||||
):
|
||||
@@ -511,30 +426,16 @@ def test_api_rooms_retrieve_administrators(
|
||||
],
|
||||
key=lambda x: x["id"],
|
||||
)
|
||||
expected_name = str(room.id)
|
||||
assert content_dict == {
|
||||
"access_level": str(room.access_level),
|
||||
"id": str(room.id),
|
||||
"configuration": {},
|
||||
"livekit": {
|
||||
"url": "test_url_value",
|
||||
"room": expected_name,
|
||||
"token": "foo",
|
||||
},
|
||||
"name": room.name,
|
||||
"pin_code": room.pin_code,
|
||||
"slug": room.slug,
|
||||
}
|
||||
|
||||
mock_token.assert_called_once_with(
|
||||
room=expected_name,
|
||||
user=user,
|
||||
username=None,
|
||||
color=None,
|
||||
sources=None,
|
||||
role=str(user_access.role),
|
||||
participant_id=None,
|
||||
)
|
||||
mock_token.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("access_level", RoomAccessLevel)
|
||||
@@ -567,3 +468,77 @@ def test_api_rooms_retrieve_authenticated_with_user_access_token():
|
||||
assert response.data["id"] == str(room.id)
|
||||
assert response.data["pin_code"] == room.pin_code
|
||||
assert "accesses" in response.data
|
||||
assert "livekit" not in response.data
|
||||
|
||||
|
||||
@pytest.mark.parametrize("access_level", RoomAccessLevel)
|
||||
@pytest.mark.parametrize("role", [None, *RoleChoices])
|
||||
@mock.patch("core.utils.generate_token", return_value="foo")
|
||||
def test_api_rooms_retrieve_never_returns_livekit_credentials(
|
||||
mock_token, role, access_level
|
||||
):
|
||||
"""Retrieving a room should never mint a LiveKit token."""
|
||||
room = RoomFactory(access_level=access_level)
|
||||
user = UserFactory()
|
||||
if role is not None:
|
||||
UserResourceAccessFactory(resource=room, user=user, role=role)
|
||||
client = APIClient()
|
||||
client.force_login(user)
|
||||
|
||||
response = client.get(f"/api/v1.0/rooms/{room.id!s}/")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert "livekit" not in response.json()
|
||||
mock_token.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("access_level", RoomAccessLevel)
|
||||
@mock.patch("core.utils.generate_token", return_value="foo")
|
||||
def test_api_rooms_retrieve_anonymous_never_returns_livekit_credentials(
|
||||
mock_token, access_level
|
||||
):
|
||||
"""An anonymous user should never get a LiveKit token by retrieving a room."""
|
||||
room = RoomFactory(access_level=access_level)
|
||||
|
||||
response = APIClient().get(f"/api/v1.0/rooms/{room.id!s}/")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert "livekit" not in response.json()
|
||||
mock_token.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("access_level", "authenticated", "role", "pin_code_exposed"),
|
||||
[
|
||||
(RoomAccessLevel.PUBLIC, False, None, True),
|
||||
(RoomAccessLevel.TRUSTED, False, None, False),
|
||||
(RoomAccessLevel.RESTRICTED, False, None, False),
|
||||
(RoomAccessLevel.PUBLIC, True, None, True),
|
||||
(RoomAccessLevel.TRUSTED, True, None, True),
|
||||
(RoomAccessLevel.RESTRICTED, True, None, False),
|
||||
(RoomAccessLevel.RESTRICTED, True, RoleChoices.MEMBER, True),
|
||||
(RoomAccessLevel.RESTRICTED, True, RoleChoices.ADMIN, True),
|
||||
(RoomAccessLevel.RESTRICTED, True, RoleChoices.OWNER, True),
|
||||
],
|
||||
)
|
||||
def test_api_rooms_retrieve_pin_code_exposure(
|
||||
access_level, authenticated, role, pin_code_exposed
|
||||
):
|
||||
"""
|
||||
The pin code should only be exposed to users who may join the room
|
||||
without going through the lobby.
|
||||
"""
|
||||
room = RoomFactory(access_level=access_level)
|
||||
client = APIClient()
|
||||
if authenticated:
|
||||
user = UserFactory()
|
||||
if role is not None:
|
||||
UserResourceAccessFactory(resource=room, user=user, role=role)
|
||||
client.force_login(user)
|
||||
|
||||
response = client.get(f"/api/v1.0/rooms/{room.id!s}/")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert ("pin_code" in response.json()) is pin_code_exposed
|
||||
if pin_code_exposed:
|
||||
assert response.json()["pin_code"] == room.pin_code
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
"""
|
||||
Test rooms API endpoints in the Meet core app: start recording throttling.
|
||||
"""
|
||||
|
||||
# pylint: disable=redefined-outer-name,unused-argument
|
||||
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from ...api.throttling import (
|
||||
StartRecordingDailyUserRateThrottle,
|
||||
StartRecordingUserRateThrottle,
|
||||
)
|
||||
from ...factories import RoomFactory, UserFactory
|
||||
from ...models import Recording
|
||||
|
||||
pytestmark = pytest.mark.django_db
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def start_recording_throttle(monkeypatch):
|
||||
"""Lower the start recording rates."""
|
||||
rates = StartRecordingUserRateThrottle.THROTTLE_RATES
|
||||
monkeypatch.setitem(rates, "start_recording", "2/minute")
|
||||
monkeypatch.setitem(rates, "start_recording_daily", "100/day")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def daily_start_recording_throttle(monkeypatch):
|
||||
"""Lower the daily start recording rate and control the clock."""
|
||||
rates = StartRecordingDailyUserRateThrottle.THROTTLE_RATES
|
||||
monkeypatch.setitem(rates, "start_recording", "100/minute")
|
||||
monkeypatch.setitem(rates, "start_recording_daily", "3/day")
|
||||
now = [1_000_000.0]
|
||||
monkeypatch.setattr(StartRecordingUserRateThrottle, "timer", lambda self: now[0])
|
||||
return now
|
||||
|
||||
|
||||
@mock.patch("core.api.viewsets.WorkerServiceMediator")
|
||||
@mock.patch("core.api.viewsets.get_worker_service")
|
||||
def test_start_recording_throttled(
|
||||
mock_get_worker_service, mock_mediator_class, start_recording_throttle, settings
|
||||
):
|
||||
"""Starting a recording should return 429 when exceeding the per-minute rate."""
|
||||
settings.RECORDING_ENABLE = True
|
||||
user = UserFactory()
|
||||
client = APIClient()
|
||||
client.force_login(user)
|
||||
|
||||
for _ in range(2):
|
||||
room = RoomFactory(users=[(user, "owner")])
|
||||
response = client.post(
|
||||
f"/api/v1.0/rooms/{room.id}/start-recording/",
|
||||
{"mode": "screen_recording"},
|
||||
)
|
||||
assert response.status_code == 201
|
||||
|
||||
room = RoomFactory(users=[(user, "owner")])
|
||||
response = client.post(
|
||||
f"/api/v1.0/rooms/{room.id}/start-recording/",
|
||||
{"mode": "screen_recording"},
|
||||
)
|
||||
|
||||
assert response.status_code == 429
|
||||
assert 0 < int(response["Retry-After"]) <= 60
|
||||
assert Recording.objects.count() == 2
|
||||
assert mock_mediator_class.return_value.start.call_count == 2
|
||||
|
||||
|
||||
@mock.patch("core.api.viewsets.WorkerServiceMediator")
|
||||
@mock.patch("core.api.viewsets.get_worker_service")
|
||||
def test_start_recording_throttle_counts_failed_attempts(
|
||||
mock_get_worker_service, mock_mediator_class, start_recording_throttle, settings
|
||||
):
|
||||
"""Failed recording starts should count toward the rate."""
|
||||
settings.RECORDING_ENABLE = True
|
||||
user = UserFactory()
|
||||
room = RoomFactory(users=[(user, "owner")])
|
||||
Recording.objects.create(room=room, mode="screen_recording", status="active")
|
||||
client = APIClient()
|
||||
client.force_login(user)
|
||||
|
||||
for _ in range(2):
|
||||
response = client.post(
|
||||
f"/api/v1.0/rooms/{room.id}/start-recording/",
|
||||
{"mode": "screen_recording"},
|
||||
)
|
||||
assert response.status_code == 409
|
||||
|
||||
response = client.post(
|
||||
f"/api/v1.0/rooms/{room.id}/start-recording/",
|
||||
{"mode": "screen_recording"},
|
||||
)
|
||||
|
||||
assert response.status_code == 429
|
||||
|
||||
|
||||
@mock.patch("core.api.viewsets.WorkerServiceMediator")
|
||||
@mock.patch("core.api.viewsets.get_worker_service")
|
||||
def test_start_recording_throttle_per_user(
|
||||
mock_get_worker_service, mock_mediator_class, start_recording_throttle, settings
|
||||
):
|
||||
"""Starting a recording should succeed when another user is throttled."""
|
||||
settings.RECORDING_ENABLE = True
|
||||
client = APIClient()
|
||||
|
||||
user = UserFactory()
|
||||
client.force_login(user)
|
||||
for _ in range(2):
|
||||
room = RoomFactory(users=[(user, "owner")])
|
||||
response = client.post(
|
||||
f"/api/v1.0/rooms/{room.id}/start-recording/",
|
||||
{"mode": "screen_recording"},
|
||||
)
|
||||
assert response.status_code == 201
|
||||
|
||||
room = RoomFactory(users=[(user, "owner")])
|
||||
response = client.post(
|
||||
f"/api/v1.0/rooms/{room.id}/start-recording/",
|
||||
{"mode": "screen_recording"},
|
||||
)
|
||||
assert response.status_code == 429
|
||||
|
||||
other_user = UserFactory()
|
||||
client.force_login(other_user)
|
||||
room = RoomFactory(users=[(other_user, "owner")])
|
||||
response = client.post(
|
||||
f"/api/v1.0/rooms/{room.id}/start-recording/",
|
||||
{"mode": "screen_recording"},
|
||||
)
|
||||
|
||||
assert response.status_code == 201
|
||||
|
||||
|
||||
@mock.patch("core.api.viewsets.WorkerServiceMediator")
|
||||
@mock.patch("core.api.viewsets.get_worker_service")
|
||||
def test_start_recording_throttle_does_not_limit_other_actions(
|
||||
mock_get_worker_service, mock_mediator_class, start_recording_throttle, settings
|
||||
):
|
||||
"""Other room actions should succeed when starting a recording is throttled."""
|
||||
settings.RECORDING_ENABLE = True
|
||||
user = UserFactory()
|
||||
client = APIClient()
|
||||
client.force_login(user)
|
||||
|
||||
rooms = RoomFactory.create_batch(3, users=[(user, "owner")])
|
||||
for room in rooms[:2]:
|
||||
response = client.post(
|
||||
f"/api/v1.0/rooms/{room.id}/start-recording/",
|
||||
{"mode": "screen_recording"},
|
||||
)
|
||||
assert response.status_code == 201
|
||||
|
||||
response = client.post(
|
||||
f"/api/v1.0/rooms/{rooms[2].id}/start-recording/",
|
||||
{"mode": "screen_recording"},
|
||||
)
|
||||
assert response.status_code == 429
|
||||
|
||||
Recording.objects.filter(room=rooms[0]).update(status="active")
|
||||
response = client.post(f"/api/v1.0/rooms/{rooms[0].id}/stop-recording/")
|
||||
assert response.status_code == 200
|
||||
|
||||
response = client.get("/api/v1.0/rooms/")
|
||||
assert response.status_code == 200
|
||||
|
||||
response = client.post("/api/v1.0/rooms/", {"name": "New room"})
|
||||
assert response.status_code == 201
|
||||
|
||||
|
||||
@mock.patch("core.api.viewsets.WorkerServiceMediator")
|
||||
@mock.patch("core.api.viewsets.get_worker_service")
|
||||
def test_start_recording_daily_throttled(
|
||||
mock_get_worker_service,
|
||||
mock_mediator_class,
|
||||
daily_start_recording_throttle,
|
||||
settings,
|
||||
):
|
||||
"""Starting a recording should return 429 when exceeding the daily rate."""
|
||||
settings.RECORDING_ENABLE = True
|
||||
now = daily_start_recording_throttle
|
||||
user = UserFactory()
|
||||
client = APIClient()
|
||||
client.force_login(user)
|
||||
|
||||
for _ in range(3):
|
||||
room = RoomFactory(users=[(user, "owner")])
|
||||
response = client.post(
|
||||
f"/api/v1.0/rooms/{room.id}/start-recording/",
|
||||
{"mode": "screen_recording"},
|
||||
)
|
||||
assert response.status_code == 201
|
||||
now[0] += 120
|
||||
|
||||
room = RoomFactory(users=[(user, "owner")])
|
||||
response = client.post(
|
||||
f"/api/v1.0/rooms/{room.id}/start-recording/",
|
||||
{"mode": "screen_recording"},
|
||||
)
|
||||
assert response.status_code == 429
|
||||
assert 60 < int(response["Retry-After"]) <= 86400
|
||||
|
||||
now[0] += 86400
|
||||
room = RoomFactory(users=[(user, "owner")])
|
||||
response = client.post(
|
||||
f"/api/v1.0/rooms/{room.id}/start-recording/",
|
||||
{"mode": "screen_recording"},
|
||||
)
|
||||
|
||||
assert response.status_code == 201
|
||||
@@ -113,6 +113,7 @@ def test_api_rooms_update_administrators(mock_update_metadata):
|
||||
format="json",
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert "livekit" not in response.json()
|
||||
room.refresh_from_db()
|
||||
assert room.name == "New name"
|
||||
assert room.slug == "new-name"
|
||||
@@ -467,6 +468,7 @@ def test_api_rooms_update_authenticated_with_user_access_token(privileged_role):
|
||||
room.accesses.filter(user=user).update(role=privileged_role)
|
||||
response = client.patch(f"/api/v1.0/rooms/{room.id!s}/", {"name": "new name"})
|
||||
assert response.status_code == 200
|
||||
assert "livekit" not in response.json()
|
||||
room.refresh_from_db()
|
||||
assert room.name == "new name"
|
||||
|
||||
|
||||
@@ -8,9 +8,12 @@ import hashlib
|
||||
import json
|
||||
from unittest import mock
|
||||
|
||||
from django.utils import timezone
|
||||
|
||||
import pytest
|
||||
from livekit import api
|
||||
|
||||
from ...factories import RecordingFactory
|
||||
from ...services.livekit_events import ActionFailedError, LiveKitEventsService
|
||||
|
||||
|
||||
@@ -184,3 +187,75 @@ def test_action_error(client, mock_livekit_config):
|
||||
content_type="application/json",
|
||||
HTTP_AUTHORIZATION=auth_token,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@mock.patch(
|
||||
"core.recording.services.recording_events.notification_service."
|
||||
"notify_external_services",
|
||||
return_value=False,
|
||||
)
|
||||
@mock.patch("core.utils.notify_participants")
|
||||
@mock.patch("core.services.room_management.RoomManagement.update_metadata")
|
||||
def test_egress_ended_keeps_a_partial_transcript(
|
||||
mock_update_metadata,
|
||||
mock_notify,
|
||||
mock_notify_external_services,
|
||||
client,
|
||||
mock_livekit_config,
|
||||
):
|
||||
"""Should save a transcript whose egress lost the room but uploaded its file.
|
||||
|
||||
LiveKit Egress v1.14 reports it as failed. The payload mirrors the one it
|
||||
sends, including a field unknown to the pinned livekit-protocol, which
|
||||
must be ignored rather than rejected.
|
||||
"""
|
||||
recording = RecordingFactory(
|
||||
worker_id="EG_hycBMAjmt6Ub", mode="transcript", status="active"
|
||||
)
|
||||
event_data = json.dumps(
|
||||
{
|
||||
"event": "egress_ended",
|
||||
"egressInfo": {
|
||||
"egressId": "EG_hycBMAjmt6Ub",
|
||||
"roomId": "RM_hycBMAjmt6Ub",
|
||||
"roomName": str(recording.room.id),
|
||||
"status": "EGRESS_FAILED",
|
||||
"error": "recording ended early: connection to room failed",
|
||||
"errorCode": 503,
|
||||
"details": "End reason: Source closed",
|
||||
"fileResults": [
|
||||
{
|
||||
"filename": f"recordings/{recording.id}.ogg",
|
||||
"location": f"https://s3.example.com/recordings/{recording.id}.ogg",
|
||||
"size": "123456",
|
||||
}
|
||||
],
|
||||
},
|
||||
"id": "EV_eugWmGhovZmm",
|
||||
"createdAt": str(int(timezone.now().timestamp())),
|
||||
}
|
||||
)
|
||||
hash64 = base64.b64encode(hashlib.sha256(event_data.encode()).digest()).decode()
|
||||
token = api.AccessToken(
|
||||
mock_livekit_config["api_key"], mock_livekit_config["api_secret"]
|
||||
)
|
||||
token.claims.sha256 = hash64
|
||||
|
||||
response = client.post(
|
||||
"/api/v1.0/rooms/webhooks-livekit/",
|
||||
data=event_data,
|
||||
content_type="application/json",
|
||||
HTTP_AUTHORIZATION=token.to_jwt(),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_notify.assert_called_once_with(
|
||||
room_name=str(recording.room.id),
|
||||
notification_data={"type": "transcriptionInterrupted"},
|
||||
)
|
||||
mock_notify_external_services.assert_called_once_with(recording)
|
||||
|
||||
recording.refresh_from_db()
|
||||
|
||||
assert recording.status == "saved"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
Test LiveKitEvents service.
|
||||
"""
|
||||
# pylint: disable=W0621,W0613, W0212, E0611, C0302
|
||||
# pylint: disable=W0621,W0613, W0212, E0611, E1101, C0302
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
@@ -11,6 +11,7 @@ from unittest import mock
|
||||
from django.utils import timezone
|
||||
|
||||
import pytest
|
||||
from faker import Faker
|
||||
from livekit.api import EgressStatus
|
||||
|
||||
from core.audit.testing import find_events
|
||||
@@ -19,12 +20,15 @@ from core.models import Room
|
||||
from core.recording.enums import RecordingWorkerEvent
|
||||
from core.recording.services.recording_events import RecordingEventsService
|
||||
from core.services.livekit_events import (
|
||||
EGRESS_CPU_EXHAUSTED_DETAILS,
|
||||
EGRESS_ROOM_CONNECTION_FAILED_ERROR,
|
||||
EGRESS_STATUS_TO_RECORDING_EVENT,
|
||||
ActionFailedError,
|
||||
AuthenticationError,
|
||||
InvalidPayloadError,
|
||||
LiveKitEventsService,
|
||||
api,
|
||||
to_ended_recording_event,
|
||||
to_recording_event,
|
||||
)
|
||||
from core.services.lobby import LobbyService
|
||||
@@ -39,6 +43,7 @@ from core.services.sip_management import (
|
||||
from core.utils import NotificationError
|
||||
|
||||
pytestmark = pytest.mark.django_db
|
||||
fake = Faker()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -494,6 +499,228 @@ def test_to_recording_event_returns_none_on_unmapped_status(caplog):
|
||||
assert "Unmapped LiveKit egress status" in caplog.text
|
||||
|
||||
|
||||
recording_filename = f"recordings/{fake.file_name(extension='ogg')}"
|
||||
|
||||
UPLOADED_FILE = api.FileInfo(
|
||||
filename=recording_filename,
|
||||
location=f"https://storage.example.com/{recording_filename}",
|
||||
size=1048576,
|
||||
)
|
||||
NOT_UPLOADED_FILE = api.FileInfo(filename=recording_filename)
|
||||
|
||||
ROOM_CONNECTION_FAILED = {
|
||||
"status": EgressStatus.EGRESS_FAILED,
|
||||
"error": EGRESS_ROOM_CONNECTION_FAILED_ERROR,
|
||||
"error_code": 503,
|
||||
"details": "End reason: Source closed",
|
||||
}
|
||||
CPU_EXHAUSTED_DRAINED = {
|
||||
"status": EgressStatus.EGRESS_COMPLETE,
|
||||
"details": EGRESS_CPU_EXHAUSTED_DETAILS,
|
||||
}
|
||||
CPU_EXHAUSTED_KILLED = {
|
||||
"status": EgressStatus.EGRESS_FAILED,
|
||||
"error": "CPU exhausted: 8.5 cores used",
|
||||
"error_code": 403,
|
||||
"details": EGRESS_CPU_EXHAUSTED_DETAILS,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("egress_info", "expected_event"),
|
||||
(
|
||||
(
|
||||
api.EgressInfo(**ROOM_CONNECTION_FAILED, file_results=[UPLOADED_FILE]),
|
||||
RecordingWorkerEvent.INTERRUPTED,
|
||||
),
|
||||
(
|
||||
api.EgressInfo(**ROOM_CONNECTION_FAILED, file_results=[NOT_UPLOADED_FILE]),
|
||||
RecordingWorkerEvent.FAILED,
|
||||
),
|
||||
(
|
||||
api.EgressInfo(**CPU_EXHAUSTED_DRAINED, file_results=[UPLOADED_FILE]),
|
||||
RecordingWorkerEvent.INTERRUPTED,
|
||||
),
|
||||
(
|
||||
api.EgressInfo(**CPU_EXHAUSTED_KILLED, file_results=[UPLOADED_FILE]),
|
||||
RecordingWorkerEvent.INTERRUPTED,
|
||||
),
|
||||
(
|
||||
api.EgressInfo(**CPU_EXHAUSTED_KILLED, file_results=[NOT_UPLOADED_FILE]),
|
||||
RecordingWorkerEvent.FAILED,
|
||||
),
|
||||
# Other failures stay failures, even with an uploaded file.
|
||||
(
|
||||
api.EgressInfo(
|
||||
status=EgressStatus.EGRESS_FAILED,
|
||||
error="pipeline frozen",
|
||||
error_code=500,
|
||||
details="End reason: Source closed",
|
||||
file_results=[UPLOADED_FILE],
|
||||
),
|
||||
RecordingWorkerEvent.FAILED,
|
||||
),
|
||||
(
|
||||
api.EgressInfo(
|
||||
status=EgressStatus.EGRESS_COMPLETE,
|
||||
details="End reason: StopEgress API",
|
||||
file_results=[UPLOADED_FILE],
|
||||
),
|
||||
RecordingWorkerEvent.COMPLETED,
|
||||
),
|
||||
(
|
||||
api.EgressInfo(
|
||||
status=EgressStatus.EGRESS_ABORTED,
|
||||
error="Stop called before pipeline could start",
|
||||
error_code=412,
|
||||
details="End reason: StopEgress API",
|
||||
),
|
||||
RecordingWorkerEvent.ABORTED,
|
||||
),
|
||||
(
|
||||
api.EgressInfo(
|
||||
status=EgressStatus.EGRESS_LIMIT_REACHED,
|
||||
error="Session limit reached",
|
||||
error_code=413,
|
||||
details="End reason: Session limit reached",
|
||||
file_results=[UPLOADED_FILE],
|
||||
),
|
||||
RecordingWorkerEvent.LIMIT_REACHED,
|
||||
),
|
||||
),
|
||||
)
|
||||
def test_to_ended_recording_event_translates_egress_info(egress_info, expected_event):
|
||||
"""Should tell an egress cut short with a partial file apart from the others."""
|
||||
|
||||
assert to_ended_recording_event(egress_info) == expected_event
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("mode", "egress_info_kwargs", "notification_type"),
|
||||
(
|
||||
("transcript", ROOM_CONNECTION_FAILED, "transcriptionInterrupted"),
|
||||
("transcript", CPU_EXHAUSTED_DRAINED, "transcriptionInterrupted"),
|
||||
("screen_recording", CPU_EXHAUSTED_DRAINED, "screenRecordingInterrupted"),
|
||||
("screen_recording", CPU_EXHAUSTED_KILLED, "screenRecordingInterrupted"),
|
||||
),
|
||||
)
|
||||
@mock.patch(
|
||||
"core.recording.services.recording_events.notification_service."
|
||||
"notify_external_services"
|
||||
)
|
||||
@mock.patch("core.utils.notify_participants")
|
||||
@mock.patch("core.services.room_management.RoomManagement.update_metadata")
|
||||
def test_handle_egress_ended_interrupted_saves_partial_recording( # noqa: PLR0913, PLR0917
|
||||
mock_update_metadata,
|
||||
mock_notify,
|
||||
mock_notify_external_services,
|
||||
mode,
|
||||
egress_info_kwargs,
|
||||
notification_type,
|
||||
service,
|
||||
caplog,
|
||||
): # pylint: disable=too-many-arguments,too-many-positional-arguments
|
||||
"""Should save an interrupted recording and tell participants it is partial."""
|
||||
|
||||
mock_notify_external_services.return_value = True
|
||||
|
||||
recording = RecordingFactory(worker_id="worker-1", mode=mode, status="active")
|
||||
data = api.WebhookEvent(
|
||||
event="egress_ended",
|
||||
egress_info=api.EgressInfo(
|
||||
egress_id=recording.worker_id,
|
||||
file_results=[UPLOADED_FILE],
|
||||
**egress_info_kwargs,
|
||||
),
|
||||
)
|
||||
|
||||
with caplog.at_level(logging.WARNING):
|
||||
service._handle_egress_ended(data)
|
||||
|
||||
mock_notify.assert_called_once_with(
|
||||
room_name=str(recording.room.id), notification_data={"type": notification_type}
|
||||
)
|
||||
mock_notify_external_services.assert_called_once_with(recording)
|
||||
mock_update_metadata.assert_called_once_with(
|
||||
str(recording.room.id), remove_keys=["recording_mode", "recording_status"]
|
||||
)
|
||||
assert (
|
||||
f"Recording worker reported interrupted for recording {recording.id}"
|
||||
in caplog.text
|
||||
)
|
||||
|
||||
recording.refresh_from_db()
|
||||
|
||||
assert recording.status == "notification_succeeded"
|
||||
|
||||
|
||||
@mock.patch(
|
||||
"core.recording.services.recording_events.notification_service."
|
||||
"notify_external_services"
|
||||
)
|
||||
@mock.patch("core.utils.notify_participants")
|
||||
@mock.patch("core.services.room_management.RoomManagement.update_metadata")
|
||||
def test_handle_egress_ended_interrupted_after_stop_does_not_notify_participants(
|
||||
mock_update_metadata, mock_notify, mock_notify_external_services, service
|
||||
):
|
||||
"""Shouldn't notify participants about a recording they already stopped."""
|
||||
|
||||
mock_notify_external_services.return_value = False
|
||||
|
||||
recording = RecordingFactory(worker_id="worker-1", status="stopped")
|
||||
data = api.WebhookEvent(
|
||||
event="egress_ended",
|
||||
egress_info=api.EgressInfo(
|
||||
egress_id=recording.worker_id,
|
||||
file_results=[UPLOADED_FILE],
|
||||
**CPU_EXHAUSTED_DRAINED,
|
||||
),
|
||||
)
|
||||
|
||||
service._handle_egress_ended(data)
|
||||
|
||||
mock_notify.assert_not_called()
|
||||
mock_notify_external_services.assert_called_once_with(recording)
|
||||
|
||||
recording.refresh_from_db()
|
||||
|
||||
assert recording.status == "saved"
|
||||
|
||||
|
||||
@mock.patch("core.utils.notify_participants")
|
||||
@mock.patch("core.services.room_management.RoomManagement.update_metadata")
|
||||
def test_handle_egress_ended_failed_on_another_error_discards_recording(
|
||||
mock_update_metadata, mock_notify, service
|
||||
):
|
||||
"""Should still flag as failed an egress that failed for another reason."""
|
||||
|
||||
recording = RecordingFactory(
|
||||
worker_id="worker-1", mode="transcript", status="active"
|
||||
)
|
||||
data = api.WebhookEvent(
|
||||
event="egress_ended",
|
||||
egress_info=api.EgressInfo(
|
||||
egress_id=recording.worker_id,
|
||||
status=EgressStatus.EGRESS_FAILED,
|
||||
error="pipeline frozen",
|
||||
error_code=500,
|
||||
details="End reason: Source closed",
|
||||
file_results=[UPLOADED_FILE],
|
||||
),
|
||||
)
|
||||
|
||||
service._handle_egress_ended(data)
|
||||
|
||||
mock_notify.assert_called_once_with(
|
||||
room_name=str(recording.room.id),
|
||||
notification_data={"type": "transcriptionFailed"},
|
||||
)
|
||||
|
||||
recording.refresh_from_db()
|
||||
|
||||
assert recording.status == "failed"
|
||||
|
||||
|
||||
@mock.patch("core.services.room_management.RoomManagement.update_metadata")
|
||||
def test_handle_egress_updated_ignores_unmapped_status(mock_update_metadata, service):
|
||||
"""Shouldn't touch the room's metadata when the egress status is unknown."""
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import json
|
||||
from unittest import mock
|
||||
|
||||
from django.core.exceptions import SuspiciousOperation
|
||||
from django.db import IntegrityError
|
||||
|
||||
import pytest
|
||||
@@ -38,6 +39,20 @@ def test_get_or_create_existing_user_is_not_audited(audit_events):
|
||||
assert not find_events(audit_events, "user.provision")
|
||||
|
||||
|
||||
def test_get_or_create_several_users_same_normalized_email(audit_events):
|
||||
"""Several users sharing the normalized email should be refused, not picked."""
|
||||
UserFactory(email="john.doe@example.com")
|
||||
UserFactory(email="John.Doe@example.com")
|
||||
|
||||
with pytest.raises(
|
||||
SuspiciousOperation, match="Multiple user accounts share a common email."
|
||||
):
|
||||
ProvisionalUserService().get_or_create(" JOHN.DOE@example.com", "my-client")
|
||||
|
||||
assert User.objects.count() == 2
|
||||
assert not find_events(audit_events, "user.provision")
|
||||
|
||||
|
||||
def test_get_or_create_creation_is_audited(audit_events):
|
||||
"""A created user is identified by its id, without sub nor email."""
|
||||
user, created = ProvisionalUserService().get_or_create(
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Tests for the user admin class."""
|
||||
|
||||
import pytest
|
||||
|
||||
from core import factories
|
||||
|
||||
pytestmark = pytest.mark.django_db
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def static_storage_without_manifest(settings):
|
||||
"""Render the admin pages without collecting the static files first."""
|
||||
settings.STORAGES = {
|
||||
**settings.STORAGES,
|
||||
"staticfiles": {
|
||||
"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _admin_client(client):
|
||||
"""Log a superuser in the client."""
|
||||
client.force_login(factories.UserFactory(is_staff=True, is_superuser=True))
|
||||
return client
|
||||
|
||||
|
||||
def test_admin_users_duplicate_email_filter(client):
|
||||
"""The filter should keep the users sharing their stored email, grouped by email
|
||||
and ordered by creation, but not the users whose email only matches through
|
||||
Unicode case folding."""
|
||||
first_jim = factories.UserFactory(email="jim@example.com")
|
||||
first_ann = factories.UserFactory(email="ann@example.com")
|
||||
second_jim = factories.UserFactory(email="JIM@example.com")
|
||||
second_ann = factories.UserFactory(email="ann@example.com")
|
||||
factories.UserFactory(email="jım@example.com")
|
||||
factories.UserFactory(email="bob@example.com")
|
||||
factories.UserFactory(email=None)
|
||||
factories.UserFactory(email=None)
|
||||
|
||||
response = _admin_client(client).get("/admin/core/user/?duplicate_email=yes")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert [user.pk for user in response.context["cl"].result_list] == [
|
||||
first_ann.pk,
|
||||
second_ann.pk,
|
||||
first_jim.pk,
|
||||
second_jim.pk,
|
||||
]
|
||||
|
||||
|
||||
def test_admin_users_last_login(client):
|
||||
"""The last login of users should be shown in the list and on the change page."""
|
||||
user = factories.UserFactory()
|
||||
admin_client = _admin_client(client)
|
||||
|
||||
changelist = admin_client.get("/admin/core/user/")
|
||||
change = admin_client.get(f"/admin/core/user/{user.pk}/change/")
|
||||
|
||||
assert changelist.status_code == 200
|
||||
assert "column-last_login" in changelist.content.decode()
|
||||
assert change.status_code == 200
|
||||
assert "field-last_login" in change.content.decode()
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Test the LiveKit reconnection settings exposed by the config endpoint."""
|
||||
|
||||
import pytest
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
pytestmark = pytest.mark.django_db
|
||||
|
||||
|
||||
def test_api_config_retrieve_livekit_reconnect_defaults():
|
||||
"""Without any override, the frontend gets the default backoff."""
|
||||
response = APIClient().get("/api/v1.0/config/")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["livekit"]["reconnect"] == {
|
||||
"backoff_enabled": True,
|
||||
"base_delay_ms": 1000,
|
||||
"max_delay_ms": 10000,
|
||||
"give_up_after_ms": 180000,
|
||||
"backoff_reset_ms": 120000,
|
||||
}
|
||||
|
||||
|
||||
def test_api_config_retrieve_livekit_reconnect_settings(settings):
|
||||
"""Each reconnection setting reaches the frontend unchanged."""
|
||||
settings.LIVEKIT_RECONNECT_BACKOFF_ENABLED = False
|
||||
settings.LIVEKIT_RECONNECT_BASE_DELAY_MS = 500
|
||||
settings.LIVEKIT_RECONNECT_MAX_DELAY_MS = 30000
|
||||
settings.LIVEKIT_RECONNECT_GIVE_UP_AFTER_MS = 600000
|
||||
settings.LIVEKIT_RECONNECT_BACKOFF_RESET_MS = 60000
|
||||
|
||||
response = APIClient().get("/api/v1.0/config/")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["livekit"]["reconnect"] == {
|
||||
"backoff_enabled": False,
|
||||
"base_delay_ms": 500,
|
||||
"max_delay_ms": 30000,
|
||||
"give_up_after_ms": 600000,
|
||||
"backoff_reset_ms": 60000,
|
||||
}
|
||||
@@ -280,19 +280,22 @@ def test_menshen_unknown_user_not_created(settings):
|
||||
|
||||
|
||||
@responses.activate
|
||||
@pytest.mark.parametrize("fallback", [True, False])
|
||||
@pytest.mark.parametrize("existing_sub", [None, "other-sub"])
|
||||
def test_menshen_unknown_user_email_already_used(settings, existing_sub):
|
||||
def test_menshen_unknown_user_email_already_used(settings, existing_sub, fallback):
|
||||
"""An unknown sub should not create a second account with an email already
|
||||
used, by a provisional user or a user with another sub, when
|
||||
OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION=True."""
|
||||
used, by a provisional user or a user with another sub, whether
|
||||
OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION is set or not."""
|
||||
|
||||
settings.OIDC_CREATE_USER = True
|
||||
settings.OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION = True
|
||||
settings.OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION = fallback
|
||||
|
||||
existing_user = UserFactory(sub=existing_sub, email="User@Example.com")
|
||||
existing_user = UserFactory(sub=existing_sub, email="user@example.com")
|
||||
|
||||
responses.add(
|
||||
responses.POST, INTROSPECTION_ENDPOINT, json=_introspection("new-sub")
|
||||
responses.POST,
|
||||
INTROSPECTION_ENDPOINT,
|
||||
json=_introspection("new-sub", email=" User@Example.COM "),
|
||||
)
|
||||
|
||||
response = _create_room()
|
||||
@@ -305,6 +308,43 @@ def test_menshen_unknown_user_email_already_used(settings, existing_sub):
|
||||
assert not Room.objects.exists()
|
||||
|
||||
|
||||
@responses.activate
|
||||
@pytest.mark.parametrize("existing_sub", [None, "other-sub"])
|
||||
def test_menshen_unknown_user_email_already_used_allowed(
|
||||
audit_events, settings, existing_sub
|
||||
):
|
||||
"""An unknown sub should get its own account, even with an email already used,
|
||||
when OIDC_ALLOW_DUPLICATE_EMAILS=True."""
|
||||
|
||||
settings.OIDC_CREATE_USER = True
|
||||
settings.OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION = False
|
||||
settings.OIDC_ALLOW_DUPLICATE_EMAILS = True
|
||||
|
||||
existing_user = UserFactory(sub=existing_sub, email="user@example.com")
|
||||
|
||||
responses.add(
|
||||
responses.POST,
|
||||
INTROSPECTION_ENDPOINT,
|
||||
json=_introspection("new-sub", email=" User@Example.COM "),
|
||||
)
|
||||
|
||||
response = _create_room()
|
||||
|
||||
assert response.status_code == 201
|
||||
assert User.objects.count() == 2
|
||||
user = User.objects.get(sub="new-sub")
|
||||
assert user != existing_user
|
||||
assert user.email == "user@example.com"
|
||||
existing_user.refresh_from_db()
|
||||
assert existing_user.sub == existing_sub
|
||||
|
||||
[provision] = find_events(audit_events, "user.provision")
|
||||
|
||||
assert provision["event"]["outcome"] == "success"
|
||||
assert provision["lasuite"]["outcome"] == "success"
|
||||
assert provision["entity"]["target"]["id"] == str(user.pk)
|
||||
|
||||
|
||||
@responses.activate
|
||||
def test_menshen_is_audited_as_application(audit_events):
|
||||
"""A call with a Menshen token is made by the client Menshen reports, acting for
|
||||
@@ -382,10 +422,12 @@ def test_menshen_unknown_user_email_already_used_is_audited(audit_events, settin
|
||||
settings.OIDC_CREATE_USER = True
|
||||
settings.OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION = True
|
||||
|
||||
existing_user = UserFactory(sub=None, email="User@Example.com")
|
||||
existing_user = UserFactory(sub=None, email="user@example.com")
|
||||
|
||||
responses.add(
|
||||
responses.POST, INTROSPECTION_ENDPOINT, json=_introspection("new-sub")
|
||||
responses.POST,
|
||||
INTROSPECTION_ENDPOINT,
|
||||
json=_introspection("new-sub", email=" User@Example.COM "),
|
||||
)
|
||||
|
||||
response = _create_room()
|
||||
|
||||
@@ -184,7 +184,7 @@ def test_api_rooms_list_with_application_disabled(mock_rs_authenticate, settings
|
||||
|
||||
@responses.activate
|
||||
def test_api_rooms_list_with_invalid_rs_token(settings):
|
||||
"""Listing rooms with invalid resource server token should return 400."""
|
||||
"""Listing rooms with invalid resource server token should return 401."""
|
||||
|
||||
settings.OIDC_OP_INTROSPECTION_ENDPOINT = "https://oidc.example.com/introspect"
|
||||
settings.OIDC_OP_URL = "https://oidc.example.com"
|
||||
@@ -202,9 +202,8 @@ def test_api_rooms_list_with_invalid_rs_token(settings):
|
||||
client.credentials(HTTP_AUTHORIZATION="Bearer invalid-token-123")
|
||||
response = client.get("/external-api/v1.0/rooms/")
|
||||
|
||||
# Return 400 instead of 401 because ResourceServerAuthentication raises
|
||||
# SuspiciousOperation when the introspected user is not active
|
||||
assert response.status_code == 400
|
||||
assert response.status_code == 401
|
||||
assert "introspected user is not active" in str(response.data).lower()
|
||||
|
||||
|
||||
def test_api_rooms_list_missing_scope():
|
||||
@@ -422,7 +421,7 @@ def test_api_rooms_retrieve_with_expired_token(settings):
|
||||
|
||||
@responses.activate
|
||||
def test_api_rooms_retrieve_with_invalid_rs_token(settings):
|
||||
"""Retrieving rooms with invalid resource server token should return 400."""
|
||||
"""Retrieving rooms with invalid resource server token should return 401."""
|
||||
|
||||
settings.OIDC_OP_INTROSPECTION_ENDPOINT = "https://oidc.example.com/introspect"
|
||||
settings.OIDC_OP_URL = "https://oidc.example.com"
|
||||
@@ -443,9 +442,8 @@ def test_api_rooms_retrieve_with_invalid_rs_token(settings):
|
||||
client.credentials(HTTP_AUTHORIZATION="Bearer invalid-token-123")
|
||||
response = client.get(f"/external-api/v1.0/rooms/{room.id}/")
|
||||
|
||||
# Return 400 instead of 401 because ResourceServerAuthentication raises
|
||||
# SuspiciousOperation when the introspected user is not active
|
||||
assert response.status_code == 400
|
||||
assert response.status_code == 401
|
||||
assert "introspected user is not active" in str(response.data).lower()
|
||||
|
||||
|
||||
def test_api_rooms_retrieve_requires_scope():
|
||||
@@ -647,7 +645,7 @@ def test_api_rooms_create_with_expired_token(settings):
|
||||
|
||||
@responses.activate
|
||||
def test_api_rooms_create_with_invalid_rs_token(settings):
|
||||
"""Creating rooms with invalid resource server token should return 400."""
|
||||
"""Creating rooms with invalid resource server token should return 401."""
|
||||
|
||||
settings.OIDC_OP_INTROSPECTION_ENDPOINT = "https://oidc.example.com/introspect"
|
||||
settings.OIDC_OP_URL = "https://oidc.example.com"
|
||||
@@ -665,9 +663,8 @@ def test_api_rooms_create_with_invalid_rs_token(settings):
|
||||
client.credentials(HTTP_AUTHORIZATION="Bearer invalid-token-123")
|
||||
response = client.post("/external-api/v1.0/rooms/")
|
||||
|
||||
# Return 400 instead of 401 because ResourceServerAuthentication raises
|
||||
# SuspiciousOperation when the introspected user is not active
|
||||
assert response.status_code == 400
|
||||
assert response.status_code == 401
|
||||
assert "introspected user is not active" in str(response.data).lower()
|
||||
|
||||
|
||||
def test_api_rooms_create_inactive_user():
|
||||
@@ -2971,6 +2968,36 @@ def test_api_rooms_missing_token_is_audited_as_denial(audit_events):
|
||||
assert event["url"]["path"] == "/external-api/v1.0/rooms/"
|
||||
|
||||
|
||||
@responses.activate
|
||||
def test_api_rooms_invalid_rs_token_is_audited_as_denial(audit_events, settings):
|
||||
"""A token refused by the identity provider is recorded as a denial."""
|
||||
settings.OIDC_OP_INTROSPECTION_ENDPOINT = "https://oidc.example.com/introspect"
|
||||
settings.OIDC_OP_URL = "https://oidc.example.com"
|
||||
|
||||
responses.add(
|
||||
responses.POST,
|
||||
"https://oidc.example.com/introspect",
|
||||
json={"iss": "https://oidc.example.com", "active": False},
|
||||
)
|
||||
|
||||
client = APIClient()
|
||||
client.credentials(HTTP_AUTHORIZATION="Bearer invalid-token-123")
|
||||
response = client.get("/external-api/v1.0/rooms/")
|
||||
|
||||
assert response.status_code == 401
|
||||
assert response.headers["WWW-Authenticate"] == "Bearer"
|
||||
responses.assert_call_count("https://oidc.example.com/introspect", 1)
|
||||
|
||||
[event] = find_events(audit_events, "room.list")
|
||||
|
||||
assert event["event"]["category"] == ["api", "authentication"]
|
||||
assert event["event"]["reason"] == "authentication_failed"
|
||||
assert event["lasuite"]["outcome"] == "denied"
|
||||
assert event["lasuite"]["actor"] == {"type": "anonymous"}
|
||||
assert event["http"]["response"] == {"status_code": 401}
|
||||
assert event["error"]["message"] == response.json()["detail"]
|
||||
|
||||
|
||||
def test_api_rooms_missing_scope_is_audited_as_denial(audit_events):
|
||||
"""A token without the required scope is a permission denial by the application."""
|
||||
user = UserFactory()
|
||||
|
||||
@@ -4,11 +4,12 @@ Unit tests for the User model
|
||||
|
||||
from unittest import mock
|
||||
|
||||
from django.contrib.auth.models import update_last_login
|
||||
from django.core.exceptions import ValidationError
|
||||
|
||||
import pytest
|
||||
|
||||
from core import factories
|
||||
from core import factories, models
|
||||
|
||||
pytestmark = pytest.mark.django_db
|
||||
|
||||
@@ -117,12 +118,13 @@ def test_models_users_email_unique_when_sub_is_null():
|
||||
|
||||
|
||||
def test_models_users_email_unique_case_insensitive_when_sub_is_null():
|
||||
"""Email uniqueness should be case-insensitive among users with no sub (pending users)."""
|
||||
factories.UserFactory(sub=None, email="Test@example.com")
|
||||
"""Email uniqueness among users with no sub (pending users) should also ignore the
|
||||
case of non-ASCII letters, which the email normalization keeps."""
|
||||
factories.UserFactory(sub=None, email="test@éxample.com")
|
||||
with pytest.raises(
|
||||
ValidationError, match="Constraint “unique_email_when_sub_is_null” is violated."
|
||||
):
|
||||
factories.UserFactory(sub=None, email="test@example.com")
|
||||
factories.UserFactory(sub=None, email="test@Éxample.com")
|
||||
|
||||
|
||||
def test_models_users_email_not_unique_when_sub_is_set():
|
||||
@@ -175,3 +177,54 @@ def test_models_users_sub_blank_is_accepted():
|
||||
"""sub='' passes validation because blank=True; null is preferred but not enforced."""
|
||||
user = factories.UserFactory.build(sub="")
|
||||
user.full_clean()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"email, expected_email",
|
||||
[
|
||||
("John.Doe@Example.COM", "john.doe@example.com"),
|
||||
(" john.doe@example.com ", "john.doe@example.com"),
|
||||
],
|
||||
)
|
||||
def test_models_users_email_normalized_on_save(email, expected_email):
|
||||
"""The email of a user should be stripped and have its ASCII letters only lowercased
|
||||
when saved."""
|
||||
user = factories.UserFactory(email=email)
|
||||
user.refresh_from_db()
|
||||
assert user.email == expected_email
|
||||
|
||||
|
||||
def test_models_users_email_normalized_on_login():
|
||||
"""The last login update at login should store a legacy email normalized."""
|
||||
user = factories.UserFactory()
|
||||
models.User.objects.filter(pk=user.pk).update(email="John.Doe@Example.COM")
|
||||
user.refresh_from_db()
|
||||
|
||||
update_last_login(None, user)
|
||||
|
||||
user.refresh_from_db()
|
||||
assert user.last_login is not None
|
||||
assert user.email == "john.doe@example.com"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("email", ["", " "])
|
||||
def test_models_users_email_blank_stored_as_null(email):
|
||||
"""An empty or whitespace-only email should be stored as NULL."""
|
||||
user = factories.UserFactory(email=email)
|
||||
user.refresh_from_db()
|
||||
assert user.email is None
|
||||
|
||||
|
||||
def test_models_users_get_user_by_sub_or_email_active_preferred(settings):
|
||||
"""An active user should be preferred over an inactive one sharing its email."""
|
||||
settings.OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION = True
|
||||
factories.UserFactory(email="john.doe@example.com", is_active=False)
|
||||
active_user = factories.UserFactory(email="John.Doe@example.com")
|
||||
factories.UserFactory(email="john.doe@example.com", is_active=False)
|
||||
|
||||
assert (
|
||||
models.User.objects.get_user_by_sub_or_email(
|
||||
"unknown-sub", "JOHN.DOE@example.com"
|
||||
)
|
||||
== active_user
|
||||
)
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
"""Unit tests for the opt-in psycopg connection pool settings."""
|
||||
|
||||
# pylint: disable=protected-access
|
||||
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
|
||||
import pytest
|
||||
|
||||
from meet import settings
|
||||
|
||||
|
||||
def make_configuration(**overrides):
|
||||
"""Build a throwaway configuration with plain values and its own DATABASES."""
|
||||
attributes = {
|
||||
"DATABASES": {
|
||||
"default": {
|
||||
"ENGINE": "django.db.backends.postgresql",
|
||||
"OPTIONS": {"sslmode": "require"},
|
||||
}
|
||||
},
|
||||
"DB_PSYCOPG_POOL_ENABLED": True,
|
||||
"DB_PSYCOPG_POOL_MIN_SIZE": 1,
|
||||
"DB_PSYCOPG_POOL_MAX_SIZE": 3,
|
||||
"DB_PSYCOPG_POOL_TIMEOUT": 30.0,
|
||||
"DB_PSYCOPG_POOL_MAX_IDLE": 600.0,
|
||||
**overrides,
|
||||
}
|
||||
return type("PoolConfiguration", (settings.Test,), attributes)
|
||||
|
||||
|
||||
def test_database_pool_disabled_leaves_options_untouched():
|
||||
"""Without the flag, no connection pool is configured."""
|
||||
configuration = make_configuration(DB_PSYCOPG_POOL_ENABLED=False)
|
||||
|
||||
configuration._configure_database_pool()
|
||||
|
||||
assert configuration.DATABASES["default"]["OPTIONS"] == {"sslmode": "require"}
|
||||
assert "CONN_HEALTH_CHECKS" not in configuration.DATABASES["default"]
|
||||
|
||||
|
||||
def test_database_pool_enabled_merges_pool_options():
|
||||
"""The pool and keepalive options are added next to the existing ones."""
|
||||
configuration = make_configuration()
|
||||
|
||||
configuration._configure_database_pool()
|
||||
|
||||
assert configuration.DATABASES["default"]["OPTIONS"] == {
|
||||
"sslmode": "require",
|
||||
"keepalives_idle": 60,
|
||||
"keepalives_interval": 10,
|
||||
"keepalives_count": 5,
|
||||
"pool": {"min_size": 1, "max_size": 3, "timeout": 30.0, "max_idle": 600.0},
|
||||
}
|
||||
|
||||
|
||||
def test_database_pool_enabled_keeps_explicit_keepalives():
|
||||
"""Keepalive values already set, e.g. from DATABASE_URL, are not overridden."""
|
||||
configuration = make_configuration(
|
||||
DATABASES={
|
||||
"default": {
|
||||
"ENGINE": "django.db.backends.postgresql",
|
||||
"OPTIONS": {"keepalives_idle": "30", "keepalives": "0"},
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
configuration._configure_database_pool()
|
||||
|
||||
options = configuration.DATABASES["default"]["OPTIONS"]
|
||||
assert options["keepalives_idle"] == "30"
|
||||
assert options["keepalives"] == "0"
|
||||
assert options["keepalives_interval"] == 10
|
||||
|
||||
|
||||
@pytest.mark.parametrize("health_checks", [None, False])
|
||||
def test_database_pool_enabled_forces_health_checks(health_checks):
|
||||
"""Pooled connections are checked on checkout, even if DATABASE_URL said no."""
|
||||
database = {"ENGINE": "django.db.backends.postgresql"}
|
||||
if health_checks is not None:
|
||||
database["CONN_HEALTH_CHECKS"] = health_checks
|
||||
configuration = make_configuration(DATABASES={"default": database})
|
||||
|
||||
configuration._configure_database_pool()
|
||||
|
||||
assert configuration.DATABASES["default"]["CONN_HEALTH_CHECKS"] is True
|
||||
|
||||
|
||||
def test_database_pool_enabled_without_options():
|
||||
"""A database without OPTIONS, as built from DATABASE_URL, gets them created."""
|
||||
configuration = make_configuration(
|
||||
DATABASES={"default": {"ENGINE": "django.db.backends.postgresql_psycopg2"}}
|
||||
)
|
||||
|
||||
configuration._configure_database_pool()
|
||||
|
||||
assert configuration.DATABASES["default"]["OPTIONS"]["pool"]["max_size"] == 3
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"overrides,match",
|
||||
[
|
||||
(
|
||||
{"DATABASES": {"default": {"ENGINE": "django.db.backends.sqlite3"}}},
|
||||
"requires the django.db.backends.postgresql engine",
|
||||
),
|
||||
(
|
||||
{
|
||||
"DATABASES": {
|
||||
"default": {
|
||||
"ENGINE": "django.db.backends.postgresql",
|
||||
"CONN_MAX_AGE": 60,
|
||||
}
|
||||
}
|
||||
},
|
||||
"cannot be combined with persistent connections",
|
||||
),
|
||||
(
|
||||
{"DB_PSYCOPG_POOL_MIN_SIZE": 6},
|
||||
"MIN_SIZE cannot be greater than",
|
||||
),
|
||||
({"DB_PSYCOPG_POOL_TIMEOUT": 0.0}, "must be positive"),
|
||||
({"DB_PSYCOPG_POOL_MAX_IDLE": -1.0}, "must be positive"),
|
||||
],
|
||||
)
|
||||
def test_database_pool_invalid_configuration(overrides, match):
|
||||
"""An invalid pool setup fails at boot."""
|
||||
configuration = make_configuration(**overrides)
|
||||
|
||||
with pytest.raises(ImproperlyConfigured, match=match):
|
||||
configuration._configure_database_pool()
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Unit tests for the value of the LiveKit reconnection delay settings."""
|
||||
|
||||
import pytest
|
||||
|
||||
from meet.settings import StrictlyPositiveIntegerValue
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw,expected", [("1", 1), (" 15000 ", 15000)])
|
||||
def test_strictly_positive_integer_value_parses(raw, expected):
|
||||
"""A delay above 0 is read as an integer."""
|
||||
assert StrictlyPositiveIntegerValue(environ=False).to_python(raw) == expected
|
||||
|
||||
|
||||
def test_strictly_positive_integer_value_rejects_zero():
|
||||
"""0 stops the settings module loading, unlike with PositiveIntegerValue."""
|
||||
with pytest.raises(ValueError, match="greater than 0"):
|
||||
StrictlyPositiveIntegerValue(environ=False).to_python("0")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", ["-1", "1e3", "1000ms", ""])
|
||||
def test_strictly_positive_integer_value_rejects_invalid(raw):
|
||||
"""A negative or non-integer value stops the settings module loading."""
|
||||
with pytest.raises(ValueError):
|
||||
StrictlyPositiveIntegerValue(environ=False).to_python(raw)
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Unit tests for the LIVEKIT_API_TIMEOUT_SECONDS setting."""
|
||||
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
from meet.settings import Test
|
||||
|
||||
|
||||
def test_livekit_api_timeout_zero_is_refused():
|
||||
"""A zero timeout would fail every LiveKit call, so it stops the settings loading."""
|
||||
with mock.patch.object(Test, "LIVEKIT_API_TIMEOUT_SECONDS", 0):
|
||||
with pytest.raises(ValueError, match="LIVEKIT_API_TIMEOUT_SECONDS"):
|
||||
Test.post_setup()
|
||||
@@ -0,0 +1,17 @@
|
||||
"""Unit tests for the OIDC_ALLOW_DUPLICATE_EMAILS setting."""
|
||||
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
from meet.settings import Test
|
||||
|
||||
|
||||
def test_oidc_allow_duplicate_emails_with_email_fallback_is_refused():
|
||||
"""Users identified by email cannot share one, so both settings stop the loading."""
|
||||
with (
|
||||
mock.patch.object(Test, "OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION", True),
|
||||
mock.patch.object(Test, "OIDC_ALLOW_DUPLICATE_EMAILS", True),
|
||||
pytest.raises(ValueError, match="OIDC_ALLOW_DUPLICATE_EMAILS"),
|
||||
):
|
||||
Test.post_setup()
|
||||
@@ -4,6 +4,8 @@ Test utils functions
|
||||
|
||||
# pylint: disable=W0621
|
||||
import json
|
||||
import socket
|
||||
import threading
|
||||
from unittest import mock
|
||||
|
||||
from django.conf import settings
|
||||
@@ -11,13 +13,21 @@ from django.contrib.auth.models import AnonymousUser
|
||||
|
||||
import jwt
|
||||
import pytest
|
||||
from asgiref.sync import async_to_sync
|
||||
from livekit.api import TwirpError
|
||||
|
||||
from core.factories import UserFactory
|
||||
from core.services.participants_management import (
|
||||
ParticipantsManagement,
|
||||
ParticipantsManagementException,
|
||||
)
|
||||
from core.services.room_management import RoomManagement, RoomManagementException
|
||||
from core.services.sip_management import SIPException, SIPManagement
|
||||
from core.utils import (
|
||||
NotificationError,
|
||||
create_livekit_client,
|
||||
generate_token,
|
||||
normalize_email,
|
||||
notify_participants,
|
||||
)
|
||||
|
||||
@@ -107,59 +117,208 @@ def test_anonymous_falls_back_to_anonymous_label():
|
||||
assert claims["name"] == "Anonymous"
|
||||
|
||||
|
||||
@mock.patch("asyncio.get_running_loop")
|
||||
@mock.patch("core.utils.LiveKitAPI")
|
||||
def test_create_livekit_client_ssl_enabled(
|
||||
mock_livekit_api, mock_get_running_loop, settings
|
||||
):
|
||||
"""Test LiveKitAPI client creation with SSL verification enabled."""
|
||||
mock_get_running_loop.return_value = mock.MagicMock()
|
||||
settings.LIVEKIT_VERIFY_SSL = True
|
||||
@pytest.fixture
|
||||
def fake_livekit(request):
|
||||
"""A LiveKit address that takes the connection, sends `request.param`, then waits."""
|
||||
server = socket.create_server(("127.0.0.1", 0))
|
||||
held = []
|
||||
|
||||
create_livekit_client()
|
||||
def accept():
|
||||
while True:
|
||||
try:
|
||||
connection, _ = server.accept()
|
||||
except OSError:
|
||||
return
|
||||
held.append(connection)
|
||||
connection.sendall(request.param)
|
||||
|
||||
mock_livekit_api.assert_called_once_with(
|
||||
**settings.LIVEKIT_CONFIGURATION, session=None
|
||||
)
|
||||
threading.Thread(target=accept, daemon=True).start()
|
||||
yield f"http://127.0.0.1:{server.getsockname()[1]:d}"
|
||||
server.close()
|
||||
for connection in held:
|
||||
connection.close()
|
||||
|
||||
|
||||
@mock.patch("core.utils.aiohttp.ClientSession")
|
||||
@mock.patch("asyncio.get_running_loop")
|
||||
@mock.patch("core.utils.LiveKitAPI")
|
||||
def test_create_livekit_client_ssl_disabled(
|
||||
mock_livekit_api, mock_get_running_loop, mock_client_session, settings
|
||||
):
|
||||
"""Test LiveKitAPI client creation with SSL verification disabled."""
|
||||
mock_get_running_loop.return_value = mock.MagicMock()
|
||||
mock_session_instance = mock.MagicMock()
|
||||
mock_client_session.return_value = mock_session_instance
|
||||
settings.LIVEKIT_VERIFY_SSL = False
|
||||
|
||||
create_livekit_client()
|
||||
|
||||
mock_livekit_api.assert_called_once_with(
|
||||
**settings.LIVEKIT_CONFIGURATION, session=mock_session_instance
|
||||
)
|
||||
|
||||
|
||||
@mock.patch("asyncio.get_running_loop")
|
||||
@mock.patch("core.utils.LiveKitAPI")
|
||||
def test_create_livekit_client_custom_configuration(
|
||||
mock_livekit_api, mock_get_running_loop, settings
|
||||
):
|
||||
"""Test LiveKitAPI client creation with custom configuration."""
|
||||
settings.LIVEKIT_VERIFY_SSL = True
|
||||
|
||||
mock_get_running_loop.return_value = mock.MagicMock()
|
||||
custom_configuration = {
|
||||
"api_key": "mock_key",
|
||||
"api_secret": "mock_secret",
|
||||
"url": "http://mock-url.com",
|
||||
@pytest.mark.parametrize(
|
||||
"fake_livekit",
|
||||
[b"", b"HTTP/1.1 200 OK\r\nContent-Length: 64\r\n\r\n"],
|
||||
ids=["no answer", "answer cut short"],
|
||||
indirect=True,
|
||||
)
|
||||
def test_create_livekit_client_gives_up_on_a_quiet_livekit(fake_livekit, settings):
|
||||
"""A LiveKit that stops answering fails the call after the timeout."""
|
||||
settings.LIVEKIT_CONFIGURATION = {
|
||||
**settings.LIVEKIT_CONFIGURATION,
|
||||
"url": fake_livekit,
|
||||
}
|
||||
settings.LIVEKIT_API_TIMEOUT_SECONDS = 1
|
||||
|
||||
create_livekit_client(custom_configuration)
|
||||
raised = []
|
||||
|
||||
mock_livekit_api.assert_called_once_with(**custom_configuration, session=None)
|
||||
def delete_room():
|
||||
try:
|
||||
RoomManagement.delete_room("room-abc")
|
||||
except RoomManagementException as error:
|
||||
raised.append(error)
|
||||
|
||||
# A thread, so a call that never gives up fails the test rather than hangs it.
|
||||
call = threading.Thread(target=delete_room, daemon=True)
|
||||
call.start()
|
||||
call.join(5)
|
||||
|
||||
assert not call.is_alive()
|
||||
assert len(raised) == 1
|
||||
assert isinstance(raised[0].__cause__, TimeoutError)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"fake_livekit",
|
||||
[b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"],
|
||||
ids=["answer"],
|
||||
indirect=True,
|
||||
)
|
||||
def test_create_livekit_client_lets_an_answer_through(fake_livekit, settings):
|
||||
"""A LiveKit that answers within the timeout is not cut off."""
|
||||
settings.LIVEKIT_CONFIGURATION = {
|
||||
**settings.LIVEKIT_CONFIGURATION,
|
||||
"url": fake_livekit,
|
||||
}
|
||||
settings.LIVEKIT_API_TIMEOUT_SECONDS = 1
|
||||
|
||||
RoomManagement.delete_room("room-abc")
|
||||
|
||||
|
||||
class TimingOutClient:
|
||||
"""A LiveKit client whose every call times out."""
|
||||
|
||||
def __getattr__(self, name):
|
||||
return self
|
||||
|
||||
async def __call__(self, *args, **kwargs):
|
||||
raise TimeoutError
|
||||
|
||||
async def aclose(self):
|
||||
"""Nothing to close."""
|
||||
|
||||
|
||||
def delete_dispatch_rule():
|
||||
"""Reach the delete call, past the listing that comes first."""
|
||||
with mock.patch.object(
|
||||
SIPManagement, "_list_dispatch_rules_ids", mock.AsyncMock(return_value=["r"])
|
||||
):
|
||||
SIPManagement().delete_dispatch_rule("room")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("call", "expected"),
|
||||
[
|
||||
pytest.param(
|
||||
lambda: ParticipantsManagement().mute("room", "id", "track"),
|
||||
ParticipantsManagementException,
|
||||
id="mute",
|
||||
),
|
||||
pytest.param(
|
||||
lambda: ParticipantsManagement().remove("room", "id"),
|
||||
ParticipantsManagementException,
|
||||
id="remove",
|
||||
),
|
||||
pytest.param(
|
||||
lambda: ParticipantsManagement().update("room", "id", name="n"),
|
||||
ParticipantsManagementException,
|
||||
id="update",
|
||||
),
|
||||
pytest.param(
|
||||
lambda: ParticipantsManagement().check_if_in_meeting("room", "id"),
|
||||
ParticipantsManagementException,
|
||||
id="check_if_in_meeting",
|
||||
),
|
||||
pytest.param(
|
||||
lambda: RoomManagement.update_metadata("room", {}),
|
||||
RoomManagementException,
|
||||
id="update_metadata",
|
||||
),
|
||||
pytest.param(
|
||||
lambda: RoomManagement.delete_room("room"),
|
||||
RoomManagementException,
|
||||
id="delete_room",
|
||||
),
|
||||
pytest.param(
|
||||
lambda: SIPManagement().create_dispatch_rule(
|
||||
mock.Mock(pk="room", pin_code="1")
|
||||
),
|
||||
SIPException,
|
||||
id="create_dispatch_rule",
|
||||
),
|
||||
pytest.param(
|
||||
lambda: SIPManagement().has_dispatch_rule("room"),
|
||||
SIPException,
|
||||
id="has_dispatch_rule",
|
||||
),
|
||||
pytest.param(delete_dispatch_rule, SIPException, id="delete_dispatch_rule"),
|
||||
pytest.param(
|
||||
lambda: notify_participants("room", {}),
|
||||
NotificationError,
|
||||
id="notify_participants",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_a_livekit_timeout_raises_the_service_exception(call, expected):
|
||||
"""A timed-out call fails the way a LiveKit error does, so callers handle it."""
|
||||
with (
|
||||
mock.patch("core.utils.create_livekit_client", return_value=TimingOutClient()),
|
||||
pytest.raises(expected) as error,
|
||||
):
|
||||
call()
|
||||
|
||||
assert error.type is expected
|
||||
assert isinstance(error.value.__cause__, TimeoutError)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("verify_ssl", [True, False])
|
||||
def test_create_livekit_client_closes_its_session(verify_ssl, settings):
|
||||
"""Closing the client closes its session, whether SSL is verified or not."""
|
||||
settings.LIVEKIT_VERIFY_SSL = verify_ssl
|
||||
|
||||
@async_to_sync
|
||||
async def open_and_close():
|
||||
client = create_livekit_client()
|
||||
await client.aclose()
|
||||
return client._session # pylint: disable=protected-access
|
||||
|
||||
session = open_and_close()
|
||||
|
||||
assert session.closed
|
||||
assert session.connector is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("verify_ssl", [True, False])
|
||||
def test_create_livekit_client_ssl(verify_ssl, settings):
|
||||
"""SSL is verified unless the setting turns it off."""
|
||||
settings.LIVEKIT_VERIFY_SSL = verify_ssl
|
||||
|
||||
@async_to_sync
|
||||
async def ssl_of_new_client():
|
||||
client = create_livekit_client()
|
||||
ssl = client._session.connector._ssl # pylint: disable=protected-access
|
||||
await client.aclose()
|
||||
return ssl
|
||||
|
||||
assert (ssl_of_new_client() is not False) is verify_ssl
|
||||
|
||||
|
||||
def test_create_livekit_client_custom_configuration():
|
||||
"""A custom configuration picks the LiveKit the client talks to."""
|
||||
|
||||
@async_to_sync
|
||||
async def url_of_new_client():
|
||||
client = create_livekit_client(
|
||||
{"api_key": "key", "api_secret": "secret", "url": "http://mock-url.com"}
|
||||
)
|
||||
url = client.room._client.host # pylint: disable=protected-access
|
||||
await client.aclose()
|
||||
return url
|
||||
|
||||
assert url_of_new_client().startswith("http://mock-url.com")
|
||||
|
||||
|
||||
@mock.patch("core.utils.create_livekit_client")
|
||||
@@ -262,3 +421,14 @@ def test_notify_participants_success(mock_create_livekit_client):
|
||||
|
||||
# Verify aclose was called
|
||||
mock_api_instance.aclose.assert_called_once()
|
||||
|
||||
|
||||
def test_normalize_email():
|
||||
"""The "normalize_email" function should strip and lowercase ASCII letters only."""
|
||||
assert normalize_email(" John.Doe@Example.COM ") == "john.doe@example.com"
|
||||
assert normalize_email("Dısk@Example.com") == "dısk@example.com"
|
||||
assert normalize_email("Diſk@Example.com") == "diſk@example.com"
|
||||
assert normalize_email("DisK@Example.com") == "disK@example.com"
|
||||
assert normalize_email("Élise@Example.com") == "Élise@example.com"
|
||||
assert normalize_email("") == ""
|
||||
assert normalize_email(None) == ""
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
"""
|
||||
Test utils.is_uuid
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from faker import Faker
|
||||
|
||||
from core import utils
|
||||
|
||||
fake = Faker()
|
||||
|
||||
UUID = fake.uuid4()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"value",
|
||||
[
|
||||
UUID,
|
||||
UUID.upper(),
|
||||
UUID.replace("-", ""),
|
||||
f"{{{UUID}}}",
|
||||
f"urn:uuid:{UUID}",
|
||||
],
|
||||
ids=["canonical", "uppercase", "hex", "braces", "urn"],
|
||||
)
|
||||
def test_utils_is_uuid_true(value):
|
||||
"""Strings that parse as a UUID should be recognized."""
|
||||
assert utils.is_uuid(value) is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"value",
|
||||
["", "my-room", "abc-defg-hij", f"{UUID}!", f"_{UUID}", UUID[:-1]],
|
||||
ids=["empty", "slug", "room-slug", "suffix", "prefix", "truncated"],
|
||||
)
|
||||
def test_utils_is_uuid_false(value):
|
||||
"""Strings that do not parse as a UUID should not be recognized."""
|
||||
assert utils.is_uuid(value) is False
|
||||
@@ -5,6 +5,7 @@ Utils functions used in the core app
|
||||
# pylint: disable=R0913, R0917
|
||||
# ruff: noqa:S311, PLR0913
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
@@ -15,7 +16,7 @@ import string
|
||||
from datetime import timedelta
|
||||
from functools import lru_cache
|
||||
from typing import List, Optional
|
||||
from uuid import uuid4
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.files.storage import default_storage
|
||||
@@ -218,19 +219,37 @@ def generate_s3_authorization_headers(key):
|
||||
return request
|
||||
|
||||
|
||||
async def bound_livekit_request(request, handler):
|
||||
"""Give up on a LiveKit request, its answer included, after the set timeout.
|
||||
|
||||
The SDK passes timeout=None to aiohttp on every call, which means no limit,
|
||||
so a timeout set on the session never applies.
|
||||
"""
|
||||
async with asyncio.timeout(settings.LIVEKIT_API_TIMEOUT_SECONDS):
|
||||
response = await handler(request)
|
||||
await response.read()
|
||||
return response
|
||||
|
||||
|
||||
class LiveKitClient(LiveKitAPI):
|
||||
"""A LiveKit API client that closes the session it is given."""
|
||||
|
||||
async def aclose(self):
|
||||
"""Close the session, which LiveKitAPI leaves open when it did not create it."""
|
||||
await self._session.close()
|
||||
|
||||
|
||||
def create_livekit_client(custom_configuration=None):
|
||||
"""Create and return a configured LiveKit API client."""
|
||||
|
||||
custom_session = None
|
||||
|
||||
if not settings.LIVEKIT_VERIFY_SSL:
|
||||
connector = aiohttp.TCPConnector(ssl=False)
|
||||
custom_session = aiohttp.ClientSession(connector=connector)
|
||||
connector = None if settings.LIVEKIT_VERIFY_SSL else aiohttp.TCPConnector(ssl=False)
|
||||
session = aiohttp.ClientSession(
|
||||
connector=connector, middlewares=(bound_livekit_request,)
|
||||
)
|
||||
|
||||
# Use default configuration if none provided
|
||||
configuration = custom_configuration or settings.LIVEKIT_CONFIGURATION
|
||||
|
||||
return LiveKitAPI(session=custom_session, **configuration)
|
||||
return LiveKitClient(session=session, **configuration)
|
||||
|
||||
|
||||
class NotificationError(Exception):
|
||||
@@ -261,7 +280,7 @@ async def notify_participants(room_name: str, notification_data: dict):
|
||||
kind="RELIABLE",
|
||||
)
|
||||
)
|
||||
except TwirpError as e:
|
||||
except (TwirpError, TimeoutError) as e:
|
||||
raise NotificationError("Failed to notify room participants") from e
|
||||
finally:
|
||||
await lkapi.aclose()
|
||||
@@ -317,6 +336,26 @@ def generate_room_slug():
|
||||
return "-".join(parts)
|
||||
|
||||
|
||||
def is_uuid(value: str) -> bool:
|
||||
"""Tell whether a value parses as a UUID."""
|
||||
try:
|
||||
UUID(value)
|
||||
except ValueError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
_ASCII_LOWERCASE_TABLE = str.maketrans(string.ascii_uppercase, string.ascii_lowercase)
|
||||
|
||||
|
||||
def normalize_email(email):
|
||||
"""Strip an email and lowercase its ASCII letters only.
|
||||
|
||||
Emails are stored in this form and compared exactly.
|
||||
"""
|
||||
return (email or "").strip().translate(_ASCII_LOWERCASE_TABLE)
|
||||
|
||||
|
||||
def detect_mimetype(file_buffer: bytes, filename: str | None = None) -> str:
|
||||
"""
|
||||
Detect MIME type using multiple methods for better accuracy.
|
||||
|
||||
@@ -17,6 +17,7 @@ import warnings
|
||||
from os import path
|
||||
from socket import gethostbyname, gethostname
|
||||
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
import dj_database_url
|
||||
@@ -67,6 +68,17 @@ class VideoCodecValue(values.Value):
|
||||
return codec
|
||||
|
||||
|
||||
class StrictlyPositiveIntegerValue(values.PositiveIntegerValue):
|
||||
"""An integer greater than 0"""
|
||||
|
||||
def to_python(self, value):
|
||||
"""Ensure the integer is greater than 0."""
|
||||
int_value = super().to_python(value)
|
||||
if int_value == 0:
|
||||
raise ValueError(f"Expected an integer greater than 0, got {value!r}.")
|
||||
return int_value
|
||||
|
||||
|
||||
class ResolutionSpec(BaseModel):
|
||||
"""An value of RECORDING_ENCODING_AVAILABLE_RESOLUTIONS."""
|
||||
|
||||
@@ -139,7 +151,7 @@ class Base(Configuration):
|
||||
)
|
||||
else {
|
||||
"ENGINE": values.Value(
|
||||
"django.db.backends.postgresql_psycopg2",
|
||||
"django.db.backends.postgresql",
|
||||
environ_name="DB_ENGINE",
|
||||
environ_prefix=None,
|
||||
),
|
||||
@@ -154,6 +166,21 @@ class Base(Configuration):
|
||||
"PORT": values.Value(5432, environ_name="DB_PORT", environ_prefix=None),
|
||||
}
|
||||
}
|
||||
DB_PSYCOPG_POOL_ENABLED = values.BooleanValue(
|
||||
False, environ_name="DB_PSYCOPG_POOL_ENABLED", environ_prefix=None
|
||||
)
|
||||
DB_PSYCOPG_POOL_MIN_SIZE = values.PositiveIntegerValue(
|
||||
1, environ_name="DB_PSYCOPG_POOL_MIN_SIZE", environ_prefix=None
|
||||
)
|
||||
DB_PSYCOPG_POOL_MAX_SIZE = values.PositiveIntegerValue(
|
||||
3, environ_name="DB_PSYCOPG_POOL_MAX_SIZE", environ_prefix=None
|
||||
)
|
||||
DB_PSYCOPG_POOL_TIMEOUT = values.FloatValue(
|
||||
30.0, environ_name="DB_PSYCOPG_POOL_TIMEOUT", environ_prefix=None
|
||||
)
|
||||
DB_PSYCOPG_POOL_MAX_IDLE = values.FloatValue(
|
||||
600.0, environ_name="DB_PSYCOPG_POOL_MAX_IDLE", environ_prefix=None
|
||||
)
|
||||
DEFAULT_AUTO_FIELD = "django.db.models.AutoField"
|
||||
|
||||
# Static files (CSS, JavaScript, Images)
|
||||
@@ -404,6 +431,16 @@ class Base(Configuration):
|
||||
environ_name="ROOM_CREATION_DAILY_THROTTLE_RATES",
|
||||
environ_prefix=None,
|
||||
),
|
||||
"start_recording": values.Value(
|
||||
default="10/minute",
|
||||
environ_name="START_RECORDING_THROTTLE_RATES",
|
||||
environ_prefix=None,
|
||||
),
|
||||
"start_recording_daily": values.Value(
|
||||
default="100/day",
|
||||
environ_name="START_RECORDING_DAILY_THROTTLE_RATES",
|
||||
environ_prefix=None,
|
||||
),
|
||||
"request_entry": values.Value(
|
||||
default="150/minute",
|
||||
environ_name="REQUEST_ENTRY_THROTTLE_RATES",
|
||||
@@ -579,6 +616,14 @@ class Base(Configuration):
|
||||
environ_name="OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION",
|
||||
environ_prefix=None,
|
||||
)
|
||||
# WARNING: Enabling this setting allows multiple user accounts to share the same email
|
||||
# address. This may cause security issues and is not recommended for production use when
|
||||
# email is activated as fallback for identification
|
||||
OIDC_ALLOW_DUPLICATE_EMAILS = values.BooleanValue(
|
||||
default=False,
|
||||
environ_name="OIDC_ALLOW_DUPLICATE_EMAILS",
|
||||
environ_prefix=None,
|
||||
)
|
||||
OIDC_USER_SUB_FIELD_IMMUTABLE = values.BooleanValue(
|
||||
default=True, environ_name="OIDC_USER_SUB_FIELD_IMMUTABLE", environ_prefix=None
|
||||
)
|
||||
@@ -761,6 +806,28 @@ class Base(Configuration):
|
||||
LIVEKIT_DEFAULT_VIDEO_CODEC = VideoCodecValue(
|
||||
"vp9", environ_name="LIVEKIT_DEFAULT_VIDEO_CODEC", environ_prefix=None
|
||||
)
|
||||
# Livekit websocket reconnection exponential backoff config sent to the frontend.
|
||||
# Before its first reconnection attempt, a client waits a random delay up to the base
|
||||
# delay. That ceiling doubles after every failed attempt, capped at the max delay, and
|
||||
# later delays fall between half the ceiling and the ceiling.
|
||||
# It gives up after the give-up delay unless the media still flows.
|
||||
# After a successful reconnection, a new disconnection starting sooner than the reset
|
||||
# delay after the last one resumes the backoff one step above where that one stopped.
|
||||
LIVEKIT_RECONNECT_BACKOFF_ENABLED = values.BooleanValue(
|
||||
True, environ_name="LIVEKIT_RECONNECT_BACKOFF_ENABLED", environ_prefix=None
|
||||
)
|
||||
LIVEKIT_RECONNECT_BASE_DELAY_MS = StrictlyPositiveIntegerValue(
|
||||
1000, environ_name="LIVEKIT_RECONNECT_BASE_DELAY_MS", environ_prefix=None
|
||||
)
|
||||
LIVEKIT_RECONNECT_MAX_DELAY_MS = StrictlyPositiveIntegerValue(
|
||||
10000, environ_name="LIVEKIT_RECONNECT_MAX_DELAY_MS", environ_prefix=None
|
||||
)
|
||||
LIVEKIT_RECONNECT_GIVE_UP_AFTER_MS = StrictlyPositiveIntegerValue(
|
||||
180000, environ_name="LIVEKIT_RECONNECT_GIVE_UP_AFTER_MS", environ_prefix=None
|
||||
)
|
||||
LIVEKIT_RECONNECT_BACKOFF_RESET_MS = values.PositiveIntegerValue(
|
||||
120000, environ_name="LIVEKIT_RECONNECT_BACKOFF_RESET_MS", environ_prefix=None
|
||||
)
|
||||
CONNECTION_TEST_ENABLED = values.BooleanValue(
|
||||
environ_name="CONNECTION_TEST_ENABLED",
|
||||
environ_prefix=None,
|
||||
@@ -788,6 +855,9 @@ class Base(Configuration):
|
||||
LIVEKIT_VERIFY_SSL = values.BooleanValue(
|
||||
True, environ_name="LIVEKIT_VERIFY_SSL", environ_prefix=None
|
||||
)
|
||||
LIVEKIT_API_TIMEOUT_SECONDS = values.PositiveIntegerValue(
|
||||
10, environ_name="LIVEKIT_API_TIMEOUT_SECONDS", environ_prefix=None
|
||||
)
|
||||
# Regex to filter webhook events by room name. Only matching events are processed.
|
||||
LIVEKIT_WEBHOOK_EVENTS_FILTER_REGEX = values.Value(
|
||||
None, environ_name="LIVEKIT_WEBHOOK_EVENTS_FILTER_REGEX", environ_prefix=None
|
||||
@@ -1530,6 +1600,50 @@ class Base(Configuration):
|
||||
f"'{cls.AUDIT_LOG_DATA_STREAM_NAMESPACE}' must not contain '-'."
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _configure_database_pool(cls):
|
||||
"""Inject the psycopg pool options into the default database when enabled."""
|
||||
if not cls.DB_PSYCOPG_POOL_ENABLED:
|
||||
return
|
||||
|
||||
database = cls.DATABASES["default"]
|
||||
if database.get("ENGINE") not in (
|
||||
"django.db.backends.postgresql",
|
||||
"django.db.backends.postgresql_psycopg2",
|
||||
):
|
||||
raise ImproperlyConfigured(
|
||||
"DB_PSYCOPG_POOL_ENABLED requires the django.db.backends.postgresql "
|
||||
f"engine, got {database.get('ENGINE')!r}."
|
||||
)
|
||||
if database.get("CONN_MAX_AGE"):
|
||||
raise ImproperlyConfigured(
|
||||
"DB_PSYCOPG_POOL_ENABLED cannot be combined with persistent "
|
||||
"connections; set CONN_MAX_AGE to 0."
|
||||
)
|
||||
if cls.DB_PSYCOPG_POOL_MIN_SIZE > cls.DB_PSYCOPG_POOL_MAX_SIZE:
|
||||
raise ImproperlyConfigured(
|
||||
"DB_PSYCOPG_POOL_MIN_SIZE cannot be greater than "
|
||||
"DB_PSYCOPG_POOL_MAX_SIZE."
|
||||
)
|
||||
if cls.DB_PSYCOPG_POOL_TIMEOUT <= 0 or cls.DB_PSYCOPG_POOL_MAX_IDLE <= 0:
|
||||
raise ImproperlyConfigured(
|
||||
"DB_PSYCOPG_POOL_TIMEOUT and DB_PSYCOPG_POOL_MAX_IDLE must be positive."
|
||||
)
|
||||
|
||||
database["OPTIONS"] = {
|
||||
"keepalives_idle": 60,
|
||||
"keepalives_interval": 10,
|
||||
"keepalives_count": 5,
|
||||
**database.get("OPTIONS", {}),
|
||||
"pool": {
|
||||
"min_size": cls.DB_PSYCOPG_POOL_MIN_SIZE,
|
||||
"max_size": cls.DB_PSYCOPG_POOL_MAX_SIZE,
|
||||
"timeout": cls.DB_PSYCOPG_POOL_TIMEOUT,
|
||||
"max_idle": cls.DB_PSYCOPG_POOL_MAX_IDLE,
|
||||
},
|
||||
}
|
||||
database["CONN_HEALTH_CHECKS"] = True
|
||||
|
||||
@classmethod
|
||||
def post_setup(cls):
|
||||
"""Post setup configuration.
|
||||
@@ -1545,6 +1659,19 @@ class Base(Configuration):
|
||||
|
||||
cls._check_recording_encoding_maps()
|
||||
cls._check_audit_log_data_stream_namespace()
|
||||
cls._configure_database_pool()
|
||||
|
||||
if cls.LIVEKIT_API_TIMEOUT_SECONDS < 1:
|
||||
raise ValueError("LIVEKIT_API_TIMEOUT_SECONDS must be at least 1")
|
||||
|
||||
if (
|
||||
cls.OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION
|
||||
and cls.OIDC_ALLOW_DUPLICATE_EMAILS
|
||||
):
|
||||
raise ValueError(
|
||||
"Both OIDC_FALLBACK_TO_EMAIL_FOR_IDENTIFICATION and "
|
||||
"OIDC_ALLOW_DUPLICATE_EMAILS cannot be set to True simultaneously."
|
||||
)
|
||||
|
||||
if (
|
||||
cls.SUMMARY_SERVICE_VERSION == 1
|
||||
|
||||
+25
-24
@@ -2,12 +2,12 @@
|
||||
# Meet package
|
||||
#
|
||||
[build-system]
|
||||
requires = ["uv_build>=0.12.6,<0.13.0"]
|
||||
requires = ["uv_build>=0.13.5,<0.14.0"]
|
||||
build-backend = "uv_build"
|
||||
|
||||
[project]
|
||||
name = "meet"
|
||||
version = "1.35.0"
|
||||
version = "1.37.0"
|
||||
authors = [{ "name" = "DINUM", "email" = "dev@mail.numerique.gouv.fr" }]
|
||||
classifiers = [
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
@@ -24,48 +24,49 @@ keywords = ["Django", "Contacts", "Templates", "RBAC"]
|
||||
license = "MIT"
|
||||
requires-python = ">=3.13"
|
||||
dependencies = [
|
||||
"boto3==1.43.80",
|
||||
"Brotli==1.2.0",
|
||||
"boto3==1.43.118",
|
||||
"Brotli==1.2.1",
|
||||
"brevo-python==1.2.0",
|
||||
"celery[redis]==5.6.3",
|
||||
"dj-database-url==3.1.2",
|
||||
"django-configurations==2.5.1",
|
||||
"django-cors-headers==4.9.0",
|
||||
"django-countries==9.0.0",
|
||||
"django-filter==26.1",
|
||||
"django-lasuite[all]==0.0.29",
|
||||
"django-countries==9.1.0",
|
||||
"django-filter==26.2",
|
||||
"django-lasuite[all]==1.0.0",
|
||||
"django-parler==2.4",
|
||||
"redis==5.2.1",
|
||||
"django-redis==7.0.0",
|
||||
"django-storages[s3]==1.14.6",
|
||||
"django-timezone-field>=5.1",
|
||||
"django-pydantic-field==0.5.4",
|
||||
"django-pydantic-field==0.5.6",
|
||||
"django==5.2.17",
|
||||
"djangorestframework==3.18.0",
|
||||
"djangorestframework==3.18.3",
|
||||
"drf_spectacular==0.30.0",
|
||||
"dockerflow==2026.3.4",
|
||||
"easy_thumbnails==2.10.1",
|
||||
"factory_boy==3.3.3",
|
||||
"gunicorn==26.2.0",
|
||||
"jsonschema==4.26.0",
|
||||
"markdown==3.10.3",
|
||||
"markdown==3.11.2",
|
||||
"menshen-client==0.2.0",
|
||||
"nested-multipart-parser==1.6.0",
|
||||
"posthog==7.44.0",
|
||||
"psycopg[binary]==3.3.4",
|
||||
"pydantic==2.13.4",
|
||||
"PyJWT==2.14.0",
|
||||
"posthog==7.75.11",
|
||||
"psycopg[binary,pool]==3.3.6",
|
||||
"pydantic==2.14.1",
|
||||
"PyJWT==2.15.1",
|
||||
"python-frontmatter==1.3.0",
|
||||
"python-magic==0.4.27",
|
||||
"requests==2.34.2",
|
||||
"sentry-sdk==2.68.1",
|
||||
"sentry-sdk==2.73.0",
|
||||
"whitenoise==6.12.0",
|
||||
"mozilla-django-oidc==5.0.2",
|
||||
"livekit-api==1.2.0",
|
||||
"aiohttp==3.14.3",
|
||||
"livekit-api==1.2.2",
|
||||
"aiohttp==3.14.5",
|
||||
"urllib3==2.8.0",
|
||||
"phonenumbers==9.0.37",
|
||||
"cryptography==50.0.1", # CVE-2026-69247
|
||||
"phonenumbers==9.0.41",
|
||||
"cryptography==50.0.2", # CVE-2026-69247
|
||||
"pillow==13.0.0", # CVE-2026-112403
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
@@ -77,10 +78,10 @@ dependencies = [
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"django-extensions==4.1",
|
||||
"drf-spectacular-sidecar==2026.8.1",
|
||||
"drf-spectacular-sidecar==2026.10.1",
|
||||
"freezegun==1.5.5",
|
||||
"ipdb==0.13.13",
|
||||
"ipython==9.16.1",
|
||||
"ipython==9.17.1",
|
||||
"pyfakefs==6.2.0",
|
||||
"pylint-django==2.8.0",
|
||||
"pylint==4.1.3",
|
||||
@@ -89,9 +90,9 @@ dev = [
|
||||
"pytest==9.1.1",
|
||||
"pytest-icdiff==0.9",
|
||||
"pytest-xdist==3.8.0",
|
||||
"responses==0.26.2",
|
||||
"ruff==0.16.4",
|
||||
"types-requests==2.33.0.20260712",
|
||||
"responses==0.26.3",
|
||||
"ruff==0.17.2",
|
||||
"types-requests==2.33.0.20261006",
|
||||
]
|
||||
|
||||
[tool.uv.build-backend]
|
||||
|
||||
Generated
+510
-364
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,6 @@
|
||||
FROM node:22-alpine AS frontend-deps
|
||||
FROM --platform=$BUILDPLATFORM node:22.23.4-alpine AS frontend-deps
|
||||
|
||||
RUN apk upgrade --no-cache ca-certificates
|
||||
|
||||
USER node
|
||||
|
||||
@@ -45,13 +47,15 @@ ENV VITE_MEDIA_BASE_URL=${VITE_MEDIA_BASE_URL}
|
||||
RUN npm run build
|
||||
|
||||
# ---- Front-end image ----
|
||||
FROM nginxinc/nginx-unprivileged:1.30.4-alpine3.24 AS frontend-production
|
||||
FROM nginxinc/nginx-unprivileged:1.30.6-alpine3.24 AS frontend-production
|
||||
|
||||
USER root
|
||||
RUN apk upgrade --no-cache libexpat && \
|
||||
apk add --no-cache --upgrade 'pcre2>=10.49-r0' 'tiff>=4.7.2-r0' \
|
||||
'libx11>=1.8.14-r0' && \
|
||||
apk del curl
|
||||
'libx11>=1.8.14-r0' 'ca-certificates>=20261020-r0' \
|
||||
'brotli-libs>=1.2.1-r0' 'musl-utils>=1.2.6-r3' && \
|
||||
apk del curl && \
|
||||
rm -f /usr/share/nginx/html/50x.html
|
||||
USER nginx
|
||||
|
||||
# Un-privileged user running the application
|
||||
|
||||
@@ -16,6 +16,17 @@ server {
|
||||
add_header Cache-Control "public, max-age=2592000";
|
||||
}
|
||||
|
||||
location = / {
|
||||
try_files /home.html /index.html;
|
||||
add_header Cache-Control "no-cache, no-store, must-revalidate";
|
||||
add_header Pragma "no-cache";
|
||||
add_header Expires 0;
|
||||
}
|
||||
|
||||
location = /home.html {
|
||||
internal;
|
||||
}
|
||||
|
||||
# Serve static files
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
@@ -23,6 +34,7 @@ server {
|
||||
add_header Cache-Control "no-cache, no-store, must-revalidate";
|
||||
add_header Pragma "no-cache"; # HTTP 1.0 header for backward compatibility
|
||||
add_header Expires 0;
|
||||
add_header X-Robots-Tag "noindex, nofollow" always;
|
||||
}
|
||||
|
||||
# Optionally, handle 404 errors by redirecting to index.html
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
|
||||
<link rel="manifest" href="/site.webmanifest">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="robots" content="noindex, nofollow" />
|
||||
<title>%VITE_APP_TITLE%</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
Generated
+20
-17
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "meet",
|
||||
"version": "1.35.0",
|
||||
"version": "1.37.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "meet",
|
||||
"version": "1.35.0",
|
||||
"version": "1.37.0",
|
||||
"dependencies": {
|
||||
"@fontsource-variable/atkinson-hyperlegible-next": "5.3.0",
|
||||
"@fontsource-variable/lexend": "5.3.0",
|
||||
@@ -21,14 +21,13 @@
|
||||
"@remixicon/react": "4.9.0",
|
||||
"@tanstack/react-query": "5.101.4",
|
||||
"@timephy/rnnoise-wasm": "1.0.0",
|
||||
"crisp-sdk-web": "1.1.2",
|
||||
"hoofd": "1.7.3",
|
||||
"humanize-duration": "3.34.1",
|
||||
"i18next": "26.3.6",
|
||||
"i18next-browser-languagedetector": "8.2.1",
|
||||
"i18next-parser": "9.4.0",
|
||||
"i18next-resources-to-backend": "1.2.3",
|
||||
"livekit-client": "2.21.0",
|
||||
"livekit-client": "2.23.0",
|
||||
"posthog-js": "1.418.10",
|
||||
"react": "18.3.1",
|
||||
"react-aria": "3.51.0",
|
||||
@@ -1028,9 +1027,9 @@
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/@livekit/protocol": {
|
||||
"version": "1.50.4",
|
||||
"resolved": "https://registry.npmjs.org/@livekit/protocol/-/protocol-1.50.4.tgz",
|
||||
"integrity": "sha512-L1uggNQAqyY21smQY8AllyOYbcv9Me9TaxwuLytL1R8ck9nbYPmQLNwEDi3pOFGAMa5F8I2nUi2Jc59W5awxlA==",
|
||||
"version": "1.52.1",
|
||||
"resolved": "https://registry.npmjs.org/@livekit/protocol/-/protocol-1.52.1.tgz",
|
||||
"integrity": "sha512-X8DxKlNbzk6Lh+v630+mjdFHSotdAFwIyzxSRSUql2DbTxCnlpa7JsvFGc6Na3mXiex2OFh0iiQtWwOBP0rIYA==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@bufbuild/protobuf": "^1.10.0"
|
||||
@@ -4563,12 +4562,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/crisp-sdk-web": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/crisp-sdk-web/-/crisp-sdk-web-1.1.2.tgz",
|
||||
"integrity": "sha512-qxSpiT4EGHnVEO6J/t1UURY6fg1ojgquLU0IIr7RNjZxXZs1R2e6AhAiFqxiGZ13Vb4o5VoUpATFU2TzX/ppOQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/cross-spawn": {
|
||||
"version": "7.0.6",
|
||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
||||
@@ -8235,16 +8228,17 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/livekit-client": {
|
||||
"version": "2.21.0",
|
||||
"resolved": "https://registry.npmjs.org/livekit-client/-/livekit-client-2.21.0.tgz",
|
||||
"integrity": "sha512-RBUhPkV/sl1nzl8lokVlK5uATPwn0AlsudCBZXissw/kDl9yz8ac4pNJ43iPpMVoHOeBYH/BZ3vUC1adqa/zFQ==",
|
||||
"version": "2.23.0",
|
||||
"resolved": "https://registry.npmjs.org/livekit-client/-/livekit-client-2.23.0.tgz",
|
||||
"integrity": "sha512-j9Kg86nJjBjNFUD+ukp2jwMCGa0k+YD5gU//RzAM+ZY3pbG631QCte7fQjwqWMmtBzhDJL9nKYuOLMv/9IbAxg==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@livekit/mutex": "1.1.1",
|
||||
"@livekit/protocol": "1.50.4",
|
||||
"@livekit/protocol": "1.52.1",
|
||||
"events": "^3.3.0",
|
||||
"jose": "^6.1.0",
|
||||
"loglevel": "^1.9.2",
|
||||
"machina": "^7.0.0",
|
||||
"sdp-transform": "^2.15.0",
|
||||
"tslib": "2.8.1",
|
||||
"typed-emitter": "^2.1.0",
|
||||
@@ -8353,6 +8347,15 @@
|
||||
"yallist": "^3.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/machina": {
|
||||
"version": "7.0.1",
|
||||
"resolved": "https://registry.npmjs.org/machina/-/machina-7.0.1.tgz",
|
||||
"integrity": "sha512-0Xkgs8NeBvO2hW6bjJT8ewLWrMfh1haMPstaghpASWjXkLjRhtDiaJG1Kb7mslaOHxZYxpH7PIjpmirRVYbMMA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=22.22"
|
||||
}
|
||||
},
|
||||
"node_modules/magic-string": {
|
||||
"version": "0.30.21",
|
||||
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "meet",
|
||||
"private": true,
|
||||
"version": "1.35.0",
|
||||
"version": "1.37.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "panda codegen && vite",
|
||||
@@ -29,14 +29,13 @@
|
||||
"@remixicon/react": "4.9.0",
|
||||
"@tanstack/react-query": "5.101.4",
|
||||
"@timephy/rnnoise-wasm": "1.0.0",
|
||||
"crisp-sdk-web": "1.1.2",
|
||||
"hoofd": "1.7.3",
|
||||
"humanize-duration": "3.34.1",
|
||||
"i18next": "26.3.6",
|
||||
"i18next-browser-languagedetector": "8.2.1",
|
||||
"i18next-parser": "9.4.0",
|
||||
"i18next-resources-to-backend": "1.2.3",
|
||||
"livekit-client": "2.21.0",
|
||||
"livekit-client": "2.23.0",
|
||||
"posthog-js": "1.418.10",
|
||||
"react": "18.3.1",
|
||||
"react-aria": "3.51.0",
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
User-agent: GPTBot
|
||||
User-agent: OAI-SearchBot
|
||||
User-agent: ChatGPT-User
|
||||
User-agent: ClaudeBot
|
||||
User-agent: Claude-SearchBot
|
||||
User-agent: Claude-User
|
||||
User-agent: PerplexityBot
|
||||
User-agent: Perplexity-User
|
||||
User-agent: Google-Extended
|
||||
User-agent: Applebot-Extended
|
||||
User-agent: CCBot
|
||||
User-agent: Meta-ExternalAgent
|
||||
User-agent: Amazonbot
|
||||
User-agent: Bytespider
|
||||
Disallow: /
|
||||
|
||||
User-agent: *
|
||||
Allow: /
|
||||
@@ -13,7 +13,9 @@ export interface ApiConfig {
|
||||
flags_api_host?: string
|
||||
}
|
||||
support?: {
|
||||
id: string
|
||||
widget_script_url?: string
|
||||
widget_api_url?: string
|
||||
widget_channel?: string
|
||||
help_article_transcript: string
|
||||
help_article_recording: string
|
||||
help_article_more_tools: string
|
||||
@@ -73,6 +75,13 @@ export interface ApiConfig {
|
||||
enable_firefox_proxy_workaround: boolean
|
||||
default_sources: Source[]
|
||||
default_video_codec: VideoCodec
|
||||
reconnect?: {
|
||||
backoff_enabled: boolean
|
||||
base_delay_ms: number
|
||||
max_delay_ms: number
|
||||
give_up_after_ms: number
|
||||
backoff_reset_ms: number
|
||||
}
|
||||
}
|
||||
transcription_destination?: string
|
||||
max_participants_for_sound: number
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useConfig } from '@/api/useConfig'
|
||||
import { useAnalytics } from '@/features/analytics/hooks/useAnalytics'
|
||||
import { useSupport } from '@/features/support/hooks/useSupport'
|
||||
import { useSyncUserPreferencesWithBackend } from '@/features/auth/api/useSyncUserPreferencesWithBackend'
|
||||
import { useEffect } from 'react'
|
||||
|
||||
@@ -8,10 +7,9 @@ export const AppInitialization = () => {
|
||||
const { data } = useConfig()
|
||||
useSyncUserPreferencesWithBackend()
|
||||
|
||||
const { analytics = {}, support = {}, custom_css_url = '' } = data ?? {}
|
||||
const { analytics = {}, custom_css_url = '' } = data ?? {}
|
||||
|
||||
useAnalytics(analytics)
|
||||
useSupport(support)
|
||||
|
||||
useEffect(() => {
|
||||
if (custom_css_url) {
|
||||
|
||||
@@ -2,12 +2,6 @@ import type { CaptureResult } from 'posthog-js'
|
||||
|
||||
const IGNORED_EXCEPTION_PATTERNS = [
|
||||
/ResizeObserver loop (completed with undelivered notifications|limit exceeded)/,
|
||||
// livekit-client leaks the raw WebSocket error Event as an unhandled
|
||||
// rejection when the signal ws errors after connect (Firefox-heavy,
|
||||
// coincides with signal reconnects). Carries zero diagnostic content —
|
||||
// the close reason is already logged by the SDK.
|
||||
// See: https://github.com/livekit/client-sdk-js/issues/2062
|
||||
/^Event captured as exception with keys: isTrusted$/,
|
||||
]
|
||||
|
||||
const shouldIgnoreException = (value: unknown): boolean =>
|
||||
|
||||
@@ -32,6 +32,7 @@ export type LogCode =
|
||||
| 'fullscreen_failure'
|
||||
| 'publish_sources_failure'
|
||||
| 'disconnect_failure'
|
||||
| 'support_widget_failure'
|
||||
| 'generic_failure'
|
||||
|
||||
export const reportError = (
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { apiUrl } from '@/api/apiUrl'
|
||||
import { terminateSupportSession } from '@/features/support/hooks/useSupport'
|
||||
import { terminateAnalyticsSession } from '@/features/analytics/hooks/useAnalytics'
|
||||
|
||||
const logoutUrl = () => {
|
||||
@@ -8,6 +7,5 @@ const logoutUrl = () => {
|
||||
|
||||
export const logout = async () => {
|
||||
await terminateAnalyticsSession()
|
||||
terminateSupportSession()
|
||||
window.location.href = logoutUrl()
|
||||
}
|
||||
|
||||
@@ -9,12 +9,8 @@ import { useState } from 'react'
|
||||
|
||||
import { menuRecipe } from '@/primitives/menuRecipe'
|
||||
import { ApiRoom } from '@/features/rooms/api/ApiRoom'
|
||||
import { useSnapshot } from 'valtio'
|
||||
import { userStore } from '@/stores/user'
|
||||
|
||||
export const CreateMeetingMenu = () => {
|
||||
const { username } = useSnapshot(userStore)
|
||||
|
||||
const { t } = useTranslation('home')
|
||||
const { mutateAsync: createRoom } = useCreateRoom()
|
||||
const [laterRoom, setLaterRoom] = useState<null | ApiRoom>(null)
|
||||
@@ -30,9 +26,9 @@ export const CreateMeetingMenu = () => {
|
||||
className={menuRecipe({ icon: true, variant: 'light' }).item}
|
||||
onAction={() => {
|
||||
const slug = generateRoomId()
|
||||
createRoom({ slug, username }).then((data) =>
|
||||
createRoom({ slug }).then((data) =>
|
||||
navigateTo('room', data.slug, {
|
||||
state: { create: true, initialRoomData: data },
|
||||
state: { create: true },
|
||||
})
|
||||
)
|
||||
}}
|
||||
@@ -45,7 +41,7 @@ export const CreateMeetingMenu = () => {
|
||||
className={menuRecipe({ icon: true, variant: 'light' }).item}
|
||||
onAction={() => {
|
||||
const slug = generateRoomId()
|
||||
createRoom({ slug, username }).then(setLaterRoom)
|
||||
createRoom({ slug }).then(setLaterRoom)
|
||||
}}
|
||||
data-attr="create-option-later"
|
||||
>
|
||||
|
||||
@@ -96,6 +96,8 @@ export const MainNotificationToast = () => {
|
||||
case NotificationType.ScreenRecordingStopped:
|
||||
case NotificationType.TranscriptionLimitReached:
|
||||
case NotificationType.ScreenRecordingLimitReached:
|
||||
case NotificationType.TranscriptionInterrupted:
|
||||
case NotificationType.ScreenRecordingInterrupted:
|
||||
case NotificationType.TranscriptionFailed:
|
||||
case NotificationType.ScreenRecordingFailed:
|
||||
case NotificationType.TranscriptionAborted:
|
||||
|
||||
@@ -10,6 +10,7 @@ export enum NotificationType {
|
||||
TranscriptionStarted = 'transcriptionStarted',
|
||||
TranscriptionStopped = 'transcriptionStopped',
|
||||
TranscriptionLimitReached = 'transcriptionLimitReached',
|
||||
TranscriptionInterrupted = 'transcriptionInterrupted',
|
||||
TranscriptionFailed = 'transcriptionFailed',
|
||||
TranscriptionAborted = 'transcriptionAborted',
|
||||
TranscriptionRequested = 'transcriptionRequested',
|
||||
@@ -17,6 +18,7 @@ export enum NotificationType {
|
||||
ScreenRecordingStopped = 'screenRecordingStopped',
|
||||
ScreenRecordingRequested = 'screenRecordingRequested',
|
||||
ScreenRecordingLimitReached = 'screenRecordingLimitReached',
|
||||
ScreenRecordingInterrupted = 'screenRecordingInterrupted',
|
||||
ScreenRecordingFailed = 'screenRecordingFailed',
|
||||
ScreenRecordingAborted = 'screenRecordingAborted',
|
||||
RecordingSaving = 'recordingSaving',
|
||||
|
||||
@@ -22,6 +22,8 @@ export function ToastAnyRecording({ state, ...props }: Readonly<ToastProps>) {
|
||||
return 'transcript.stopped'
|
||||
case NotificationType.TranscriptionLimitReached:
|
||||
return 'transcript.limitReached'
|
||||
case NotificationType.TranscriptionInterrupted:
|
||||
return 'transcript.interrupted'
|
||||
case NotificationType.TranscriptionFailed:
|
||||
return 'transcript.failed'
|
||||
case NotificationType.TranscriptionAborted:
|
||||
@@ -32,6 +34,8 @@ export function ToastAnyRecording({ state, ...props }: Readonly<ToastProps>) {
|
||||
return 'screenRecording.stopped'
|
||||
case NotificationType.ScreenRecordingLimitReached:
|
||||
return 'screenRecording.limitReached'
|
||||
case NotificationType.ScreenRecordingInterrupted:
|
||||
return 'screenRecording.interrupted'
|
||||
case NotificationType.ScreenRecordingFailed:
|
||||
return 'screenRecording.failed'
|
||||
case NotificationType.ScreenRecordingAborted:
|
||||
|
||||
@@ -58,6 +58,8 @@ const renderToast = (
|
||||
case NotificationType.ScreenRecordingStarted:
|
||||
case NotificationType.ScreenRecordingStopped:
|
||||
case NotificationType.ScreenRecordingLimitReached:
|
||||
case NotificationType.TranscriptionInterrupted:
|
||||
case NotificationType.ScreenRecordingInterrupted:
|
||||
case NotificationType.TranscriptionFailed:
|
||||
case NotificationType.ScreenRecordingFailed:
|
||||
case NotificationType.TranscriptionAborted:
|
||||
|
||||
@@ -12,6 +12,10 @@ export const useRecordingWaitingForTracks = (mode: RecordingMode) => {
|
||||
mode === RecordingMode.Transcript ? [Track.Source.Microphone] : undefined,
|
||||
{ onlySubscribed: false }
|
||||
)
|
||||
const hasTracks =
|
||||
mode === RecordingMode.Transcript
|
||||
? tracks.some((track) => !track.publication.isMuted)
|
||||
: tracks.length > 0
|
||||
const [delayElapsed, setDelayElapsed] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
@@ -25,5 +29,5 @@ export const useRecordingWaitingForTracks = (mode: RecordingMode) => {
|
||||
return () => window.clearTimeout(timeout)
|
||||
}, [isStarting, mode])
|
||||
|
||||
return isStarting && delayElapsed && tracks.length === 0
|
||||
return isStarting && delayElapsed && !hasTracks
|
||||
}
|
||||
|
||||
@@ -31,7 +31,6 @@ export type ApiRoom = {
|
||||
name: string
|
||||
slug: string
|
||||
pin_code?: string
|
||||
is_administrable: boolean
|
||||
access_level: ApiAccessLevel
|
||||
livekit?: ApiLiveKit
|
||||
configuration?: RoomConfiguration
|
||||
|
||||
@@ -6,15 +6,13 @@ import type { ApiRoom } from './ApiRoom'
|
||||
export interface CreateRoomParams {
|
||||
slug: string
|
||||
callbackId?: string
|
||||
username?: string
|
||||
}
|
||||
|
||||
const createRoom = ({
|
||||
slug,
|
||||
callbackId,
|
||||
username = '',
|
||||
}: CreateRoomParams): Promise<ApiRoom> => {
|
||||
return fetchApi(`rooms/?username=${encodeURIComponent(username)}`, {
|
||||
return fetchApi('rooms/', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
name: slug,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user