using Khaemhat.Application.Security;
using Khaemhat.Core.Security;
using Khaemhat.Infrastructure.Security;
using Khaemhat.Web.Tests.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Khaemhat.Web.Tests.Shell;
/// "Il mio profilo": the user changes name, e-mail, password and two-step verification alone (issue #31).
[TestClass]
public sealed class ProfileServiceTests
{
private const string NewPassword = "Altra-Password-2026";
[TestMethod]
public async Task InstanceAccount_ChangesData_Password_AndTurnsOnTheVerification()
{
var (app, _, _) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var profiles = app.Services.GetRequiredService();
var sessions = app.Services.GetRequiredService();
var owner = new SessionOwner(null, 1);
var info = await profiles.GetAsync(owner);
Assert.IsNotNull(info);
Assert.AreEqual(TestInstance.SuperUser, info.UserName);
Assert.IsTrue(info.TotpRequired, "Instance accounts always need the two-step verification.");
// Name and e-mail are checked, then saved.
CollectionAssert.AreEquivalent(
new[] { ProfileService.DisplayNameInvalid, ProfileService.EmailInvalid }, (await profiles.UpdateAsync(owner, " ", "not-an-address")).ToList());
Assert.IsEmpty(await profiles.UpdateAsync(owner, " Amministratore Prova ", "admin@example.com"));
info = await profiles.GetAsync(owner);
Assert.AreEqual("Amministratore Prova", info!.DisplayName);
Assert.AreEqual("admin@example.com", info.Email);
// The password: the current one is checked, the policy applies, the other sessions are closed.
await sessions.CreateAsync(owner, SessionState.Active, null, "10.0.0.1", "test-a", persistent: false);
await sessions.CreateAsync(owner, SessionState.Active, null, "10.0.0.2", "test-b", persistent: false);
var kept = (await sessions.ListAsync(owner))[0].Id;
CollectionAssert.AreEqual(new[] { SecurityErrors.CurrentPasswordWrong }, (await profiles.ChangePasswordAsync(owner, kept, "wrong", NewPassword)).ToList());
CollectionAssert.Contains((await profiles.ChangePasswordAsync(owner, kept, TestInstance.SuperUserPassword, "short")).ToList(), SecurityErrors.PasswordTooShort);
Assert.IsEmpty(await profiles.ChangePasswordAsync(owner, kept, TestInstance.SuperUserPassword, NewPassword));
Assert.AreEqual(kept, (await sessions.ListAsync(owner)).Single().Id, "Only the session that changed the password stays open.");
CollectionAssert.AreEqual(new[] { SecurityErrors.CurrentPasswordWrong }, (await profiles.ChangePasswordAsync(owner, kept, TestInstance.SuperUserPassword, "Terza-Password-2026")).ToList());
// The two-step verification: the same secret until confirmed, ten recovery codes, cannot be turned off.
var setup = await profiles.BeginTotpSetupAsync(owner, null);
Assert.IsNotNull(setup);
Assert.AreEqual(setup.Secret, (await profiles.BeginTotpSetupAsync(owner, null))!.Secret);
Assert.IsNull(await profiles.ConfirmTotpSetupAsync(owner, "abc"));
var codes = await profiles.ConfirmTotpSetupAsync(owner, CodeOf(setup.Secret));
Assert.HasCount(10, codes!);
info = await profiles.GetAsync(owner);
Assert.IsTrue(info!.TotpEnabled);
Assert.AreEqual(10, info.RecoveryCodesLeft);
Assert.IsNull(await profiles.BeginTotpSetupAsync(owner, null), "Already active.");
CollectionAssert.AreEqual(new[] { ProfileService.TotpRequiredError }, (await profiles.DisableTotpAsync(owner, NewPassword)).ToList());
// New recovery codes need the password and replace the old ones.
Assert.IsNull(await profiles.RenewRecoveryCodesAsync(owner, "wrong"));
var renewed = await profiles.RenewRecoveryCodesAsync(owner, NewPassword);
Assert.HasCount(10, renewed!);
Assert.IsEmpty(renewed!.Intersect(codes!).ToList());
await app.StopAsync();
}
}
[TestMethod]
public async Task CompanyUser_MayTurnTheVerificationOff_WithThePassword()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var profiles = app.Services.GetRequiredService();
var users = app.Services.GetRequiredService();
var root = new Actor(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
var (user, password) = await users.CreateAsync(root, company, new NewCompanyUser("lucia", "Lucia Bianchi", null, UserKind.Human, [], new UserFlags(false, false, false, false)));
var owner = new SessionOwner(company, user.Id);
var setup = await profiles.BeginTotpSetupAsync(owner, company);
Assert.Contains("lucia%40", setup!.ProvisioningUri, "The app shows user and company.");
Assert.IsNotNull(await profiles.ConfirmTotpSetupAsync(owner, CodeOf(setup.Secret)));
Assert.IsFalse((await profiles.GetAsync(owner))!.TotpRequired);
CollectionAssert.AreEqual(new[] { SecurityErrors.CurrentPasswordWrong }, (await profiles.DisableTotpAsync(owner, "wrong")).ToList());
Assert.IsEmpty(await profiles.DisableTotpAsync(owner, password!));
var info = await profiles.GetAsync(owner);
Assert.IsFalse(info!.TotpEnabled);
Assert.AreEqual(0, info.RecoveryCodesLeft);
await app.StopAsync();
}
}
private static string CodeOf(string secret) => TotpGenerator.Compute(Base32.Decode(secret), TotpGenerator.StepOf(DateTimeOffset.UtcNow));
}