Add persistent Inbox and RFC 8291/8292 Web Push notification system

This commit is contained in:
tyuXX 2026-10-31 15:41:51 +03:00
parent 4714d25724
commit 7cc9ba7f4d
27 changed files with 3573 additions and 17 deletions

View file

@ -50,6 +50,7 @@ public class EndToEndChatTests : IAsyncLifetime
builder.WebHost.UseUrls(_serverUrl);
builder.Logging.ClearProviders(); // Keep test output clean
var (vapidPub, vapidPriv) = GsDChat.Core.Security.WebPushCrypto.GenerateVapidKeys();
var serverOptions = new ServerOptions
{
Host = "127.0.0.1",
@ -58,7 +59,10 @@ public class EndToEndChatTests : IAsyncLifetime
DataDirectory = _testDir,
ServerName = "E2E Test Server",
Motd = "Testing GsDChat E2E",
MaxWebSocketMessageSizeBytes = 1048576
MaxWebSocketMessageSizeBytes = 1048576,
VapidPublicKey = vapidPub,
VapidPrivateKey = vapidPriv,
VapidSubject = "mailto:test@gsdchat.local"
};
builder.Services.AddSingleton(serverOptions);
@ -66,6 +70,7 @@ public class EndToEndChatTests : IAsyncLifetime
builder.Services.AddSingleton<InviteTokenService>();
builder.Services.AddSingleton<IAuthService, AuthService>();
builder.Services.AddSingleton<FileStorageService>();
builder.Services.AddSingleton<WebPushService>();
builder.Services.AddSingleton<ChatWebSocketManager>();
builder.Services.AddSingleton<RateLimitService>();
builder.Services.AddSingleton<ConnectionLimiterService>();
@ -103,9 +108,52 @@ public class EndToEndChatTests : IAsyncLifetime
MaxFileSizeMb = opt.MaxFileSizeMb,
AllowMemberChannelCreation = opt.AllowMemberChannelCreation,
AllowDmE2ee = opt.AllowDmE2ee,
MaxGroupChatUsers = opt.MaxGroupChatUsers
MaxGroupChatUsers = opt.MaxGroupChatUsers,
VapidPublicKey = opt.VapidPublicKey
}));
_app.MapGet("/api/push/vapid-public-key", (ServerOptions opt) =>
{
return Results.Ok(new { publicKey = opt.VapidPublicKey });
});
_app.MapPost("/api/push/subscribe", async (PushSubscribeRequest req, HttpRequest httpReq, IAuthService auth, ChatDatabase chatDb) =>
{
string? token = ExtractToken(httpReq);
var user = await auth.ValidateSessionTokenAsync(token ?? "");
if (user == null) return Results.Unauthorized();
await chatDb.SavePushSubscriptionAsync(new PushSubscriptionRecord
{
UserId = user.Id,
Endpoint = req.Endpoint.Trim(),
P256dh = req.P256dh.Trim(),
Auth = req.Auth.Trim(),
UserAgent = req.UserAgent ?? string.Empty
});
return Results.Ok(new { success = true });
});
_app.MapPost("/api/push/unsubscribe", async (PushUnsubscribeRequest req, HttpRequest httpReq, IAuthService auth, ChatDatabase chatDb) =>
{
string? token = ExtractToken(httpReq);
var user = await auth.ValidateSessionTokenAsync(token ?? "");
if (user == null) return Results.Unauthorized();
await chatDb.RemovePushSubscriptionAsync(user.Id, req.Endpoint.Trim());
return Results.Ok(new { success = true });
});
_app.MapPost("/api/push/test", async (HttpRequest httpReq, IAuthService auth, WebPushService webPush) =>
{
string? token = ExtractToken(httpReq);
var user = await auth.ValidateSessionTokenAsync(token ?? "");
if (user == null) return Results.Unauthorized();
bool delivered = await webPush.SendTestPushAsync(user.Id, user.Username);
return Results.Ok(new { success = delivered });
});
_app.MapPost("/api/auth/register", async (RegisterRequest req, IAuthService auth, CsrfProtectionService csrf, HttpContext context) =>
{
string? csrfToken = context.Request.Headers["X-CSRF-Token"];
@ -872,5 +920,233 @@ public class EndToEndChatTests : IAsyncLifetime
Assert.Contains(charlieGroupMsgs, m => m.Content == "Hello team members!");
Assert.False(stateDave.ChannelMessages.ContainsKey(groupId));
}
[Fact]
public async Task InboxNotifications_MentionsAnnouncementsFollowedChannelsAndDms_ShouldDeliverAndMarkReadOnJoin()
{
var stateAlice = CreateClientState();
using var connAlice = new ChatClientConnection(stateAlice);
var regAlice = await connAlice.RegisterAsync("AliceInbox", "Pass123!");
stateAlice.Token = regAlice.Token!;
stateAlice.CurrentUserId = regAlice.UserId!;
stateAlice.CurrentUsername = regAlice.Username!;
stateAlice.CurrentUserRole = regAlice.Role!;
var stateBob = CreateClientState();
using var connBob = new ChatClientConnection(stateBob);
var regBob = await connBob.RegisterAsync("BobInbox", "Pass123!");
stateBob.Token = regBob.Token!;
stateBob.CurrentUserId = regBob.UserId!;
stateBob.CurrentUsername = regBob.Username!;
stateBob.CurrentUserRole = regBob.Role!;
await connAlice.StartWebSocketAsync();
await connBob.StartWebSocketAsync();
await Task.Delay(300);
string generalId = stateAlice.Channels.First(c => c.Name == "general").Id;
string announcementsId = stateAlice.Channels.First(c => c.Name == "announcements").Id;
// 1. Alice mentions @BobInbox in #general -> Bob receives an unread Mention inbox item
await connAlice.SendChatMessageAsync(generalId, "Hello @BobInbox please review the PR!");
for (int i = 0; i < 20; i++)
{
if (stateBob.UnreadInboxCount >= 1) break;
await Task.Delay(100);
}
Assert.Equal(1, stateBob.UnreadInboxCount);
var bobItems = stateBob.GetInboxItems();
Assert.Single(bobItems);
Assert.Equal(InboxCategories.Mention, bobItems[0].Category);
Assert.Contains("Hello @BobInbox", bobItems[0].ContentPreview);
Assert.False(bobItems[0].IsRead);
// 2. Alice posts in #announcements -> Bob receives an unread Announcement inbox item
await connAlice.SendChatMessageAsync(announcementsId, "Release v2.0 is live!");
for (int i = 0; i < 20; i++)
{
if (stateBob.UnreadInboxCount >= 2) break;
await Task.Delay(100);
}
Assert.Equal(2, stateBob.UnreadInboxCount);
bobItems = stateBob.GetInboxItems();
Assert.Contains(bobItems, x => x.Category == InboxCategories.Announcement && x.ContentPreview.Contains("Release v2.0"));
// 3. Bob joins #announcements -> auto-marks #announcements inbox items as read!
await connBob.JoinChannelAsync(announcementsId);
for (int i = 0; i < 20; i++)
{
if (stateBob.UnreadInboxCount == 1) break;
await Task.Delay(100);
}
Assert.Equal(1, stateBob.UnreadInboxCount);
// 4. Bob follows #general -> non-mention messages in #general now create FollowedChannel inbox items for Bob
await connBob.ToggleFollowChannelAsync(generalId, follow: true);
for (int i = 0; i < 20; i++)
{
if (stateBob.IsConversationFollowed(stateBob.Channels.First(c => c.Id == generalId))) break;
await Task.Delay(100);
}
Assert.True(stateBob.IsConversationFollowed(stateBob.Channels.First(c => c.Id == generalId)));
await connAlice.SendChatMessageAsync(generalId, "Regular update in followed general channel");
for (int i = 0; i < 20; i++)
{
if (stateBob.UnreadInboxCount >= 2) break;
await Task.Delay(100);
}
bobItems = stateBob.GetInboxItems();
Assert.Contains(bobItems, x => x.Category == InboxCategories.FollowedChannel && x.ContentPreview.Contains("Regular update"));
// 5. Bob marks all read and clears read items
await connBob.SendInboxActionAsync("mark_all_read");
for (int i = 0; i < 20; i++)
{
if (stateBob.UnreadInboxCount == 0) break;
await Task.Delay(100);
}
Assert.Equal(0, stateBob.UnreadInboxCount);
await connBob.SendInboxActionAsync("clear_read");
for (int i = 0; i < 20; i++)
{
if (stateBob.GetInboxItems().Count == 0) break;
await Task.Delay(100);
}
Assert.Empty(stateBob.GetInboxItems());
}
[Fact]
public async Task InboxNotifications_WithE2eeDirectMessage_ShouldDecryptInClientInboxAndDeliverEncryptedWebPush()
{
var serverOptions = _app!.Services.GetRequiredService<ServerOptions>();
serverOptions.AllowDmE2ee = true;
var db = _app.Services.GetRequiredService<ChatDatabase>();
// Spin up a local mock Web Push receiver endpoint to capture the RFC 8291 encrypted push HTTP POST
using var pushListener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
pushListener.Start();
int pushPort = ((System.Net.IPEndPoint)pushListener.LocalEndpoint).Port;
pushListener.Stop();
byte[]? receivedEncryptedPushBody = null;
string? receivedAuthHeader = null;
string? receivedContentEncoding = null;
var pushBuilder = WebApplication.CreateBuilder();
pushBuilder.WebHost.UseUrls($"http://127.0.0.1:{pushPort}");
pushBuilder.Logging.ClearProviders();
await using var pushEndpointApp = pushBuilder.Build();
pushEndpointApp.MapPost("/push-sink", async (HttpContext ctx) =>
{
receivedAuthHeader = ctx.Request.Headers["Authorization"].ToString();
receivedContentEncoding = ctx.Request.Headers["Content-Encoding"].ToString();
using var ms = new MemoryStream();
await ctx.Request.Body.CopyToAsync(ms);
receivedEncryptedPushBody = ms.ToArray();
return Results.StatusCode(201);
});
await pushEndpointApp.StartAsync();
try
{
var stateAlice = CreateClientState();
using var connAlice = new ChatClientConnection(stateAlice);
var regAlice = await connAlice.RegisterAsync("AlicePushDm", "Pass123!");
stateAlice.Token = regAlice.Token!;
stateAlice.CurrentUserId = regAlice.UserId!;
stateAlice.CurrentUsername = regAlice.Username!;
var stateBob = CreateClientState();
using var connBob = new ChatClientConnection(stateBob);
var regBob = await connBob.RegisterAsync("BobPushDm", "Pass123!");
stateBob.Token = regBob.Token!;
stateBob.CurrentUserId = regBob.UserId!;
stateBob.CurrentUsername = regBob.Username!;
await connAlice.StartWebSocketAsync();
await connBob.StartWebSocketAsync();
await Task.Delay(250);
// Register a simulated browser Web Push subscription for Bob
var (subPub, subPriv) = GsDChat.Core.Security.WebPushCrypto.GenerateVapidKeys();
byte[] authBytes = new byte[16];
System.Security.Cryptography.RandomNumberGenerator.Fill(authBytes);
string subAuth = GsDChat.Core.Security.WebPushCrypto.Base64UrlEncode(authBytes);
using var http = new HttpClient { BaseAddress = new Uri(_serverUrl) };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", stateBob.Token);
var subPayload = JsonSerializer.Serialize(new PushSubscribeRequest
{
Endpoint = $"http://127.0.0.1:{pushPort}/push-sink",
P256dh = subPub,
Auth = subAuth,
UserAgent = "Xunit-Push-Test"
});
var subRes = await http.PostAsync("/api/push/subscribe", new StringContent(subPayload, Encoding.UTF8, "application/json"));
Assert.True(subRes.IsSuccessStatusCode);
// Start E2EE DM between Alice and Bob
await connAlice.StartDmAsync("BobPushDm");
for (int i = 0; i < 20; i++)
{
if (stateAlice.DirectMessages.Count > 0 && stateBob.DirectMessages.Count > 0) break;
await Task.Delay(100);
}
string dmId = stateAlice.DirectMessages[0].Id;
Assert.True((await connAlice.UnlockOrInitializeE2eeWithPinAsync("alice-pin-123")).Success);
Assert.True((await connBob.UnlockOrInitializeE2eeWithPinAsync("bob-pin-456")).Success);
for (int i = 0; i < 20; i++)
{
if (!string.IsNullOrEmpty(stateAlice.GetPeerPublicKeyForDm(stateAlice.DirectMessages[0]))) break;
await Task.Delay(100);
}
// Alice sends an E2EE DM to Bob
string secretText = "Secret Inbox & Push DM payload!";
await connAlice.SendChatMessageAsync(dmId, secretText);
for (int i = 0; i < 30; i++)
{
if (stateBob.UnreadInboxCount >= 1 && receivedEncryptedPushBody != null) break;
await Task.Delay(100);
}
// 1. Verify Server DB stored only ciphertext in inbox_items
var dbInboxItems = await db.GetInboxItemsForUserAsync(stateBob.CurrentUserId);
Assert.Single(dbInboxItems);
Assert.True(dbInboxItems[0].IsEncrypted);
Assert.StartsWith("E2EE:v1:", dbInboxItems[0].ContentPreview);
Assert.DoesNotContain("Secret Inbox", dbInboxItems[0].ContentPreview);
// 2. Verify Bob's client decrypted the Inbox item preview automatically using his unlocked E2EE key vault
var bobClientInbox = stateBob.GetInboxItems();
Assert.Single(bobClientInbox);
Assert.Equal(InboxCategories.DirectMessage, bobClientInbox[0].Category);
Assert.Equal(secretText, bobClientInbox[0].ContentPreview);
// 3. Verify WebPushService sent an RFC 8292 VAPID + RFC 8291 aes128gcm Push Notification to Bob's subscription
Assert.NotNull(receivedEncryptedPushBody);
Assert.Equal("aes128gcm", receivedContentEncoding);
Assert.NotNull(receivedAuthHeader);
Assert.StartsWith("vapid t=", receivedAuthHeader);
// Decrypt the Web Push payload as the browser would, and verify E2EE privacy is preserved in OS push banner
byte[] pushJsonBytes = GsDChat.Core.Security.WebPushCrypto.DecryptPayload(receivedEncryptedPushBody!, subPub, subPriv, subAuth);
string pushJson = Encoding.UTF8.GetString(pushJsonBytes);
Assert.Contains("New encrypted message from @AlicePushDm", pushJson);
Assert.DoesNotContain("Secret Inbox", pushJson);
}
finally
{
await pushEndpointApp.StopAsync();
}
}
}