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>
268 lines
14 KiB
C#
268 lines
14 KiB
C#
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using Febe.App;
|
|
using Febe.Browser.Hosting;
|
|
using Febe.Core.Abstractions;
|
|
using Febe.Core.Library;
|
|
using Febe.Core.Security;
|
|
using Febe.Server;
|
|
using Febe.Tests.Support;
|
|
using Febe.Web.Engine;
|
|
|
|
namespace Febe.Tests.Server;
|
|
|
|
/// <summary>
|
|
/// Issue #36, S4, spec §11 and §13.2, on the Docker side: the option «raccolta» (pages by default), the key of the saved
|
|
/// session from FEBE_CHIAVE_SESSIONE or Dati/sessione/chiave.bin, its checks at start-up, and the child processes that
|
|
/// never inherit the password or the key. No value of a secret ever appears in a text. Keys are made at run time.
|
|
/// </summary>
|
|
[TestClass]
|
|
public sealed class SessionKeyOptionsTests
|
|
{
|
|
private const string Password = "password-di-prova";
|
|
|
|
[TestMethod]
|
|
public void TheCollectionRouteIsPagesByDefaultAndComesFromTheOptionOrTheEnvironment()
|
|
{
|
|
Assert.IsTrue(ServerOptions.TryParse([], Env(("FEBE_PASSWORD", Password)), out var plain, out var problem), problem);
|
|
Assert.AreEqual(CollectionRoute.Pages, plain.Collection, "nothing changes by default");
|
|
Assert.AreEqual(CollectionRoute.Pages, plain.AppOptions().Collection);
|
|
|
|
Assert.IsTrue(ServerOptions.TryParse([], Env(("FEBE_PASSWORD", Password), ("FEBE_RACCOLTA", "richieste")), out var fromEnvironment, out problem), problem);
|
|
Assert.AreEqual(CollectionRoute.Requests, fromEnvironment.Collection);
|
|
Assert.AreEqual(CollectionRoute.Requests, fromEnvironment.AppOptions().Collection);
|
|
|
|
Assert.IsTrue(ServerOptions.TryParse(["--raccolta", "Pagine"], Env(("FEBE_RACCOLTA", "richieste")), out var commandLineWins, out problem), problem);
|
|
Assert.AreEqual(CollectionRoute.Pages, commandLineWins.Collection, "the command line wins over the environment");
|
|
|
|
Assert.IsTrue(ServerOptions.TryParse(["--raccolta", "richieste"], Env(), out var fromOption, out problem), problem);
|
|
Assert.AreEqual(CollectionRoute.Requests, fromOption.Collection);
|
|
|
|
Assert.IsFalse(ServerOptions.TryParse(["--raccolta", "browser"], Env(), out _, out problem));
|
|
StringAssert.Contains(problem, "--raccolta");
|
|
StringAssert.Contains(problem, "pagine oppure richieste");
|
|
Assert.IsFalse(ServerOptions.TryParse(["--raccolta"], Env(), out _, out problem));
|
|
StringAssert.Contains(problem, "Dopo --raccolta");
|
|
Assert.IsFalse(ServerOptions.TryParse([], Env(("FEBE_RACCOLTA", "tutto")), out _, out problem));
|
|
StringAssert.Contains(problem, "FEBE_RACCOLTA");
|
|
}
|
|
|
|
[TestMethod]
|
|
public void FebeChiaveSessioneIsReadAndNeverInWarningsTheTextOrTheProblems()
|
|
{
|
|
var key = RandomNumberGenerator.GetBytes(SessionKey.Length);
|
|
var text = Convert.ToBase64String(key);
|
|
Assert.IsTrue(ServerOptions.TryParse([], Env(("FEBE_PASSWORD", Password), (SessionKey.EnvironmentVariable, text)), out var o, out var problem), problem);
|
|
CollectionAssert.AreEqual(key, o.SessionKey);
|
|
Assert.IsNull(o.SessionKeyProblem);
|
|
Assert.IsEmpty(o.Warnings);
|
|
|
|
// The generated text of a record would print the password and the key: this one says only whether they are set.
|
|
foreach (var shown in new[] { o.ToString(), $"{o}", o.AppOptions().ToString() })
|
|
{
|
|
Assert.DoesNotContain(Password, shown);
|
|
Assert.DoesNotContain(text, shown);
|
|
Assert.DoesNotContain(Convert.ToHexString(key), shown);
|
|
}
|
|
|
|
StringAssert.Contains(o.ToString(), "FEBE_CHIAVE_SESSIONE = impostata");
|
|
StringAssert.Contains(o.ToString(), "FEBE_PASSWORD = impostata");
|
|
Assert.IsEmpty(StartupChecks.Run(o with { DataFolder = Path.GetTempPath() }).Where(p => p.Code.StartsWith("chiave", StringComparison.Ordinal)));
|
|
|
|
// 64 hexadecimal digits are a key too.
|
|
Assert.IsTrue(ServerOptions.TryParse([], Env((SessionKey.EnvironmentVariable, Convert.ToHexString(key))), out var hex, out problem), problem);
|
|
CollectionAssert.AreEqual(key, hex.SessionKey);
|
|
}
|
|
|
|
[TestMethod]
|
|
[DataRow("non-una-chiave")]
|
|
[DataRow("corta")]
|
|
public void AWrongSessionKeyIsAStartupProblemThatNeverEchoesTheValue(string wrong)
|
|
{
|
|
foreach (var value in new[] { wrong, Convert.ToBase64String(RandomNumberGenerator.GetBytes(16)), Convert.ToBase64String(RandomNumberGenerator.GetBytes(48)) })
|
|
{
|
|
Assert.IsTrue(ServerOptions.TryParse([], Env(("FEBE_PASSWORD", Password), (SessionKey.EnvironmentVariable, value)), out var o, out var parseProblem), parseProblem);
|
|
Assert.IsNull(o.SessionKey);
|
|
Assert.IsNotNull(o.SessionKeyProblem);
|
|
Assert.DoesNotContain(value, o.SessionKeyProblem);
|
|
Assert.DoesNotContain(value, o.ToString());
|
|
StringAssert.Contains(o.ToString(), "FEBE_CHIAVE_SESSIONE = non valida");
|
|
|
|
// Always said, whatever the «raccolta»: the engine and the browser do not start.
|
|
foreach (var route in new[] { CollectionRoute.Pages, CollectionRoute.Requests })
|
|
{
|
|
var problem = StartupChecks.Run(o with { DataFolder = Path.GetTempPath(), Collection = route }).Single();
|
|
Assert.AreEqual(StartupChecks.SessionKeyInvalid, problem.Code);
|
|
StringAssert.Contains(problem.Message, "32 byte");
|
|
StringAssert.Contains(problem.Remedy, "openssl rand -base64 32");
|
|
foreach (var shown in new[] { problem.Title, problem.Message, problem.Remedy, problem.ToString() })
|
|
{
|
|
Assert.DoesNotContain(value, shown);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
public void AChiaveBinThatIsNotAKeyStopsOnlyTheRequestsRoute()
|
|
{
|
|
using var temp = new TempFolder("chiave-sessione");
|
|
var data = new DataFolderLayout(temp.Path);
|
|
Directory.CreateDirectory(data.Session);
|
|
File.WriteAllBytes(data.SessionKeyFile, Encoding.ASCII.GetBytes("prova"));
|
|
Assert.IsTrue(ServerOptions.TryParse(["--dati", temp.Path], Env(("FEBE_PASSWORD", Password)), out var o, out var parseProblem), parseProblem);
|
|
|
|
Assert.IsEmpty(StartupChecks.Run(o), "by the pages chiave.bin is never read");
|
|
|
|
var problem = StartupChecks.Run(o with { Collection = CollectionRoute.Requests }).Single();
|
|
Assert.AreEqual(StartupChecks.SessionKeyFileInvalid, problem.Code);
|
|
StringAssert.Contains(problem.Message, "chiave.bin");
|
|
StringAssert.Contains(problem.Message, "5 byte");
|
|
StringAssert.Contains(problem.Remedy, "Cancella Dati/sessione/chiave.bin");
|
|
Assert.DoesNotContain("prova", problem.Message);
|
|
|
|
// With the variable set, chiave.bin is not read at all.
|
|
var key = Convert.ToBase64String(RandomNumberGenerator.GetBytes(SessionKey.Length));
|
|
Assert.IsTrue(ServerOptions.TryParse(["--dati", temp.Path, "--raccolta", "richieste"], Env(("FEBE_PASSWORD", Password), (SessionKey.EnvironmentVariable, key)), out var withKey, out parseProblem), parseProblem);
|
|
Assert.IsEmpty(StartupChecks.Run(withKey));
|
|
|
|
// A missing chiave.bin is no problem: it will be made.
|
|
File.Delete(data.SessionKeyFile);
|
|
Assert.IsEmpty(StartupChecks.Run(o with { Collection = CollectionRoute.Requests }));
|
|
}
|
|
|
|
[TestMethod]
|
|
public void TheDockerProtectorTakesTheKeyFromTheVariableOrFromChiaveBinAndLogsNoKey()
|
|
{
|
|
using var temp = new TempFolder("chiave-sessione");
|
|
using var console = new StringWriter();
|
|
var clock = new ManualClock(new DateTimeOffset(2026, 11, 17, 10, 0, 0, TimeSpan.Zero));
|
|
using var log = new FebeLog(null, console, clock);
|
|
var data = new DataFolderLayout(temp.Combine("dati"));
|
|
var context = new FebePlatformContext(
|
|
new FebeAppOptions { DataFolder = data.Root, LibraryFolder = temp.Combine("libreria") },
|
|
data,
|
|
null!,
|
|
clock,
|
|
log,
|
|
new BrowserUseTracker());
|
|
var plain = Encoding.UTF8.GetBytes("testo della sessione di prova");
|
|
|
|
// No variable: chiave.bin is made once, owner-only, and the next start reads the same key.
|
|
Assert.IsTrue(ServerOptions.TryParse(["--dati", data.Root], Env(("FEBE_PASSWORD", Password)), out var o, out var problem), problem);
|
|
var first = new DockerPlatform(o).CreateSessionProtector(context);
|
|
Assert.AreEqual("aes-gcm", first.Scheme);
|
|
Assert.AreEqual(SessionKey.Length, new FileInfo(data.SessionKeyFile).Length);
|
|
if (!OperatingSystem.IsWindows())
|
|
{
|
|
Assert.AreEqual(OwnerOnlyFiles.OwnerFile, File.GetUnixFileMode(data.SessionKeyFile));
|
|
Assert.AreEqual(OwnerOnlyFiles.OwnerFolder, File.GetUnixFileMode(data.Session));
|
|
}
|
|
|
|
var stored = File.ReadAllBytes(data.SessionKeyFile);
|
|
var blob = first.Protect(plain);
|
|
var second = new DockerPlatform(o).CreateSessionProtector(context);
|
|
CollectionAssert.AreEqual(plain, second.Unprotect(blob), "the same chiave.bin after a restart");
|
|
CollectionAssert.AreEqual(stored, File.ReadAllBytes(data.SessionKeyFile), "chiave.bin is never replaced");
|
|
|
|
// The variable wins; the unused chiave.bin is named, not read.
|
|
var key = RandomNumberGenerator.GetBytes(SessionKey.Length);
|
|
var text = Convert.ToBase64String(key);
|
|
Assert.IsTrue(ServerOptions.TryParse(["--dati", data.Root], Env(("FEBE_PASSWORD", Password), (SessionKey.EnvironmentVariable, text)), out var withKey, out problem), problem);
|
|
var fromVariable = new DockerPlatform(withKey).CreateSessionProtector(context);
|
|
Assert.ThrowsExactly<SessionUnreadableException>(() => fromVariable.Unprotect(blob), "another key");
|
|
CollectionAssert.AreEqual(plain, new AesGcmSessionProtector(key).Unprotect(fromVariable.Protect(plain)));
|
|
|
|
var lines = console.ToString();
|
|
StringAssert.Contains(lines, "chiave da Dati/sessione/chiave.bin");
|
|
StringAssert.Contains(lines, "chiave da FEBE_CHIAVE_SESSIONE");
|
|
StringAssert.Contains(lines, "chiave.bin non si usa");
|
|
foreach (var secret in new[] { text, Convert.ToHexString(key), Convert.ToBase64String(stored), Convert.ToHexString(stored), Password })
|
|
{
|
|
Assert.DoesNotContain(secret, lines);
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
public void ChildProcessesNeverInheritThePasswordOrTheSessionKey()
|
|
{
|
|
var environment = new Dictionary<string, string?>(StringComparer.Ordinal)
|
|
{
|
|
["PATH"] = "/usr/bin",
|
|
["FEBE_PASSWORD"] = Password,
|
|
["febe_chiave_sessione"] = "chiave-di-prova",
|
|
[SessionKey.EnvironmentVariable] = "chiave-di-prova",
|
|
["FEBE_PORTA"] = "8480",
|
|
};
|
|
ChildProcessEnvironment.RemoveSecrets(environment);
|
|
CollectionAssert.AreEquivalent(new[] { "PATH", "FEBE_PORTA" }, environment.Keys.ToList());
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task ChromiumStartsWithoutThePasswordOrTheKeyWhateverItsOptionsHold()
|
|
{
|
|
// The options of the launch are applied first, the secrets are removed last: neither the parent's environment
|
|
// nor an option can hand them to the browser, which runs the site's code.
|
|
await using var host = new ChromiumProcessHost(new ChromiumLaunchOptions
|
|
{
|
|
Environment = new Dictionary<string, string?>
|
|
{
|
|
["LANG"] = "it_IT.UTF-8",
|
|
["FEBE_PASSWORD"] = Password,
|
|
[SessionKey.EnvironmentVariable] = "chiave-di-prova",
|
|
},
|
|
});
|
|
var info = host.BuildStartInfo("chromium", ["--no-first-run"], new BrowserOptions("/tmp/febe-profilo", 1280, 900, 9333) { Display = ":99" });
|
|
Assert.AreEqual("it_IT.UTF-8", info.Environment["LANG"]);
|
|
Assert.AreEqual(":99", info.Environment["DISPLAY"]);
|
|
foreach (var name in ChildProcessEnvironment.SecretVariables)
|
|
{
|
|
Assert.IsFalse(info.Environment.Keys.Any(k => string.Equals(k, name, StringComparison.OrdinalIgnoreCase)), name);
|
|
}
|
|
|
|
await using var xvfb = new XvfbProcess(executable: "Xvfb");
|
|
var display = xvfb.BuildStartInfo("Xvfb");
|
|
Assert.IsFalse(display.Environment.Keys.Any(ChildProcessEnvironment.IsSecret));
|
|
}
|
|
|
|
[TestMethod]
|
|
[DoNotParallelize]
|
|
public void FfmpegAndFfprobeStartWithoutThePasswordOrTheKeyOfFebesEnvironment()
|
|
{
|
|
// Febe's own environment holds both (as in Docker): ffprobe and ffmpeg must not inherit them (spec §13.2).
|
|
using var folder = new TempFolder("figli");
|
|
var tool = folder.Combine("strumento-di-prova");
|
|
File.WriteAllText(tool, string.Empty);
|
|
var before = ChildProcessEnvironment.SecretVariables.Select(n => (Name: n, Value: Environment.GetEnvironmentVariable(n))).ToList();
|
|
try
|
|
{
|
|
foreach (var name in ChildProcessEnvironment.SecretVariables)
|
|
{
|
|
Environment.SetEnvironmentVariable(name, "valore-di-prova");
|
|
}
|
|
|
|
Assert.IsTrue(new System.Diagnostics.ProcessStartInfo("x").Environment.Keys.Any(ChildProcessEnvironment.IsSecret), "The parent holds them.");
|
|
var probe = Febe.Core.Import.FfprobeVideoMetadataProbe.TryCreate(tool)!.BuildStartInfo("video-di-prova.mp4");
|
|
var frame = VideoFrameExtractor.TryCreate(tool)!.BuildStartInfo("video-di-prova.mp4", "1");
|
|
foreach (var info in new[] { probe, frame })
|
|
{
|
|
Assert.IsFalse(info.Environment.Keys.Any(ChildProcessEnvironment.IsSecret), info.FileName);
|
|
CollectionAssert.Contains(info.ArgumentList.ToArray(), "video-di-prova.mp4");
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
foreach (var (name, value) in before)
|
|
{
|
|
Environment.SetEnvironmentVariable(name, value);
|
|
}
|
|
}
|
|
}
|
|
|
|
private static Func<string, string?> Env(params (string Name, string Value)[] values)
|
|
{
|
|
var map = values.ToDictionary(v => v.Name, v => v.Value, StringComparer.Ordinal);
|
|
return name => map.GetValueOrDefault(name);
|
|
}
|
|
}
|