Files
Febe/tests/Febe.Tests/Collection/SessionProtectorTests.cs
T
Alby96andClaude Opus 5.5 c87768766c
verifica / controlli (push) Successful in 22s
verifica / prove (push) Successful in 16m46s
verifica / installatore (push) Successful in 4m43s
verifica / immagine (push) Successful in 21m2s
Sessione salvata cifrata, copiata a «Ho finito» (#36, S4)
Il client del sito ha bisogno della sessione del browser di Febe: ora la copia
c'è, cifrata e dietro un interruttore, senza cambiare nulla di predefinito.

- Opzione «raccolta» (pagine predefinita, richieste): solo con «richieste» e
  almeno un'operazione configurata si costruiscono sessione salvata, client del
  sito e copia. Con Instagram nulla cambia: le dieci operazioni restano non
  configurate (mancano __spin_*, __req, __s, __dyn, __csr e altri).
- Cookie con dominio, percorso, solo-host, Secure, HttpOnly e scadenza, mandati
  solo dove il browser li manderebbe (RFC 6265).
- Sezione «page» del catalogo: dove la pagina tiene ogni valore; nuovi campi rev,
  hs, hsi, dpr, ccg, comet_req, entry_nonce. Il caricatore rifiuta
  un'operazione configurata con un valore di sessione senza fonte nella pagina.
- Dati/sessione/sessione.json: DPAPI su Windows, AES-256-GCM in Docker (chiave
  da FEBE_CHIAVE_SESSIONE o chiave.bin), scrittura atomica, file illeggibile =
  nessuna sessione. «Scollega» la cancella; chiave.bin resta.
- Copia a «Ho finito» con Network.getCookies e una sola Runtime.evaluate in sola
  lettura, solo da una pagina del sito e finché dura il permesso di guida.
- FEBE_PASSWORD e FEBE_CHIAVE_SESSIONE non passano a Chromium, Xvfb, ffmpeg.
- Sito di prova: csrftoken, cookie limitato a /api/, registro di moduli suo.
- Revisione su tre lenti: 11 punti confermati, tutti corretti.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:43:43 +01:00

222 lines
11 KiB
C#

using System.Security.Cryptography;
using System.Text;
using Febe.Core.Security;
using Febe.Tests.Support;
namespace Febe.Tests.Collection;
/// <summary>
/// The encryption of the saved session in Docker (issue #36, S4, spec §13.2): AES-256-GCM with a fresh nonce per write,
/// the key from FEBE_CHIAVE_SESSIONE or from chiave.bin made once, owner-only, never replaced; files replaced at once.
/// Keys are made at run time (no key in the repository, gitleaks); no text ever holds a key or a plain value.
/// </summary>
[TestClass]
public sealed class SessionProtectorTests
{
private static readonly byte[] Plain = Encoding.UTF8.GetBytes("""{"cookies":[{"name":"sessionid","value":"valore-in-chiaro-1"}]}""");
[TestMethod]
public void ARoundTripGivesTheSameBytesAndEveryWriteHasAFreshNonce()
{
var protector = new AesGcmSessionProtector(RandomNumberGenerator.GetBytes(SessionKey.Length));
var first = protector.Protect(Plain);
var second = protector.Protect(Plain);
CollectionAssert.AreEqual(Plain, protector.Unprotect(first));
CollectionAssert.AreEqual(Plain, protector.Unprotect(second));
Assert.IsTrue(SessionBlob.HasHeader(first, SessionBlob.AesGcm), "FEBS, version, scheme.");
Assert.AreEqual("FEBS", Encoding.ASCII.GetString(first, 0, 4));
Assert.AreEqual(SessionBlob.HeaderLength + 12 + 16 + Plain.Length, first.Length);
CollectionAssert.AreNotEqual(first, second, "A fresh nonce for every write.");
Assert.AreEqual(-1, IndexOf(first, Encoding.UTF8.GetBytes("valore-in-chiaro-1")), "Nothing in clear.");
Assert.AreEqual("aes-gcm", protector.Scheme);
}
[TestMethod]
public void ATamperedByteAnotherKeyOrAnotherSchemeIsUnreadableAndTheMessageHasNoValue()
{
var key = RandomNumberGenerator.GetBytes(SessionKey.Length);
var protector = new AesGcmSessionProtector(key);
var blob = protector.Protect(Plain);
foreach (var index in new[] { 5, SessionBlob.HeaderLength + 1, SessionBlob.HeaderLength + 13, blob.Length - 1 })
{
var tampered = (byte[])blob.Clone();
tampered[index] ^= 0x01;
var refused = Assert.ThrowsExactly<SessionUnreadableException>(() => protector.Unprotect(tampered));
Assert.AreEqual(SessionUnreadableException.Text, refused.Message);
Assert.IsNull(refused.InnerException, "No inner text is passed on.");
}
var other = new AesGcmSessionProtector(RandomNumberGenerator.GetBytes(SessionKey.Length));
Assert.ThrowsExactly<SessionUnreadableException>(() => other.Unprotect(blob));
Assert.ThrowsExactly<SessionUnreadableException>(() => protector.Unprotect(blob.AsSpan(0, 10)));
Assert.ThrowsExactly<SessionUnreadableException>(() => protector.Unprotect(Plain), "Not a blob of Febe.");
var dpapiHeader = (byte[])blob.Clone();
dpapiHeader[5] = SessionBlob.Dpapi;
Assert.ThrowsExactly<SessionUnreadableException>(() => protector.Unprotect(dpapiHeader));
Assert.ThrowsExactly<ArgumentException>(() => new AesGcmSessionProtector(new byte[16]));
Assert.IsFalse(protector.ToString().Contains(Convert.ToBase64String(key), StringComparison.Ordinal));
}
[TestMethod]
public void TheKeyIsBase64Of32BytesOr64HexAndAWrongValueIsRefusedWithoutEchoingIt()
{
var key = RandomNumberGenerator.GetBytes(SessionKey.Length);
Assert.IsTrue(SessionKey.TryParse(Convert.ToBase64String(key), out var fromBase64, out var none));
CollectionAssert.AreEqual(key, fromBase64);
Assert.IsNull(none);
Assert.IsTrue(SessionKey.TryParse(" " + Convert.ToHexString(key).ToLowerInvariant() + "\n", out var fromHex, out _));
CollectionAssert.AreEqual(key, fromHex);
foreach (var wrong in new[] { "chiave-troppo-corta", Convert.ToBase64String(new byte[16]), Convert.ToBase64String(new byte[33]), new string('z', 64), " " })
{
Assert.IsFalse(SessionKey.TryParse(wrong, out var parsed, out var problem), wrong);
Assert.IsNull(parsed);
Assert.IsNotNull(problem);
StringAssert.Contains(problem, SessionKey.EnvironmentVariable);
if (wrong.Trim().Length > 0)
{
Assert.IsFalse(problem.Contains(wrong.Trim(), StringComparison.Ordinal), "Never the value.");
}
}
Assert.IsFalse(SessionKey.TryParse(null, out _, out _));
}
[TestMethod]
public void ChiaveBinIsCreatedOnceOwnerOnlyAndNeverReplaced()
{
using var folder = new TempFolder("sessione-chiave");
var file = folder.Combine("sessione", "chiave.bin");
var first = SessionKey.LoadOrCreate(file);
var again = SessionKey.LoadOrCreate(file);
Assert.AreEqual(SessionKey.Length, first.Length);
CollectionAssert.AreEqual(first, again, "Made once, then read.");
CollectionAssert.AreEqual(first, File.ReadAllBytes(file));
if (!OperatingSystem.IsWindows())
{
Assert.AreEqual(OwnerOnlyFiles.OwnerFile, File.GetUnixFileMode(file), "0600 from its creation.");
Assert.AreEqual(OwnerOnlyFiles.OwnerFolder, File.GetUnixFileMode(folder.Combine("sessione")), "0700.");
}
Assert.ThrowsExactly<IOException>(() => OwnerOnlyFiles.CreateNew(file, new byte[SessionKey.Length]), "Never replaced.");
CollectionAssert.AreEqual(first, File.ReadAllBytes(file));
}
[TestMethod]
public void AKeyWriteTheDiskRefusesLeavesNoChiaveBinSoTheNextStartMakesOne()
{
using var folder = new TempFolder("sessione-chiave");
var file = folder.Combine("sessione", "chiave.bin");
// The disk fills up after the first bytes: the error comes out, and nothing short is left as «the key».
Assert.ThrowsExactly<IOException>(() => SessionKey.LoadOrCreate(file, null, static (stream, bytes) =>
{
stream.Write(bytes[..4]);
throw new IOException("Spazio esaurito sul disco (prova).");
}));
Assert.IsFalse(File.Exists(file), "No short chiave.bin behind.");
Assert.IsEmpty(Directory.GetFiles(folder.Combine("sessione")), "Nor a part file.");
Assert.IsNull(SessionKey.CheckFile(file), "The next start is not stopped by a key problem.");
var key = SessionKey.LoadOrCreate(file);
Assert.AreEqual(SessionKey.Length, key.Length);
CollectionAssert.AreEqual(key, File.ReadAllBytes(file));
Assert.IsEmpty(Directory.GetFiles(folder.Combine("sessione"), "*" + OwnerOnlyFiles.PartSuffix));
}
[TestMethod]
public void AChiaveBinOfTheWrongLengthIsAProblemNotARegeneration()
{
using var folder = new TempFolder("sessione-chiave");
var file = folder.Combine("chiave.bin");
File.WriteAllBytes(file, Encoding.ASCII.GetBytes("non-una-chiave"));
var problem = SessionKey.CheckFile(file);
Assert.IsNotNull(problem);
StringAssert.Contains(problem, "chiave.bin");
Assert.IsFalse(problem.Contains("non-una-chiave", StringComparison.Ordinal));
var refused = Assert.ThrowsExactly<InvalidDataException>(() => SessionKey.LoadOrCreate(file));
Assert.IsFalse(refused.Message.Contains("non-una-chiave", StringComparison.Ordinal));
CollectionAssert.AreEqual(Encoding.ASCII.GetBytes("non-una-chiave"), File.ReadAllBytes(file), "Left as it is, never made again.");
Assert.IsNull(SessionKey.CheckFile(folder.Combine("manca.bin")), "A missing file will be made.");
}
[TestMethod]
public void LooserModesAreNarrowedToTheOwnerOnUnix()
{
using var folder = new TempFolder("sessione-chiave");
var file = folder.Combine("chiave.bin");
File.WriteAllBytes(file, RandomNumberGenerator.GetBytes(SessionKey.Length));
var warnings = new List<string>();
if (OperatingSystem.IsWindows())
{
Assert.IsFalse(OwnerOnlyFiles.Tighten(file), "No Unix modes on Windows.");
Assert.AreEqual(SessionKey.Length, SessionKey.LoadOrCreate(file, warnings.Add).Length);
Assert.AreEqual(0, warnings.Count);
return;
}
File.SetUnixFileMode(file, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.OtherRead);
Assert.AreEqual(SessionKey.Length, SessionKey.LoadOrCreate(file, warnings.Add).Length);
Assert.AreEqual(OwnerOnlyFiles.OwnerFile, File.GetUnixFileMode(file));
Assert.AreEqual(1, warnings.Count);
StringAssert.Contains(warnings[0], "solo il proprietario");
}
[TestMethod]
public void TheEnvironmentKeyWinsAndAnUnusedChiaveBinIsNamedNeverRead()
{
using var folder = new TempFolder("sessione-chiave");
var file = folder.Combine("chiave.bin");
var key = RandomNumberGenerator.GetBytes(SessionKey.Length);
var text = Convert.ToBase64String(key);
var log = new List<string>();
CollectionAssert.AreEqual(key, SessionKey.Resolve(text, file, log.Add));
Assert.IsFalse(File.Exists(file), "With the variable, no chiave.bin is made.");
var stored = SessionKey.Resolve(null, file, log.Add);
Assert.IsTrue(File.Exists(file));
CollectionAssert.AreEqual(stored, SessionKey.Resolve(" ", file, log.Add), "An empty variable is no variable.");
CollectionAssert.AreEqual(key, SessionKey.Resolve(text, file, log.Add));
Assert.IsTrue(log.Any(l => l.Contains("non si usa", StringComparison.Ordinal)), string.Join("\n", log));
var refused = Assert.ThrowsExactly<InvalidDataException>(() => SessionKey.Resolve("chiave-sbagliata", file, log.Add));
Assert.IsFalse(refused.Message.Contains("chiave-sbagliata", StringComparison.Ordinal));
foreach (var line in log)
{
Assert.IsFalse(line.Contains(text, StringComparison.Ordinal) || line.Contains(Convert.ToBase64String(stored), StringComparison.Ordinal), line);
}
}
[TestMethod]
public void AnAtomicWriteReplacesTheFileAndLeavesNoPartFile()
{
using var folder = new TempFolder("sessione-file");
var file = folder.Combine("sessione.json");
OwnerOnlyFiles.WriteAtomic(file, "uno"u8);
OwnerOnlyFiles.WriteAtomic(file, "due"u8);
Assert.AreEqual("due", File.ReadAllText(file));
CollectionAssert.AreEqual(new[] { "sessione.json" }, Directory.GetFiles(folder.Path).Select(Path.GetFileName).ToArray());
if (!OperatingSystem.IsWindows())
{
Assert.AreEqual(OwnerOnlyFiles.OwnerFile, File.GetUnixFileMode(file));
}
// A broken write left a part file: deleting the session takes it too.
File.WriteAllText(file + ".abcdef12" + OwnerOnlyFiles.PartSuffix, "resto");
File.WriteAllText(folder.Combine("altro.txt"), "non è della sessione");
OwnerOnlyFiles.DeleteWithLeftovers(file);
CollectionAssert.AreEqual(new[] { "altro.txt" }, Directory.GetFiles(folder.Path).Select(Path.GetFileName).ToArray());
OwnerOnlyFiles.DeleteWithLeftovers(file);
}
private static int IndexOf(byte[] haystack, byte[] needle) => haystack.AsSpan().IndexOf(needle);
}