Skip to content
86 changes: 86 additions & 0 deletions js/net/src/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1003,6 +1003,48 @@ test("lite-07 ignores a draining session's late refusal while its successor retr
});

// moq-lite carries patterns, so every grant arrives exactly as issued.
test("lite-07 a token granted on a draining session stays held until its successor answers", async () => {
const protocol = Lite.ALPN_07_WIP;
const handle = new Handle();
const pair = createMockTransportPair(protocol);
const [client, server] = await Promise.all([
connectSession({ url, transport: pair.client, publish: new OriginProducer().consume(), auth: handle }),
acceptSession({ transport: pair.server, url }),
]);
const requests = server.auth.requests();
const setup = await requests.next();
if (!setup) throw new Error("missing setup token");
const issued = [setup.accept(grant([], []))];
const token = handle.present("token");
const request = await requests.next();
if (!request) throw new Error("missing token");
issued.push(request.accept(grant(["a"], [])));
await token.answered;
expect(token.held).toBe(true);

const stream = await Stream.open(pair.server, { version: Lite.Version.DRAFT_07 });
await stream.writer.u53(Lite.StreamId.Goaway);
await new Lite.Goaway("").encode(stream.writer, Lite.Version.DRAFT_07);
await settles(() => !wireOf(client).auth.active);

const next = await connect({ publish: new OriginProducer(), protocol, auth: handle });
const successorRequests = next.server.auth.requests();
try {
const successorSetup = await successorRequests.next();
if (!successorSetup) throw new Error("missing successor setup token");
issued.push(successorSetup.accept(grant([], [])));
expect(await successorRequests.next()).toBeDefined();
// The live session has not answered, but the draining one still grants it.
expect(token.grant.peek()).toBeUndefined();
expect(token.held).toBe(true);
} finally {
client.abort();
server.abort();
next.client.abort();
next.server.abort();
}
});

test("a fetch abandoned while its token waits never reaches the wire", async () => {
const logged = spyOn(console, "debug");
const origin = new OriginProducer();
Expand Down Expand Up @@ -1345,6 +1387,50 @@ test("withdrawn queued tokens are pruned before the next application decision",
}
});

test("grants issued while a reply is blocked replace the one still queued", async () => {
const { client, server } = await connect({ publish: new OriginProducer(), protocol: Lite.ALPN_07_WIP });
const grants = Array.from({ length: 100 }, (_, i) => grant([`${i}`], []));
const original = LiteAuthWire.prototype.grant;
// Which of `grants` reached the wire, in order.
const sent: number[] = [];
let release!: () => void;
const blocked = new Promise<void>((resolve) => {
release = resolve;
});
const spy = spyOn(LiteAuthWire.prototype, "grant").mockImplementation(async function (
this: LiteAuthWire,
stream,
grant,
) {
const index = grants.findIndex((issued) => issued.publish === grant.publish);
if (index >= 0) sent.push(index);
if (index === 0) await blocked;
return original.call(this, stream, grant);
});
try {
const requests = server.auth.requests();
const setup = await requests.next();
if (!setup) throw new Error("setup token missing");
setup.accept(grant(["a"], []));
const live = client.auth.add("live");
live.catch(() => void 0);
const request = await requests.next();
if (!request) throw new Error("live token missing");
const issued = request.accept(grants[0]);
await settles(() => sent.length === 1);
for (const update of grants.slice(1)) issued.update(update);
release();
await live;
await settles(() => sent.length === 2);
for (let i = 0; i < 10; i++) await yieldNow();
expect(sent).toEqual([0, 99]);
} finally {
spy.mockRestore();
client.abort();
server.abort();
}
});

// Capture the acceptor's actual AUTH writer after a valid setup grant. The following
// bytes travel through the same connection dispatcher and presenter as a real peer.
describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("AUTH violations %s", (protocol) => {
Expand Down
65 changes: 52 additions & 13 deletions js/net/src/auth_session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,20 @@ class Presented {
}
}

/**
* A token {@link Handle.present} returned before its answer.
*
* @internal
*/
export interface Pending extends Credential {
Comment thread
kixelated marked this conversation as resolved.
Resolved
/** Resolves once a peer accepts the token, or rejects as {@link Handle.add} does. */
readonly answered: Promise<void>;
/** Whether any session holds a grant for it now, a draining one included. */
readonly held: boolean;
}

/** A token the application added to a {@link Handle}, presented on every session of it. */
class Token implements Credential {
class Token implements Pending {
readonly grant = new Signal<Grant | undefined>(undefined);
readonly closed: Promise<Error | null>;
readonly answered: Promise<void>;
Expand All @@ -166,14 +178,14 @@ class Token implements Credential {
isAnswered = false;
ended = false;

#withdraw: (token: Token) => void;
#state: HandleState;
#close!: (err: Error | null) => void;
#answer!: () => void;
#refuse!: (err: Error) => void;

constructor(bytes: Uint8Array, withdraw: (token: Token) => void) {
constructor(bytes: Uint8Array, state: HandleState) {
this.bytes = bytes;
this.#withdraw = withdraw;
this.#state = state;
this.closed = new Promise((resolve) => {
this.#close = resolve;
});
Expand Down Expand Up @@ -202,8 +214,12 @@ class Token implements Credential {
this.#close(err);
}

get held(): boolean {
return this.#state.sessions.some((session) => session.grantOf(this) !== undefined);
}

close() {
this.#withdraw(this);
this.#state.withdraw(this);
}
}

Expand Down Expand Up @@ -264,7 +280,7 @@ class HandleState {
if (this.own && !this.sessions.some((session) => session.active)) {
throw new StreamError(StreamCode.GoingAway);
}
const token = new Token(bytes, (token) => this.withdraw(token));
const token = new Token(bytes, this);
this.tokens.add(token);
for (const session of [...this.sessions]) session.offer(token);
return token;
Expand Down Expand Up @@ -359,13 +375,23 @@ export class Handle {
* request whose route names it carries it.
*/
async add(token: string | Uint8Array): Promise<Credential> {
// A copy, so the caller reusing its buffer never changes what a request carries.
const bytes = typeof token === "string" ? new TextEncoder().encode(token) : token.slice();
const added = stateOf(this).add(bytes);
const added = this.present(token);
await added.answered;
return added;
}

/**
* Present another token like {@link add}, returning it at once with its answer, so it can be
* withdrawn before the peer answers.
*
* @internal
*/
present(token: string | Uint8Array): Pending {
// A copy, so the caller reusing its buffer never changes what a request carries.
const bytes = typeof token === "string" ? new TextEncoder().encode(token) : token.slice();
return stateOf(this).add(bytes);
}

/**
* Answer every token the peer presents, instead of the default: granting what this side
* publishes and consumes for the connection's own credential and refusing any other.
Expand Down Expand Up @@ -445,6 +471,8 @@ class IssuedGrant implements Issued {
#stream: Stream;
#wire: AuthWire;
#writes = Promise.resolve();
/** The latest grant, until its write starts: a newer one replaces it rather than queueing. */
#queued: Grant | undefined;
#done = false;

constructor(stream: Stream, wire: AuthWire) {
Expand All @@ -470,20 +498,31 @@ class IssuedGrant implements Issued {
// reply that fails to encode.
if (!(err instanceof Unsupported)) console.warn("auth reply not sent", err);
this.#done = true;
this.#queued = undefined;
return this.#wire.unsupported(this.#stream, error(err).message).catch(() => void 0);
});
}

update(grant: Grant): void {
if (this.#done) return;
const expires = grant.expires === undefined ? undefined : grant.expires - wall();
this.#write(() =>
this.#wire.grant(this.#stream, { publish: grant.publish, subscribe: grant.subscribe, expires }),
);
// A grant still waiting to be written is replaced, so a peer withholding stream credit
// holds at most one.
const queued = this.#queued !== undefined;
this.#queued = grant;
if (queued) return;
this.#write(async () => {
const grant = this.#queued;
this.#queued = undefined;
if (grant === undefined) return;
const expires = grant.expires === undefined ? undefined : grant.expires - wall();
await this.#wire.grant(this.#stream, { publish: grant.publish, subscribe: grant.subscribe, expires });
});
}

revoke(code: SessionCode, reason: string): void {
if (this.#done) return;
// The peer never saw a grant still queued, so the refusal replaces it.
this.#queued = undefined;
this.#write(() => this.#wire.refuse(this.#stream, code, reason));
this.close();
}
Expand Down
30 changes: 20 additions & 10 deletions js/net/src/connection/tokens.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { expect, test } from "bun:test";
import type { Credential, Handle } from "../auth.ts";
import type { Handle } from "../auth.ts";
import type { Pending } from "../auth_session.ts";
import * as Ietf from "../ietf/index.ts";
import { createMockTransportPair } from "../mock.ts";
import { Reader } from "../stream.ts";
Expand Down Expand Up @@ -55,19 +56,26 @@ test("no tokens present nothing", () => {

/** A handle whose answers the test releases one token at a time. */
function handle() {
const answers = new Map<string, (auth: Credential) => void>();
const answers = new Map<string, () => void>();
const closed: string[] = [];
const presented: string[] = [];
const fake = {
add(token: string) {
present(token: string) {
presented.push(token);
return new Promise<Credential>((resolve) => answers.set(token, resolve));
const pending = { held: false, answered: Promise.resolve(), close: () => closed.push(token) };
pending.answered = new Promise<void>((resolve) =>
answers.set(token, () => {
pending.held = true;
resolve();
}),
);
return pending as unknown as Pending;
},
} as unknown as Handle;
const answer = async (token: string) => {
const resolve = answers.get(token);
if (!resolve) throw new Error(`${token} was never presented`);
resolve({ close: () => closed.push(token) } as unknown as Credential);
resolve();
// Let the answer and the settle it schedules run.
for (let i = 0; i < 3; i++) await Promise.resolve();
};
Expand All @@ -89,15 +97,17 @@ test("a replaced token is withdrawn only once its replacement answers", async ()
expect(closed).toEqual(["old"]);
});

test("a token replaced before its answer closes when it arrives", async () => {
test("a token replaced before its answer is withdrawn at once", async () => {
const { fake, closed, answer } = handle();
const held = new Held(fake, credential(URL_, ["connection"], true));
held.update(["connection", "old"]);
held.update(["connection", "new"]);
await answer("new");
expect(closed).toEqual([]);
await answer("old");
expect(closed).toEqual(["old"]);
held.update(["connection", "first"]);
held.update(["connection", "second"]);
// The unanswered replacement adds nothing; the granted token waits for an answer.
expect(closed).toEqual(["first"]);
await answer("second");
expect(closed).toEqual(["first", "old"]);
});

test("sessions sharing an auth handle present each configured token once", async () => {
Expand Down
Loading
Loading