Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion doc/concept/moq-lite.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,12 @@ to a prefix. Right after setup both sides present the credential the connection
already carried (the URL token, a client certificate, or nothing), so a
publisher learns before anyone subscribes whether its broadcasts can reach the
peer. More tokens can be added without reconnecting; the session's scope is the
union of every open token's grant. A token the peer has no verifier for, or
union of every open token's grant. A request outside the known union waits
while a non-empty token already presented is unanswered, then proceeds or
fails against the settled union; a covered request does not wait. Each wait
logs its path and duration. To renew without interrupting live requests the
new grant still covers, await the new token's acceptance before dropping the
old one. A token the peer has no verifier for, or
whose grant is too large to send, fails with `Unsupported` and ends only that
token; the session and its other grants stay up. A relay with an
[auth server](/bin/relay/auth#in-band-renewal) verifies these tokens through it,
Expand Down
10 changes: 9 additions & 1 deletion drafts/draft-lcurley-moq-lite.md
Original file line number Diff line number Diff line change
Expand Up @@ -563,6 +563,7 @@ Either endpoint can open an Auth Stream (0x7) to present a token and learn what
The opener sends a single AUTH message and keeps its side open for as long as the token applies.
Each endpoint SHOULD open one Auth Stream with an empty token right after the session starts, so both learn what the credential the connection already presented (the request URI, a client certificate, or nothing) allows.
The acceptor replies with an AUTH_OK carrying the grant, or an AUTH_ERROR refusing the token.
The grant MUST join the acceptor's scope before it sends AUTH_OK.
It MAY send further AUTH_OK messages to replace the grant, such as with a lowered expiry, and MAY send an AUTH_ERROR after an AUTH_OK to revoke it; the latest AUTH_OK is the token's grant.
After an AUTH_ERROR the acceptor closes its side of the stream.
The opener withdraws a token by closing or resetting its side of the stream, and the acceptor then closes its own.
Expand All @@ -571,7 +572,13 @@ A grant names the paths the opener may publish to the acceptor and subscribe to
An endpoint's scope is the union of the grants of its open Auth Streams, and a stream that ends removes its grant from the union.
When the union shrinks, an endpoint SHOULD withdraw its announcements and cancel its subscriptions that the union no longer covers, keeping the session and everything still covered.
An endpoint that cancels a subscription, or refuses or stops serving a request, because the union does not cover it resets the stream with UNAUTHORIZED.
An endpoint that announces a broadcast outside the union once its own setup tokens are answered SHOULD close the session with UNAUTHORIZED, rather than wait for a subscription that will never come.
The acceptor judges each request against the union when it reads the request.
A presenter MUST NOT send a request outside its known union while any non-empty token it presented remains unanswered; an unknown union covers no paths for this rule.
Once those tokens are answered, it sends the request if the union covers it, or refuses it locally.
An empty token does not hold requests: the connection credential is judged before the session serves requests.
The same wait applies before closing the session for announcing a broadcast outside the union.
An endpoint that announces a broadcast outside the settled union, and still announces it once the wait ends, SHOULD close the session with UNAUTHORIZED, rather than wait for a subscription that will never come.
To renew a token without interrupting requests the new grant still covers, the presenter waits for the new token's AUTH_OK before withdrawing the old token.

An acceptor that does not verify a token in band, or cannot express its grant in AUTH_OK, MUST send AUTH_ERROR with NOT_SUPPORTED and close its side of the stream.
This applies before or after an AUTH_OK, including when a grant exceeds the message size limit.
Expand Down Expand Up @@ -1635,6 +1642,7 @@ The `Message Length` describes the payload size on the wire.
- A Report-level publisher reads and ignores PROBE targets instead of resetting the Probe Stream.
- Added NOT_SUPPORTED (0x30) to session errors; unsupported Auth Stream tokens and grants use AUTH_ERROR before or after a grant.
- Added the Auth Stream (0x7) with AUTH, AUTH_OK, and AUTH_ERROR: either endpoint presents a token on its own stream and learns the [path patterns](#path-pattern) it may publish and subscribe to. The union of a session's open grants is its scope. A shrink withdraws what it no longer covers, and an announcement outside the scope closes the session with UNAUTHORIZED. A peer without the stream resets it.
- Required scope widening before AUTH_OK and presenter-side waiting for unanswered non-empty tokens before sending an uncovered request or rejecting a publication; renewal waits for AUTH_OK before withdrawing the old token.

## moq-lite-06

Expand Down
306 changes: 305 additions & 1 deletion js/net/src/auth.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, spyOn, test } from "bun:test";
import { Milli, Nano } from "@moq/clock";
import { Manual, Milli, Nano } from "@moq/clock";
import type { Getter } from "@moq/signals";
import { type Grant, type Issued, Unsupported } from "./auth.ts";
import type { AuthSession } from "./auth_session.ts";
Expand All @@ -17,6 +17,7 @@ import { createMockTransportPair, type MockTransport } from "./mock.ts";
import { Producer as OriginProducer } from "./origin.ts";
import * as Path from "./path.ts";
import { type Stream, Writer } from "./stream.ts";
import { abandoned } from "./util/demand.ts";
import { withTimeout } from "./util/timeout.ts";
import { nextTask } from "./util/yield.ts";
import { wireOf } from "./wire.ts";
Expand Down Expand Up @@ -47,6 +48,19 @@ async function waitFor<T>(getter: Getter<T>, ready: (value: T) => boolean): Prom
return value;
}

/** Whether a request on `path` logged the end of its authorization wait. */
function waited(logged: { mock: { calls: unknown[][] } }, path: string): boolean {
return logged.mock.calls.some(([line]) =>
String(line).startsWith(`request waited for authorization: path=${path} `),
);
}

/** Yield until `done` holds, failing if it never does. */
async function settles(done: () => boolean): Promise<void> {
for (let i = 0; i < 50 && !done(); i++) await nextTask();
expect(done()).toBe(true);
}

interface Pair {
client: Established;
server: Established;
Expand Down Expand Up @@ -141,6 +155,39 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_17, Ietf.ALPN.DRAFT_22])("%s",
server.abort();
});

test("a broadcast withdrawn while its token waits is not refused", async () => {
const origin = new OriginProducer();
const { client, server, transport } = await connect({ publish: origin, protocol });
const requests = server.auth.requests();
const setup = await requests.next();
if (!setup) throw new Error("missing setup token");
const initial = setup.accept(grant(["baz"], []));
await waitFor(client.auth.grant, (g) => g !== undefined);
const adding = client.auth.add("new");
try {
const unanswered = await requests.next();
if (!unanswered) throw new Error("missing token");
const withdrawn = origin.createBroadcast(Path.from("foo/bar"));
withdrawn.announce();
await nextTask();
withdrawn.unannounce();
await nextTask();
const issued = unanswered.accept(grant(["other"], []));
await adding;
// Still enforcing: the next uncovered broadcast is the one named.
origin.createBroadcast(Path.from("still-bad")).announce();
const info = await transport.closed;
expect(info.closeCode).toBe(SessionCode.Unauthorized);
expect(info.reason).toBe("unauthorized: still-bad");
issued.close();
} finally {
initial.close();
client.abort();
server.abort();
await adding.catch(() => void 0);
}
});

test("a revoked grant withdraws its broadcasts without closing the session", async () => {
const origin = new OriginProducer();
const { client, server, transport } = await connect({ publish: origin, protocol });
Expand Down Expand Up @@ -240,6 +287,175 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_17, Ietf.ALPN.DRAFT_22])("%s",
server.abort();
});

test("a request waits for its token and survives union renewal", async () => {
const clock = new Manual();
const restore = clock.install();
const logged = spyOn(console, "debug");
const origin = new OriginProducer();
const broadcast = origin.createBroadcast(Path.from("room/x"));
broadcast.announce();
const published = broadcast.createTrack("video");
published.appendGroup().writeFrame({ payload: new Uint8Array([1]) });
const { client, server } = await connect({ serverPublish: origin, protocol });
const requests = server.auth.requests();
await (client.auth as AuthSession).ready(Path.from("room/x"), "subscribe");
const setup = await requests.next();
if (!setup) throw new Error("missing setup token");
const initial = setup.accept(grant([], []));
await waitFor(client.auth.grant, (g) => g !== undefined);
const adding = client.auth.add("first");
try {
const unanswered = await requests.next();
if (!unanswered) throw new Error("missing token");
const track = wireOf(client).consume(Path.from("room/x")).track("video").subscribe();
await nextTask();
expect(track.closed.peek()).toBeUndefined();
clock.advance(Nano.fromMilli(Milli(7)));
const firstGrant = unanswered.accept(grant([], ["room"]));
const first = await adding;
expect(await track.recvGroup()).toBeDefined();
expect(
logged.mock.calls.filter(([line]) => String(line).startsWith("request waited for authorization:")),
).toEqual([["request waited for authorization: path=room/x waited=7ms"]]);
const renewing = client.auth.add("renewal");
const renewal = await requests.next();
if (!renewal) throw new Error("missing renewal");
broadcast
.createTrack("audio")
.appendGroup()
.writeFrame({ payload: new Uint8Array([3]) });
const covered = wireOf(client).consume(Path.from("room/x")).track("audio").subscribe();
expect(await covered.recvGroup()).toBeDefined();
covered.close();
const renewedGrant = renewal.accept(grant([], ["room"]));
const renewed = await renewing;
first.close();
await nextTask();
expect(track.closed.peek()).toBeUndefined();
published.appendGroup().writeFrame({ payload: new Uint8Array([2]) });
expect(await track.recvGroup()).toBeDefined();
track.close();
renewed.close();
firstGrant.close();
renewedGrant.close();
} finally {
initial.close();
client.abort();
server.abort();
await adding.catch(() => void 0);
logged.mockRestore();
restore();
}
});

test("an abandoned request stops waiting for its token", async () => {
const { client, server } = await connect({ protocol });
const requests = server.auth.requests();
const setup = await requests.next();
if (!setup) throw new Error("missing setup token");
const initial = setup.accept(grant([], []));
await waitFor(client.auth.grant, (g) => g !== undefined);
const adding = client.auth.add("first");
try {
const unanswered = await requests.next();
if (!unanswered) throw new Error("missing token");
const track = new OriginProducer().createBroadcast(Path.from("room/x")).createTrack("video");
const reader = track.subscribe();
const ready = (client.auth as AuthSession).ready(Path.from("room/x"), "subscribe", {
until: () => abandoned(track.demand()),
});
let settled = false;
void ready.then(() => {
settled = true;
});
await nextTask();
expect(settled).toBe(false);
reader.close();
expect(await ready).toBe(false);
unanswered.accept(grant([], [])).close();
} finally {
initial.close();
client.abort();
server.abort();
await adding.catch(() => void 0);
}
});

test("a subscribe abandoned while its token waits never reaches the wire", async () => {
const logged = spyOn(console, "debug");
const origin = new OriginProducer();
const broadcast = origin.createBroadcast(Path.from("room/x"));
broadcast.announce();
broadcast.createTrack("video");
const { client, server, transport } = await connect({ serverPublish: origin, protocol });
const requests = server.auth.requests();
const setup = await requests.next();
if (!setup) throw new Error("missing setup token");
const initial = setup.accept(grant([], []));
await waitFor(client.auth.grant, (g) => g !== undefined);
const adding = client.auth.add("first");
try {
const unanswered = await requests.next();
if (!unanswered) throw new Error("missing token");
const track = wireOf(client).consume(Path.from("room/x")).track("video").subscribe();
await nextTask();
track.close();
await settles(() => waited(logged, "room/x"));
const opened = transport.sendStreams.bidi.length;
const issued = unanswered.accept(grant([], ["room"]));
await adding;
for (let i = 0; i < 10; i++) await nextTask();
expect(transport.sendStreams.bidi.length).toBe(opened);
issued.close();
} finally {
initial.close();
client.abort();
server.abort();
await adding.catch(() => void 0);
logged.mockRestore();
}
});

// The window between the wait seeing the reader leave and acting on it spans a few
// microtasks, so sweep where the new reader lands.
test.each(Array.from({ length: 17 }, (_, gap) => gap))(
"a subscribe that regains a reader while its token waits keeps waiting (%d)",
async (gap) => {
const origin = new OriginProducer();
const broadcast = origin.createBroadcast(Path.from("room/x"));
broadcast.announce();
const published = broadcast.createTrack("video");
published.appendGroup().writeFrame({ payload: new Uint8Array([7]) });
const { client, server } = await connect({ serverPublish: origin, protocol });
const requests = server.auth.requests();
const setup = await requests.next();
if (!setup) throw new Error("missing setup token");
const initial = setup.accept(grant([], []));
await waitFor(client.auth.grant, (g) => g !== undefined);
const adding = client.auth.add("first");
try {
const unanswered = await requests.next();
if (!unanswered) throw new Error("missing token");
const track = wireOf(client).consume(Path.from("room/x")).track("video");
const first = track.subscribe();
await nextTask();
first.close();
for (let i = 0; i < gap; i++) await Promise.resolve();
const second = track.subscribe();
const issued = unanswered.accept(grant([], ["room"]));
await adding;
expect(await second.recvGroup()).toBeDefined();
second.close();
issued.close();
} finally {
initial.close();
client.abort();
server.abort();
await adding.catch(() => void 0);
}
},
);

test("a session's close is not a revocation of its subscriptions", async () => {
const origin = new OriginProducer();
const broadcast = origin.createBroadcast(Path.from("room/x"));
Expand Down Expand Up @@ -364,6 +580,94 @@ describe.each([Ietf.ALPN.DRAFT_17, Ietf.ALPN.DRAFT_22])("%s", (protocol) => {
});

// moq-lite carries patterns, so every grant arrives exactly as issued.
test("a fetch abandoned while its token waits never reaches the wire", async () => {
const logged = spyOn(console, "debug");
const origin = new OriginProducer();
const broadcast = origin.createBroadcast(Path.from("room/x"));
broadcast.announce();
broadcast
.createTrack("video")
.appendGroup()
.writeFrame({ payload: new Uint8Array([1]) });
const { client, server, transport } = await connect({ serverPublish: origin, protocol: Lite.ALPN_07_WIP });
const requests = server.auth.requests();
const setup = await requests.next();
if (!setup) throw new Error("missing setup token");
const initial = setup.accept(grant([], []));
await waitFor(client.auth.grant, (g) => g !== undefined);
const adding = client.auth.add("first");
try {
const unanswered = await requests.next();
if (!unanswered) throw new Error("missing token");
const abort = new AbortController();
const fetched = wireOf(client)
.consume(Path.from("room/x"))
.track("video")
.fetchGroup(0, { signal: abort.signal });
await nextTask();
abort.abort(new Error("left"));
await expect(fetched).rejects.toThrow();
await settles(() => waited(logged, "room/x"));
const opened = transport.sendStreams.bidi.length;
const issued = unanswered.accept(grant([], ["room"]));
await adding;
for (let i = 0; i < 10; i++) await nextTask();
expect(transport.sendStreams.bidi.length).toBe(opened);
issued.close();
} finally {
initial.close();
client.abort();
server.abort();
await adding.catch(() => void 0);
logged.mockRestore();
}
});

// The window between the wait seeing the caller leave and acting on it spans a few
// microtasks, so sweep where the new caller lands.
test.each(Array.from({ length: 17 }, (_, gap) => gap))(
"a fetch that regains a caller while its token waits keeps waiting (%d)",
async (gap) => {
const origin = new OriginProducer();
const broadcast = origin.createBroadcast(Path.from("room/x"));
broadcast.announce();
broadcast
.createTrack("video")
.appendGroup()
.writeFrame({ payload: new Uint8Array([7]) });
const { client, server } = await connect({ serverPublish: origin, protocol: Lite.ALPN_07_WIP });
const requests = server.auth.requests();
const setup = await requests.next();
if (!setup) throw new Error("missing setup token");
const initial = setup.accept(grant([], []));
await waitFor(client.auth.grant, (g) => g !== undefined);
const adding = client.auth.add("first");
try {
const unanswered = await requests.next();
if (!unanswered) throw new Error("missing token");
const track = wireOf(client).consume(Path.from("room/x")).track("video");
const abort = new AbortController();
const first = track.fetchGroup(0, { signal: abort.signal });
await nextTask();
// The last caller leaves and another coalesces before the wait observes it.
abort.abort(new Error("left"));
for (let i = 0; i < gap; i++) await Promise.resolve();
const second = track.fetchGroup(0);
await expect(first).rejects.toThrow();
const issued = unanswered.accept(grant([], ["room"]));
await adding;
const group = await second;
expect((await group.readFrame())?.payload).toEqual(new Uint8Array([7]));
issued.close();
} finally {
initial.close();
client.abort();
server.abort();
await adding.catch(() => void 0);
}
},
);

test("lite-07 carries literal and wildcard grants exactly", async () => {
const { client, server } = await connect({ publish: new OriginProducer(), protocol: Lite.ALPN_07_WIP });
const requests = server.auth.requests();
Expand Down
Loading
Loading