Skip to content

Fix cancellation and provider limits in SDK directory clients - #942

Open
ersinkoc wants to merge 4 commits into
google:mainfrom
ersinkoc:audit/sdk-directory-client
Open

ersinkoc wants to merge 4 commits into
google:mainfrom
ersinkoc:audit/sdk-directory-client

Conversation

@ersinkoc

Copy link
Copy Markdown

Three directory client fixes with independent regressions.

  • Preserve the caller's abort reason in JavaScript. An earlier empty reply must not turn a cancelled lookup into a successful one.
  • Close an opened Python directory stream under a bounded cancellation shield.
  • Handle zero result limits locally in both SDKs and reject limits outside the unsigned 32-bit range before encoding a request.

The regressions reproduced the three issues on the previous code and passed three focused runs after each fix.

Linux full SDK tests passed on Node.js 22 (156 tests) and Python 3.12 (171 tests). The JavaScript type check, package and examples builds, and browser bundle passed.

@ersinkoc
ersinkoc requested a review from aojea as a code owner November 24, 2026 23:28

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request adds input validation for the provider limit in both JavaScript and Python SDKs, ensuring it is a valid unsigned 32-bit integer, and returns early when the limit is zero. It also improves cancellation handling by checking the abort signal throughout the request flow and ensuring streams are properly closed when cancelled. The review feedback suggests checking the abort signal at the start of findProviders in JavaScript to handle pre-aborted signals when the limit is zero, and expanding test coverage in both languages to include edge cases like non-integers and values exceeding the 32-bit integer range.

Comment thread sdk/js/src/discovery.ts
Comment on lines 165 to 172
export async function findProviders(routers: DirectoryRouter[], key: Uint8Array, limit = DEFAULT_LIMIT, signal?: AbortSignal): Promise<PeerRecord[]> {
const resp = await request(routers, create(DirectoryRequestSchema, { request: { case: "findProviders", value: { key, limit: Math.max(limit, 1) } } }), signal);
if (!Number.isInteger(limit) || limit < 0 || limit > 0xffffffff) {
throw new RangeError("directory provider limit must be an unsigned 32-bit integer");
}
if (limit === 0) return [];
const resp = await request(routers, create(DirectoryRequestSchema, { request: { case: "findProviders", value: { key, limit } } }), signal);
return resp.providers.slice(0, limit);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

General Correctness & Robustness

If limit === 0, findProviders returns [] immediately without calling request. However, if the caller passed an already aborted signal, they would expect the promise to reject with the abort reason rather than succeeding with an empty array. To ensure consistent cancellation behavior, we should check signal?.throwIfAborted() at the very beginning of the function.

Suggested change
export async function findProviders(routers: DirectoryRouter[], key: Uint8Array, limit = DEFAULT_LIMIT, signal?: AbortSignal): Promise<PeerRecord[]> {
const resp = await request(routers, create(DirectoryRequestSchema, { request: { case: "findProviders", value: { key, limit: Math.max(limit, 1) } } }), signal);
if (!Number.isInteger(limit) || limit < 0 || limit > 0xffffffff) {
throw new RangeError("directory provider limit must be an unsigned 32-bit integer");
}
if (limit === 0) return [];
const resp = await request(routers, create(DirectoryRequestSchema, { request: { case: "findProviders", value: { key, limit } } }), signal);
return resp.providers.slice(0, limit);
}
export async function findProviders(routers: DirectoryRouter[], key: Uint8Array, limit = DEFAULT_LIMIT, signal?: AbortSignal): Promise<PeerRecord[]> {
signal?.throwIfAborted();
if (!Number.isInteger(limit) || limit < 0 || limit > 0xffffffff) {
throw new RangeError("directory provider limit must be an unsigned 32-bit integer");
}
if (limit === 0) return [];
const resp = await request(routers, create(DirectoryRequestSchema, { request: { case: "findProviders", value: { key, limit } } }), signal);
return resp.providers.slice(0, limit);
}

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, taken in 290e63d: findProviders now calls signal?.throwIfAborted() before anything else, so an already aborted lookup rejects with the abort reason even when the limit is 0. directory rejects an already aborted provider lookup covers it. (The Python find_providers takes no signal; it is cancelled through its trio scope.)

Comment on lines +19 to +24
test("directory validates the provider limit before contacting routers", async () => {
const key = new Uint8Array();
assert.deepEqual(await findProviders([], key, 0), []);
await assert.rejects(findProviders([], key, -1), RangeError);
await assert.rejects(findProviders([], key, 0.5), RangeError);
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Section 3: Test coverage must follow the pyramid

Consider adding a test case for limits exceeding the 32-bit unsigned integer range (e.g., 0xffffffff + 1) to fully cover the validation logic and ensure parity with the implementation.

Suggested change
test("directory validates the provider limit before contacting routers", async () => {
const key = new Uint8Array();
assert.deepEqual(await findProviders([], key, 0), []);
await assert.rejects(findProviders([], key, -1), RangeError);
await assert.rejects(findProviders([], key, 0.5), RangeError);
});
test("directory validates the provider limit before contacting routers", async () => {
const key = new Uint8Array();
assert.deepEqual(await findProviders([], key, 0), []);
await assert.rejects(findProviders([], key, -1), RangeError);
await assert.rejects(findProviders([], key, 0.5), RangeError);
await assert.rejects(findProviders([], key, 0xffffffff + 1), RangeError);
});
References
  1. Any new feature or codepath MUST have the corresponding testing coverage. (link)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 290e63d: the test now also rejects 0xffffffff + 1 and NaN.

Comment on lines +21 to +27
def test_directory_checks_provider_limit_before_contacting_routers():
async def run():
assert await find_providers(None, [], b"", limit=0) == []
with pytest.raises(ValueError, match="limit"):
await find_providers(None, [], b"", limit=-1)

trio.run(run)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Section 3: Test coverage must follow the pyramid

To ensure the Python test suite is as comprehensive as the JavaScript one, consider adding test cases for non-integer limits (like 0.5) and limits exceeding the 32-bit unsigned integer range (like 0xFFFFFFFF + 1).

Suggested change
def test_directory_checks_provider_limit_before_contacting_routers():
async def run():
assert await find_providers(None, [], b"", limit=0) == []
with pytest.raises(ValueError, match="limit"):
await find_providers(None, [], b"", limit=-1)
trio.run(run)
def test_directory_checks_provider_limit_before_contacting_routers():
async def run():
assert await find_providers(None, [], b"", limit=0) == []
with pytest.raises(ValueError, match="limit"):
await find_providers(None, [], b"", limit=-1)
with pytest.raises(ValueError, match="limit"):
await find_providers(None, [], b"", limit=0.5)
with pytest.raises(ValueError, match="limit"):
await find_providers(None, [], b"", limit=0xFFFFFFFF + 1)
trio.run(run)
References
  1. Any new feature or codepath MUST have the corresponding testing coverage. (link)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 290e63d: the Python test now rejects -1, 0.5 and 0xFFFFFFFF + 1, the same cases as the JavaScript test.

@aojea

aojea commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator

Thanks, rebase to get the fix for the govulcheck and reply to the bot review comments , feel free to push back on those if they are not accurate

findProviders in the JavaScript SDK answered a zero limit with an empty
list before it looked at the signal, so a caller that had already given
up saw success. Check the signal first. The limit tests in both SDKs now
also cover values past the unsigned 32-bit range, non-integers and NaN.
@ersinkoc
ersinkoc force-pushed the audit/sdk-directory-client branch from cc410ba to 290e63d Compare November 25, 2026 13:47
@ersinkoc

Copy link
Copy Markdown
Author

Thanks! Rebased #936–#942 on main with the govulncheck fix, and replied to every bot comment on them: most are taken with a test, and two are pushed back with the reason in the thread (#936, where preventDefault() on the request error would let a failed IndexedDB write commit as a success, and the second half of #940).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants