using System.Net.Http.Json; using Backend.Data; using Backend.Jobs; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using Shared.Contracts.Api; using Shared.Contracts.Messages; using Shared.Contracts.Models; using Shared.Contracts.Serialization; using Xunit; namespace Backend.Tests; /// /// Run From File, Clean Up After Run and Set Working Directory: stored on the /// script, sealed into a run's snapshot like the script's other fields, and /// carried to the agent in the script command. /// public class ScriptRunOptionsTests(BackendTestFixture fixture) : IClassFixture { private static SaveScriptRequest Request( string name, ScriptEngine engine = ScriptEngine.PowerShell, bool? fromFile = null, bool? cleanUp = null, bool? workingDirectory = null) => new(name, null, "'hello'", Engine: engine, RunFromFile: fromFile, CleanUpAfterRun: cleanUp, SetWorkingDirectory: workingDirectory); private static async Task SaveAsync(HttpClient client, SaveScriptRequest request, Guid? id = null) { var response = id is null ? await client.PostAsJsonAsync(ApiRoutes.Scripts, request, JsonDefaults.Options) : await client.PutAsJsonAsync(ApiRoutes.For.Script(id.Value), request, JsonDefaults.Options); response.EnsureSuccessStatusCode(); return (await response.Content.ReadFromJsonAsync(JsonDefaults.Options))!; } private static (bool, bool, bool) Options(ScriptDto dto) => (dto.RunFromFile, dto.CleanUpAfterRun, dto.SetWorkingDirectory); [Fact] public async Task ANewScriptRunsFromMemoryAndCleansUp() { using var client = await fixture.SignedInAsync("options-admin"); var created = await SaveAsync(client, Request("options-defaults")); Assert.Equal((false, true, false), Options(created)); } [Fact] public async Task TheOptionsAreSavedAndLeftOutKeepsThem() { using var client = await fixture.SignedInAsync("options-admin"); var created = await SaveAsync(client, Request("options-saved", fromFile: true, cleanUp: false, workingDirectory: true)); Assert.Equal((true, false, true), Options(created)); var read = await client.GetFromJsonAsync(ApiRoutes.For.Script(created.Id), JsonDefaults.Options); Assert.Equal((true, false, true), Options(read!)); // An older console sends none of them: nothing changes. var kept = await SaveAsync(client, Request("options-saved"), created.Id); Assert.Equal((true, false, true), Options(kept)); var changed = await SaveAsync(client, Request("options-saved", fromFile: true, cleanUp: true, workingDirectory: false), created.Id); Assert.Equal((true, true, false), Options(changed)); var stored = await fixture.WithDbAsync(db => db.Scripts.AsNoTracking().SingleAsync(s => s.Id == created.Id)); Assert.Equal((true, true, false), (stored.RunFromFile, stored.CleanUpAfterRun, stored.SetWorkingDirectory)); } [Theory] [InlineData(ScriptEngine.PowerShell, false, false)] [InlineData(ScriptEngine.PowerShell, true, true)] [InlineData(ScriptEngine.WindowsPowerShell, false, true)] [InlineData(ScriptEngine.Bash, false, true)] public async Task WorkingDirectoryNeedsAStagedFile(ScriptEngine engine, bool fromFile, bool kept) { using var client = await fixture.SignedInAsync("options-admin"); var created = await SaveAsync(client, Request($"options-wd-{engine}-{fromFile}", engine, fromFile, workingDirectory: true)); Assert.Equal(kept, created.SetWorkingDirectory); } [Fact] public async Task TheScriptCommandCarriesTheOptions() { fixture.Scripts.Accept = true; using var client = await fixture.SignedInAsync("options-admin"); var script = await SaveAsync(client, Request("options-dispatch", fromFile: true, cleanUp: false, workingDirectory: true)); var device = await fixture.SeedDeviceAsync("OPTIONS-DISPATCH"); (await client.PostAsJsonAsync(ApiRoutes.Jobs, new CreateJobRequest(device, script.Id), JsonDefaults.Options)).EnsureSuccessStatusCode(); var command = Sent(device).Single(); Assert.Equal((true, false, true), (command.RunFromFile, command.CleanUpAfterRun, command.SetWorkingDirectory)); Assert.Equal("options-dispatch", command.ScriptName); } [Fact] public async Task AStaggeredRunKeepsTheOptionsItStartedWith() { fixture.Scripts.Accept = true; using var client = await fixture.SignedInAsync("options-admin"); var script = await SaveAsync(client, Request("options-snapshot", fromFile: true, cleanUp: false, workingDirectory: true)); var devices = new[] { await fixture.SeedDeviceAsync("OPTIONS-SNAP-1"), await fixture.SeedDeviceAsync("OPTIONS-SNAP-2") }; var response = await client.PostAsJsonAsync( ApiRoutes.Jobs, new CreateJobRequest(null, script.Id, ClientIds: devices, StaggerSeconds: 600), JsonDefaults.Options); response.EnsureSuccessStatusCode(); var run = (await response.Content.ReadFromJsonAsync(JsonDefaults.Options))!; // Edited after the start: the devices still waiting get the script as it was. await SaveAsync(client, Request("options-snapshot", fromFile: false, cleanUp: true, workingDirectory: false), script.Id); var latest = await fixture.WithDbAsync(db => db.Jobs.AsNoTracking().Where(j => j.RunId == run.RunId).MaxAsync(j => j.NotBeforeUtc)); await new JobDispatcher(fixture.Services.GetRequiredService(), NullLogger.Instance) .RunPassAsync(latest!.Value.AddSeconds(1), CancellationToken.None); var commands = devices.SelectMany(Sent).ToList(); Assert.Equal(2, commands.Count); Assert.All(commands, c => Assert.Equal((true, false, true), (c.RunFromFile, c.CleanUpAfterRun, c.SetWorkingDirectory))); } [Fact] public void ASnapshotSealedBeforeTheOptionsExistedUsesTheDefaults() { var snapshot = JsonDefaults.Deserialize( $$"""{"scriptId":"{{Guid.NewGuid()}}","name":"n","language":"PowerShell","content":"c"}""")!; var script = snapshot.ToScript(); Assert.Equal((false, true, false), (script.RunFromFile, script.CleanUpAfterRun, script.SetWorkingDirectory)); } [Fact] public void AnOlderBackendsCommandKeepsTheAgentDefaults() { var command = JsonDefaults.Deserialize( $$"""{"jobId":"{{Guid.NewGuid()}}","scriptId":"{{Guid.NewGuid()}}","scriptName":"n","content":"c"}""")!; Assert.Equal((false, true, false), (command.RunFromFile, command.CleanUpAfterRun, command.SetWorkingDirectory)); } [Fact] public async Task TheMigrationKeepsExistingScriptsCleaningUp() { var path = Path.Combine(Path.GetTempPath(), $"run-options-migration-{Guid.NewGuid():N}.db"); try { await using var db = new SqliteAppDbContext( new DbContextOptionsBuilder().UseSqlite($"Data Source={path}").Options); var migrator = db.GetService(); var migrations = db.Database.GetMigrations().ToList(); var target = migrations.Single(m => m.EndsWith("_ScriptRunOptions", StringComparison.Ordinal)); await migrator.MigrateAsync(migrations[migrations.IndexOf(target) - 1]); var id = Guid.NewGuid(); await db.Database.ExecuteSqlRawAsync( "INSERT INTO Scripts (Id, Name, Folder, FolderKey, Language, Content, CreatedUtc, UpdatedUtc) " + "VALUES ({0}, 'before', '/', '/', 'PowerShell', 'x', {1}, {1})", id.ToString().ToUpperInvariant(), DateTimeOffset.UtcNow.UtcTicks); await migrator.MigrateAsync(); var script = await db.Scripts.AsNoTracking().SingleAsync(s => s.Id == id); Assert.Equal((false, true, false), (script.RunFromFile, script.CleanUpAfterRun, script.SetWorkingDirectory)); Assert.Empty(await db.Database.GetPendingMigrationsAsync()); db.Scripts.Add(new ScriptEntity { Id = Guid.NewGuid(), Name = "after", Language = "PowerShell", Content = "x", CleanUpAfterRun = false, RunFromFile = true, }); await db.SaveChangesAsync(); var after = await db.Scripts.AsNoTracking().SingleAsync(s => s.Name == "after"); Assert.Equal((true, false), (after.RunFromFile, after.CleanUpAfterRun)); } finally { SqliteConnection.ClearAllPools(); File.Delete(path); } } private List Sent(string clientId) { lock (fixture.Scripts.Sent) { return fixture.Scripts.Sent.Where(s => s.ClientId == clientId).Select(s => s.Command).ToList(); } } }