Stop probing the homeserver when using the CS API which always includes the delegation endpoint

This commit is contained in:
Johannes Marbach
2026-11-25 12:02:02 +01:00
parent 511848ccdd
commit 1d982467f7
4 changed files with 51 additions and 58 deletions
+6 -5
View File
@@ -228,10 +228,9 @@ for (const { shape, via } of delegationCases) {
await SpaHelpers.expectVideoTilesCount(page, 2);
await SpaHelpers.expectVideoTilesCount(guestPage, 2);
// The guest handed its delayed leave over, after probing for delegation
// support with bodiless requests, which count as supported unless they
// 404. The homeserver is always probed; the JWT service only when there
// is one.
// The guest handed its delayed leave over. A JWT service is first probed
// for delegation support with a bodiless request, which counts as
// supported unless it 404s. A homeserver that issued the token is not.
await expect
.poll(() => delegations.at(-1))
.toEqual({
@@ -241,7 +240,9 @@ for (const { shape, via } of delegationCases) {
...(via === "homeserver" && { sfuUrl }),
});
const probes = delegations.slice(0, -1);
expect(probes.some((probe) => probe.via === via)).toBe(true);
expect(probes.map((probe) => probe.via)).toEqual(
via === "service" ? ["service"] : [],
);
for (const probe of probes) {
expect(probe.status).toBeGreaterThanOrEqual(400);
expect(probe.status).not.toBe(404);
+7 -6
View File
@@ -121,10 +121,10 @@ LiveKit participants.
The session discovers the transport from the homeserver and the backend prepares
it, both before `join()`, so that the membership can name it and the first frames
go out as soon as the state event is sent. Preparing is the backend's own
business: for LiveKit the token exchange for the publisher connection, and the
probe that decides whether the service that issued the token can take over the
delayed leave, which picks the delayed leave timings the join uses. The join
waits for the publisher to hold its token, so that the LiveKit room exists
business: for LiveKit the token exchange for the publisher connection, and
with it whether that service can take over the delayed leave (assumed for a homeserver
probed for a JWT service), which picks the delayed leave timings the join uses. The
join waits for the publisher to hold its token, so that the LiveKit room exists
before a subscriber, who lacks the permission to create it, asks for a token
of its own. The tracks are created once the membership is `joined`, with their
upstream paused until then. A lobby that wants them earlier captures them with
@@ -603,8 +603,9 @@ homeserver that advertises a `url` without implementing MSC4195 is misconfigured
and fails with `NoMatrix2AuthorizationService`, so the admin hears about it.
The MatrixRTC mode plays no part in the choice. The delayed leave is delegated
through the same flow that issued the publisher's token, so that the identity
the service watches for on the SFU is the one we publish under, and the
delegation probe before the join asks only that service.
the service watches for on the SFU is the one we publish under. A homeserver
that issued the token is assumed to delegate. Only a JWT service is probed,
before the join.
The client-server API needs the name of the homeserver the transport belongs to:
our own homeserver asks that server for the token, over federation where it is
@@ -148,7 +148,6 @@ describe("toMediaConnectionState", () => {
describe("createLivekitBackend", () => {
const homeserver = "https://matrix.example.org";
const homeserverEndpoint = `${homeserver}/_matrix/client/unstable/io.element.msc4195/rtc/livekit/delegate_delayed_leave`;
const urlTransport: UnstableLivekitTransport = {
type: "livekit",
url: "wss://sfu.example.org",
@@ -235,14 +234,13 @@ describe("createLivekitBackend", () => {
// publisher: the JWT service wherever the transport names one, the
// homeserver for a `url` alone
it.each([
["the JWT service", exampleTransport, 404, 401, true],
["the JWT service, and only it", bothTransport, 401, 404, false],
["the homeserver", urlTransport, 401, 404, true],
["neither", exampleTransport, 404, 404, false],
["a JWT service that delegates", exampleTransport, 401, true],
["a JWT service that does not", exampleTransport, 404, false],
["the JWT service over the homeserver", bothTransport, 401, true],
["the homeserver", urlTransport, 404, true],
])(
"prepares the local transport and asks %s about delegation",
async (_name, transport, homeserverStatus, serviceStatus, expected) => {
fetchMock.post(homeserverEndpoint, homeserverStatus);
"prepares the local transport for delegation through %s",
async (_name, transport, serviceStatus, expected) => {
fetchMock.post(
`${exampleServiceUrl}/delegate_delayed_leave`,
serviceStatus,
@@ -251,6 +249,10 @@ describe("createLivekitBackend", () => {
const capabilities = await backend().prepareLocalTransport(transport);
expect(capabilities).toEqual({ canDelegateDelayedLeave: expected });
// Only the service that issued the publisher's token is asked.
expect(
fetchMock.called(`${exampleServiceUrl}/delegate_delayed_leave`),
).toBe("livekit_service_url" in transport);
expect(connections).toHaveLength(1);
expect(connections[0].connection.role).toBe("publisher");
expect(connections[0].connection.transport).toEqual(transport);
@@ -259,9 +261,8 @@ describe("createLivekitBackend", () => {
);
it("prepares a remote SFU's transport on its homeserver, where delegation is not possible", async () => {
// Our own homeserver would delegate, so only the SFU being remote can
// explain delegation being skipped
fetchMock.post(homeserverEndpoint, 401);
// A token through the homeserver means delegation, unless the SFU is
// another homeserver's.
const remoteTransport: UnstableLivekitTransport = {
type: "livekit",
url: "wss://sfu.sample.com",
@@ -276,7 +277,6 @@ describe("createLivekitBackend", () => {
});
it("waits for the publisher connection to hold its token before the join", async () => {
fetchMock.post(homeserverEndpoint, 404);
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
stubFactory({ state: "authenticating" });
@@ -293,7 +293,6 @@ describe("createLivekitBackend", () => {
});
it("fails the preparation with the publisher connection's error", async () => {
fetchMock.post(homeserverEndpoint, 404);
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
stubFactory({ state: "authenticating" });
const preparing = backend().prepareLocalTransport(exampleTransport);
@@ -304,7 +303,6 @@ describe("createLivekitBackend", () => {
});
it("delegates the leave through the flow that authenticated the publisher", async () => {
fetchMock.post(homeserverEndpoint, 401);
const delegate = vi.spyOn(auth, "delegateDelayedLeave").mockResolvedValue();
const b = backend();
await expect(b.delegateDelayedLeave("delay-1")).rejects.toThrow(
@@ -359,7 +357,6 @@ describe("createLivekitBackend", () => {
async function prepared(): Promise<
ReturnType<typeof createLivekitBackend>
> {
fetchMock.post(homeserverEndpoint, 404);
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
const b = backend();
await b.prepareLocalTransport(bothTransport);
+26 -32
View File
@@ -69,7 +69,7 @@ import { createLivekitLocalMedia } from "./LocalMedia";
export interface LivekitBackendOptions {
/**
* `getOpenIdToken` for the JWT service flow, the MSC4195 methods for the
* client-server API flow, `baseUrl` for the delegation probe and handover.
* client-server API flow, `baseUrl` for the delegation handover.
*/
client: Pick<
MatrixClient,
@@ -143,13 +143,6 @@ export function createLivekitBackend(
logger,
});
// Probed once: the answer cannot change within a session
const homeserverSupportsDelegation = supportsDelegation(
`${client.baseUrl}/_matrix/client/unstable/io.element.msc4195/rtc/livekit/delegate_delayed_leave`,
"homeserver",
logger,
);
const ownServerName = serverNameOf(ownMembershipIdentity.userId);
const prepareLocalTransport = async (
@@ -162,35 +155,36 @@ export function createLivekitBackend(
ownMembershipIdentity.userId,
);
const locator: TransportLocator = { transport, serverName };
let canDelegate: Promise<boolean>;
if (serverName !== ownServerName) {
// Our homeserver only takes over leaves for its own SFUs
logger.info(
`Publishing on a remote SFU of ${serverName}, delegation is not possible`,
);
canDelegate = Promise.resolve(false);
} else {
// Check for support using the same auth flow that we intend to use later
const flow = chooseAuthFlow(transport);
canDelegate =
flow.kind === "openID"
? supportsDelegation(
`${flow.serviceUrl}/delegate_delayed_leave`,
`transport ${flow.serviceUrl}`,
logger,
)
: homeserverSupportsDelegation;
}
localTransport$.next(locator);
// The membership is only sent once the publisher connection holds its
// token, so that the LiveKit room exists before anyone subscribes to it:
// a subscriber lacks the permission to create it and would fail without
// retrying
const [, canDelegateDelayedLeave] = await Promise.all([
authenticated(localMedia_.connection$),
canDelegate,
]);
return { canDelegateDelayedLeave };
await authenticated(localMedia_.connection$);
if (serverName !== ownServerName) {
// Our homeserver only takes over leaves for its own SFUs
logger.info(
`Publishing on a remote SFU of ${serverName}, delegation is not possible`,
);
return { canDelegateDelayedLeave: false };
}
// Now that we are authenticated, check which flow was used so that we can
// use the same flow for delegation.
const flow = chooseAuthFlow(transport);
if (flow.kind === "csApi") {
// If the client-server authentication endpoint is available, the delegation
// endpoint is available, too. Both have been released together in lk-jwt-service.
return { canDelegateDelayedLeave: true };
}
// The OpenID flow was used but the lk-jwt-instance may still predate delegation. Check
// if the delegation endpoint is supported.
return {
canDelegateDelayedLeave: await supportsDelegation(
`${flow.serviceUrl}/delegate_delayed_leave`,
`transport ${flow.serviceUrl}`,
logger,
),
};
};
const delegateLeave = async (delayId: string): Promise<void> => {