Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using LocalInstaller.Core.Features.Installation.Models;
using LocalInstaller.Core.Features.MacOsInstallation.Models;

namespace LocalInstaller.Core.Tests.Features.MacOsInstallation.Model;

[TestFixture]
public class MacOsInstallerManifestEnvironmentVariablesTests
{
[Test]
public void LaunchDaemonPlist_includesServerComponentEnvironmentVariables()
{
var product = new ProductManifest("Acme Studio", "acme-studio", "ACMESTUDIO")
{
Components =
[
ProductComponent.Server with
{
EnvironmentVariables = new Dictionary<string, string> { ["EXAMPLE_FLAG"] = "true" }
}
]
};

var manifest = MacOsInstallerManifest.From(product, "1.0.0");
var plist = new MacOsInstallerPlistGenerator(manifest).LaunchDaemonPlist();

Assert.That(plist, Does.Contain("<key>EXAMPLE_FLAG</key>"));
Assert.That(plist, Does.Contain("<string>true</string>"));
}

[Test]
public void LaunchDaemonPlist_omitsExtraEnvironmentVariablesWhenNoneDeclared()
{
var product = new ProductManifest("Acme Studio", "acme-studio", "ACMESTUDIO")
{
Components = [ProductComponent.Server]
};

var manifest = MacOsInstallerManifest.From(product, "1.0.0");
var plist = new MacOsInstallerPlistGenerator(manifest).LaunchDaemonPlist();

Assert.That(plist, Does.Contain("ASPNETCORE_URLS"));
Assert.That(plist, Does.Not.Contain("EXAMPLE_FLAG"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,8 @@ public async Task ExecuteInstallAsync_runsElevatedScriptContainingAllComponents(
Assert.That(script, Does.Contain("cp -r '/payload/server'/."));
Assert.That(script, Does.Contain("cp '/payload/agent-up-server.service' '/etc/systemd/system/agent-up-server.service'"));
Assert.That(script, Does.Contain("systemctl daemon-reload"));
Assert.That(script, Does.Contain("systemctl enable --now 'agent-up-server.service'"));
Assert.That(script, Does.Contain("systemctl enable 'agent-up-server.service'"));
Assert.That(script, Does.Contain("systemctl restart 'agent-up-server.service'"));

// CLI operations
Assert.That(script, Does.Contain("rm -rf '/opt/agent-up/cli'"));
Expand All @@ -78,6 +79,43 @@ public async Task ExecuteInstallAsync_runsElevatedScriptContainingAllComponents(
Assert.That(script, Does.Contain("ln -sf '/opt/agent-up/cli/AgentUp.CLI' '/usr/bin/agent-up'"));
}

[Test]
public async Task ExecuteInstallAsync_writesSystemdDropInWhenManifestDeclaresServerEnvironmentVariables()
{
var commands = new ScriptCapturingCommandRunner();
var manifest = UbuntuInstallerManifest.ForProduct(AgentUpTestManifests.Product()) with
{
EnvironmentVariables = new Dictionary<string, string> { ["EXAMPLE_FLAG"] = "true" }
};
var options = Options() with { Manifest = manifest };
var adapter = new UbuntuInstallerPlatformAdapter(
commands,
new RecordingUbuntuFileSystem(),
options,
new RequiredCommandRunner(commands),
new DockerPrerequisite(new DockerPrerequisiteProvider(commands), new Version(27, 0, 0)));

await adapter.ExecuteInstallAsync(Session()).DrainAsync();

var script = commands.CapturedScript;
Assert.That(script, Does.Contain("mkdir -p '/etc/systemd/system/agent-up-server.service.d'"));
Assert.That(script, Does.Contain("[Service]"));
Assert.That(script, Does.Contain("Environment=\"EXAMPLE_FLAG=true\""));
}

[Test]
public async Task ExecuteInstallAsync_writesNoDropInWhenManifestDeclaresNoServerEnvironmentVariables()
{
var commands = new ScriptCapturingCommandRunner();
var adapter = Adapter(commands, new RecordingUbuntuFileSystem());

await adapter.ExecuteInstallAsync(Session()).DrainAsync();

var script = commands.CapturedScript;
Assert.That(script, Does.Not.Contain("mkdir -p '/etc/systemd/system/agent-up-server.service.d'"));
Assert.That(script, Does.Not.Contain("[Service]"));
}

[Test]
public async Task ValidateInstalledStateAsync_reportsSuccessFromUbuntuState()
{
Expand Down Expand Up @@ -130,7 +168,8 @@ public async Task ExecuteComponentActionAsync_installServer_copiesTrayPayloadAnd
{
// Server payload is installed
Assert.That(script, Does.Contain("cp -r '/payload/server'/."));
Assert.That(script, Does.Contain("systemctl enable --now 'agent-up-server.service'"));
Assert.That(script, Does.Contain("systemctl enable 'agent-up-server.service'"));
Assert.That(script, Does.Contain("systemctl restart 'agent-up-server.service'"));
// Tray payload is bundled with server
Assert.That(script, Does.Contain("cp -r '/payload/tray'/."));
Assert.That(script, Does.Contain("chmod +x '/opt/agent-up/tray/AgentUp.Tray'"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,76 @@ public void PostInstallScript_doesNotRunInstallCore()
Assert.That(script, Does.Not.Contain("--install-core"));
}

[Test]
public void EnvironmentOverrideConf_isEmptyWhenNoVariablesDeclared()
{
var conf = UbuntuInstallerManifest.ForProduct(AgentUpTestManifests.Product()).EnvironmentOverrideConf();

Assert.That(conf, Is.Empty);
}

[Test]
public void EnvironmentOverrideConf_quotesValuesContainingSpaces()
{
var manifest = UbuntuInstallerManifest.ForProduct(AgentUpTestManifests.Product()) with
{
EnvironmentVariables = new Dictionary<string, string> { ["EXAMPLE_MESSAGE"] = "hello world" }
};

var conf = manifest.EnvironmentOverrideConf();

Assert.That(conf, Does.Contain("Environment=\"EXAMPLE_MESSAGE=hello world\""));
}

[Test]
public void EnvironmentOverrideConf_doublesEmbeddedBackslashes()
{
var manifest = UbuntuInstallerManifest.ForProduct(AgentUpTestManifests.Product()) with
{
EnvironmentVariables = new Dictionary<string, string> { ["EXAMPLE_PATH"] = @"C:\tools" }
};

var conf = manifest.EnvironmentOverrideConf();

Assert.That(conf, Does.Contain(@"Environment=""EXAMPLE_PATH=C:\\tools"""));
}

[Test]
public void EnvironmentOverrideConf_escapesEmbeddedQuotes()
{
var manifest = UbuntuInstallerManifest.ForProduct(AgentUpTestManifests.Product()) with
{
EnvironmentVariables = new Dictionary<string, string> { ["EXAMPLE_MESSAGE"] = "say \"hi\"" }
};

var conf = manifest.EnvironmentOverrideConf();

const string q = "\"";
Assert.That(conf, Does.Contain($"Environment={q}EXAMPLE_MESSAGE=say \\{q}hi\\{q}{q}"));
}

[Test]
public void EnvironmentOverrideConf_rejectsValuesContainingNewlines()
{
var manifest = UbuntuInstallerManifest.ForProduct(AgentUpTestManifests.Product()) with
{
EnvironmentVariables = new Dictionary<string, string> { ["EXAMPLE_FLAG"] = "line1\nline2" }
};

Assert.That(() => manifest.EnvironmentOverrideConf(), Throws.ArgumentException);
}

[Test]
public void EnvironmentOverrideConf_rejectsKeysContainingNewlines()
{
var manifest = UbuntuInstallerManifest.ForProduct(AgentUpTestManifests.Product()) with
{
EnvironmentVariables = new Dictionary<string, string> { ["EXAMPLE_FLAG\nSERVICE_ENVIRONMENT"] = "true" }
};

Assert.That(() => manifest.EnvironmentOverrideConf(), Throws.ArgumentException);
}

[Test]
public void DesktopEntryText_declaresStartupWmClassForUbuntuTaskbarIcon()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using LocalInstaller.Core.Features.WindowsInstallation.Models;
using LocalInstaller.Core.Features.WindowsInstallation.Services;

namespace LocalInstaller.Core.Tests.Features.WindowsInstallation.Service;

[TestFixture]
public class WindowsInstallerCommandsEnvironmentTests
{
[Test]
public void ServiceEnvironmentPowerShell_returnsNullWhenManifestDeclaresNoEnvironmentVariables()
{
var manifest = Manifest(null);

Assert.That(WindowsInstallerCommands.ServiceEnvironmentPowerShell(manifest), Is.Null);
}

[Test]
public void ServiceEnvironmentPowerShell_writesRegistryEnvironmentValueWhenDeclared()
{
var manifest = Manifest(new Dictionary<string, string> { ["EXAMPLE_FLAG"] = "true" });

var script = WindowsInstallerCommands.ServiceEnvironmentPowerShell(manifest);

Assert.That(script, Is.Not.Null);
Assert.That(script, Does.Contain($"HKLM:\\SYSTEM\\CurrentControlSet\\Services\\{manifest.ServiceName}"));
Assert.That(script, Does.Contain("-Name Environment"));
Assert.That(script, Does.Contain("-PropertyType MultiString"));
Assert.That(script, Does.Contain("EXAMPLE_FLAG=true"));
}

private static WindowsInstallerManifest Manifest(IReadOnlyDictionary<string, string>? environmentVariables)
=> new(
ProductName: "Acme Studio",
Manufacturer: "Acme Labs",
Version: "1.0.0",
UpgradeCode: "16357A7B-6C17-4635-85D5-28E74D12F4F3",
ServiceName: "acme-studio-server",
CliShimName: "acme-studio.cmd",
BundleName: "Acme Studio",
ServerUrl: "http://127.0.0.1:5000",
EnvironmentVariables: environmentVariables);
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ public static ProductComponent ToProductComponent(this LocalInstallerArtifactDes
TargetFor(descriptor.Target),
descriptor.ExecutableName,
descriptor.PayloadDirectoryName,
descriptor.SourceProjectPath);
descriptor.SourceProjectPath,
descriptor.EnvironmentVariables);

private static InstallerComponentTarget TargetFor(LocalInstallerArtifactTarget target)
=> target switch
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ public sealed record ProductComponent(
InstallerComponentTarget? Target = null,
string? ExecutableName = null,
string? PayloadDirectoryName = null,
string? SourceProjectPath = null)
string? SourceProjectPath = null,
IReadOnlyDictionary<string, string>? EnvironmentVariables = null)
{
public static ProductComponent Desktop
=> new("desktop", "Desktop", "Desktop application.", InstallerComponentTarget.Desktop, "desktop", "desktop");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,13 @@ public string DefaultInstallRoot()

public IReadOnlyList<ProductComponent> InstallableComponents
=> InstallerOptions.Count == 0 ? Components : InstallerOptions;

/// <summary>
/// Extra environment variables the Server component's manifest declared, applied when the platform
/// adapter registers the native service. Empty when the Server component declares none.
/// </summary>
public IReadOnlyDictionary<string, string> ServerEnvironmentVariables
=> InstallableComponents.FirstOrDefault(component => component.Target == InstallerComponentTarget.Server)
?.EnvironmentVariables
?? new Dictionary<string, string>();
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ public sealed partial record MacOsInstallerManifest(
string ServerUrl,
string DesktopExecutableName = "desktop",
string InstallerExecutableName = "installer",
string ServerExecutableName = "server")
string ServerExecutableName = "server",
IReadOnlyDictionary<string, string>? EnvironmentVariables = null)
{
private static readonly Regex SafeSlug = new(@"^[a-z][a-z0-9-]+$", RegexOptions.Compiled);
private static readonly Regex SafeName = new(@"^[A-Za-z][A-Za-z0-9 -]*$", RegexOptions.Compiled);
Expand All @@ -29,7 +30,8 @@ public static MacOsInstallerManifest From(
return manifest with
{
DesktopExecutableName = ExecutableName(product, InstallerComponentTarget.Desktop, "desktop"),
ServerExecutableName = ExecutableName(product, InstallerComponentTarget.Server, "server")
ServerExecutableName = ExecutableName(product, InstallerComponentTarget.Server, "server"),
EnvironmentVariables = product.ServerEnvironmentVariables
};
}

Expand Down Expand Up @@ -130,7 +132,10 @@ public string LaunchDaemonPlist()
new XElement("dict",
KeyString("ASPNETCORE_URLS", _manifest.ServerUrl),
KeyString("Storage__DataDirectory", $"/Library/Application Support/{_manifest.ProductName}"),
KeyString("DOTNET_BUNDLE_EXTRACT_BASE_DIR", $"/Library/Application Support/{_manifest.ProductName}/bundle-cache")),
KeyString("DOTNET_BUNDLE_EXTRACT_BASE_DIR", $"/Library/Application Support/{_manifest.ProductName}/bundle-cache"),
(_manifest.EnvironmentVariables ?? new Dictionary<string, string>())
.SelectMany(pair => KeyString(pair.Key, pair.Value))
.ToArray()),
new XElement("key", "RunAtLoad"),
new XElement("true"),
new XElement("key", "KeepAlive"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ public sealed partial record UbuntuInstallerManifest(
string DesktopExecutableName,
string ServerExecutableName,
string CliExecutableName,
string TrayExecutableName)
string TrayExecutableName,
IReadOnlyDictionary<string, string>? EnvironmentVariables = null)
{
public static UbuntuInstallerManifest ForProduct(ProductManifest manifest)
=> new(
Expand All @@ -21,7 +22,30 @@ public static UbuntuInstallerManifest ForProduct(ProductManifest manifest)
DesktopExecutableName: ExecutableName(manifest, InstallerComponentTarget.Desktop, "desktop"),
ServerExecutableName: ExecutableName(manifest, InstallerComponentTarget.Server, "server"),
CliExecutableName: ExecutableName(manifest, InstallerComponentTarget.Cli, "cli"),
TrayExecutableName: ExecutableName(manifest, InstallerComponentTarget.Tray, "tray"));
TrayExecutableName: ExecutableName(manifest, InstallerComponentTarget.Tray, "tray"),
EnvironmentVariables: manifest.ServerEnvironmentVariables);

/// <summary>
/// Extra systemd drop-in `Environment=` lines for <see cref="EnvironmentVariables"/>, empty when the
/// Server manifest declared none. Each assignment is quoted per systemd.exec(5) config quoting rules
/// so values containing spaces, quotes, or backslashes parse as a single assignment.
/// </summary>
public string EnvironmentOverrideConf()
=> string.Concat((EnvironmentVariables ?? new Dictionary<string, string>())
.Select(pair => $"Environment={SystemdAssignment(pair.Key, pair.Value)}" + Environment.NewLine));

private static string SystemdAssignment(string key, string value)
{
if (string.IsNullOrEmpty(key) || key.Contains('=') || key.Any(c => c is '\n' or '\r' || char.IsControl(c)))
throw new ArgumentException($"Environment variable key '{key}' is invalid.", nameof(key));

if (value.Any(c => c is '\n' or '\r' || char.IsControl(c)))
throw new ArgumentException(
$"Environment variable '{key}' value must not contain control characters.", nameof(value));

var escaped = $"{key}={value}".Replace("\\", "\\\\").Replace("\"", "\\\"");
return $"\"{escaped}\"";
}

public string DesktopEntryText(string executablePath, string version)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ namespace LocalInstaller.Core.Features.UbuntuInstallation.Providers;

public sealed class UbuntuInstallerPlatformAdapter : IInstallerPlatformAdapter
{
private const string EnvironmentDropInFileName = "10-environment.conf";

private readonly ICommandRunner _commands;
private readonly IUbuntuInstallerFileSystem _files;
private readonly UbuntuInstallerOptions _options;
Expand Down Expand Up @@ -186,8 +188,26 @@ private string BuildInstallScript(InstallSummary summary, Dictionary<string, str
sb.AppendLine($"cp -r {Q(_options.Payload.ServerDirectory)}/. {Q(_options.Paths.ServerDirectory)}");
sb.AppendLine($"chmod +x {Q(_options.Paths.ServerExecutable)}");
sb.AppendLine($"cp {Q(_options.Payload.ServiceFilePath)} {Q(_options.Paths.ServicePath)}");

var dropInDirectory = $"{_options.Paths.ServicePath}.d";
var environmentDropIn = Path.Join(dropInDirectory, EnvironmentDropInFileName);
sb.AppendLine($"rm -f {Q(environmentDropIn)}");
var environmentOverride = _options.Manifest.EnvironmentOverrideConf();
if (!string.IsNullOrEmpty(environmentOverride))
{
sb.AppendLine($"mkdir -p {Q(dropInDirectory)}");
sb.AppendLine($"cat > {Q(environmentDropIn)} << 'SERVICE_ENVIRONMENT'");
sb.AppendLine("[Service]");
sb.Append(environmentOverride);
Comment thread
themassiveone marked this conversation as resolved.
Resolved
sb.AppendLine("SERVICE_ENVIRONMENT");
}

sb.AppendLine("systemctl daemon-reload");
sb.AppendLine($"systemctl enable --now {Q(_options.Manifest.ServiceUnitName)}");
sb.AppendLine($"systemctl enable {Q(_options.Manifest.ServiceUnitName)}");
// enable --now would not restart an already-active unit, so an upgrade's new
// drop-in environment would not take effect; restart always applies it and
// still starts a stopped unit.
sb.AppendLine($"systemctl restart {Q(_options.Manifest.ServiceUnitName)}");
}

if (summary.Includes(InstallerComponent.Tray))
Expand Down Expand Up @@ -233,6 +253,7 @@ private string BuildUninstallScript(InstallerComponentTarget target)
case InstallerComponentTarget.Server:
sb.AppendLine($"systemctl disable --now {Q(_options.Manifest.ServiceUnitName)} 2>/dev/null || true");
sb.AppendLine($"rm -f {Q(_options.Paths.ServicePath)}");
sb.AppendLine($"rm -f {Q(Path.Join($"{_options.Paths.ServicePath}.d", EnvironmentDropInFileName))}");
sb.AppendLine("systemctl daemon-reload");
sb.AppendLine($"rm -rf {Q(_options.Paths.ServerDirectory)}");
sb.AppendLine($"rm -f {Q(_options.Paths.XdgAutostartPath)}");
Expand Down
Loading