Skip to content

Reject duplicate SignalR upload stream IDs - #68525

Merged
javiercn merged 7 commits into
mainfrom
javiercn/reject-duplicate-upload-stream-ids
Aug 19, 2026
Merged

Reject duplicate SignalR upload stream IDs#68525
javiercn merged 7 commits into
mainfrom
javiercn/reject-duplicate-upload-stream-ids

Conversation

@javiercn

@javiercn javiercn commented Aug 14, 2026

Copy link
Copy Markdown
Member

Fixes #68301

Overview

SignalR upload streams were registered with dictionary assignment, so a protocol-invalid duplicate stream ID replaced the active channel and could leave the displaced hub argument permanently unreachable. This change makes registration atomic and rejects an active duplicate immediately, while preserving valid multi-stream uploads and reuse after completion. The cross-cutting constraint is ownership-safe cleanup: a rejected invocation must roll back streams it registered without completing a stream owned by another invocation.

Design

There is no public API change. Internally, each upload-stream invocation receives one allocation-free owner ID, and the stream dictionary remains keyed only by the protocol stream ID because StreamItem and Completion messages contain no owner information. Its value is an allocation-free tuple containing the owner and converter:

// src/SignalR/server/Core/src/StreamTracker.cs
// Owner IDs need only be unique within this connection's StreamTracker.
private readonly ConcurrentDictionary<string, (long Owner, IStreamConverter Converter)> _lookup = new();
private long _nextStreamOwner;

public long GetNextStreamOwner()
{
    return Interlocked.Increment(ref _nextStreamOwner);
}

Alternatives considered:

  • Use dictionary Add instead of assignment: this detects duplicates, but does not solve cleanup. The rejected invocation's existing finally path would still complete the pre-existing stream by ID. TryAdd also allows the deterministic Stream ID '7' is already in use. protocol error.
  • Use (streamId, owner) as the dictionary key: this would permit duplicate protocol stream IDs under different owners and make item/completion lookup ambiguous because those messages carry only the stream ID.
  • Track every successful registration in a list: correct, including partial rollback, but adds invocation plumbing and a list allocation. One owner ID lets cleanup use the existing StreamIds while proving ownership.
  • Use an object or Guid owner: both work. A connection-local monotonic long is allocation-free and cheaper; the tuple dictionary value is also a value type.
  • Return null on collision: possible, but argument binding would need a separate failure-propagation path to prevent invoking the hub with a null stream. Throwing HubException reuses the dispatcher's existing invocation-error handling for this rare protocol violation.

Implementation

Registration now uses TryAdd; a collision leaves the current entry untouched and aborts argument binding through the existing error path. Reader conversion occurs only after registration succeeds:

// src/SignalR/server/Core/src/StreamTracker.cs
public object AddStream(string streamId, Type itemType, Type targetType, long streamOwner)
{
    var newConverter = CreateConverter(itemType); // reflection details omitted
    if (!_lookup.TryAdd(streamId, (streamOwner, newConverter)))
    {
        throw new HubException($"Stream ID '{streamId}' is already in use.");
    }

    return newConverter.GetReaderAsObject(targetType);
}

The dispatcher lazily assigns one numeric owner ID when it encounters the invocation's first streaming argument. All streams from that invocation share it:

// src/SignalR/server/Core/src/Internal/DefaultHubDispatcher.cs
arguments[parameterPointer] = connection.StreamTracker.AddStream(
    hubMethodInvocationMessage.StreamIds[streamPointer],
    itemType,
    descriptor.OriginalParameterTypes[parameterPointer],
    streamOwner ??= connection.StreamTracker.GetNextStreamOwner());

If argument replacement fails after creating a linked CancellationTokenSource, a finally disposes it before the exception propagates. Successfully replaced arguments transfer that source to the existing invocation cleanup path.

Cleanup separates lookup, ownership validation, and mutation. TryRemove(KeyValuePair) atomically removes only the exact key/value observed; if the stream was completed and its ID reused before older asynchronous cleanup ran, the tuple no longer matches and the newer stream remains intact:

// src/SignalR/server/Core/src/StreamTracker.cs
public bool TryComplete(string streamId, long streamOwner)
{
    if (!_lookup.TryGetValue(streamId, out var registration) || registration.Owner != streamOwner)
    {
        return false;
    }

    if (!_lookup.TryRemove(KeyValuePair.Create(streamId, registration)))
    {
        return false;
    }

    registration.Converter.TryComplete(null);
    return true;
}

The regression tests cover the distinct behavior classes once each: duplicate IDs within one invocation under a buffer capacity of one while a later invocation still completes; a second invocation attempting to reuse an active ID without disturbing the original; reuse after completion; and multiple unique upload streams continuing to work.

Outcome

Behavior Result
Duplicate ID in one invocation Prompt deterministic completion error; connection continues processing
Duplicate ID across active invocations Existing stream remains registered and receives its items/completion
Partial registration failure Cleanup completes only entries owned by the rejected invocation
ID reuse after completion Supported unchanged
Multiple unique upload streams Supported unchanged
Allocation impact No owner or registration object allocation

Validation: the complete Microsoft.AspNetCore.SignalR.Tests project passes with zero warnings and errors via eng\build.cmd -nobuildnative -noBuildJava -projects .\src\SignalR\server\SignalR\test\Microsoft.AspNetCore.SignalR.Tests\Microsoft.AspNetCore.SignalR.Tests.csproj -test.

Copilot AI lite review requested due to automatic review settings August 14, 2026 12:45

Copilot AI 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.

Pull request overview

This PR enforces Hub Protocol uniqueness for client upload stream IDs by making stream registration atomic and ownership-aware, preventing active streams from being replaced and avoiding cleanup that could affect other invocations (fixes #68301).

Changes:

  • Make StreamTracker.AddStream reject duplicate active stream IDs via ConcurrentDictionary.TryAdd, throwing a deterministic HubException.
  • Track per-invocation successful stream registrations and use them during cleanup to avoid completing/removing streams owned by other invocations.
  • Add regression tests covering duplicate IDs, connection progress under buffer pressure, ownership preservation, unique streams, and ID reuse after completion.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

File Description
src/SignalR/server/SignalR/test/Microsoft.AspNetCore.SignalR.Tests/HubConnectionHandlerTestUtils/Hubs.cs Adds a hub method accepting two upload streams for duplicate/unique stream ID test scenarios.
src/SignalR/server/SignalR/test/Microsoft.AspNetCore.SignalR.Tests/HubConnectionHandlerTests.cs Adds regression tests for duplicate upload stream IDs, non-blocking connection behavior, and ID reuse after completion.
src/SignalR/server/Core/src/StreamTracker.cs Implements atomic stream registration and introduces an ownership token for safe cleanup.
src/SignalR/server/Core/src/Internal/DefaultHubDispatcher.cs Uses per-invocation stream registration tracking to ensure cleanup is ownership-safe.

💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.

@javiercn
javiercn force-pushed the javiercn/reject-duplicate-upload-stream-ids branch from 171dac8 to 119f206 Compare August 17, 2026 12:22
Comment thread src/SignalR/server/Core/src/StreamTracker.cs Outdated
Comment thread src/SignalR/server/Core/src/StreamTracker.cs
@javiercn
javiercn force-pushed the javiercn/reject-duplicate-upload-stream-ids branch from 62dd2f2 to 3c42b67 Compare August 19, 2026 07:24
javiercn and others added 7 commits August 19, 2026 09:29
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 82e97f5a-a052-4dbe-9cf1-b62f45cf7ee2
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 82e97f5a-a052-4dbe-9cf1-b62f45cf7ee2
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 82e97f5a-a052-4dbe-9cf1-b62f45cf7ee2
@javiercn
javiercn force-pushed the javiercn/reject-duplicate-upload-stream-ids branch from 3c42b67 to 41b010c Compare August 19, 2026 07:29
@javiercn
javiercn enabled auto-merge (squash) August 19, 2026 07:32
@javiercn
javiercn merged commit 42e0847 into main Aug 19, 2026
27 checks passed
@javiercn
javiercn deleted the javiercn/reject-duplicate-upload-stream-ids branch August 19, 2026 09:20
@javiercn

Copy link
Copy Markdown
Member Author

/backport to release/11.0-rc1

@github-actions

Copy link
Copy Markdown
Contributor

Started backporting to release/11.0-rc1 (link to workflow run)

@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Aug 20, 2026
wtgodbe pushed a commit that referenced this pull request Aug 21, 2026
* Reject duplicate SignalR upload stream IDs



* Simplify upload stream ownership cleanup



* Avoid upload stream ownership allocations



* Simplify upload stream registration ownership



* Defer upload stream reader creation





* Dispose cancellation source after binding failure





* Reuse upload stream test helper





---------

Co-authored-by: Javier Calvarro Nelson <jacalvar@microsoft.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 82e97f5a-a052-4dbe-9cf1-b62f45cf7ee2
wtgodbe added a commit that referenced this pull request Aug 22, 2026
* [SignalR] Reject duplicate SignalR upload stream IDs (#68525) (#68638)

* Reject duplicate SignalR upload stream IDs



* Simplify upload stream ownership cleanup



* Avoid upload stream ownership allocations



* Simplify upload stream registration ownership



* Defer upload stream reader creation





* Dispose cancellation source after binding failure





* Reuse upload stream test helper





---------

Co-authored-by: Javier Calvarro Nelson <jacalvar@microsoft.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 82e97f5a-a052-4dbe-9cf1-b62f45cf7ee2

* Honor all sign-in confirmation requirements after registration (#68631) (#68655)

Co-authored-by: Brennan <brecon@microsoft.com>

* Preserve BadHttpRequestException status codes (#68632) (#68649)

* Preserve BadHttpRequestException status codes



* Preserve exception handler 404 safeguard



---------

Co-authored-by: Stephen Halter <halter73@gmail.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* SignInManager: return SignInResult.Failed for expired passkey session challenge (#67539) (#68654)

Co-authored-by: Grant Totinov <granttotinov604@gmail.com>

* Don't apply the CSRF verdict to remote authentication callbacks (#68669)

* Don't apply the CSRF verdict to remote authentication callbacks

A remote provider's callback (OIDC response_mode=form_post, WS-Federation)
is a cross-site form POST by protocol design, so the auto-injected CSRF
protection records an invalid IAntiforgeryValidationFeature verdict for it.
The handler then throws while reading its own callback body, before any of
its events can run, so apps have no way to opt out.

Suppress the verdict while a remote handler owns the request, and restore it
if the handler declines so the rest of the pipeline still sees it.

Fixes #68666

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: cb987098-3301-465b-9a3d-2e63aabf43bd

* test both antiforgery & csrf

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: cb987098-3301-465b-9a3d-2e63aabf43bd

* Use model display names in Blazor input parsing errors (#68667) (#68688)

* Use display attributes in input parsing errors

* Address test coverage feedback from review.

* Apply dedup cleanup from feedback.

Co-authored-by: Ilona Tomkowicz <32700855+ilonatommy@users.noreply.github.com>

* [release/11.0-rc1] Extract IsAuthenticated helper method (#68658)

* Extract IsAuthenticated helper method

Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com>

* Reorder using

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com>

* Use SecurityHelper for authentication revalidation

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com>

---------

Co-authored-by: Youssef1313 <youssefvictor00@gmail.com>
Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com>
Co-authored-by: Milos Kotlar <kotlarmilos@gmail.com>

* Fix  InitialItemIndex viewport underfill for small items in big container or on window resize (#67936) (#68689)

Co-authored-by: Ilona Tomkowicz <32700855+ilonatommy@users.noreply.github.com>

* fix nullable<union> for openapi gen (#68665)

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Javier Calvarro Nelson <jacalvar@microsoft.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Brennan <brecon@microsoft.com>
Co-authored-by: Stephen Halter <halter73@gmail.com>
Co-authored-by: Grant Totinov <granttotinov604@gmail.com>
Co-authored-by: Korolev Dmitry <dmkorolev@microsoft.com>
Co-authored-by: Ilona Tomkowicz <32700855+ilonatommy@users.noreply.github.com>
Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Youssef1313 <youssefvictor00@gmail.com>
Co-authored-by: Youssef1313 <31348972+Youssef1313@users.noreply.github.com>
Co-authored-by: Milos Kotlar <kotlarmilos@gmail.com>
Co-authored-by: William Godbe <wigodbe@microsoft.com>
Copilot-Session: 82e97f5a-a052-4dbe-9cf1-b62f45cf7ee2
Copilot-Session: cb987098-3301-465b-9a3d-2e63aabf43bd
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.

SignalR should reject duplicate client upload stream IDs instead of replacing active streams

4 participants