Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make unit test runnable in user mode under linux #368

Merged
merged 4 commits into from
Jan 30, 2025
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
48 changes: 48 additions & 0 deletions src/Fluxzy.Core/Misc/ProcessUtilX.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,18 @@

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace Fluxzy.Misc
{
internal static class ProcessUtilX
{
private static readonly string[] AskPassBinaries = new[] { "ssh-askpass", "ksshaskpass", "lxqt-sudo" };


private static readonly HashSet<string> RequiredCapabilities = new HashSet<string>(
new[] { "cap_net_raw", "cap_net_admin" },
StringComparer.OrdinalIgnoreCase);
Expand All @@ -35,5 +40,48 @@ public static async Task<bool> HasCaptureCapabilities()

return availableCapabilities.IsSupersetOf(RequiredCapabilities);
}

public static async Task<string?> GetExecutablePath(string executableName)
{
var processRunResult = await ProcessUtils.QuickRunAsync("which", executableName, null);

if (processRunResult.ExitCode != 0)
return null;

return processRunResult.StandardOutputMessage?.Trim('\r', '\n');
}


public static async Task<Process> RunElevatedSudoALinux(
string commandName, string[] args, bool redirectStdOut,
string askPasswordPrompt, bool redirectStandardError = false)
{
var tasks = AskPassBinaries
.Select(binary => GetExecutablePath(binary));

var results = await Task.WhenAll(tasks);
var result = results.FirstOrDefault(x => x != null) ??
throw new Exception(
$"No askpass binary found. Must install one of the following:" +
$" {string.Join(", ", AskPassBinaries)}");

var execCommandName = "sudo";
var preArgs = new List<string>() { "-A", "-E", "-p", $"{askPasswordPrompt}", commandName };

var startInfo = new ProcessStartInfo() {
FileName = execCommandName,
RedirectStandardOutput = redirectStdOut,
RedirectStandardError = redirectStandardError,
UseShellExecute = false,
};

startInfo.EnvironmentVariables["SUDO_ASKPASS"] = result;
foreach (var arg in preArgs.Concat(args))
startInfo.ArgumentList.Add(arg);

var process = Process.Start(startInfo);

return process!;
}
}
}
3 changes: 3 additions & 0 deletions src/Fluxzy.Core/Misc/ProcessUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,9 @@ public static bool IsCommandAvailable(string commandName)
return process;
}




public static Process? RunElevated(
string commandName, string[] args, bool redirectStdOut,
string askPasswordPrompt)
Expand Down
1 change: 0 additions & 1 deletion src/Fluxzy/System/OutOfProcAuthorityManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ await ProcessUtils.QuickRunAsync($"{_currentBinaryFullPath.RemoveFileExtension()
$" cert uninstall {thumbPrint}");

// We are using pkexec for linux

var result = await ProcessUtils.QuickRunAsync("pkexec",
$"{_currentBinaryFullPath.RemoveFileExtension()} cert uninstall {thumbPrint}");

Expand Down
5 changes: 3 additions & 2 deletions test/Fluxzy.Tests/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Fluxzy.Certificates;
Expand Down Expand Up @@ -50,8 +51,8 @@ public Startup(IMessageSink messageSink)
CertificateContext.InstallDefaultCertificate();

if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) {
_ = Task.Run(async () =>
await Utility.AcquireCapabilities(new FileInfo("fluxzynetcap").FullName))
Task.Run(async () => { await Utility.AcquireCapabilitiesLinux(new FileInfo("fluxzynetcap").FullName);
})
.GetAwaiter().GetResult();
}
}
Expand Down
2 changes: 2 additions & 0 deletions test/Fluxzy.Tests/UnitTests/Rules/AverageThrottlerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ public async Task SimpleThrottle(int delaySeconds)
var stream = await response.Content.ReadAsStreamAsync();
await stream.CopyToAsync(Stream.Null);

await Task.Delay(500);

watch.Stop();

Assert.True(watch.ElapsedMilliseconds > delaySeconds * 1000,
Expand Down
19 changes: 10 additions & 9 deletions test/Fluxzy.Tests/Utility.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// Copyright 2021 - Haga Rakotoharivelo - https://github.com/haga-rak

using System;
using System.IO;
using System.Threading.Tasks;
using Fluxzy.Misc;

Expand All @@ -11,25 +13,24 @@ public static class Utility
/// Make an executable have the required capabilities
/// </summary>
/// <returns></returns>
public static async Task<bool> AcquireCapabilities(string executablePath)
public static async Task<bool> AcquireCapabilitiesLinux(string executablePath)
{
if (!File.Exists(executablePath)) {
executablePath = (await ProcessUtilX.GetExecutablePath(executablePath))
?? throw new InvalidOperationException("Executable not found");
}

if (await ProcessUtilX.CanElevated())
return true; // Already root - no need to set capabilities

if (!ProcessUtils.IsCommandAvailable("setcap"))
return false;

if (!ProcessUtils.IsCommandAvailable("pkexec"))
return false;

var fullCommand = $"setcap cap_net_raw,cap_net_admin=eip \"{executablePath}\"";

var process = await ProcessUtils.RunElevatedAsync("pkexec",
new []{ "setcap", "cap_net_raw,cap_net_admin=eip", executablePath},
var process = await ProcessUtilX.RunElevatedSudoALinux("setcap",
new []{ "cap_net_raw,cap_net_admin=eip", executablePath},
false, "Please enter your password to set the required capabilities");

await process!.WaitForExitAsync();

return process.ExitCode == 0;
}
}
Expand Down
Loading