Skip to content

Commit b6876fe

Browse files
committed
fix: scope SignalR channel reads and release 10.4.5
1 parent 3c22a2c commit b6876fe

8 files changed

Lines changed: 198 additions & 7 deletions

File tree

‎Directory.Build.props‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
<AnalysisLevel>latest-recommended</AnalysisLevel>
1212
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
1313
<NoWarn>$(NoWarn);CS1591;CA1707;CA1848;CA1859;CA1873</NoWarn>
14-
<Version>10.4.4</Version>
14+
<Version>10.4.5</Version>
1515
<PackageVersion>$(Version)</PackageVersion>
1616
</PropertyGroup>
1717

‎ManagedCode.Orleans.Identity.Client/Filters/SignalRAuthorizationFilter.cs‎

Lines changed: 61 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
using System.Collections.Concurrent;
2+
using System.Diagnostics.CodeAnalysis;
23
using System.Reflection;
34
using System.Security.Claims;
5+
using System.Threading.Channels;
46
using Microsoft.AspNetCore.SignalR;
57

68
namespace ManagedCode.Orleans.Identity.Client.Filters;
@@ -10,6 +12,8 @@ public sealed class SignalRAuthorizationFilter : IHubFilter
1012
private static readonly ConcurrentDictionary<Type, Func<object, ClaimsPrincipal?, object>?> StreamWrappers = new();
1113
private static readonly MethodInfo WrapStreamMethod = typeof(SignalRAuthorizationFilter)
1214
.GetMethod(nameof(WrapStream), BindingFlags.NonPublic | BindingFlags.Static)!;
15+
private static readonly MethodInfo WrapChannelMethod = typeof(SignalRAuthorizationFilter)
16+
.GetMethod(nameof(WrapChannel), BindingFlags.NonPublic | BindingFlags.Static)!;
1317

1418
public async ValueTask<object?> InvokeMethodAsync(
1519
HubInvocationContext invocationContext,
@@ -39,9 +43,22 @@ public sealed class SignalRAuthorizationFilter : IHubFilter
3943
}
4044

4145
var stream = IsAsyncEnumerable(returnType) ? returnType : Array.Find(returnType.GetInterfaces(), IsAsyncEnumerable);
42-
return stream is null ? null : WrapStreamMethod
43-
.MakeGenericMethod(stream.GenericTypeArguments[0])
44-
.CreateDelegate<Func<object, ClaimsPrincipal?, object>>();
46+
if (stream is not null)
47+
{
48+
return WrapStreamMethod.MakeGenericMethod(stream.GenericTypeArguments[0])
49+
.CreateDelegate<Func<object, ClaimsPrincipal?, object>>();
50+
}
51+
52+
for (Type? type = returnType; type is not null; type = type.BaseType)
53+
{
54+
if (type.IsConstructedGenericType && type.GetGenericTypeDefinition() == typeof(ChannelReader<>))
55+
{
56+
return WrapChannelMethod.MakeGenericMethod(type.GenericTypeArguments[0])
57+
.CreateDelegate<Func<object, ClaimsPrincipal?, object>>();
58+
}
59+
}
60+
61+
return null;
4562
}
4663

4764
private static bool IsAsyncEnumerable(Type type) =>
@@ -83,6 +100,47 @@ public async ValueTask DisposeAsync()
83100
}
84101
}
85102

103+
private static object WrapChannel<T>(object channel, ClaimsPrincipal? user) =>
104+
new ScopedChannelReader<T>((ChannelReader<T>)channel, user);
105+
106+
private sealed class ScopedChannelReader<T>(ChannelReader<T> reader, ClaimsPrincipal? user) : ChannelReader<T>
107+
{
108+
public override Task Completion => reader.Completion;
109+
public override bool CanCount => reader.CanCount;
110+
public override bool CanPeek => reader.CanPeek;
111+
public override int Count => reader.Count;
112+
113+
public override bool TryRead([MaybeNullWhen(false)] out T item)
114+
{
115+
using var scope = new OrleansRequestContextScope(user);
116+
return reader.TryRead(out item);
117+
}
118+
119+
public override bool TryPeek([MaybeNullWhen(false)] out T item)
120+
{
121+
using var scope = new OrleansRequestContextScope(user);
122+
return reader.TryPeek(out item);
123+
}
124+
125+
public override async ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken = default)
126+
{
127+
using var scope = new OrleansRequestContextScope(user);
128+
return await reader.WaitToReadAsync(cancellationToken);
129+
}
130+
131+
public override async ValueTask<T> ReadAsync(CancellationToken cancellationToken = default)
132+
{
133+
using var scope = new OrleansRequestContextScope(user);
134+
return await reader.ReadAsync(cancellationToken);
135+
}
136+
137+
public override IAsyncEnumerable<T> ReadAllAsync(CancellationToken cancellationToken = default)
138+
{
139+
using var scope = new OrleansRequestContextScope(user);
140+
return new ScopedStream<T>(reader.ReadAllAsync(cancellationToken), user);
141+
}
142+
}
143+
86144
public async Task OnConnectedAsync(HubLifetimeContext context, Func<HubLifetimeContext, Task> next)
87145
{
88146
using var scope = new OrleansRequestContextScope(context.Context.User);

‎ManagedCode.Orleans.Identity.Server/GrainCallFilter/StreamingAuthorizationState.cs‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,19 @@ private bool MatchesPrincipal(ClaimsPrincipal? current)
8080
return identities.Length == 0;
8181
}
8282

83+
var currentIdentities = current.Identities;
84+
if (currentIdentities is IReadOnlyList<ClaimsIdentity> list)
85+
{
86+
if (identities.Length != list.Count) return false;
87+
for (var i = 0; i < identities.Length; i++)
88+
{
89+
if (!identities[i].Matches(list[i])) return false;
90+
}
91+
return true;
92+
}
93+
8394
var index = 0;
84-
foreach (var identity in current.Identities)
95+
foreach (var identity in currentIdentities)
8596
{
8697
if (index == identities.Length || !identities[index++].Matches(identity))
8798
{
@@ -109,8 +120,19 @@ public bool Matches(ClaimsIdentity current)
109120
return false;
110121
}
111122

123+
var currentClaims = current.Claims;
124+
if (currentClaims is IReadOnlyList<Claim> list)
125+
{
126+
if (claims.Length != list.Count) return false;
127+
for (var i = 0; i < claims.Length; i++)
128+
{
129+
if (!claims[i].Matches(list[i])) return false;
130+
}
131+
return true;
132+
}
133+
112134
var index = 0;
113-
foreach (var claim in current.Claims)
135+
foreach (var claim in currentClaims)
114136
{
115137
if (index == claims.Length || !claims[index++].Matches(claim))
116138
{

‎ManagedCode.Orleans.Identity.Tests/ClientFilterTests.cs‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
using System.Security.Claims;
2+
using System.Threading.Channels;
23
using ManagedCode.Orleans.Identity.Client.Extensions;
34
using ManagedCode.Orleans.Identity.Client.Filters;
45
using ManagedCode.Orleans.Identity.Core.Constants;
6+
using ManagedCode.Orleans.Identity.Tests.TestApp;
57
using Microsoft.AspNetCore.Http;
68
using Microsoft.AspNetCore.Http.Features;
79
using Microsoft.AspNetCore.Mvc;
@@ -134,6 +136,41 @@ async Task AssertPrincipalAsync()
134136
}
135137
}
136138

139+
[Fact]
140+
public async Task SignalRChannel_PreservesReaderCapabilitiesAndCancellation()
141+
{
142+
var channel = Channel.CreateUnbounded<string>();
143+
var user = CreatePrincipal(CurrentUserName);
144+
using var hub = new TestAuthorizeHub(null!);
145+
using var services = new ServiceCollection().BuildServiceProvider();
146+
var method = typeof(TestAuthorizeHub).GetMethod(nameof(TestAuthorizeHub.ReadChannel))!;
147+
var context = new HubInvocationContext(new LifecycleCallerContext(user), services, hub, method, []);
148+
var result = await new SignalRAuthorizationFilter().InvokeMethodAsync(context,
149+
_ => ValueTask.FromResult<object?>(channel.Reader));
150+
var reader = Assert.IsAssignableFrom<ChannelReader<string>>(result);
151+
152+
reader.Completion.ShouldBeSameAs(channel.Reader.Completion);
153+
reader.CanCount.ShouldBe(channel.Reader.CanCount);
154+
reader.CanPeek.ShouldBe(channel.Reader.CanPeek);
155+
using var cancellation = new CancellationTokenSource();
156+
var pending = reader.ReadAsync(cancellation.Token).AsTask();
157+
await cancellation.CancelAsync();
158+
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => pending);
159+
160+
channel.Writer.TryWrite("first").ShouldBeTrue();
161+
channel.Writer.TryWrite("second").ShouldBeTrue();
162+
channel.Writer.Complete();
163+
164+
reader.Count.ShouldBe(2);
165+
reader.TryPeek(out var first).ShouldBeTrue();
166+
first.ShouldBe("first");
167+
(await reader.ReadAsync()).ShouldBe("first");
168+
var remaining = new List<string>();
169+
await foreach (var item in reader.ReadAllAsync()) remaining.Add(item);
170+
remaining.ShouldBe(["second"]);
171+
await reader.Completion;
172+
}
173+
137174
private sealed class LifecycleHub : Hub;
138175

139176
private sealed class LifecycleCallerContext(ClaimsPrincipal? user) : HubCallerContext

‎ManagedCode.Orleans.Identity.Tests/Jwt/JwtSignalRTests.cs‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,24 @@ public async Task SignalR_StreamForwardsPrincipalForEachItem(string method)
176176
values.ShouldBe(["hub0", "hub1", "hub2"]);
177177
}
178178

179+
[Theory]
180+
[InlineData("ReadChannel")]
181+
[InlineData("ReadChannelAsync")]
182+
public async Task SignalR_ChannelForwardsPrincipalDuringDeferredRead(string method)
183+
{
184+
var token = await GetJwtToken("admin");
185+
await using var connection = await CreateSignalRConnection(token);
186+
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
187+
188+
var values = new List<string>();
189+
await foreach (var value in connection.StreamAsync<string>(method, timeout.Token))
190+
{
191+
values.Add(value);
192+
}
193+
194+
values.ShouldBe(["Hello, admin!"]);
195+
}
196+
179197
[Fact]
180198
public async Task SignalR_ConnectWithoutToken_ShouldFail()
181199
{

‎ManagedCode.Orleans.Identity.Tests/StreamingAuthorizationStateTests.cs‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,30 @@ public void TerminatedEntry_WaitsForBothInFlightOperationsBeforeRemoval()
9999
entry.Finish(disposing: false).ShouldBeTrue();
100100
}
101101

102+
[Fact]
103+
public void Continuation_MatchesIteratorBackedIdentitiesAndClaims()
104+
{
105+
var entry = new StreamingAuthorizationState.Entry(default, null, Principal("owner"));
106+
var identity = new IteratorIdentity("owner");
107+
var principal = new IteratorPrincipal(identity);
108+
109+
entry.CanContinue(null, principal, disposing: false).ShouldBeTrue();
110+
111+
identity.AddClaim(new Claim(ClaimTypes.Role, "additional"));
112+
entry.CanContinue(null, principal, disposing: false).ShouldBeFalse();
113+
}
114+
115+
private sealed class IteratorPrincipal(ClaimsIdentity identity) : ClaimsPrincipal(identity)
116+
{
117+
public override IEnumerable<ClaimsIdentity> Identities => base.Identities.Where(static _ => true);
118+
}
119+
120+
private sealed class IteratorIdentity(string name)
121+
: ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, name)], "stream-test")
122+
{
123+
public override IEnumerable<Claim> Claims => base.Claims.Where(static _ => true);
124+
}
125+
102126
private static ClaimsPrincipal PrincipalWithIdentities(string first, string second) =>
103127
new([Principal(first).Identities.Single(), Principal(second).Identities.Single()]);
104128

‎ManagedCode.Orleans.Identity.Tests/TestApp/TestAuthorizeHub.cs‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
using System.Diagnostics.CodeAnalysis;
2+
using System.Threading.Channels;
13
using ManagedCode.Orleans.Identity.Tests.Cluster.Grains;
24
using Microsoft.AspNetCore.Authorization;
35
using Microsoft.AspNetCore.SignalR;
@@ -38,6 +40,36 @@ public IAsyncEnumerable<string> ReadStream() =>
3840
[Authorize]
3941
public Task<IAsyncEnumerable<string>> ReadStreamAsync() => Task.FromResult(ReadStream());
4042

43+
[Authorize]
44+
public ChannelReader<string> ReadChannel() => new GrainChannelReader(clusterClient.GetGrain<IUserGrain>("channel"));
45+
46+
[Authorize]
47+
public Task<ChannelReader<string>> ReadChannelAsync() => Task.FromResult(ReadChannel());
48+
49+
private sealed class GrainChannelReader(IUserGrain grain) : ChannelReader<string>
50+
{
51+
private string? pending;
52+
private bool fetched;
53+
54+
public override async ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken = default)
55+
{
56+
if (!fetched)
57+
{
58+
pending = await grain.GetUser().WaitAsync(cancellationToken);
59+
fetched = true;
60+
}
61+
62+
return pending is not null;
63+
}
64+
65+
public override bool TryRead([MaybeNullWhen(false)] out string item)
66+
{
67+
item = pending;
68+
pending = null;
69+
return item is not null;
70+
}
71+
}
72+
4173
[AllowAnonymous]
4274
public async Task<string> GetPublicInfo()
4375
{

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ app.Run();
102102
```
103103

104104
The filters installed by `AddOrleansIdentity` forward the authenticated principal through MVC action and result execution,
105-
SignalR hub callbacks, and enumeration of async streams returned by hub methods.
105+
SignalR hub callbacks, and reads from `IAsyncEnumerable<T>` and `ChannelReader<T>` streams returned by hub methods.
106106

107107
### 3. Enforce authorization in grains
108108

0 commit comments

Comments
 (0)