Add cryptographic session key management for users

Introduces a new cryptographic key management system for user sessions, including models, DTOs, interfaces, and services for handling identity keys, signed pre-keys, and one-time pre-keys. Updates the SessionKeysController and DI configuration to use the new services. Adds related EF Core configurations and migrations, and updates the UserSession model to reference the new UserCryptoSession. Removes the obsolete ISessionKeyService interface.
This commit is contained in:
Artemy
2025-07-30 21:26:35 +07:00
parent dc560ba698
commit 1d442d037c
27 changed files with 1608 additions and 83 deletions
@@ -0,0 +1,70 @@
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Application.Interfaces.UserSession.Crypto;
using Govor.Core.Models.Users.Crypto;
using Govor.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Govor.Application.Services.UserSessions.Crypto;
public class OneTimePreKeysRotator : IOneTimePreKeysRotator
{
private readonly ILogger<SessionKeyAttacher> _logger;
private readonly ICurrentUserService _current;
private readonly GovorDbContext _context;
public OneTimePreKeysRotator(ILogger<SessionKeyAttacher> logger, ICurrentUserService current, GovorDbContext context)
{
_logger = logger;
_current = current;
_context = context;
}
public async Task RotateOneTimePreKeysAsync(Guid sessionId, IEnumerable<byte[]> newOneTimePreKeys)
{
var cryptoSession = await _context.UserCryptoSessions
.Include(c => c.OneTimePreKeys)
.FirstOrDefaultAsync(c => c.UserSessionId == sessionId);
if (cryptoSession == null)
throw new ArgumentException("Crypto session not found", nameof(sessionId));
// Удаляем все использованные ключи
var usedKeys = cryptoSession.OneTimePreKeys.Where(k => k.IsUsed).ToList();
if (usedKeys.Any())
{
_context.OneTimePreKeys.RemoveRange(usedKeys);
}
// Добавляем новые ключи (возможно, стоит ограничить количество)
foreach (var key in newOneTimePreKeys)
{
cryptoSession.OneTimePreKeys.Add(new OneTimePreKey
{
Id = Guid.NewGuid(),
PublicKey = key,
IsUsed = false,
UploadedAt = DateTime.UtcNow
});
}
await _context.SaveChangesAsync();
}
public async Task MarkOneTimePreKeyAsUsedAsync(Guid sessionId, Guid oneTimePreKeyId)
{
var key = await _context.OneTimePreKeys
.Include(k => k.UserCryptoSession)
.FirstOrDefaultAsync(k => k.Id == oneTimePreKeyId && k.UserCryptoSession.UserSessionId == sessionId);
if (key == null)
throw new ArgumentException("One-Time PreKey not found for this session", nameof(oneTimePreKeyId));
if (key.IsUsed)
return; // Уже помечен
key.IsUsed = true;
await _context.SaveChangesAsync();
}
}