using System.Text;
using Febe.Core.Security;
using Febe.Desktop.Security;
namespace Febe.Tests.Windows;
///
/// The saved session on Windows (issue #36, S4, spec ยง13.2): DPAPI for the current user, from the desktop framework of
/// .NET with no package. No WebView2 needed. A blob that does not open is ,
/// whose text holds nothing of the session.
///
[TestClass]
public sealed class DpapiSessionProtectorTests
{
private const string Secret = "valore-di-prova-della-sessione";
private static readonly byte[] Plain = Encoding.UTF8.GetBytes("{\"cookies\":[{\"name\":\"sessione_prova\",\"value\":\"" + Secret + "\"}]}");
[TestMethod]
public void ARoundTripForTheCurrentUserGivesTheSameBytes()
{
var protector = new DpapiSessionProtector();
Assert.AreEqual("dpapi", protector.Scheme);
var blob = protector.Protect(Plain);
Assert.IsTrue(SessionBlob.HasHeader(blob, SessionBlob.Dpapi), "the shared header with the DPAPI scheme");
CollectionAssert.AreEqual(Plain, protector.Unprotect(blob));
CollectionAssert.AreEqual(Plain, new DpapiSessionProtector().Unprotect(blob), "another instance of the same user");
CollectionAssert.AreNotEqual(blob, protector.Protect(Plain), "DPAPI salts every blob");
}
[TestMethod]
public void TheBlobHoldsNoValueInClear()
{
var blob = new DpapiSessionProtector().Protect(Plain);
foreach (var form in new[] { Encoding.UTF8.GetBytes(Secret), Encoding.Unicode.GetBytes(Secret), Encoding.ASCII.GetBytes(Convert.ToBase64String(Encoding.UTF8.GetBytes(Secret))) })
{
Assert.AreEqual(-1, blob.AsSpan().IndexOf(form), "a form of the value is in the blob");
}
}
[TestMethod]
public void ATamperedBlobOrAnotherSchemeIsUnreadableAndTheMessageHasNoValue()
{
var protector = new DpapiSessionProtector();
var blob = protector.Protect(Plain);
var changedByte = blob.ToArray();
changedByte[^5] ^= 0x40;
var changedHeader = blob.ToArray();
changedHeader[4] = 9;
var aesHeader = blob.ToArray();
aesHeader[5] = SessionBlob.AesGcm;
var headerOnly = SessionBlob.Header(SessionBlob.Dpapi);
foreach (var wrong in new[] { changedByte, changedHeader, aesHeader, headerOnly, [], Encoding.UTF8.GetBytes(Secret) })
{
var error = Assert.ThrowsExactly(() => protector.Unprotect(wrong));
Assert.AreEqual(SessionUnreadableException.Text, error.Message);
Assert.IsNull(error.InnerException, "nothing of DPAPI's own text is passed on");
Assert.DoesNotContain(Secret, error.ToString());
}
Assert.DoesNotContain(Secret, protector.ToString());
}
}