using System.Net; using System.Net.Http.Json; using System.Text.Json; using Backend.Data; using Microsoft.EntityFrameworkCore; using Shared.Contracts.Api; using Shared.Contracts.Models; using Shared.Contracts.Serialization; using Xunit; namespace Backend.Tests; /// The param() import endpoint, and required values checked the same way by every start. public class ScriptParameterEndpointTests(BackendTestFixture fixture) : IClassFixture { private static readonly ScriptParameter RequiredName = new("Name", ScriptParameterType.String, Required: true); private static readonly ScriptParameter OptionalCount = new("Count", ScriptParameterType.Number); private static Dictionary Args(object values) => JsonSerializer.Deserialize>(JsonSerializer.Serialize(values))!; [Fact] public async Task ParseMergesTheParamBlockIntoTheCurrentParameters() { using var client = await fixture.SignedInAsync("params-admin"); var response = await client.PostAsJsonAsync(ApiRoutes.ScriptParametersParse, new ParseScriptParametersRequest( "param([Parameter(Mandatory)][string]$Name, [int]$Count = 2)", Current: [new ScriptParameter("Name", ScriptParameterType.Number, Expansion: ValueExpansion.Literal), new("Old", ScriptParameterType.String)]), JsonDefaults.Options); response.EnsureSuccessStatusCode(); var result = (await response.Content.ReadFromJsonAsync(JsonDefaults.Options))!; Assert.True(result.Merged); Assert.Equal(["Name", "Count"], result.Parameters.Select(p => p.Name)); Assert.Equal((ScriptParameterType.String, true, ValueExpansion.Literal), (result.Parameters[0].Type, result.Parameters[0].Required, result.Parameters[0].Expansion)); Assert.Equal(2, result.Parameters[1].DefaultValue!.Value.GetInt32()); } [Fact] public async Task ParseLeavesParametersAloneWhileTheCodeHasErrors() { using var client = await fixture.SignedInAsync("params-admin"); ScriptParameter[] current = [new("Name", ScriptParameterType.String)]; var response = await client.PostAsJsonAsync(ApiRoutes.ScriptParametersParse, new ParseScriptParametersRequest("param([string]$Na", Current: current), JsonDefaults.Options); response.EnsureSuccessStatusCode(); var result = (await response.Content.ReadFromJsonAsync(JsonDefaults.Options))!; Assert.False(result.Merged); Assert.Equal(["Name"], result.Parameters.Select(p => p.Name)); Assert.Contains(result.Diagnostics, d => d.Severity == "error"); } [Fact] public async Task ParseRefusesBash() { using var client = await fixture.SignedInAsync("params-admin"); var response = await client.PostAsJsonAsync(ApiRoutes.ScriptParametersParse, new ParseScriptParametersRequest("echo hi", ScriptEngine.Bash), JsonDefaults.Options); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); } [Fact] public async Task ARunNeedsEveryRequiredValueWithoutADefault() { using var client = await fixture.SignedInAsync("params-admin"); var scriptId = await SeedScriptAsync("required-run", RequiredName, OptionalCount); var device = await fixture.SeedDeviceAsync("PARAMS-RUN"); var missing = await client.PostAsJsonAsync(ApiRoutes.Jobs, new CreateJobRequest(null, scriptId, ClientIds: [device]), JsonDefaults.Options); Assert.Equal(HttpStatusCode.BadRequest, missing.StatusCode); Assert.Contains("“Name” needs a value", await missing.Content.ReadAsStringAsync()); var blank = await client.PostAsJsonAsync(ApiRoutes.Jobs, new CreateJobRequest(null, scriptId, Args(new { Name = " " }), ClientIds: [device]), JsonDefaults.Options); Assert.Equal(HttpStatusCode.BadRequest, blank.StatusCode); var given = await client.PostAsJsonAsync(ApiRoutes.Jobs, new CreateJobRequest(null, scriptId, Args(new { Name = "widget" }), ClientIds: [device]), JsonDefaults.Options); given.EnsureSuccessStatusCode(); } [Fact] public async Task ADefaultSatisfiesARequiredParameter() { using var client = await fixture.SignedInAsync("params-admin"); var scriptId = await SeedScriptAsync("required-default", RequiredName with { DefaultValue = JsonSerializer.SerializeToElement("fallback") }); var device = await fixture.SeedDeviceAsync("PARAMS-DEFAULT"); var response = await client.PostAsJsonAsync(ApiRoutes.Jobs, new CreateJobRequest(null, scriptId, ClientIds: [device]), JsonDefaults.Options); response.EnsureSuccessStatusCode(); } [Theory] [InlineData("""{ "Name": "x", "Count": "many" }""", "must be a number")] [InlineData("""{ "Name": "x", "Nope": 1 }""", "not a parameter")] [InlineData("""{ "name": "x" }""", "not a parameter")] [InlineData("""{ "Name": ["x"] }""", "must be text")] public async Task ARunRefusesValuesThatDoNotFit(string arguments, string error) { using var client = await fixture.SignedInAsync("params-admin"); var scriptId = await SeedScriptAsync($"misfit-{Guid.NewGuid():N}", RequiredName, OptionalCount); var device = await fixture.SeedDeviceAsync("PARAMS-MISFIT"); var response = await client.PostAsJsonAsync(ApiRoutes.Jobs, new CreateJobRequest( null, scriptId, JsonSerializer.Deserialize>(arguments), ClientIds: [device]), JsonDefaults.Options); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Contains(error, await response.Content.ReadAsStringAsync()); } [Fact] public async Task AValidateSetLimitsTheValues() { using var client = await fixture.SignedInAsync("params-admin"); var scriptId = await SeedScriptAsync("validate-set", new ScriptParameter("Mode", ScriptParameterType.String, AllowedValues: ["Fast", "Safe"])); var device = await fixture.SeedDeviceAsync("PARAMS-SET"); var wrong = await client.PostAsJsonAsync(ApiRoutes.Jobs, new CreateJobRequest(null, scriptId, Args(new { Mode = "Reckless" }), ClientIds: [device]), JsonDefaults.Options); Assert.Equal(HttpStatusCode.BadRequest, wrong.StatusCode); var anyCase = await client.PostAsJsonAsync(ApiRoutes.Jobs, new CreateJobRequest(null, scriptId, Args(new { Mode = "safe" }), ClientIds: [device]), JsonDefaults.Options); anyCase.EnsureSuccessStatusCode(); } [Fact] public async Task ATriggerNeedsTheRequiredValuesToo() { using var client = await fixture.SignedInAsync("params-admin"); var scriptId = await SeedScriptAsync("required-trigger", RequiredName); var missing = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest( scriptId, ScriptTriggerType.Scheduled, AllDevices: true, CronExpression: "0 1 * * *"), JsonDefaults.Options); Assert.Equal(HttpStatusCode.BadRequest, missing.StatusCode); Assert.Contains("needs a value", await missing.Content.ReadAsStringAsync()); var given = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest( scriptId, ScriptTriggerType.Scheduled, AllDevices: true, CronExpression: "0 1 * * *", Arguments: Args(new { Name = "x" })), JsonDefaults.Options); given.EnsureSuccessStatusCode(); } [Fact] public async Task AScheduleFollowsDefaultsAndStopsWhenTheScriptGainsARequiredValue() { using var client = await fixture.SignedInAsync("params-admin"); var scriptId = await SeedScriptAsync("evolving", OptionalCount); var device = await fixture.SeedDeviceAsync("PARAMS-EVOLVE"); var create = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest( scriptId, ScriptTriggerType.Scheduled, ClientIds: [device], CronExpression: "0 1 * * *"), JsonDefaults.Options); create.EnsureSuccessStatusCode(); var triggerId = (await create.Content.ReadFromJsonAsync>(JsonDefaults.Options))!["id"]; // The script gains a required parameter with no default after the schedule was saved. await SetParametersAsync(scriptId, OptionalCount, RequiredName); var listed = (await client.GetFromJsonAsync>(ApiRoutes.Triggers, JsonDefaults.Options))! .Single(t => t.Id == triggerId); Assert.Contains("“Name” needs a value", listed.ArgumentsProblem); var fired = await (await client.PostAsync(ApiRoutes.For.TriggerRun(triggerId), null)) .Content.ReadFromJsonAsync(JsonDefaults.Options); Assert.Equal(0, fired!.Queued); Assert.StartsWith("Not run:", fired.Message); var trigger = await fixture.WithDbAsync(db => db.ScriptTriggers.SingleAsync(t => t.Id == triggerId)); Assert.True(trigger.Enabled); // A default on the script is enough: the untouched value follows it. await SetParametersAsync(scriptId, OptionalCount, RequiredName with { DefaultValue = JsonSerializer.SerializeToElement("now set") }); var again = await (await client.PostAsync(ApiRoutes.For.TriggerRun(triggerId), null)) .Content.ReadFromJsonAsync(JsonDefaults.Options); Assert.Equal(1, again!.Queued); } [Fact] public async Task SavingABashScriptChecksItsParameters() { using var client = await fixture.SignedInAsync("params-admin"); var badDefault = await client.PostAsJsonAsync(ApiRoutes.Scripts, new SaveScriptRequest( "bad-default", null, "echo $Count", [new ScriptParameter("Count", ScriptParameterType.Number, DefaultValue: JsonSerializer.SerializeToElement("lots"))], Engine: ScriptEngine.Bash), JsonDefaults.Options); Assert.Equal(HttpStatusCode.BadRequest, badDefault.StatusCode); var duplicate = await client.PostAsJsonAsync(ApiRoutes.Scripts, new SaveScriptRequest( "duplicate", null, "", [new ScriptParameter("A", ScriptParameterType.String), new("a", ScriptParameterType.String)], Engine: ScriptEngine.Bash), JsonDefaults.Options); Assert.Equal(HttpStatusCode.BadRequest, duplicate.StatusCode); var good = await SaveAsync(client, new SaveScriptRequest( "good-defaults", null, "echo $Ports", [new ScriptParameter("Ports", ScriptParameterType.Array, ElementType: PrimitiveType.Number, DefaultValue: JsonSerializer.SerializeToElement(new[] { 80, 443 }))], Engine: ScriptEngine.Bash)); Assert.Equal("[80,443]", Assert.Single(good.Parameters).DefaultValue!.Value.GetRawText()); } [Fact] public async Task SavingAPowerShellScriptStoresWhatTheCodeDeclares() { using var client = await fixture.SignedInAsync("params-admin"); const string code = """ <# .PARAMETER Documented From help. #> param([Parameter(Mandatory)][int[]]$Ports = @(80, 443), [string]$Path, [string]$Documented) """; // Whatever the client sent: wrong types, a parameter the code lacks, none for one it has. var created = await SaveAsync(client, new SaveScriptRequest("from-code", null, code, [ new ScriptParameter("ports", ScriptParameterType.String, Expansion: ValueExpansion.Literal), new("Path", ScriptParameterType.Number, Description: "Hand-written"), new("Documented", ScriptParameterType.String, Description: "Replaced by help"), new("Stale", ScriptParameterType.String), ])); Assert.Equal(["Ports", "Path", "Documented"], created.Parameters.Select(p => p.Name)); var ports = created.Parameters[0]; Assert.Equal((ScriptParameterType.Array, PrimitiveType.Number, true), (ports.Type, ports.ElementType, ports.Required)); Assert.Equal("[80,443]", ports.DefaultValue!.Value.GetRawText()); Assert.Equal(ValueExpansion.Literal, ports.Expansion); Assert.Equal((ScriptParameterType.String, "Hand-written"), (created.Parameters[1].Type, created.Parameters[1].Description)); Assert.Equal("From help.", created.Parameters[2].Description); // An update that sends no parameters keeps the user-owned fields already stored. var response = await client.PutAsJsonAsync(ApiRoutes.For.Script(created.Id), new SaveScriptRequest("from-code", null, code + "\n# edited"), JsonDefaults.Options); response.EnsureSuccessStatusCode(); var updated = (await response.Content.ReadFromJsonAsync(JsonDefaults.Options))!; Assert.Equal(ValueExpansion.Literal, updated.Parameters[0].Expansion); Assert.Equal("Hand-written", updated.Parameters[1].Description); // Code that does not parse keeps what the editor last read from it. var broken = await client.PutAsJsonAsync(ApiRoutes.For.Script(created.Id), new SaveScriptRequest("from-code", null, "param([string]$Half", [new ScriptParameter("Half", ScriptParameterType.String)]), JsonDefaults.Options); broken.EnsureSuccessStatusCode(); Assert.Equal(["Half"], (await broken.Content.ReadFromJsonAsync(JsonDefaults.Options))!.Parameters.Select(p => p.Name)); } private static async Task SaveAsync(HttpClient client, SaveScriptRequest request) { var response = await client.PostAsJsonAsync(ApiRoutes.Scripts, request, JsonDefaults.Options); Assert.Equal(HttpStatusCode.Created, response.StatusCode); return (await response.Content.ReadFromJsonAsync(JsonDefaults.Options))!; } private Task SeedScriptAsync(string name, params ScriptParameter[] parameters) => fixture.WithDbAsync(async db => { var script = new ScriptEntity { Id = Guid.NewGuid(), Name = name, Language = "PowerShell", Content = "param($Name, $Count)", ParametersJson = JsonDefaults.Serialize(parameters), CreatedUtc = DateTimeOffset.UtcNow, UpdatedUtc = DateTimeOffset.UtcNow, }; db.Scripts.Add(script); await db.SaveChangesAsync(); return script.Id; }); private Task SetParametersAsync(Guid scriptId, params ScriptParameter[] parameters) => fixture.WithDbAsync(async db => { var script = await db.Scripts.SingleAsync(s => s.Id == scriptId); script.ParametersJson = JsonDefaults.Serialize(parameters); await db.SaveChangesAsync(); return 0; }); }