mirror of
https://github.com/Govor-team/Govor.git
synced 2026-11-18 05:15:06 +00:00
Expand server tests and enforce coverage
Consolidate server tests under tests/, upgrade them to .NET 10, and add CI coverage thresholds and reports. Expand API and application boundary coverage while fixing related issues in media handling, friend blocking, session crypto, presence, username validation, and local storage.
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Jose;
|
||||
using AesGcm = System.Security.Cryptography.AesGcm;
|
||||
|
||||
@@ -8,19 +9,39 @@ namespace Govor.Application.E2ee;
|
||||
|
||||
// Shared verbatim with the mobile client. JOSE implements RFC 7515/7516;
|
||||
// the application envelope binds the ciphertext to its author and conversation.
|
||||
public sealed record DeviceKey(Guid UserId, Guid SessionId, string IdentityKey,
|
||||
string EncryptionKey, string Signature)
|
||||
public sealed record DeviceKey(
|
||||
Guid UserId,
|
||||
Guid SessionId,
|
||||
string IdentityKey,
|
||||
string EncryptionKey,
|
||||
string Signature)
|
||||
{
|
||||
public string Fingerprint => E2eeProtocol.Fingerprint(IdentityKey, EncryptionKey);
|
||||
}
|
||||
|
||||
public sealed record ConversationKeys(Guid ConversationId, int RecipientType,
|
||||
Guid[] Members, DeviceKey[] Devices);
|
||||
public sealed record ConversationKeys(
|
||||
Guid ConversationId,
|
||||
int RecipientType,
|
||||
Guid[] Members,
|
||||
DeviceKey[] Devices);
|
||||
|
||||
public sealed record AttachmentSecret(Guid MediaId, string Key, string FileName, string MimeType);
|
||||
|
||||
public sealed record MessagePlaintext(string Text, AttachmentSecret[] Attachments);
|
||||
public sealed record EncryptedMessage(int Version, Guid MessageId, Guid ConversationId,
|
||||
int RecipientType, DeviceKey Sender, Guid? ReplyToMessageId, long CreatedAt,
|
||||
bool IsEdit, string[] Recipients, Guid[] MediaIds, string Ciphertext);
|
||||
|
||||
public sealed record EncryptedMessage(
|
||||
int Version,
|
||||
Guid MessageId,
|
||||
Guid ConversationId,
|
||||
int RecipientType,
|
||||
DeviceKey Sender,
|
||||
Guid? ReplyToMessageId,
|
||||
long CreatedAt,
|
||||
bool IsEdit,
|
||||
string[] Recipients,
|
||||
Guid[] MediaIds,
|
||||
string Ciphertext);
|
||||
|
||||
public sealed record DevicePrivateKeys(string IdentityKey, string EncryptionKey);
|
||||
|
||||
public static class E2eeProtocol
|
||||
@@ -31,13 +52,16 @@ public static class E2eeProtocol
|
||||
public const string EncryptedMimeType = "application/vnd.govor.encrypted";
|
||||
public static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
public static bool IsEncrypted(string? value) => value?.StartsWith(Prefix, StringComparison.Ordinal) == true;
|
||||
public static bool IsEncrypted(string? value)
|
||||
{
|
||||
return value?.StartsWith(Prefix, StringComparison.Ordinal) == true;
|
||||
}
|
||||
|
||||
public static DevicePrivateKeys GenerateKeys()
|
||||
{
|
||||
using var signing = ECDsa.Create(ECCurve.NamedCurves.nistP256);
|
||||
using var encryption = RSA.Create(3072);
|
||||
return new(Convert.ToBase64String(signing.ExportPkcs8PrivateKey()),
|
||||
return new DevicePrivateKeys(Convert.ToBase64String(signing.ExportPkcs8PrivateKey()),
|
||||
Convert.ToBase64String(encryption.ExportPkcs8PrivateKey()));
|
||||
}
|
||||
|
||||
@@ -50,7 +74,7 @@ public static class E2eeProtocol
|
||||
// Domain separation prevents using this signature as a message signature.
|
||||
var signature = signing.SignData(KeyBinding(publicEncryption), HashAlgorithmName.SHA256,
|
||||
DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
|
||||
return new(user, session, identity, publicEncryption, Convert.ToBase64String(signature));
|
||||
return new DeviceKey(user, session, identity, publicEncryption, Convert.ToBase64String(signature));
|
||||
}
|
||||
|
||||
public static void ValidatePublicKey(DeviceKey key)
|
||||
@@ -69,8 +93,11 @@ public static class E2eeProtocol
|
||||
throw new CryptographicException("Invalid E2EE key binding signature.");
|
||||
}
|
||||
|
||||
public static string Fingerprint(string identity, string encryption) =>
|
||||
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes($"govor-device-v1\n{identity}\n{encryption}")));
|
||||
public static string Fingerprint(string identity, string encryption)
|
||||
{
|
||||
return Convert.ToHexString(
|
||||
SHA256.HashData(Encoding.UTF8.GetBytes($"govor-device-v1\n{identity}\n{encryption}")));
|
||||
}
|
||||
|
||||
public static string Encrypt(MessagePlaintext plaintext, DevicePrivateKeys privateKeys,
|
||||
DeviceKey sender, ConversationKeys conversation, Guid messageId, Guid? replyTo = null,
|
||||
@@ -96,7 +123,8 @@ public static class E2eeProtocol
|
||||
}).ToArray();
|
||||
var ciphertext = JWE.Encrypt(JsonSerializer.Serialize(plaintext), recipients, JweEncryption.A256GCM);
|
||||
var envelope = new EncryptedMessage(1, messageId, conversation.ConversationId,
|
||||
conversation.RecipientType, sender, replyTo, createdAt ?? DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
|
||||
conversation.RecipientType, sender, replyTo,
|
||||
createdAt ?? DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
|
||||
isEdit, devices.Select(k => k.Fingerprint).Order(StringComparer.Ordinal).ToArray(),
|
||||
plaintext.Attachments.Select(a => a.MediaId).Order().ToArray(), ciphertext);
|
||||
using var signing = SigningPrivateKey(privateKeys);
|
||||
@@ -104,7 +132,10 @@ public static class E2eeProtocol
|
||||
if (result.Length > MaxEnvelopeLength) throw new CryptographicException("E2EE envelope is too large.");
|
||||
return result;
|
||||
}
|
||||
finally { foreach (var key in keys) key.Dispose(); }
|
||||
finally
|
||||
{
|
||||
foreach (var key in keys) key.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
// Reading the unverified payload is used only to select its verification key.
|
||||
@@ -116,7 +147,7 @@ public static class E2eeProtocol
|
||||
var parts = value[Prefix.Length..].Split('.');
|
||||
if (parts.Length != 3) throw new CryptographicException("Invalid signed E2EE envelope.");
|
||||
var envelope = JsonSerializer.Deserialize<EncryptedMessage>(Base64Url.Decode(parts[1]), Json)
|
||||
?? throw new CryptographicException("Invalid E2EE envelope.");
|
||||
?? throw new CryptographicException("Invalid E2EE envelope.");
|
||||
if (envelope.Version != 1 || envelope.Sender is null || envelope.MessageId == Guid.Empty ||
|
||||
envelope.ConversationId == Guid.Empty || envelope.RecipientType is < 0 or > 1 ||
|
||||
envelope.Recipients is null || envelope.Recipients.Length is 0 or > MaxDevices ||
|
||||
@@ -142,7 +173,8 @@ public static class E2eeProtocol
|
||||
header.RootElement.TryGetProperty("zip", out _))
|
||||
throw new CryptographicException("Unsupported content encryption.");
|
||||
var recipients = root.TryGetProperty("recipients", out var many)
|
||||
? many.EnumerateArray().ToArray() : new[] { root };
|
||||
? many.EnumerateArray().ToArray()
|
||||
: new[] { root };
|
||||
if (recipients.Length != envelope.Recipients.Length ||
|
||||
recipients.Any(r => r.GetProperty("header").GetProperty("alg").GetString() != "RSA-OAEP-256") ||
|
||||
!recipients.Select(r => r.GetProperty("header").GetProperty("kid").GetString())
|
||||
@@ -170,16 +202,17 @@ public static class E2eeProtocol
|
||||
throw new CryptographicException("This device cannot decrypt this message.");
|
||||
// Select our recipient explicitly. In particular Windows CNG can throw an
|
||||
// OS-specific error while trying another recipient's RSA-OAEP encrypted key.
|
||||
var selected = System.Text.Json.Nodes.JsonNode.Parse(envelope.Ciphertext)!;
|
||||
if (selected["recipients"] is System.Text.Json.Nodes.JsonArray recipients)
|
||||
var selected = JsonNode.Parse(envelope.Ciphertext)!;
|
||||
if (selected["recipients"] is JsonArray recipients)
|
||||
{
|
||||
var recipient = recipients.Single(r => r!["header"]!["kid"]!.GetValue<string>() == fingerprint)!;
|
||||
selected["recipients"] = new System.Text.Json.Nodes.JsonArray(recipient.DeepClone());
|
||||
selected["recipients"] = new JsonArray(recipient.DeepClone());
|
||||
}
|
||||
|
||||
var decrypted = JWE.Decrypt(selected.ToJsonString(), rsa,
|
||||
JweAlgorithm.RSA_OAEP_256, JweEncryption.A256GCM);
|
||||
var plaintext = JsonSerializer.Deserialize<MessagePlaintext>(decrypted.Plaintext, Json)
|
||||
?? throw new CryptographicException("Invalid encrypted content.");
|
||||
?? throw new CryptographicException("Invalid encrypted content.");
|
||||
if (plaintext.Text is null || plaintext.Text.Length > 20_000 || plaintext.Attachments is null ||
|
||||
!plaintext.Attachments.Select(a => a.MediaId).Order().SequenceEqual(envelope.MediaIds.Order()))
|
||||
throw new CryptographicException("Invalid encrypted attachment manifest.");
|
||||
@@ -195,11 +228,15 @@ public static class E2eeProtocol
|
||||
var data = new byte[12 + plaintext.Length + 16];
|
||||
RandomNumberGenerator.Fill(data.AsSpan(0, 12));
|
||||
using var aes = new AesGcm(key, 16);
|
||||
aes.Encrypt(data.AsSpan(0, 12), plaintext, data.AsSpan(12, plaintext.Length), data.AsSpan(12 + plaintext.Length, 16),
|
||||
aes.Encrypt(data.AsSpan(0, 12), plaintext, data.AsSpan(12, plaintext.Length),
|
||||
data.AsSpan(12 + plaintext.Length, 16),
|
||||
"govor-attachment-v1"u8);
|
||||
return (data, Convert.ToBase64String(key));
|
||||
}
|
||||
finally { CryptographicOperations.ZeroMemory(key); }
|
||||
finally
|
||||
{
|
||||
CryptographicOperations.ZeroMemory(key);
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] DecryptAttachment(byte[] ciphertext, string encodedKey)
|
||||
@@ -215,26 +252,57 @@ public static class E2eeProtocol
|
||||
ciphertext.AsSpan(12 + plaintext.Length, 16), plaintext, "govor-attachment-v1"u8);
|
||||
return plaintext;
|
||||
}
|
||||
finally { CryptographicOperations.ZeroMemory(key); }
|
||||
finally
|
||||
{
|
||||
CryptographicOperations.ZeroMemory(key);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] KeyBinding(string encryption)
|
||||
{
|
||||
return Encoding.UTF8.GetBytes("govor-key-binding-v1\n" + encryption);
|
||||
}
|
||||
|
||||
private static byte[] KeyBinding(string encryption) => Encoding.UTF8.GetBytes("govor-key-binding-v1\n" + encryption);
|
||||
private static ECDsa SigningPrivateKey(DevicePrivateKeys keys)
|
||||
{
|
||||
var bytes = Convert.FromBase64String(keys.IdentityKey);
|
||||
var key = ECDsa.Create();
|
||||
try { key.ImportPkcs8PrivateKey(bytes, out _); return key; }
|
||||
catch { key.Dispose(); throw; }
|
||||
finally { CryptographicOperations.ZeroMemory(bytes); }
|
||||
try
|
||||
{
|
||||
key.ImportPkcs8PrivateKey(bytes, out _);
|
||||
return key;
|
||||
}
|
||||
catch
|
||||
{
|
||||
key.Dispose();
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
CryptographicOperations.ZeroMemory(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
private static RSA EncryptionPrivateKey(DevicePrivateKeys keys)
|
||||
{
|
||||
var bytes = Convert.FromBase64String(keys.EncryptionKey);
|
||||
var key = RSA.Create();
|
||||
try { key.ImportPkcs8PrivateKey(bytes, out _); return key; }
|
||||
catch { key.Dispose(); throw; }
|
||||
finally { CryptographicOperations.ZeroMemory(bytes); }
|
||||
try
|
||||
{
|
||||
key.ImportPkcs8PrivateKey(bytes, out _);
|
||||
return key;
|
||||
}
|
||||
catch
|
||||
{
|
||||
key.Dispose();
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
CryptographicOperations.ZeroMemory(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
private static ECDsa SigningPublicKey(DeviceKey device)
|
||||
{
|
||||
var key = ECDsa.Create();
|
||||
@@ -245,8 +313,13 @@ public static class E2eeProtocol
|
||||
if (read != bytes.Length) throw new CryptographicException("Trailing public key data.");
|
||||
return key;
|
||||
}
|
||||
catch { key.Dispose(); throw; }
|
||||
catch
|
||||
{
|
||||
key.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static RSA EncryptionPublicKey(DeviceKey device)
|
||||
{
|
||||
var key = RSA.Create();
|
||||
@@ -257,6 +330,10 @@ public static class E2eeProtocol
|
||||
if (read != bytes.Length) throw new CryptographicException("Trailing public key data.");
|
||||
return key;
|
||||
}
|
||||
catch { key.Dispose(); throw; }
|
||||
catch
|
||||
{
|
||||
key.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,50 @@
|
||||
using Govor.Domain;
|
||||
using Govor.Domain.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Govor.Application.Friends;
|
||||
|
||||
public class FriendsBlockService : IFriendsBlockService
|
||||
public class FriendsBlockService(GovorDbContext context) : IFriendsBlockService
|
||||
{
|
||||
public Task BlockFriendRequestAsync(Guid userId, Guid currentUserId)
|
||||
public async Task BlockFriendRequestAsync(Guid userId, Guid currentUserId)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
if (userId == Guid.Empty || currentUserId == Guid.Empty || userId == currentUserId)
|
||||
throw new ArgumentException("Two distinct users are required.");
|
||||
if (await context.Users.CountAsync(u => u.Id == userId || u.Id == currentUserId) != 2)
|
||||
throw new KeyNotFoundException("User not found.");
|
||||
var friendship = await FindAsync(userId, currentUserId);
|
||||
if (friendship?.Status == FriendshipStatus.Blocked)
|
||||
{
|
||||
if (friendship.RequesterId != currentUserId)
|
||||
throw new UnauthorizedAccessException("Only the user who blocked this conversation can change the block.");
|
||||
return;
|
||||
}
|
||||
if (friendship is null)
|
||||
{
|
||||
friendship = new Friendship { Id = Guid.NewGuid() };
|
||||
context.Friendships.Add(friendship);
|
||||
}
|
||||
// A blocked row records its owner as Requester; requests cannot overwrite it.
|
||||
friendship.RequesterId = currentUserId;
|
||||
friendship.AddresseeId = userId;
|
||||
friendship.Status = FriendshipStatus.Blocked;
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
public Task UnblockFriendRequestAsync(Guid userId, Guid currentUserId)
|
||||
public async Task UnblockFriendRequestAsync(Guid userId, Guid currentUserId)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
if (userId == Guid.Empty || currentUserId == Guid.Empty || userId == currentUserId)
|
||||
throw new ArgumentException("Two distinct users are required.");
|
||||
var friendship = await FindAsync(userId, currentUserId);
|
||||
if (friendship?.Status != FriendshipStatus.Blocked) return;
|
||||
if (friendship.RequesterId != currentUserId)
|
||||
throw new UnauthorizedAccessException("Only the user who blocked this conversation can remove the block.");
|
||||
// Unblocking permits a new request; it does not restore friendship without consent.
|
||||
friendship.Status = FriendshipStatus.Rejected;
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private Task<Friendship?> FindAsync(Guid userId, Guid currentUserId) => context.Friendships.FirstOrDefaultAsync(f =>
|
||||
(f.RequesterId == userId && f.AddresseeId == currentUserId) ||
|
||||
(f.RequesterId == currentUserId && f.AddresseeId == userId));
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ public class UsernameValidator : IUsernameValidator
|
||||
|
||||
public Result<Unit, Error> Validate(string username)
|
||||
{
|
||||
if (username.Length < UserConstants.MIN_LENGHT_OF_NAME || username.Length > UserConstants.MAX_LENGHT_OF_NAME)
|
||||
if (string.IsNullOrEmpty(username) || username.Length < UserConstants.MIN_LENGHT_OF_NAME || username.Length > UserConstants.MAX_LENGHT_OF_NAME)
|
||||
{
|
||||
return Result.Failure(Error.Validation(
|
||||
ErrorCode,
|
||||
|
||||
@@ -78,24 +78,29 @@ public class MediaService : IMediaService
|
||||
return new Unit();
|
||||
}
|
||||
|
||||
public Task<Result<Media, Error>> GetMediaByUrlAsync(string url)
|
||||
public async Task<Result<Media, Error>> GetMediaByUrlAsync(string url)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
if (string.IsNullOrWhiteSpace(url))
|
||||
return Result.Failure<Media>(Error.Validation("File.GetMediaByUrl", "Media URL is required."));
|
||||
var file = await _dbContext.MediaFiles.AsNoTracking().FirstOrDefaultAsync(m => m.Url == url);
|
||||
return await ReadMediaAsync(file, "File.GetMediaByUrl");
|
||||
}
|
||||
|
||||
public async Task<Result<Media, Error>> GetMediaByIdAsync(Guid mediaId)
|
||||
{
|
||||
var file = await _dbContext.MediaFiles.AsNoTracking().FirstOrDefaultAsync(m => m.Id == mediaId);
|
||||
return await ReadMediaAsync(file, "File.GetMediaById");
|
||||
}
|
||||
|
||||
private async Task<Result<Media, Error>> ReadMediaAsync(MediaFile? mediaFile, string errorCode)
|
||||
{
|
||||
try
|
||||
{
|
||||
var mediaFile = await _dbContext.MediaFiles
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(x => x.Id == mediaId);
|
||||
|
||||
if (mediaFile is null)
|
||||
{
|
||||
return Result<Media, Error>.Failure(Error.NotFound(
|
||||
"File.GetMediaById",
|
||||
$"File with given id ({mediaId}) doesn't exist!")
|
||||
errorCode,
|
||||
"Media file does not exist.")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -114,7 +119,7 @@ public class MediaService : IMediaService
|
||||
return new Media(
|
||||
mediaFile.UploaderId,
|
||||
mediaFile.DateCreated,
|
||||
mediaFile.MediaType.ToString(),
|
||||
Path.GetFileName(mediaFile.Url),
|
||||
contentBytes,
|
||||
mediaFile.MediaType,
|
||||
mediaFile.MineType,
|
||||
@@ -125,8 +130,8 @@ public class MediaService : IMediaService
|
||||
}
|
||||
catch (FileNotFoundException ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Media file ({0}) not found on storage.", mediaId);
|
||||
return Result<Media, Error>.Failure(Error.ServerError("File.GetMediaById", $"Media file not found on storage!"));
|
||||
_logger.LogWarning(ex, "Media file {MediaId} not found on storage.", mediaFile?.Id);
|
||||
return Result<Media, Error>.Failure(Error.ServerError(errorCode, "Media file not found on storage!"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ public class LocalStorageService : IStorageService
|
||||
|
||||
public LocalStorageService(string contentRootPath)
|
||||
{
|
||||
_storagePath = Path.Combine(contentRootPath, "uploads");
|
||||
_storagePath = Path.GetFullPath(Path.Combine(contentRootPath, "uploads"));
|
||||
|
||||
if (!Directory.Exists(_storagePath))
|
||||
{
|
||||
@@ -38,7 +38,7 @@ public class LocalStorageService : IStorageService
|
||||
|
||||
public async Task<Stream> LoadAsync(string url)
|
||||
{
|
||||
var filePath = Path.Combine(_storagePath, url);
|
||||
var filePath = ResolvePath(url);
|
||||
|
||||
if (!File.Exists(filePath))
|
||||
throw new FileNotFoundException("File not found.", filePath);
|
||||
@@ -48,15 +48,7 @@ public class LocalStorageService : IStorageService
|
||||
|
||||
public async Task RemoveAsync(string url)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(url))
|
||||
throw new ArgumentException("Invalid file url");
|
||||
|
||||
var rootPath = Path.GetFullPath(_storagePath);
|
||||
|
||||
var fullPath = Path.GetFullPath(Path.Combine(rootPath, url));
|
||||
|
||||
if (!fullPath.StartsWith(rootPath, StringComparison.OrdinalIgnoreCase))
|
||||
throw new UnauthorizedAccessException("Invalid file path");
|
||||
var fullPath = ResolvePath(url);
|
||||
|
||||
if (!File.Exists(fullPath))
|
||||
return;
|
||||
@@ -80,4 +72,15 @@ public class LocalStorageService : IStorageService
|
||||
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
private string ResolvePath(string url)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(url)) throw new ArgumentException("Invalid file url", nameof(url));
|
||||
if (Path.IsPathRooted(url)) throw new UnauthorizedAccessException("Invalid file path");
|
||||
var fullPath = Path.GetFullPath(Path.Combine(_storagePath, url));
|
||||
var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
|
||||
if (!fullPath.StartsWith(_storagePath + Path.DirectorySeparatorChar, comparison))
|
||||
throw new UnauthorizedAccessException("Invalid file path");
|
||||
return fullPath;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
using Govor.Domain;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Govor.Application.Users.UserOnlineStatus;
|
||||
|
||||
public class UserPresenceReader : IUserPresenceReader
|
||||
public class UserPresenceReader(GovorDbContext context) : IUserPresenceReader
|
||||
{
|
||||
public Task<DateTime?> GetLastSeenAsync(Guid userId)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
return context.Users.AsNoTracking().Where(u => u.Id == userId)
|
||||
.Select(u => (DateTime?)u.WasOnline).FirstOrDefaultAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,10 +23,13 @@ public class OneTimePreKeysRotator : IOneTimePreKeysRotator
|
||||
{
|
||||
var cryptoSession = await _context.UserCryptoSessions
|
||||
.Include(c => c.OneTimePreKeys)
|
||||
.Include(c => c.UserSession)
|
||||
.FirstOrDefaultAsync(c => c.UserSessionId == sessionId);
|
||||
|
||||
if (cryptoSession == null)
|
||||
throw new ArgumentException("Crypto session not found", nameof(sessionId));
|
||||
if (cryptoSession.UserSession.UserId != _current.GetCurrentUserId())
|
||||
throw new UnauthorizedAccessException("Only the session owner can rotate its keys.");
|
||||
|
||||
// Удаляем все использованные ключи
|
||||
var usedKeys = cryptoSession.OneTimePreKeys.Where(k => k.IsUsed).ToList();
|
||||
@@ -38,9 +41,10 @@ public class OneTimePreKeysRotator : IOneTimePreKeysRotator
|
||||
// Добавляем новые ключи (возможно, стоит ограничить количество)
|
||||
foreach (var key in newOneTimePreKeys)
|
||||
{
|
||||
cryptoSession.OneTimePreKeys.Add(new OneTimePreKey
|
||||
_context.OneTimePreKeys.Add(new OneTimePreKey
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserCryptoSessionId = cryptoSession.Id,
|
||||
PublicKey = key,
|
||||
IsUsed = false,
|
||||
UploadedAt = DateTime.UtcNow
|
||||
@@ -54,10 +58,13 @@ public class OneTimePreKeysRotator : IOneTimePreKeysRotator
|
||||
{
|
||||
var key = await _context.OneTimePreKeys
|
||||
.Include(k => k.UserCryptoSession)
|
||||
.ThenInclude(c => c.UserSession)
|
||||
.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.UserCryptoSession.UserSession.UserId != _current.GetCurrentUserId())
|
||||
throw new UnauthorizedAccessException("Only the session owner can consume its keys.");
|
||||
|
||||
if (key.IsUsed)
|
||||
return; // Уже помечен
|
||||
@@ -66,4 +73,4 @@ public class OneTimePreKeysRotator : IOneTimePreKeysRotator
|
||||
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,9 +64,10 @@ public class SessionKeyAttacher : ISessionKeyAttacher
|
||||
};
|
||||
|
||||
session.CryptoSession = cryptoSession;
|
||||
_context.UserCryptoSessions.Add(cryptoSession);
|
||||
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
_logger.LogInformation("Attached keys to session {SessionId}", sessionId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,6 +55,7 @@ public class SessionKeysReader : ISessionKeysReader
|
||||
.AsNoTracking()
|
||||
.Include(c => c.OneTimePreKeys)
|
||||
.Include(c => c.UserSession)
|
||||
.Include(c => c.SignedPreKey)
|
||||
.FirstOrDefaultAsync(c => c.UserSessionId == sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,23 +61,6 @@ public class UserSessionOpener : IUserSessionOpener
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<RefreshResult> UpdateExistingSessionAsync(User user, string deviceInfo, UserSession session)
|
||||
{
|
||||
var (accessToken, refreshToken) = await GenerateTokensAsync(user, session.Id);
|
||||
|
||||
var newTokenHash = _jwtTokenHasher.HashToken(refreshToken);
|
||||
var newExpiresAt = DateTime.UtcNow.AddDays(_options.RefreshTokenLifetimeDays);
|
||||
|
||||
session.RefreshTokenHash = newTokenHash;
|
||||
session.ExpiresAt = newExpiresAt;
|
||||
session.CreatedAt = DateTime.UtcNow;
|
||||
session.IsRevoked = false;
|
||||
|
||||
_logger.LogInformation("Updated session for user {UserId} on device '{DeviceInfo}'", user.Id, deviceInfo);
|
||||
|
||||
return new RefreshResult(refreshToken, accessToken);
|
||||
}
|
||||
|
||||
private async Task<RefreshResult> CreateNewSessionAsync(User user, string deviceInfo)
|
||||
{
|
||||
var sessionId = Guid.NewGuid();
|
||||
|
||||
Reference in New Issue
Block a user